From a54c9e0c9eb5103685b5a4aa41c0950ca1714942 Mon Sep 17 00:00:00 2001 From: Amit Pandey Date: Mon, 11 Jun 2018 13:48:30 +0530 Subject: [PATCH 01/11] Bael 4461 2 (#4444) * [BAEL-4462] - Fixed integration tests * [BAEL-4462] - Fixed integration tests * [BAEL-4462] - Fixed integration tests * [BAEL-4462] - Fixed integration tests * [BAEL-4462] - Fixed integration tests * [BAEL-4462] - Fixed integration tests * [BAEL-4462] - Fixed integration tests * [BAEL-4462] - Fixed integration tests * [BAEL-4462] - Fixed integration tests * [BAEL-4462] - Fixed integration tests * [BAEL-4462] - Fixed integration tests * [BAEL-4462] - Fixed integration tests * [BAEL-4462] - Fixed integration tests * [BAEL-4462] - Fixed integration tests * Fix verification times --- .../powerpoint/PowerPointIntegrationTest.java | 13 +++-- .../baeldung/array/JaggedArrayUnitTest.java | 2 +- .../money/JavaMoneyUnitManualTest.java | 2 +- .../baeldung/scripting/NashornUnitTest.java | 2 +- .../async/service/ClusterServiceImpl.java | 6 ++ .../async/service/TutorialBucketService.java | 1 + ...ersonCrudServiceIntegrationTestConfig.java | 24 ++++++++ ...st.java => PersonCrudServiceLiveTest.java} | 22 +++++--- ...nTest.java => ClusterServiceLiveTest.java} | 2 +- ....java => StudentGradeServiceLiveTest.java} | 4 +- ...IntegrationTest.java => N1QLLiveTest.java} | 37 ++++++------ ...st.java => PersonCrudServiceLiveTest.java} | 2 +- ...nTest.java => ClusterServiceLiveTest.java} | 2 +- jaxb/pom.xml | 5 ++ .../resources/log4jstructuraldp.properties | 9 +++ .../jaxb/test/JaxbIntegrationTest.java | 2 +- jaxb/src/test/resources/book.xml | 5 ++ ...tionTest.java => ConvListValLiveTest.java} | 2 +- ...t.java => AutomaticTimerBeanLiveTest.java} | 2 +- ...rammaticAtFixedRateTimerBeanLiveTest.java} | 2 +- ...ava => ProgrammaticTimerBeanLiveTest.java} | 2 +- ...maticWithFixedDelayTimerBeanLiveTest.java} | 2 +- ...st.java => ScheduleTimerBeanLiveTest.java} | 2 +- ...Test.java => StoredProcedureLiveTest.java} | 2 +- .../jcache/EntryProcessorIntegrationTest.java | 5 +- .../jcache/EventListenerIntegrationTest.java | 5 +- .../jcache/JCacheIntegrationTest.java | 2 +- .../resources/reladomo/ReladomoTestConfig.xml | 2 +- .../tests/JSONLayoutIntegrationTest.java | 1 + .../resources/log4jstructuraldp.properties | 9 +++ .../RedissonConfigurationIntegrationTest.java | 4 +- .../com/baeldung/RedissonIntegrationTest.java | 4 +- .../jdbc/AutomapInterfaceIntegrationTest.java | 15 ++--- .../jdbc/BasicQueryTypesIntegrationTest.java | 16 +++--- .../jdbc/InsertClobIntegrationTest.java | 8 +-- .../jdbc/ReturnKeysIntegrationTest.java | 6 +- .../jdbc/TransactionIntegrationTest.java | 5 +- .../PowerMockitoIntegrationTest.java | 8 ++- .../mockito/MockitoMockIntegrationTest.java | 2 +- .../JUnitManagedIntegrationTest.java | 56 ++++++++++++------- 40 files changed, 201 insertions(+), 101 deletions(-) create mode 100644 couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java rename couchbase/src/test/java/com/baeldung/couchbase/async/person/{PersonCrudServiceIntegrationTest.java => PersonCrudServiceLiveTest.java} (90%) rename couchbase/src/test/java/com/baeldung/couchbase/async/service/{ClusterServiceIntegrationTest.java => ClusterServiceLiveTest.java} (94%) rename couchbase/src/test/java/com/baeldung/couchbase/mapreduce/{StudentGradeServiceIntegrationTest.java => StudentGradeServiceLiveTest.java} (98%) rename couchbase/src/test/java/com/baeldung/couchbase/n1ql/{N1QLIntegrationTest.java => N1QLLiveTest.java} (97%) rename couchbase/src/test/java/com/baeldung/couchbase/spring/person/{PersonCrudServiceIntegrationTest.java => PersonCrudServiceLiveTest.java} (97%) rename couchbase/src/test/java/com/baeldung/couchbase/spring/service/{ClusterServiceIntegrationTest.java => ClusterServiceLiveTest.java} (94%) create mode 100644 jaxb/src/main/resources/log4jstructuraldp.properties create mode 100644 jaxb/src/test/resources/book.xml rename jee-7/src/test/java/com/baeldung/convListVal/{ConvListValIntegrationTest.java => ConvListValLiveTest.java} (98%) rename jee-7/src/test/java/com/baeldung/timer/{AutomaticTimerBeanIntegrationTest.java => AutomaticTimerBeanLiveTest.java} (98%) rename jee-7/src/test/java/com/baeldung/timer/{ProgrammaticAtFixedRateTimerBeanIntegrationTest.java => ProgrammaticAtFixedRateTimerBeanLiveTest.java} (96%) rename jee-7/src/test/java/com/baeldung/timer/{ProgrammaticTimerBeanIntegrationTest.java => ProgrammaticTimerBeanLiveTest.java} (97%) rename jee-7/src/test/java/com/baeldung/timer/{ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java => ProgrammaticWithFixedDelayTimerBeanLiveTest.java} (96%) rename jee-7/src/test/java/com/baeldung/timer/{ScheduleTimerBeanIntegrationTest.java => ScheduleTimerBeanLiveTest.java} (97%) rename jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/{StoredProcedureIntegrationTest.java => StoredProcedureLiveTest.java} (98%) create mode 100644 patterns/design-patterns/src/main/resources/log4jstructuraldp.properties diff --git a/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java b/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java index 5319208e85..7253238e80 100644 --- a/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java +++ b/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java @@ -1,25 +1,30 @@ package com.baeldung.poi.powerpoint; +import java.io.File; +import java.util.List; + import org.apache.poi.xslf.usermodel.XMLSlideShow; import org.apache.poi.xslf.usermodel.XSLFShape; import org.apache.poi.xslf.usermodel.XSLFSlide; import org.junit.After; import org.junit.Assert; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; - -import java.io.File; -import java.util.List; +import org.junit.rules.TemporaryFolder; public class PowerPointIntegrationTest { private PowerPointHelper pph; private String fileLocation; private static final String FILE_NAME = "presentation.pptx"; + + @Rule + public TemporaryFolder tempFolder = new TemporaryFolder(); @Before public void setUp() throws Exception { - File currDir = new File("."); + File currDir = tempFolder.newFolder(); String path = currDir.getAbsolutePath(); fileLocation = path.substring(0, path.length() - 1) + FILE_NAME; diff --git a/core-java/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java b/core-java/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java index f432436190..a4dd7e25c3 100644 --- a/core-java/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java +++ b/core-java/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java @@ -46,7 +46,7 @@ public class JaggedArrayUnitTest { ByteArrayOutputStream outContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent)); obj.printElements(jaggedArr); - assertEquals("[1, 2]\n[3, 4, 5]\n[6, 7, 8, 9]\n", outContent.toString()); + assertEquals("[1, 2][3, 4, 5][6, 7, 8, 9]", outContent.toString().replace("\r", "").replace("\n", "")); System.setOut(System.out); } diff --git a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java index fe2747bcee..04d2886a82 100644 --- a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java +++ b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java @@ -179,7 +179,7 @@ public class JavaMoneyUnitManualTest { MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder .of(Locale.US) .set(CurrencyStyle.NAME) - .set("pattern", "00000.00 �") + .set("pattern", "00000.00 US Dollar") .build()); String customFormatted = customFormat.format(oneDollar); diff --git a/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java b/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java index 7f165cec86..9abe8a927c 100644 --- a/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java +++ b/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java @@ -104,7 +104,7 @@ public class NashornUnitTest { public void loadExamples() throws ScriptException { Object loadResult = engine.eval("load('classpath:js/script.js');" + "increment(5)"); - Assert.assertEquals(6.0, loadResult); + Assert.assertEquals(6, ((Double) loadResult).intValue()); Object math = engine.eval("var math = loadWithNewGlobal('classpath:js/math_module.js');" + "math.increment(5);"); diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java b/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java index e708922988..3100f0c70b 100644 --- a/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java +++ b/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java @@ -5,6 +5,7 @@ import java.util.concurrent.ConcurrentHashMap; import javax.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.couchbase.client.java.Bucket; @@ -18,6 +19,11 @@ public class ClusterServiceImpl implements ClusterService { private Cluster cluster; private Map buckets = new ConcurrentHashMap<>(); + + @Autowired + public ClusterServiceImpl(Cluster cluster) { + this.cluster = cluster; + } @PostConstruct private void init() { diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java b/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java index 459585d995..75a196ff5d 100644 --- a/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java +++ b/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java @@ -18,6 +18,7 @@ public class TutorialBucketService extends AbstractBucketService { @Autowired public TutorialBucketService(ClusterService clusterService) { super(clusterService); + openBucket(); } @Override diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java new file mode 100644 index 0000000000..9e650752d2 --- /dev/null +++ b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java @@ -0,0 +1,24 @@ +package com.baeldung.couchbase.async.person; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +import com.couchbase.client.java.Cluster; +import com.couchbase.client.java.CouchbaseCluster; +import com.couchbase.client.java.env.CouchbaseEnvironment; +import com.couchbase.client.java.env.DefaultCouchbaseEnvironment; + +@Configuration +@ComponentScan(basePackages = {"com.baeldung.couchbase.async.service", "com.baeldung.couchbase.n1ql"}) +public class PersonCrudServiceIntegrationTestConfig { + + @Bean + public Cluster cluster() { + CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder() + .connectTimeout(60000) + .build(); + return CouchbaseCluster.create(env, "127.0.0.1"); + } + +} diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java similarity index 90% rename from couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java index 565aaed5da..267071ab35 100644 --- a/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java +++ b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java @@ -1,27 +1,31 @@ package com.baeldung.couchbase.async.person; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.UUID; -import javax.annotation.PostConstruct; - import org.apache.commons.lang3.RandomStringUtils; +import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.baeldung.couchbase.async.AsyncIntegrationTest; -import com.baeldung.couchbase.async.person.Person; -import com.baeldung.couchbase.async.person.PersonCrudService; -import com.baeldung.couchbase.async.person.PersonDocumentConverter; import com.baeldung.couchbase.async.service.BucketService; import com.couchbase.client.java.Bucket; import com.couchbase.client.java.document.JsonDocument; -public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest { +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {PersonCrudServiceIntegrationTestConfig.class}) +public class PersonCrudServiceLiveTest extends AsyncIntegrationTest { @Autowired private PersonCrudService personService; @@ -35,8 +39,8 @@ public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest { private Bucket bucket; - @PostConstruct - private void init() { + @Before + public void init() { bucket = bucketService.getBucket(); } diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java similarity index 94% rename from couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java index d0db5d37a3..5f478ae788 100644 --- a/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java +++ b/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java @@ -18,7 +18,7 @@ import com.couchbase.client.java.Bucket; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { AsyncIntegrationTestConfig.class }) @TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) -public class ClusterServiceIntegrationTest extends AsyncIntegrationTest { +public class ClusterServiceLiveTest extends AsyncIntegrationTest { @Autowired private ClusterService couchbaseService; diff --git a/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java similarity index 98% rename from couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java index 00d462e32a..d260795ed3 100644 --- a/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceIntegrationTest.java +++ b/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java @@ -14,8 +14,8 @@ import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.view.ViewResult; import com.couchbase.client.java.view.ViewRow; -public class StudentGradeServiceIntegrationTest { - private static final Logger logger = LoggerFactory.getLogger(StudentGradeServiceIntegrationTest.class); +public class StudentGradeServiceLiveTest { + private static final Logger logger = LoggerFactory.getLogger(StudentGradeServiceLiveTest.class); static StudentGradeService studentGradeService; static Set gradeIds = new HashSet<>(); diff --git a/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java similarity index 97% rename from couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java index 8112d7d222..602bb5b8a5 100644 --- a/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java +++ b/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java @@ -1,5 +1,23 @@ package com.baeldung.couchbase.n1ql; +import static com.baeldung.couchbase.n1ql.CodeSnippets.extractJsonResult; +import static com.couchbase.client.java.query.Select.select; +import static com.couchbase.client.java.query.dsl.Expression.i; +import static com.couchbase.client.java.query.dsl.Expression.s; +import static com.couchbase.client.java.query.dsl.Expression.x; +import static org.junit.Assert.assertNotNull; + +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + import com.couchbase.client.java.Bucket; import com.couchbase.client.java.Cluster; import com.couchbase.client.java.document.JsonDocument; @@ -10,28 +28,13 @@ import com.couchbase.client.java.query.N1qlQueryResult; import com.couchbase.client.java.query.N1qlQueryRow; import com.couchbase.client.java.query.Statement; import com.fasterxml.jackson.databind.JsonNode; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + import rx.Observable; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; -import java.util.stream.IntStream; -import java.util.stream.Stream; - -import static com.baeldung.couchbase.n1ql.CodeSnippets.extractJsonResult; -import static com.couchbase.client.java.query.Select.select; -import static com.couchbase.client.java.query.dsl.Expression.*; -import static org.junit.Assert.assertNotNull; - @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { IntegrationTestConfig.class }) -public class N1QLIntegrationTest { +public class N1QLLiveTest { @Autowired diff --git a/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java similarity index 97% rename from couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java index ec15be1acc..493b326d49 100644 --- a/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java +++ b/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java @@ -10,7 +10,7 @@ import org.springframework.beans.factory.annotation.Autowired; import com.baeldung.couchbase.spring.IntegrationTest; -public class PersonCrudServiceIntegrationTest extends IntegrationTest { +public class PersonCrudServiceLiveTest extends IntegrationTest { private static final String CLARK_KENT = "Clark Kent"; private static final String SMALLVILLE = "Smallville"; diff --git a/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java similarity index 94% rename from couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java index ead247dfbc..7a89a208f7 100644 --- a/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java +++ b/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java @@ -17,7 +17,7 @@ import com.couchbase.client.java.Bucket; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { IntegrationTestConfig.class }) @TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) -public class ClusterServiceIntegrationTest extends IntegrationTest { +public class ClusterServiceLiveTest extends IntegrationTest { @Autowired private ClusterService couchbaseService; diff --git a/jaxb/pom.xml b/jaxb/pom.xml index 26d7c8d362..f8e5ec0977 100644 --- a/jaxb/pom.xml +++ b/jaxb/pom.xml @@ -39,6 +39,11 @@ commons-lang3 ${commons-lang3.version} + + javax.activation + activation + 1.1 + diff --git a/jaxb/src/main/resources/log4jstructuraldp.properties b/jaxb/src/main/resources/log4jstructuraldp.properties new file mode 100644 index 0000000000..5bc2bfe4b9 --- /dev/null +++ b/jaxb/src/main/resources/log4jstructuraldp.properties @@ -0,0 +1,9 @@ + +# Root logger +log4j.rootLogger=INFO, file, stdout + +# Write to console +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file diff --git a/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java b/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java index b2dde85c0f..77b7f1a0b3 100644 --- a/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java +++ b/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java @@ -44,7 +44,7 @@ public class JaxbIntegrationTest { File bookFile = new File(this.getClass().getResource("/book.xml").getFile()); String sampleBookXML = FileUtils.readFileToString(sampleBookFile, "UTF-8"); String marshallerBookXML = FileUtils.readFileToString(bookFile, "UTF-8"); - Assert.assertEquals(sampleBookXML, marshallerBookXML); + Assert.assertEquals(sampleBookXML.replace("\r", "").replace("\n", ""), marshallerBookXML.replace("\r", "").replace("\n", "")); } @Test diff --git a/jaxb/src/test/resources/book.xml b/jaxb/src/test/resources/book.xml new file mode 100644 index 0000000000..605d531b16 --- /dev/null +++ b/jaxb/src/test/resources/book.xml @@ -0,0 +1,5 @@ + + + Book1 + 2016-12-16T17:28:49.718Z + diff --git a/jee-7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java b/jee-7/src/test/java/com/baeldung/convListVal/ConvListValLiveTest.java similarity index 98% rename from jee-7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/convListVal/ConvListValLiveTest.java index caeba95e45..0d6fd295e6 100644 --- a/jee-7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java +++ b/jee-7/src/test/java/com/baeldung/convListVal/ConvListValLiveTest.java @@ -22,7 +22,7 @@ import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; @RunWith(Arquillian.class) -public class ConvListValIntegrationTest { +public class ConvListValLiveTest { @ArquillianResource private URL deploymentUrl; diff --git a/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanLiveTest.java similarity index 98% rename from jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanLiveTest.java index 0e4c91ad67..41dde6549d 100644 --- a/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java +++ b/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanLiveTest.java @@ -21,7 +21,7 @@ import static org.hamcrest.Matchers.equalTo; @RunWith(Arquillian.class) -public class AutomaticTimerBeanIntegrationTest { +public class AutomaticTimerBeanLiveTest { //the @AutomaticTimerBean has a method called every 10 seconds //testing the difference ==> 100000 diff --git a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanLiveTest.java similarity index 96% rename from jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanLiveTest.java index 13cd1729db..350c094f38 100644 --- a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java +++ b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanLiveTest.java @@ -21,7 +21,7 @@ import static org.hamcrest.Matchers.is; @RunWith(Arquillian.class) -public class ProgrammaticAtFixedRateTimerBeanIntegrationTest { +public class ProgrammaticAtFixedRateTimerBeanLiveTest { final static long TIMEOUT = 1000; final static long TOLERANCE = 500l; diff --git a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanLiveTest.java similarity index 97% rename from jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanLiveTest.java index b90cb6d909..ad079c131b 100644 --- a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java +++ b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanLiveTest.java @@ -19,7 +19,7 @@ import static org.hamcrest.Matchers.is; @RunWith(Arquillian.class) -public class ProgrammaticTimerBeanIntegrationTest { +public class ProgrammaticTimerBeanLiveTest { final static long TIMEOUT = 5000l; final static long TOLERANCE = 1000l; diff --git a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanLiveTest.java similarity index 96% rename from jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanLiveTest.java index e2e660f79b..974f0a285f 100644 --- a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java +++ b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanLiveTest.java @@ -21,7 +21,7 @@ import static org.hamcrest.Matchers.is; @RunWith(Arquillian.class) -public class ProgrammaticWithFixedDelayTimerBeanIntegrationTest { +public class ProgrammaticWithFixedDelayTimerBeanLiveTest { final static long TIMEOUT = 15000l; final static long TOLERANCE = 1000l; diff --git a/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanLiveTest.java similarity index 97% rename from jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanLiveTest.java index 580edade77..a4ed9ceb68 100644 --- a/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java +++ b/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanLiveTest.java @@ -20,7 +20,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @RunWith(Arquillian.class) -public class ScheduleTimerBeanIntegrationTest { +public class ScheduleTimerBeanLiveTest { private final static long TIMEOUT = 5000l; private final static long TOLERANCE = 1000l; diff --git a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java b/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java similarity index 98% rename from jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java rename to jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java index c0fb5485aa..8bc8c854da 100644 --- a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java +++ b/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java @@ -15,7 +15,7 @@ import org.junit.Test; import com.baeldung.jpa.model.Car; -public class StoredProcedureIntegrationTest { +public class StoredProcedureLiveTest { private static EntityManagerFactory factory = null; private static EntityManager entityManager = null; diff --git a/libraries-data/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java index 61c98d0126..fd1e9c29a9 100644 --- a/libraries-data/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java +++ b/libraries-data/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java @@ -15,12 +15,13 @@ import static org.junit.Assert.assertEquals; public class EntryProcessorIntegrationTest { private static final String CACHE_NAME = "MyCache"; + private static final String CACHE_PROVIDER_NAME = "com.hazelcast.cache.HazelcastCachingProvider"; private Cache cache; @Before public void instantiateCache() { - CachingProvider cachingProvider = Caching.getCachingProvider(); + CachingProvider cachingProvider = Caching.getCachingProvider(CACHE_PROVIDER_NAME); CacheManager cacheManager = cachingProvider.getCacheManager(); MutableConfiguration config = new MutableConfiguration<>(); this.cache = cacheManager.createCache(CACHE_NAME, config); @@ -29,7 +30,7 @@ public class EntryProcessorIntegrationTest { @After public void tearDown() { - Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME); + Caching.getCachingProvider(CACHE_PROVIDER_NAME).getCacheManager().destroyCache(CACHE_NAME); } @Test diff --git a/libraries-data/src/test/java/com/baeldung/jcache/EventListenerIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/jcache/EventListenerIntegrationTest.java index fcbfbe6111..512a75ec61 100644 --- a/libraries-data/src/test/java/com/baeldung/jcache/EventListenerIntegrationTest.java +++ b/libraries-data/src/test/java/com/baeldung/jcache/EventListenerIntegrationTest.java @@ -17,6 +17,7 @@ import static org.junit.Assert.assertEquals; public class EventListenerIntegrationTest { private static final String CACHE_NAME = "MyCache"; + private static final String CACHE_PROVIDER_NAME = "com.hazelcast.cache.HazelcastCachingProvider"; private Cache cache; private SimpleCacheEntryListener listener; @@ -24,7 +25,7 @@ public class EventListenerIntegrationTest { @Before public void setup() { - CachingProvider cachingProvider = Caching.getCachingProvider(); + CachingProvider cachingProvider = Caching.getCachingProvider(CACHE_PROVIDER_NAME); CacheManager cacheManager = cachingProvider.getCacheManager(); MutableConfiguration config = new MutableConfiguration(); this.cache = cacheManager.createCache("MyCache", config); @@ -33,7 +34,7 @@ public class EventListenerIntegrationTest { @After public void tearDown() { - Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME); + Caching.getCachingProvider(CACHE_PROVIDER_NAME).getCacheManager().destroyCache(CACHE_NAME); } @Test diff --git a/libraries-data/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java index fac3d32bcb..33521469fa 100644 --- a/libraries-data/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java +++ b/libraries-data/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java @@ -14,7 +14,7 @@ public class JCacheIntegrationTest { @Test public void instantiateCache() { - CachingProvider cachingProvider = Caching.getCachingProvider(); + CachingProvider cachingProvider = Caching.getCachingProvider("com.hazelcast.cache.HazelcastCachingProvider"); CacheManager cacheManager = cachingProvider.getCacheManager(); MutableConfiguration config = new MutableConfiguration<>(); Cache cache = cacheManager.createCache("simpleCache", config); diff --git a/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml b/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml index a1951f09b7..6e5d212fb8 100644 --- a/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml +++ b/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml @@ -2,6 +2,6 @@ - + \ No newline at end of file diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutIntegrationTest.java index e4404a6528..53634002a0 100644 --- a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutIntegrationTest.java +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutIntegrationTest.java @@ -12,6 +12,7 @@ import org.apache.logging.log4j.Logger; import org.junit.Before; import org.junit.Test; + import com.fasterxml.jackson.databind.ObjectMapper; public class JSONLayoutIntegrationTest extends Log4j2BaseIntegrationTest { diff --git a/patterns/design-patterns/src/main/resources/log4jstructuraldp.properties b/patterns/design-patterns/src/main/resources/log4jstructuraldp.properties new file mode 100644 index 0000000000..5bc2bfe4b9 --- /dev/null +++ b/patterns/design-patterns/src/main/resources/log4jstructuraldp.properties @@ -0,0 +1,9 @@ + +# Root logger +log4j.rootLogger=INFO, file, stdout + +# Write to console +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file diff --git a/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java index 1862d6b035..860ca0927a 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java @@ -27,7 +27,9 @@ public class RedissonConfigurationIntegrationTest { @AfterClass public static void destroy() { redisServer.stop(); - client.shutdown(); + if (client != null) { + client.shutdown(); + } } @Test diff --git a/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java index 766963e5cf..53d77c2699 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java @@ -37,7 +37,9 @@ public class RedissonIntegrationTest { @AfterClass public static void destroy() { redisServer.stop(); - client.shutdown(); + if (client != null) { + client.shutdown(); + } } @Test diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java index 477a2a1cb8..ec766ac7ac 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java @@ -18,26 +18,27 @@ public class AutomapInterfaceIntegrationTest { private ConnectionProvider connectionProvider = Connector.connectionProvider; private Database db = Database.from(connectionProvider); - private Observable create = null; + private Observable truncate = null; private Observable insert1, insert2 = null; @Before public void setup() { - create = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int primary key, name varchar(255))") + Observable create = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int primary key, name varchar(255))") .count(); + truncate = db.update("TRUNCATE TABLE EMPLOYEE") + .dependsOn(create) + .count(); insert1 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(1, 'Alan')") - .dependsOn(create) + .dependsOn(truncate) .count(); insert2 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(2, 'Sarah')") - .dependsOn(create) + .dependsOn(insert1) .count(); } @Test public void whenSelectFromTableAndAutomap_thenCorrect() { List employees = db.select("select id, name from EMPLOYEE") - .dependsOn(create) - .dependsOn(insert1) .dependsOn(insert2) .autoMap(Employee.class) .toList() @@ -57,7 +58,7 @@ public class AutomapInterfaceIntegrationTest { @After public void close() { db.update("DROP TABLE EMPLOYEE") - .dependsOn(create); + .dependsOn(truncate); connectionProvider.close(); } } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java index 5f445234d7..2fb3b3abd7 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java @@ -22,24 +22,24 @@ public class BasicQueryTypesIntegrationTest { @Test public void whenCreateTableAndInsertRecords_thenCorrect() { - create = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int primary key, name varchar(255))") + create = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE_TABLE(id int primary key, name varchar(255))") .count(); - Observable insert1 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(1, 'John')") + Observable insert1 = db.update("INSERT INTO EMPLOYEE_TABLE(id, name) VALUES(1, 'John')") .dependsOn(create) .count(); - Observable update = db.update("UPDATE EMPLOYEE SET name = 'Alan' WHERE id = 1") + Observable update = db.update("UPDATE EMPLOYEE_TABLE SET name = 'Alan' WHERE id = 1") .dependsOn(create) .count(); - Observable insert2 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(2, 'Sarah')") + Observable insert2 = db.update("INSERT INTO EMPLOYEE_TABLE(id, name) VALUES(2, 'Sarah')") .dependsOn(create) .count(); - Observable insert3 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(3, 'Mike')") + Observable insert3 = db.update("INSERT INTO EMPLOYEE_TABLE(id, name) VALUES(3, 'Mike')") .dependsOn(create) .count(); - Observable delete = db.update("DELETE FROM EMPLOYEE WHERE id = 2") + Observable delete = db.update("DELETE FROM EMPLOYEE_TABLE WHERE id = 2") .dependsOn(create) .count(); - List names = db.select("select name from EMPLOYEE where id < ?") + List names = db.select("select name from EMPLOYEE_TABLE where id < ?") .parameter(3) .dependsOn(create) .dependsOn(insert1) @@ -57,7 +57,7 @@ public class BasicQueryTypesIntegrationTest { @After public void close() { - db.update("DROP TABLE EMPLOYEE") + db.update("DROP TABLE EMPLOYEE_TABLE") .dependsOn(create); connectionProvider.close(); } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java index 189bca4adb..284ecc4078 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java @@ -27,7 +27,7 @@ public class InsertClobIntegrationTest { @Before public void setup() throws IOException { - create = db.update("CREATE TABLE IF NOT EXISTS SERVERLOG (id int primary key, document CLOB)") + create = db.update("CREATE TABLE IF NOT EXISTS SERVERLOG_TABLE (id int primary key, document CLOB)") .count(); InputStream actualInputStream = new FileInputStream("src/test/resources/actual_clob"); @@ -35,7 +35,7 @@ public class InsertClobIntegrationTest { InputStream expectedInputStream = new FileInputStream("src/test/resources/expected_clob"); this.expectedDocument = Utils.getStringFromInputStream(expectedInputStream); - this.insert = db.update("insert into SERVERLOG(id,document) values(?,?)") + this.insert = db.update("insert into SERVERLOG_TABLE(id,document) values(?,?)") .parameter(1) .parameter(Database.toSentinelIfNull(actualDocument)) .dependsOn(create) @@ -44,7 +44,7 @@ public class InsertClobIntegrationTest { @Test public void whenSelectCLOB_thenCorrect() throws IOException { - db.select("select document from SERVERLOG where id = 1") + db.select("select document from SERVERLOG_TABLE where id = 1") .dependsOn(create) .dependsOn(insert) .getAs(String.class) @@ -56,7 +56,7 @@ public class InsertClobIntegrationTest { @After public void close() { - db.update("DROP TABLE SERVERLOG") + db.update("DROP TABLE SERVERLOG_TABLE") .dependsOn(create); connectionProvider.close(); } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java index 2018a9427c..c9e06a347f 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java @@ -22,14 +22,14 @@ public class ReturnKeysIntegrationTest { @Before public void setup() { begin = db.beginTransaction(); - createStatement = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int auto_increment primary key, name varchar(255))") + createStatement = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE_SAMPLE(id int auto_increment primary key, name varchar(255))") .dependsOn(begin) .count(); } @Test public void whenInsertAndReturnGeneratedKey_thenCorrect() { - Integer key = db.update("INSERT INTO EMPLOYEE(name) VALUES('John')") + Integer key = db.update("INSERT INTO EMPLOYEE_SAMPLE(name) VALUES('John')") .dependsOn(createStatement) .returnGeneratedKeys() .getAs(Integer.class) @@ -41,7 +41,7 @@ public class ReturnKeysIntegrationTest { @After public void close() { - db.update("DROP TABLE EMPLOYEE") + db.update("DROP TABLE EMPLOYEE_SAMPLE") .dependsOn(createStatement); connectionProvider.close(); } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java index 4e24d7f10e..d5f09be23c 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java @@ -24,8 +24,11 @@ public class TransactionIntegrationTest { .update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int primary key, name varchar(255))") .dependsOn(begin) .count(); + Observable truncateStatement = db.update("TRUNCATE TABLE EMPLOYEE") + .dependsOn(createStatement) + .count(); Observable insertStatement = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(1, 'John')") - .dependsOn(createStatement) + .dependsOn(truncateStatement) .count(); Observable updateStatement = db.update("UPDATE EMPLOYEE SET name = 'Tom' WHERE id = 1") .dependsOn(insertStatement) diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoIntegrationTest.java b/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoIntegrationTest.java index 4a98bbcb87..1b6431f0c2 100644 --- a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoIntegrationTest.java +++ b/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoIntegrationTest.java @@ -7,6 +7,8 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.*; @RunWith(PowerMockRunner.class) @@ -23,7 +25,7 @@ public class PowerMockitoIntegrationTest { when(collaborator.helloMethod()).thenReturn("Hello Baeldung!"); String welcome = collaborator.helloMethod(); - Mockito.verify(collaborator).helloMethod(); + verify(collaborator).helloMethod(); assertEquals("Hello Baeldung!", welcome); } @@ -42,7 +44,7 @@ public class PowerMockitoIntegrationTest { assertEquals("Hello Baeldung!", firstWelcome); assertEquals("Hello Baeldung!", secondWelcome); - verifyStatic(Mockito.times(2)); + verifyStatic(times(2)); CollaboratorWithStaticMethods.firstMethod(Mockito.anyString()); verifyStatic(Mockito.never()); @@ -67,7 +69,7 @@ public class PowerMockitoIntegrationTest { when(mock.finalMethod()).thenReturn("I am a final mock method."); returnValue = mock.finalMethod(); - Mockito.verify(mock).finalMethod(); + verify(mock,times(3)).finalMethod(); assertEquals("I am a final mock method.", returnValue); when(mock, "privateMethod").thenReturn("I am a private mock method."); diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java index f846907fd7..6ec3b34db5 100644 --- a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java @@ -24,7 +24,7 @@ public class MockitoMockIntegrationTest { } @Rule - private ExpectedException thrown = ExpectedException.none(); + public ExpectedException thrown = ExpectedException.none(); @Test public void whenUsingSimpleMock_thenCorrect() { diff --git a/testing-modules/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/JUnitManagedIntegrationTest.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/JUnitManagedIntegrationTest.java index aa0c6696a4..834d266cc6 100644 --- a/testing-modules/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/JUnitManagedIntegrationTest.java +++ b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/JUnitManagedIntegrationTest.java @@ -1,19 +1,5 @@ package com.baeldung.rest.wiremock.introduction; -import com.github.tomakehurst.wiremock.junit.WireMockRule; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.junit.Rule; -import org.junit.Test; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Scanner; - import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.containing; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; @@ -29,16 +15,46 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.junit.Assert.assertEquals; +import java.io.IOException; +import java.io.InputStream; +import java.net.ServerSocket; +import java.util.Scanner; + +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.junit.Rule; +import org.junit.Test; +import com.github.tomakehurst.wiremock.junit.WireMockRule; + public class JUnitManagedIntegrationTest { private static final String BAELDUNG_WIREMOCK_PATH = "/baeldung/wiremock"; private static final String APPLICATION_JSON = "application/json"; - + static int port; + + static { + + try { + // Get a free port + ServerSocket s = new ServerSocket(0); + port = s.getLocalPort(); + s.close(); + + } catch (IOException e) { + // No OPS + } + } + @Rule - public WireMockRule wireMockRule = new WireMockRule(); + public WireMockRule wireMockRule = new WireMockRule(port); @Test public void givenJUnitManagedServer_whenMatchingURL_thenCorrect() throws IOException { + stubFor(get(urlPathMatching("/baeldung/.*")) .willReturn(aResponse() .withStatus(200) @@ -46,7 +62,7 @@ public class JUnitManagedIntegrationTest { .withBody("\"testing-library\": \"WireMock\""))); CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpGet request = new HttpGet("http://localhost:8080/baeldung/wiremock"); + HttpGet request = new HttpGet(String.format("http://localhost:%s/baeldung/wiremock", port)); HttpResponse httpResponse = httpClient.execute(request); String stringResponse = convertHttpResponseToString(httpResponse); @@ -66,7 +82,7 @@ public class JUnitManagedIntegrationTest { .withBody("!!! Service Unavailable !!!"))); CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpGet request = new HttpGet("http://localhost:8080/baeldung/wiremock"); + HttpGet request = new HttpGet(String.format("http://localhost:%s/baeldung/wiremock", port)); request.addHeader("Accept", "text/html"); HttpResponse httpResponse = httpClient.execute(request); String stringResponse = convertHttpResponseToString(httpResponse); @@ -91,7 +107,7 @@ public class JUnitManagedIntegrationTest { StringEntity entity = new StringEntity(jsonString); CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpPost request = new HttpPost("http://localhost:8080/baeldung/wiremock"); + HttpPost request = new HttpPost(String.format("http://localhost:%s/baeldung/wiremock", port)); request.addHeader("Content-Type", APPLICATION_JSON); request.setEntity(entity); HttpResponse response = httpClient.execute(request); @@ -137,7 +153,7 @@ public class JUnitManagedIntegrationTest { private HttpResponse generateClientAndReceiveResponseForPriorityTests() throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpGet request = new HttpGet("http://localhost:8080/baeldung/wiremock"); + HttpGet request = new HttpGet(String.format("http://localhost:%s/baeldung/wiremock", port)); request.addHeader("Accept", "text/xml"); return httpClient.execute(request); } From b5dc7fa1af4d514f5308f1eadfe3ad2d44fafbcd Mon Sep 17 00:00:00 2001 From: smokeyrobot Date: Mon, 11 Jun 2018 10:10:38 -0400 Subject: [PATCH 02/11] Bael 1765 (#4342) Guide to java.util.Arrays Issue: BAEL-1765 --- .../com/baeldung/arrays/ArraysUnitTest.java | 153 ++++++++++++++++++ 1 file changed, 153 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/arrays/ArraysUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/arrays/ArraysUnitTest.java b/core-java/src/test/java/com/baeldung/arrays/ArraysUnitTest.java new file mode 100644 index 0000000000..9e6d3d6131 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/arrays/ArraysUnitTest.java @@ -0,0 +1,153 @@ +package com.baeldung.arrays; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Stream; + +public class ArraysUnitTest { + private String[] intro; + + @Rule + public final ExpectedException exception = ExpectedException.none(); + + @Before + public void setup() { + intro = new String[] { "once", "upon", "a", "time" }; + } + + @Test + public void whenCopyOfRange_thenAbridgedArray() { + String[] abridgement = Arrays.copyOfRange(intro, 0, 3); + + assertArrayEquals(new String[] { "once", "upon", "a" }, abridgement); + assertFalse(Arrays.equals(intro, abridgement)); + } + + @Test + public void whenCopyOf_thenNullElement() { + String[] revised = Arrays.copyOf(intro, 3); + String[] expanded = Arrays.copyOf(intro, 5); + + assertArrayEquals(Arrays.copyOfRange(intro, 0, 3), revised); + assertNull(expanded[4]); + } + + @Test + public void whenFill_thenAllMatch() { + String[] stutter = new String[3]; + Arrays.fill(stutter, "once"); + + assertTrue(Stream.of(stutter).allMatch(el -> "once".equals(el))); + } + + @Test + public void whenEqualsContent_thenMatch() { + assertTrue(Arrays.equals(new String[] { "once", "upon", "a", "time" }, intro)); + assertFalse(Arrays.equals(new String[] { "once", "upon", "a", null }, intro)); + } + + @Test + public void whenNestedArrays_thenDeepEqualsPass() { + String[] end = { "the", "end" }; + Object[] story = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end }; + Object[] copy = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end }; + + assertTrue(Arrays.deepEquals(story, copy)); + assertFalse(Arrays.equals(story, copy)); + } + + @Test + public void whenSort_thenArraySorted() { + String[] sorted = Arrays.copyOf(intro, 4); + Arrays.sort(sorted); + + assertArrayEquals(new String[] { "a", "once", "time", "upon" }, sorted); + } + + @Test + public void whenBinarySearch_thenFindElements() { + String[] sorted = Arrays.copyOf(intro, 4); + Arrays.sort(sorted); + int exact = Arrays.binarySearch(sorted, "time"); + int caseInsensitive = Arrays.binarySearch(sorted, "TiMe", String::compareToIgnoreCase); + + assertEquals("time", sorted[exact]); + assertEquals(2, exact); + assertEquals(exact, caseInsensitive); + } + + @Test + public void whenNullElement_thenArraysHashCodeNotEqual() { + int beforeChange = Arrays.hashCode(intro); + int before = intro.hashCode(); + intro[3] = null; + int after = intro.hashCode(); + int afterChange = Arrays.hashCode(intro); + + assertNotEquals(beforeChange, afterChange); + assertEquals(before, after); + } + + @Test + public void whenNestedArrayNullElement_thenEqualsFailDeepHashPass() { + Object[] looping = new Object[] { intro, intro }; + int deepHashBefore = Arrays.deepHashCode(looping); + int hashBefore = Arrays.hashCode(looping); + + intro[3] = null; + + int hashAfter = Arrays.hashCode(looping); + int deepHashAfter = Arrays.deepHashCode(looping); + + assertEquals(hashAfter, hashBefore); + assertNotEquals(deepHashAfter, deepHashBefore); + } + + @Test + public void whenStreamBadIndex_thenException() { + assertEquals(Arrays.stream(intro).count(), 4); + + exception.expect(ArrayIndexOutOfBoundsException.class); + Arrays.stream(intro, 2, 1).count(); + } + + @Test + public void whenSetAllToUpper_thenAppliedToAllElements() { + String[] longAgo = new String[4]; + Arrays.setAll(longAgo, i -> intro[i].toUpperCase()); + + assertArrayEquals(longAgo, new String[] { "ONCE", "UPON", "A", "TIME" }); + } + + @Test + public void whenToString_thenFormattedArrayString() { + assertEquals("[once, upon, a, time]", Arrays.toString(intro)); + } + + @Test + public void whenNestedArrayDeepString_thenFormattedArraysString() { + String[] end = { "the", "end" }; + Object[] story = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end }; + + assertEquals("[[once, upon, a, time], [chapter one, chapter two], [the, end]]", Arrays.deepToString(story)); + } + + @Test + public void whenAsList_thenImmutableArray() { + List rets = Arrays.asList(intro); + + assertTrue(rets.contains("upon")); + assertTrue(rets.contains("time")); + assertEquals(rets.size(), 4); + + exception.expect(UnsupportedOperationException.class); + rets.add("the"); + } +} From b62c35bd7a1f2c6c5b926d41c5d149982b4501fb Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Mon, 11 Jun 2018 22:50:27 +0800 Subject: [PATCH 03/11] Delete README.MD (#4461) duplicate file vs README.md --- spring-boot-ops/README.MD | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 spring-boot-ops/README.MD diff --git a/spring-boot-ops/README.MD b/spring-boot-ops/README.MD deleted file mode 100644 index 26caccb727..0000000000 --- a/spring-boot-ops/README.MD +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Deploy a Spring Boot WAR into a Tomcat Server](http://www.baeldung.com/spring-boot-war-tomcat-deploy) From 2a07b03b699a20547d183529678202e703b81453 Mon Sep 17 00:00:00 2001 From: Marcos Lopez Gonzalez Date: Tue, 12 Jun 2018 03:12:07 +0200 Subject: [PATCH 04/11] BAEL-1773 Find the middle element of a Linked List (#4463) * BAEL-1773 - find middle element of linked list * changes from review * changes from review * find middle element in linked list * typo * changes from CR * BAEL-1773 formatting --- .../com/baeldung/linkedlist/LinkedList.java | 58 -------------- .../linkedlist/MiddleElementLookup.java | 25 +++--- .../MiddleElementLookupUnitTest.java | 76 +++++++++++++++---- 3 files changed, 76 insertions(+), 83 deletions(-) delete mode 100644 core-java/src/main/java/com/baeldung/linkedlist/LinkedList.java diff --git a/core-java/src/main/java/com/baeldung/linkedlist/LinkedList.java b/core-java/src/main/java/com/baeldung/linkedlist/LinkedList.java deleted file mode 100644 index 12c73f2489..0000000000 --- a/core-java/src/main/java/com/baeldung/linkedlist/LinkedList.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.linkedlist; - -/** - * Implementation of a singly linked list. - */ -public class LinkedList { - private Node head; - private Node tail; - - public Node head() { - return head; - } - - public void add(String data) { - Node newNode = new Node(data); - - if (head == null) { - head = newNode; - tail = newNode; - } else { - tail.next = newNode; - tail = newNode; - } - } - - public static class Node { - private Node next; - private String data; - - public Node(String data) { - this.data = data; - } - - public String data() { - return data; - } - - public void setData(String data) { - this.data = data; - } - - public boolean hasNext() { - return next != null; - } - - public Node next() { - return next; - } - - public void setNext(Node next) { - this.next = next; - } - - public String toString() { - return this.data; - } - } -} diff --git a/core-java/src/main/java/com/baeldung/linkedlist/MiddleElementLookup.java b/core-java/src/main/java/com/baeldung/linkedlist/MiddleElementLookup.java index 2caf17fd0c..4cfa0d411b 100644 --- a/core-java/src/main/java/com/baeldung/linkedlist/MiddleElementLookup.java +++ b/core-java/src/main/java/com/baeldung/linkedlist/MiddleElementLookup.java @@ -1,22 +1,23 @@ package com.baeldung.linkedlist; import java.util.LinkedList; +import java.util.Optional; import com.baeldung.linkedlist.Node; public class MiddleElementLookup { - public static String findMiddleElementLinkedList(LinkedList linkedList) { + public static Optional findMiddleElementLinkedList(LinkedList linkedList) { if (linkedList == null || linkedList.isEmpty()) { - return null; + return Optional.empty(); } - return linkedList.get((linkedList.size() - 1) / 2); + return Optional.ofNullable(linkedList.get((linkedList.size() - 1) / 2)); } - public static String findMiddleElementFromHead(Node head) { + public static Optional findMiddleElementFromHead(Node head) { if (head == null) { - return null; + return Optional.empty(); } // calculate the size of the list @@ -33,17 +34,17 @@ public class MiddleElementLookup { current = current.next(); } - return current.data(); + return Optional.ofNullable(current.data()); } - public static String findMiddleElementFromHead1PassRecursively(Node head) { + public static Optional findMiddleElementFromHead1PassRecursively(Node head) { if (head == null) { - return null; + return Optional.empty(); } MiddleAuxRecursion middleAux = new MiddleAuxRecursion(); findMiddleRecursively(head, middleAux); - return middleAux.middle.data(); + return Optional.ofNullable(middleAux.middle.data()); } private static void findMiddleRecursively(Node node, MiddleAuxRecursion middleAux) { @@ -63,9 +64,9 @@ public class MiddleElementLookup { middleAux.length--; } - public static String findMiddleElementFromHead1PassIteratively(Node head) { + public static Optional findMiddleElementFromHead1PassIteratively(Node head) { if (head == null) { - return null; + return Optional.empty(); } Node slowPointer = head; @@ -78,7 +79,7 @@ public class MiddleElementLookup { slowPointer = slowPointer.next(); } - return slowPointer.data(); + return Optional.ofNullable(slowPointer.data()); } private static class MiddleAuxRecursion { diff --git a/core-java/src/test/java/com/baeldung/linkedlist/MiddleElementLookupUnitTest.java b/core-java/src/test/java/com/baeldung/linkedlist/MiddleElementLookupUnitTest.java index 08a4e52ff9..2801bbfc9e 100644 --- a/core-java/src/test/java/com/baeldung/linkedlist/MiddleElementLookupUnitTest.java +++ b/core-java/src/test/java/com/baeldung/linkedlist/MiddleElementLookupUnitTest.java @@ -1,6 +1,7 @@ package com.baeldung.linkedlist; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import java.util.LinkedList; @@ -10,34 +11,83 @@ public class MiddleElementLookupUnitTest { @Test public void whenFindingMiddleLinkedList_thenMiddleFound() { - assertEquals("3", MiddleElementLookup.findMiddleElementLinkedList(createLinkedList(5))); - assertEquals("2", MiddleElementLookup.findMiddleElementLinkedList(createLinkedList(4))); + assertEquals("3", MiddleElementLookup + .findMiddleElementLinkedList(createLinkedList(5)) + .get()); + assertEquals("2", MiddleElementLookup + .findMiddleElementLinkedList(createLinkedList(4)) + .get()); } @Test public void whenFindingMiddleFromHead_thenMiddleFound() { - assertEquals("3", MiddleElementLookup.findMiddleElementFromHead(createNodesList(5))); - assertEquals("2", MiddleElementLookup.findMiddleElementFromHead(createNodesList(4))); + assertEquals("3", MiddleElementLookup + .findMiddleElementFromHead(createNodesList(5)) + .get()); + assertEquals("2", MiddleElementLookup + .findMiddleElementFromHead(createNodesList(4)) + .get()); } @Test public void whenFindingMiddleFromHead1PassRecursively_thenMiddleFound() { - assertEquals("3", MiddleElementLookup.findMiddleElementFromHead1PassRecursively(createNodesList(5))); - assertEquals("2", MiddleElementLookup.findMiddleElementFromHead1PassRecursively(createNodesList(4))); + assertEquals("3", MiddleElementLookup + .findMiddleElementFromHead1PassRecursively(createNodesList(5)) + .get()); + assertEquals("2", MiddleElementLookup + .findMiddleElementFromHead1PassRecursively(createNodesList(4)) + .get()); } @Test public void whenFindingMiddleFromHead1PassIteratively_thenMiddleFound() { - assertEquals("3", MiddleElementLookup.findMiddleElementFromHead1PassIteratively(createNodesList(5))); - assertEquals("2", MiddleElementLookup.findMiddleElementFromHead1PassIteratively(createNodesList(4))); + assertEquals("3", MiddleElementLookup + .findMiddleElementFromHead1PassIteratively(createNodesList(5)) + .get()); + assertEquals("2", MiddleElementLookup + .findMiddleElementFromHead1PassIteratively(createNodesList(4)) + .get()); } @Test - public void whenListEmptyOrNull_thenMiddleNull() { - assertEquals(null, MiddleElementLookup.findMiddleElementLinkedList(null)); - assertEquals(null, MiddleElementLookup.findMiddleElementFromHead(null)); - assertEquals(null, MiddleElementLookup.findMiddleElementFromHead1PassIteratively(null)); - assertEquals(null, MiddleElementLookup.findMiddleElementFromHead1PassRecursively(null)); + public void whenListEmptyOrNull_thenMiddleNotFound() { + // null list + assertFalse(MiddleElementLookup + .findMiddleElementLinkedList(null) + .isPresent()); + assertFalse(MiddleElementLookup + .findMiddleElementFromHead(null) + .isPresent()); + assertFalse(MiddleElementLookup + .findMiddleElementFromHead1PassIteratively(null) + .isPresent()); + assertFalse(MiddleElementLookup + .findMiddleElementFromHead1PassRecursively(null) + .isPresent()); + + // empty LinkedList + assertFalse(MiddleElementLookup + .findMiddleElementLinkedList(new LinkedList<>()) + .isPresent()); + + // LinkedList with nulls + LinkedList nullsList = new LinkedList<>(); + nullsList.add(null); + nullsList.add(null); + assertFalse(MiddleElementLookup + .findMiddleElementLinkedList(nullsList) + .isPresent()); + + // nodes with null values + assertFalse(MiddleElementLookup + .findMiddleElementFromHead(new Node(null)) + .isPresent()); + assertFalse(MiddleElementLookup + .findMiddleElementFromHead1PassIteratively(new Node(null)) + .isPresent()); + assertFalse(MiddleElementLookup + .findMiddleElementFromHead1PassRecursively(new Node(null)) + .isPresent()); } private static LinkedList createLinkedList(int n) { From b59da11c6661d79f0ad76ebed6bf1be3f7f55f2c Mon Sep 17 00:00:00 2001 From: psevestre Date: Wed, 13 Jun 2018 02:12:05 -0300 Subject: [PATCH 05/11] Code for BAEL-1474 (#4472) * Code for BAEL-1474 * Renamed test to conform to PMD rules --- pom.xml | 1 + ...java => FileProcessorIntegrationTest.java} | 2 +- spring-webflux-amqp/.gitignore | 25 ++ spring-webflux-amqp/pom.xml | 92 ++++++ .../src/docker/docker-compose.yml | 23 ++ .../spring/amqp/DestinationsConfig.java | 59 ++++ .../amqp/SpringWebfluxAmqpApplication.java | 270 ++++++++++++++++++ .../src/main/resources/application.yml | 27 ++ .../amqp/SpringWebfluxAmqpLiveTest.java | 26 ++ 9 files changed, 524 insertions(+), 1 deletion(-) rename spring-core/src/test/java/com/baeldung/dependson/processor/{FileProcessorTest.java => FileProcessorIntegrationTest.java} (96%) create mode 100755 spring-webflux-amqp/.gitignore create mode 100755 spring-webflux-amqp/pom.xml create mode 100755 spring-webflux-amqp/src/docker/docker-compose.yml create mode 100755 spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/DestinationsConfig.java create mode 100755 spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/SpringWebfluxAmqpApplication.java create mode 100755 spring-webflux-amqp/src/main/resources/application.yml create mode 100755 spring-webflux-amqp/src/test/java/org/baeldung/spring/amqp/SpringWebfluxAmqpLiveTest.java diff --git a/pom.xml b/pom.xml index d42c3ac617..38f88a2784 100644 --- a/pom.xml +++ b/pom.xml @@ -263,6 +263,7 @@ performance-tests twilio java-ee-8-security-api + spring-webflux-amqp diff --git a/spring-core/src/test/java/com/baeldung/dependson/processor/FileProcessorTest.java b/spring-core/src/test/java/com/baeldung/dependson/processor/FileProcessorIntegrationTest.java similarity index 96% rename from spring-core/src/test/java/com/baeldung/dependson/processor/FileProcessorTest.java rename to spring-core/src/test/java/com/baeldung/dependson/processor/FileProcessorIntegrationTest.java index b54ac16125..11d9daf3bf 100644 --- a/spring-core/src/test/java/com/baeldung/dependson/processor/FileProcessorTest.java +++ b/spring-core/src/test/java/com/baeldung/dependson/processor/FileProcessorIntegrationTest.java @@ -16,7 +16,7 @@ import com.baeldung.dependson.shared.File; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = TestConfig.class) -public class FileProcessorTest { +public class FileProcessorIntegrationTest { @Autowired ApplicationContext context; diff --git a/spring-webflux-amqp/.gitignore b/spring-webflux-amqp/.gitignore new file mode 100755 index 0000000000..82eca336e3 --- /dev/null +++ b/spring-webflux-amqp/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/spring-webflux-amqp/pom.xml b/spring-webflux-amqp/pom.xml new file mode 100755 index 0000000000..75fafd7b10 --- /dev/null +++ b/spring-webflux-amqp/pom.xml @@ -0,0 +1,92 @@ + + + 4.0.0 + + org.baeldung.spring + spring-webflux-amqp + 1.0.0-SNAPSHOT + jar + + spring-webflux-amqp + Spring WebFlux AMQP Sample + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-amqp + + + org.springframework.boot + spring-boot-starter-webflux + + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + org.springframework.boot + spring-boot-starter-test + test + + + + io.projectreactor + reactor-test + test + + + + org.springframework.boot + spring-boot-starter-integration + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/libs-snapshot + + true + + + + + + + spring-releases + Spring Releases + https://repo.spring.io/libs-release + + + + + diff --git a/spring-webflux-amqp/src/docker/docker-compose.yml b/spring-webflux-amqp/src/docker/docker-compose.yml new file mode 100755 index 0000000000..03292aeb63 --- /dev/null +++ b/spring-webflux-amqp/src/docker/docker-compose.yml @@ -0,0 +1,23 @@ +## +## Create a simple RabbitMQ environment with multiple clients +## +version: "3" + +services: + +## +## RabitMQ server +## + rabbitmq: + image: rabbitmq:3 + hostname: rabbit + environment: + RABBITMQ_ERLANG_COOKIE: test + ports: + - "5672:5672" + volumes: + - rabbitmq-data:/var/lib/rabbitmq + +volumes: + rabbitmq-data: + diff --git a/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/DestinationsConfig.java b/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/DestinationsConfig.java new file mode 100755 index 0000000000..410b87c764 --- /dev/null +++ b/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/DestinationsConfig.java @@ -0,0 +1,59 @@ +package org.baeldung.spring.amqp; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties("destinations") +public class DestinationsConfig { + + + private Map queues = new HashMap<>(); + + private Map topics = new HashMap<>(); + + + + public Map getQueues() { + return queues; + } + + public void setQueues(Map queues) { + this.queues = queues; + } + + public Map getTopics() { + return topics; + } + + public void setTopics(Map topics) { + this.topics = topics; + } + + // DestinationInfo stores the Exchange name and routing key used + // by our producers when posting messages + static class DestinationInfo { + + private String exchange; + private String routingKey; + + + public String getExchange() { + return exchange; + } + public void setExchange(String exchange) { + this.exchange = exchange; + } + public String getRoutingKey() { + return routingKey; + } + public void setRoutingKey(String routingKey) { + this.routingKey = routingKey; + } + + + + } + +} diff --git a/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/SpringWebfluxAmqpApplication.java b/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/SpringWebfluxAmqpApplication.java new file mode 100755 index 0000000000..eb3b858ddc --- /dev/null +++ b/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/SpringWebfluxAmqpApplication.java @@ -0,0 +1,270 @@ +package org.baeldung.spring.amqp; + +import java.util.stream.Stream; + +import org.baeldung.spring.amqp.DestinationsConfig.DestinationInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.amqp.AmqpException; +import org.springframework.amqp.core.AmqpAdmin; +import org.springframework.amqp.core.AmqpTemplate; +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.BindingBuilder; +import org.springframework.amqp.core.Exchange; +import org.springframework.amqp.core.ExchangeBuilder; +import org.springframework.amqp.core.Queue; +import org.springframework.amqp.core.QueueBuilder; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; + +@SpringBootApplication +@EnableConfigurationProperties(DestinationsConfig.class) +@RestController +public class SpringWebfluxAmqpApplication { + + private static Logger log = LoggerFactory.getLogger(SpringWebfluxAmqpApplication.class); + + @Autowired + private AmqpTemplate amqpTemplate; + + @Autowired + private AmqpAdmin amqpAdmin; + + @Autowired + private DestinationsConfig destinationsConfig; + + + public static void main(String[] args) { + SpringApplication.run(SpringWebfluxAmqpApplication.class, args); + } + + @Bean + public CommandLineRunner setupQueueDestinations(AmqpAdmin amqpAdmin,DestinationsConfig destinationsConfig) { + + return (args) -> { + + log.info("[I48] Creating Destinations..."); + + destinationsConfig.getQueues() + .forEach((key, destination) -> { + + log.info("[I54] Creating directExchange: key={}, name={}, routingKey={}", key, destination.getExchange(), destination.getRoutingKey()); + + Exchange ex = ExchangeBuilder + .directExchange(destination.getExchange()) + .durable(true) + .build(); + + amqpAdmin.declareExchange(ex); + + Queue q = QueueBuilder + .durable(destination.getRoutingKey()) + .build(); + + amqpAdmin.declareQueue(q); + + Binding b = BindingBuilder.bind(q) + .to(ex) + .with(destination.getRoutingKey()) + .noargs(); + amqpAdmin.declareBinding(b); + + log.info("[I70] Binding successfully created."); + + }); + + }; + + } + + @Bean + public CommandLineRunner setupTopicDestinations(AmqpAdmin amqpAdmin, DestinationsConfig destinationsConfig) { + + return (args) -> { + + // For topic each consumer will have its own Queue, so no binding + destinationsConfig.getTopics() + .forEach((key, destination) -> { + + log.info("[I98] Creating TopicExchange: name={}, exchange={}", key, destination.getExchange()); + + Exchange ex = ExchangeBuilder.topicExchange(destination.getExchange()) + .durable(true) + .build(); + + amqpAdmin.declareExchange(ex); + + log.info("[I107] Topic Exchange successfully created."); + + }); + }; + } + + @PostMapping(value = "/queue/{name}") + public Mono> sendMessageToQueue(@PathVariable String name, @RequestBody String payload) { + + // Lookup exchange details + final DestinationInfo d = destinationsConfig.getQueues() + .get(name); + if (d == null) { + // Destination not found. + return Mono.just(ResponseEntity.notFound().build()); + } + + return Mono.fromCallable(() -> { + + log.info("[I51] sendMessageToQueue: queue={}, routingKey={}", d.getExchange(), d.getRoutingKey()); + amqpTemplate.convertAndSend(d.getExchange(), d.getRoutingKey(), payload); + + return ResponseEntity.accepted().build(); + + }); + + } + + + /** + * Receive messages for the given queue + * @param name + * @return + */ + @GetMapping(value = "/queue/{name}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public Flux receiveMessagesFromQueue(@PathVariable String name) { + + final DestinationInfo d = destinationsConfig.getQueues().get(name); + + if (d == null) { + return Flux.just(ResponseEntity.notFound().build()); + } + + Stream s = Stream.generate(() -> { + String queueName = d.getRoutingKey(); + + log.info("[I137] Polling {}", queueName); + + Object payload = amqpTemplate.receiveAndConvert(queueName,5000); + if ( payload == null ) { + payload = "No news is good news..."; + } + + return payload.toString(); + }); + + + return Flux + .fromStream(s) + .subscribeOn(Schedulers.elastic()); + + } + + /** + * send message to a given topic + * @param name + * @param payload + * @return + */ + @PostMapping(value = "/topic/{name}") + public Mono> sendMessageToTopic(@PathVariable String name, @RequestBody String payload) { + + // Lookup exchange details + final DestinationInfo d = destinationsConfig.getTopics().get(name); + if (d == null) { + // Destination not found. + return Mono.just(ResponseEntity.notFound().build()); + } + + return Mono.fromCallable(() -> { + + log.info("[I51] sendMessageToTopic: topic={}, routingKey={}", d.getExchange(), d.getRoutingKey()); + amqpTemplate.convertAndSend(d.getExchange(), d.getRoutingKey(), payload); + + return ResponseEntity.accepted().build(); + + }); + } + + + @GetMapping(value = "/topic/{name}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public Flux receiveMessagesFromTopic(@PathVariable String name) { + + DestinationInfo d = destinationsConfig.getTopics().get(name); + + if (d == null) { + return Flux.just(ResponseEntity.notFound().build()); + } + + final Queue topicQueue = createTopicQueue(d); + + Stream s = Stream.generate(() -> { + String queueName = topicQueue.getName(); + + log.info("[I137] Polling {}", queueName); + + try { + Object payload = amqpTemplate.receiveAndConvert(queueName,5000); + if ( payload == null ) { + payload = "No news is good news..."; + } + + return payload.toString(); + } + catch(AmqpException ex) { + log.warn("[W247] Received an AMQP Exception: {}", ex.getMessage()); + return null; + } + }); + + + return Flux.fromStream(s) + .doOnCancel(() -> { + log.info("[I250] doOnCancel()"); + amqpAdmin.deleteQueue(topicQueue.getName()); + }) + .subscribeOn(Schedulers.elastic()); + + + } + + + private Queue createTopicQueue(DestinationInfo destination) { + + Exchange ex = ExchangeBuilder.topicExchange(destination.getExchange()) + .durable(true) + .build(); + + amqpAdmin.declareExchange(ex); + + // Create a durable queue + Queue q = QueueBuilder + .durable() + .build(); + + amqpAdmin.declareQueue(q); + + Binding b = BindingBuilder.bind(q) + .to(ex) + .with(destination.getRoutingKey()) + .noargs(); + + amqpAdmin.declareBinding(b); + + return q; + } + + +} diff --git a/spring-webflux-amqp/src/main/resources/application.yml b/spring-webflux-amqp/src/main/resources/application.yml new file mode 100755 index 0000000000..3f527ce4c5 --- /dev/null +++ b/spring-webflux-amqp/src/main/resources/application.yml @@ -0,0 +1,27 @@ +spring: + rabbitmq: + host: 192.168.99.100 + port: 5672 + username: guest + password: guest + +destinations: + queues: + NYSE: + exchange: nyse + routing-key: NYSE + IBOV: + exchange: ibov + routing-key: IBOV + + + topics: + weather: + exchange: alerts + routing-key: WEATHER + + + + + + diff --git a/spring-webflux-amqp/src/test/java/org/baeldung/spring/amqp/SpringWebfluxAmqpLiveTest.java b/spring-webflux-amqp/src/test/java/org/baeldung/spring/amqp/SpringWebfluxAmqpLiveTest.java new file mode 100755 index 0000000000..bda490c189 --- /dev/null +++ b/spring-webflux-amqp/src/test/java/org/baeldung/spring/amqp/SpringWebfluxAmqpLiveTest.java @@ -0,0 +1,26 @@ +package org.baeldung.spring.amqp; + +import org.junit.Test; +import org.springframework.test.web.reactive.server.WebTestClient; + + +public class SpringWebfluxAmqpLiveTest { + + @Test + public void whenSendingAMessageToQueue_thenAcceptedReturnCode() { + + WebTestClient client = WebTestClient.bindToServer() + .baseUrl("http://localhost:8080") + .build(); + + client.post() + .uri("/queue/NYSE") + .syncBody("Test Message") + .exchange() + .expectStatus().isAccepted(); + + } + + + +} From 272f018f90673a5d7e86a7742aadb8a58d4cd33e Mon Sep 17 00:00:00 2001 From: Eric Goebelbecker Date: Wed, 13 Jun 2018 11:15:57 -0400 Subject: [PATCH 06/11] BAEL-1614 - Docker with Java Guest Post (#4474) * BAEL-1614 - additions for docker * BAEL-1614 - move docker project to guest module --- .../WebContent/META-INF/MANIFEST.MF | 1 - guest/spring-boot-app/docker/Dockerfile | 16 ++++++++++++++++ guest/spring-boot-app/docker/logback.xml | 15 +++++++++++++++ guest/spring-boot-app/docker/run.sh | 4 ++++ guest/spring-boot-app/pom.xml | 18 +++++++++++++++++- spring-boot-ops/pom.xml | 1 - 6 files changed, 52 insertions(+), 3 deletions(-) create mode 100644 guest/spring-boot-app/docker/Dockerfile create mode 100644 guest/spring-boot-app/docker/logback.xml create mode 100755 guest/spring-boot-app/docker/run.sh diff --git a/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF b/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF index 254272e1c0..e3c07ab38a 100644 --- a/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF +++ b/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF @@ -1,3 +1,2 @@ Manifest-Version: 1.0 Class-Path: - diff --git a/guest/spring-boot-app/docker/Dockerfile b/guest/spring-boot-app/docker/Dockerfile new file mode 100644 index 0000000000..211e8927a3 --- /dev/null +++ b/guest/spring-boot-app/docker/Dockerfile @@ -0,0 +1,16 @@ +# Alpine Linux with OpenJDK JRE +FROM openjdk:8-jre-alpine +RUN apk add --no-cache bash + +# copy fat WAR +COPY spring-boot-app-0.0.1-SNAPSHOT.war /app.war + +# copy fat WAR +COPY logback.xml /logback.xml + +COPY run.sh /run.sh + +# runs application +#CMD ["/usr/bin/java", "-jar", "-Dspring.profiles.active=default", "-Dlogging.config=/logback.xml", "/app.war"] + +ENTRYPOINT ["/run.sh"] diff --git a/guest/spring-boot-app/docker/logback.xml b/guest/spring-boot-app/docker/logback.xml new file mode 100644 index 0000000000..7e03ddc827 --- /dev/null +++ b/guest/spring-boot-app/docker/logback.xml @@ -0,0 +1,15 @@ + + + + + /var/log/Application/application.log + true + + %-7d{yyyy-MM-dd HH:mm:ss:SSS} %m%n + + + + + + + diff --git a/guest/spring-boot-app/docker/run.sh b/guest/spring-boot-app/docker/run.sh new file mode 100755 index 0000000000..aeecc29371 --- /dev/null +++ b/guest/spring-boot-app/docker/run.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +java -Dspring.profiles.active=$1 -Dlogging.config=/logback.xml -jar /app.war + diff --git a/guest/spring-boot-app/pom.xml b/guest/spring-boot-app/pom.xml index ba57bbd5c5..c02eef7ef3 100644 --- a/guest/spring-boot-app/pom.xml +++ b/guest/spring-boot-app/pom.xml @@ -51,6 +51,22 @@ WebContent + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + com.stackify.Application + ${project.basedir}/docker + + + + + @@ -58,4 +74,4 @@ 8.0.43 - \ No newline at end of file + diff --git a/spring-boot-ops/pom.xml b/spring-boot-ops/pom.xml index b34fef8e6f..dce826dbb5 100644 --- a/spring-boot-ops/pom.xml +++ b/spring-boot-ops/pom.xml @@ -138,7 +138,6 @@ com.baeldung.webjar.WebjarsdemoApplication - ${project.basedir}/docker From 2b0c6ed6550fda9ae77fd500382ef9ea905e102e Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Wed, 13 Jun 2018 17:19:03 +0200 Subject: [PATCH 07/11] Kiview ftpclient (#4456) * Add example for FTP client Using Apache Commons Net * Add missing resource * Fix wrong file download in integration test * Add example for using FTP support in JDK * Close input stream after copy * Fix test name --- libraries/pom.xml | 16 ++++ .../main/java/com/baeldung/ftp/FtpClient.java | 63 ++++++++++++++++ .../baeldung/javalin/User/UserController.java | 2 +- .../ftp/FtpClientIntegrationTest.java | 73 +++++++++++++++++++ .../ftp/JdkFtpClientIntegrationTest.java | 63 ++++++++++++++++ libraries/src/test/resources/ftp/baz.txt | 0 spring-boot-ops/README.md | 2 +- 7 files changed, 217 insertions(+), 2 deletions(-) create mode 100644 libraries/src/main/java/com/baeldung/ftp/FtpClient.java create mode 100644 libraries/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java create mode 100644 libraries/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java create mode 100644 libraries/src/test/resources/ftp/baz.txt diff --git a/libraries/pom.xml b/libraries/pom.xml index 4f90d63d93..663b9e68bb 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -709,6 +709,20 @@ xchart ${xchart-version} + + + commons-net + commons-net + ${commons-net.version} + + + org.mockftpserver + MockFtpServer + ${mockftpserver.version} + test + + + @@ -923,6 +937,8 @@ 2.5.11 3.6.1 3.5.2 + 3.6 + 2.7.1 \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/ftp/FtpClient.java b/libraries/src/main/java/com/baeldung/ftp/FtpClient.java new file mode 100644 index 0000000000..209bed35f0 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/ftp/FtpClient.java @@ -0,0 +1,63 @@ +package com.baeldung.ftp; + +import org.apache.commons.net.PrintCommandListener; +import org.apache.commons.net.ftp.FTPClient; +import org.apache.commons.net.ftp.FTPFile; +import org.apache.commons.net.ftp.FTPReply; + +import java.io.*; +import java.util.Arrays; +import java.util.Collection; +import java.util.stream.Collectors; + +class FtpClient { + + private final String server; + private final int port; + private final String user; + private final String password; + private FTPClient ftp; + + FtpClient(String server, int port, String user, String password) { + this.server = server; + this.port = port; + this.user = user; + this.password = password; + } + + void open() throws IOException { + ftp = new FTPClient(); + + ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); + + ftp.connect(server, port); + int reply = ftp.getReplyCode(); + if (!FTPReply.isPositiveCompletion(reply)) { + ftp.disconnect(); + throw new IOException("Exception in connecting to FTP Server"); + } + + ftp.login(user, password); + } + + void close() throws IOException { + ftp.disconnect(); + } + + Collection listFiles(String path) throws IOException { + FTPFile[] files = ftp.listFiles(path); + + return Arrays.stream(files) + .map(FTPFile::getName) + .collect(Collectors.toList()); + } + + void putFileToPath(File file, String path) throws IOException { + ftp.storeFile(path, new FileInputStream(file)); + } + + void downloadFile(String source, String destination) throws IOException { + FileOutputStream out = new FileOutputStream(destination); + ftp.retrieveFile(source, out); + } +} diff --git a/libraries/src/main/java/com/baeldung/javalin/User/UserController.java b/libraries/src/main/java/com/baeldung/javalin/User/UserController.java index fd713606cf..685890c6d7 100644 --- a/libraries/src/main/java/com/baeldung/javalin/User/UserController.java +++ b/libraries/src/main/java/com/baeldung/javalin/User/UserController.java @@ -14,7 +14,7 @@ public class UserController { public static Handler fetchById = ctx -> { int id = Integer.parseInt(Objects.requireNonNull(ctx.param("id"))); UserDao dao = UserDao.instance(); - User user = dao.getUserById(id); + User user = dao.getUserById(id).get(); if (user == null) { ctx.html("Not Found"); } else { diff --git a/libraries/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java b/libraries/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java new file mode 100644 index 0000000000..43da69f96d --- /dev/null +++ b/libraries/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java @@ -0,0 +1,73 @@ +package com.baeldung.ftp; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockftpserver.fake.FakeFtpServer; +import org.mockftpserver.fake.UserAccount; +import org.mockftpserver.fake.filesystem.DirectoryEntry; +import org.mockftpserver.fake.filesystem.FileEntry; +import org.mockftpserver.fake.filesystem.FileSystem; +import org.mockftpserver.fake.filesystem.UnixFakeFileSystem; + +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.Collection; + +import static org.assertj.core.api.Assertions.assertThat; + +public class FtpClientIntegrationTest { + + private FakeFtpServer fakeFtpServer; + + private FtpClient ftpClient; + + @Before + public void setup() throws IOException { + fakeFtpServer = new FakeFtpServer(); + fakeFtpServer.addUserAccount(new UserAccount("user", "password", "/data")); + + FileSystem fileSystem = new UnixFakeFileSystem(); + fileSystem.add(new DirectoryEntry("/data")); + fileSystem.add(new FileEntry("/data/foobar.txt", "abcdef 1234567890")); + fakeFtpServer.setFileSystem(fileSystem); + fakeFtpServer.setServerControlPort(0); + + fakeFtpServer.start(); + + ftpClient = new FtpClient("localhost", fakeFtpServer.getServerControlPort(), "user", "password"); + ftpClient.open(); + } + + @After + public void teardown() throws IOException { + ftpClient.close(); + fakeFtpServer.stop(); + } + + @Test + public void givenRemoteFile_whenListingRemoteFiles_thenItIsContainedInList() throws IOException { + Collection files = ftpClient.listFiles(""); + + assertThat(files).contains("foobar.txt"); + } + + @Test + public void givenRemoteFile_whenDownloading_thenItIsOnTheLocalFilesystem() throws IOException { + ftpClient.downloadFile("/foobar.txt", "downloaded_buz.txt"); + + assertThat(new File("downloaded_buz.txt")).exists(); + new File("downloaded_buz.txt").delete(); // cleanup + } + + @Test + public void givenLocalFile_whenUploadingIt_thenItExistsOnRemoteLocation() throws URISyntaxException, IOException { + File file = new File(getClass().getClassLoader().getResource("ftp/baz.txt").toURI()); + + ftpClient.putFileToPath(file, "/buz.txt"); + + assertThat(fakeFtpServer.getFileSystem().exists("/buz.txt")).isTrue(); + } + +} diff --git a/libraries/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java b/libraries/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java new file mode 100644 index 0000000000..ef6809b02d --- /dev/null +++ b/libraries/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java @@ -0,0 +1,63 @@ +package com.baeldung.ftp; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockftpserver.fake.FakeFtpServer; +import org.mockftpserver.fake.UserAccount; +import org.mockftpserver.fake.filesystem.DirectoryEntry; +import org.mockftpserver.fake.filesystem.FileEntry; +import org.mockftpserver.fake.filesystem.FileSystem; +import org.mockftpserver.fake.filesystem.UnixFakeFileSystem; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; +import java.nio.file.Files; +import java.util.Collection; + +import static org.assertj.core.api.Assertions.assertThat; + +public class JdkFtpClientIntegrationTest { + + private FakeFtpServer fakeFtpServer; + + + @Before + public void setup() throws IOException { + fakeFtpServer = new FakeFtpServer(); + fakeFtpServer.addUserAccount(new UserAccount("user", "password", "/data")); + + FileSystem fileSystem = new UnixFakeFileSystem(); + fileSystem.add(new DirectoryEntry("/data")); + fileSystem.add(new FileEntry("/data/foobar.txt", "abcdef 1234567890")); + fakeFtpServer.setFileSystem(fileSystem); + fakeFtpServer.setServerControlPort(0); + + fakeFtpServer.start(); + } + + @After + public void teardown() throws IOException { + fakeFtpServer.stop(); + } + + @Test + public void givenRemoteFile_whenDownloading_thenItIsOnTheLocalFilesystem() throws IOException { + String ftpUrl = String.format("ftp://user:password@localhost:%d/foobar.txt", fakeFtpServer.getServerControlPort()); + + URLConnection urlConnection = new URL(ftpUrl).openConnection(); + InputStream inputStream = urlConnection.getInputStream(); + Files.copy(inputStream, new File("downloaded_buz.txt").toPath()); + inputStream.close(); + + assertThat(new File("downloaded_buz.txt")).exists(); + + new File("downloaded_buz.txt").delete(); // cleanup + } + +} diff --git a/libraries/src/test/resources/ftp/baz.txt b/libraries/src/test/resources/ftp/baz.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot-ops/README.md b/spring-boot-ops/README.md index 02c4c100aa..26caccb727 100644 --- a/spring-boot-ops/README.md +++ b/spring-boot-ops/README.md @@ -1,3 +1,3 @@ -### Relevant articles +### Relevant Articles: - [Deploy a Spring Boot WAR into a Tomcat Server](http://www.baeldung.com/spring-boot-war-tomcat-deploy) From 2fe0dee64e97c1f7babf228cfaea89b8653cc1c3 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Thu, 14 Jun 2018 01:50:33 +0800 Subject: [PATCH 08/11] Update 13 README.md and create 2 README.md (#4468) * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Create README.md * Create README.md --- README.md | 1 + core-java-8/README.md | 2 +- core-java-9/README.md | 1 + core-java/README.md | 4 ++++ javax-servlets/README.md | 1 + msf4j/README.md | 2 +- patterns/design-patterns/README.md | 2 +- performance-tests/README.md | 3 +++ spring-5-reactive/README.md | 1 + spring-boot-ops/README.md | 7 +++++++ spring-core/README.md | 1 + spring-data-rest-querydsl/README.md | 2 ++ spring-mockito/README.md | 1 + spring-mvc-java/README.md | 3 +++ testing-modules/junit-5/README.md | 3 +-- 15 files changed, 29 insertions(+), 5 deletions(-) create mode 100644 performance-tests/README.md create mode 100644 spring-data-rest-querydsl/README.md diff --git a/README.md b/README.md index 62d2d5b55e..1d916c8409 100644 --- a/README.md +++ b/README.md @@ -39,3 +39,4 @@ This tutorials project is being built **[>> HERE](https://rest-security.ci.cloud - [Apache Maven Standard Directory Layout](http://www.baeldung.com/maven-directory-structure) - [Apache Maven Tutorial](http://www.baeldung.com/maven) +- [Designing a User Friendly Java Library](http://www.baeldung.com/design-a-user-friendly-java-library) diff --git a/core-java-8/README.md b/core-java-8/README.md index df6d50ad30..2eb8d49983 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -52,4 +52,4 @@ - [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time) - [Java Optional – orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get) - [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table) - +- [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection) diff --git a/core-java-9/README.md b/core-java-9/README.md index 4223e57d4b..a76dcefc69 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -25,3 +25,4 @@ - [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue) - [A Guide to Java 9 Modularity](http://www.baeldung.com/java-9-modularity) - [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional) +- [Java 9 java.lang.Module API](http://www.baeldung.com/java-9-module-api) diff --git a/core-java/README.md b/core-java/README.md index 79f7b4169e..fa2d7e4cf0 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -156,3 +156,7 @@ - [Flyweight Pattern in Java](http://www.baeldung.com/java-flyweight) - [The Observer Pattern in Java](http://www.baeldung.com/java-observer-pattern) - [Service Locator Pattern](http://www.baeldung.com/java-service-locator-pattern) +- [The Thread.join() Method in Java](http://www.baeldung.com/java-thread-join) +- [Guide to the super Java Keyword](http://www.baeldung.com/java-super) +- [Guide to the this Java Keyword](http://www.baeldung.com/java-this) +- [Jagged Arrays In Java](http://www.baeldung.com/java-jagged-arrays) diff --git a/javax-servlets/README.md b/javax-servlets/README.md index de8a8e4498..55ca1116aa 100644 --- a/javax-servlets/README.md +++ b/javax-servlets/README.md @@ -4,3 +4,4 @@ - [Handling Cookies and a Session in a Java Servlet](http://www.baeldung.com/java-servlet-cookies-session) - [Uploading Files with Servlets and JSP](http://www.baeldung.com/upload-file-servlet) - [Example of Downloading File in a Servlet](http://www.baeldung.com/servlet-download-file) +- [Returning a JSON Response from a Servlet](http://www.baeldung.com/servlet-json-response) diff --git a/msf4j/README.md b/msf4j/README.md index 19e611832c..7c66b8dc5f 100644 --- a/msf4j/README.md +++ b/msf4j/README.md @@ -1,3 +1,3 @@ ### Relevant Articles: -- [Introduction to Java Microservices with MSF4J](http://www.baeldung.com/spring-boot-war-tomcat-deploy) +- [Introduction to Java Microservices with MSF4J](http://www.baeldung.com/msf4j) diff --git a/patterns/design-patterns/README.md b/patterns/design-patterns/README.md index fb80f4bd6a..77ead0b317 100644 --- a/patterns/design-patterns/README.md +++ b/patterns/design-patterns/README.md @@ -8,4 +8,4 @@ - [Service Locator Pattern](http://www.baeldung.com/java-service-locator-pattern) - [Double-Checked Locking with Singleton](http://www.baeldung.com/java-singleton-double-checked-locking) - [Composite Design Pattern in Java](http://www.baeldung.com/java-composite-pattern) - +- [Visitor Design Pattern in Java](http://www.baeldung.com/java-visitor-pattern) diff --git a/performance-tests/README.md b/performance-tests/README.md new file mode 100644 index 0000000000..5af735b708 --- /dev/null +++ b/performance-tests/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Performance of Java Mapping Frameworks](http://www.baeldung.com/java-performance-mapping-frameworks) diff --git a/spring-5-reactive/README.md b/spring-5-reactive/README.md index 9998dbf751..df96d933ba 100644 --- a/spring-5-reactive/README.md +++ b/spring-5-reactive/README.md @@ -17,3 +17,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Boot Actuator](http://www.baeldung.com/spring-boot-actuators) - [Spring Webflux Filters](http://www.baeldung.com/spring-webflux-filters) - [Reactive Flow with MongoDB, Kotlin, and Spring WebFlux](http://www.baeldung.com/kotlin-mongodb-spring-webflux) +- [Spring Data Reactive Repositories with MongoDB](http://www.baeldung.com/spring-data-mongodb-reactive) diff --git a/spring-boot-ops/README.md b/spring-boot-ops/README.md index 26caccb727..7eca307924 100644 --- a/spring-boot-ops/README.md +++ b/spring-boot-ops/README.md @@ -1,3 +1,10 @@ ### Relevant Articles: - [Deploy a Spring Boot WAR into a Tomcat Server](http://www.baeldung.com/spring-boot-war-tomcat-deploy) +- [Spring Boot Dependency Management with a Custom Parent](http://www.baeldung.com/spring-boot-dependency-management-custom-parent) +- [A Custom Data Binder in Spring MVC](http://www.baeldung.com/spring-mvc-custom-data-binder) +- [Create a Fat Jar App with Spring Boot](http://www.baeldung.com/deployable-fat-jar-spring-boot) +- [Introduction to WebJars](http://www.baeldung.com/maven-webjars) +- [Intro to Spring Boot Starters](http://www.baeldung.com/spring-boot-starters) +- [A Quick Guide to Maven Wrapper](http://www.baeldung.com/maven-wrapper) +- [Shutdown a Spring Boot Application](http://www.baeldung.com/spring-boot-shutdown) diff --git a/spring-core/README.md b/spring-core/README.md index cec85534f5..3684c7f6e9 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -15,3 +15,4 @@ - [How to Inject a Property Value Into a Class Not Managed by Spring?](http://www.baeldung.com/inject-properties-value-non-spring-class) - [@Lookup Annotation in Spring](http://www.baeldung.com/spring-lookup) - [BeanNameAware and BeanFactoryAware Interfaces in Spring](http://www.baeldung.com/spring-bean-name-factory-aware) +- [Spring – Injecting Collections](http://www.baeldung.com/spring-injecting-collections) diff --git a/spring-data-rest-querydsl/README.md b/spring-data-rest-querydsl/README.md new file mode 100644 index 0000000000..03b5fee06a --- /dev/null +++ b/spring-data-rest-querydsl/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [REST Query Language Over Multiple Tables with Querydsl Web Support](http://www.baeldung.com/rest-querydsl-multiple-tables) diff --git a/spring-mockito/README.md b/spring-mockito/README.md index 3ced7161fa..969954c15e 100644 --- a/spring-mockito/README.md +++ b/spring-mockito/README.md @@ -5,3 +5,4 @@ ### Relevant Articles: - [Injecting Mockito Mocks into Spring Beans](http://www.baeldung.com/injecting-mocks-in-spring) +- [Mockito ArgumentMatchers](http://www.baeldung.com/mockito-argument-matchers) diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 877439145d..b97b961e60 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -29,3 +29,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring MVC @PathVariable with a dot (.) gets truncated](http://www.baeldung.com/spring-mvc-pathvariable-dot) - [A Quick Example of Spring Websockets’ @SendToUser Annotation](http://www.baeldung.com/spring-websockets-sendtouser) - [Spring Boot Annotations](http://www.baeldung.com/spring-boot-annotations) +- [Spring Scheduling Annotations](http://www.baeldung.com/spring-scheduling-annotations) +- [Spring Web Annotations](http://www.baeldung.com/spring-mvc-annotations) +- [Spring Core Annotations](http://www.baeldung.com/spring-core-annotations) diff --git a/testing-modules/junit-5/README.md b/testing-modules/junit-5/README.md index 6ab00e58d5..2292c3272a 100644 --- a/testing-modules/junit-5/README.md +++ b/testing-modules/junit-5/README.md @@ -12,5 +12,4 @@ - [JUnit Assert an Exception is Thrown](http://www.baeldung.com/junit-assert-exception) - [@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll](http://www.baeldung.com/junit-before-beforeclass-beforeeach-beforeall) - [Migrating from JUnit 4 to JUnit 5](http://www.baeldung.com/junit-5-migration) - - +- [JUnit5 Programmatic Extension Registration with @RegisterExtension](http://www.baeldung.com/junit-5-registerextension-annotation) From 7afbfb69686bd378ac7538a0516e01077d36ac0f Mon Sep 17 00:00:00 2001 From: Orry Date: Wed, 13 Jun 2018 21:44:30 +0200 Subject: [PATCH 09/11] BAEL-1755: Big O Notation Explained (#4440) * BAEL-1701: Create SQSApplication, add most functionality (still need to format, and add queue monitoring) * BAEL-1701: Complete examples * BAEL-1755: Big O Explained * BAEL-1755: Move code to test folder * BAEL-1755: Remove main() method from test class * BAEL-1755: BBD stylify the unit tests and separate them into their own methods --- .../analysis/AnalysisRunnerLiveTest.java | 139 ++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 algorithms/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java b/algorithms/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java new file mode 100644 index 0000000000..1e9188f726 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java @@ -0,0 +1,139 @@ +package com.baeldung.algorithms.analysis; + +import org.junit.Test; + +public class AnalysisRunnerLiveTest { + + int n = 10; + int total = 0; + + @Test + public void whenConstantComplexity_thenConstantRuntime() { + + System.out.println("**** n = " + n + " ****"); + System.out.println(); + + // Constant Time + System.out.println("**** Constant time ****"); + + System.out.println("Hey - your input is: " + n); + System.out.println("Running time not dependent on input size!"); + System.out.println(); + } + + @Test + public void whenLogarithmicComplexity_thenLogarithmicRuntime() { + // Logarithmic Time + System.out.println("**** Logarithmic Time ****"); + for (int i = 1; i < n; i = i * 2) { + // System.out.println("Hey - I'm busy looking at: " + i); + total++; + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + } + + @Test + public void whenLinearComplexity_thenLinearRuntime() { + // Linear Time + System.out.println("**** Linear Time ****"); + for (int i = 0; i < n; i++) { + // System.out.println("Hey - I'm busy looking at: " + i); + total++; + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + + } + + @Test + public void whenNLogNComplexity_thenNLogNRuntime() { + // N Log N Time + System.out.println("**** nlogn Time ****"); + total = 0; + for ( + + int i = 1; i <= n; i++) { + for (int j = 1; j < n; j = j * 2) { + // System.out.println("Hey - I'm busy looking at: " + i + " and " + j); + total++; + } + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + } + + @Test + public void whenQuadraticComplexity_thenQuadraticRuntime() { + // Quadratic Time + System.out.println("**** Quadratic Time ****"); + total = 0; + for ( + + int i = 1; i <= n; i++) { + for (int j = 1; j <= n; j++) { + // System.out.println("Hey - I'm busy looking at: " + i + " and " + j); + total++; + } + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + } + + @Test + public void whenCubicComplexity_thenCubicRuntime() { + // Cubic Time + System.out.println("**** Cubic Time ****"); + total = 0; + for ( + + int i = 1; i <= n; i++) { + for (int j = 1; j <= n; j++) { + for (int k = 1; k <= n; k++) { + // System.out.println("Hey - I'm busy looking at: " + i + " and " + j + " and " + k); + total++; + } + } + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + } + + @Test + public void whenExponentialComplexity_thenExponentialRuntime() { + // Exponential Time + System.out.println("**** Exponential Time ****"); + total = 0; + for ( + + int i = 1; i <= Math.pow(2, n); i++) { + // System.out.println("Hey - I'm busy looking at: " + i); + total++; + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + } + + @Test + public void whenFactorialComplexity_thenFactorialRuntime() { + // Factorial Time + System.out.println("**** Factorial Time ****"); + total = 0; + for ( + + int i = 1; i <= + + factorial(n); i++) { + // System.out.println("Hey - I'm busy looking at: " + i); + total++; + } + System.out.println("Total amount of times run: " + total); + } + + static int factorial(int n) { + if (n == 0 || n == 1) + return 1; + else + return n * factorial(n - 1); + } +} From 0da637d1f970c9ef5c3c6cf4f217ad5922bb3d49 Mon Sep 17 00:00:00 2001 From: Tino M Thomas Date: Wed, 13 Jun 2018 22:51:53 +0300 Subject: [PATCH 10/11] Spring shutdown callback methodologies - BAEL 1831 --- .../ShutdownHookApplication.java | 14 +++++++++++ .../baeldung/shutdownhooks/beans/Bean1.java | 14 +++++++++++ .../baeldung/shutdownhooks/beans/Bean2.java | 14 +++++++++++ .../baeldung/shutdownhooks/beans/Bean3.java | 8 ++++++ .../config/ExampleServletContextListener.java | 18 +++++++++++++ .../config/ShutdownHookConfiguration.java | 25 +++++++++++++++++++ 6 files changed, 93 insertions(+) create mode 100644 spring-boot/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java create mode 100644 spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java create mode 100644 spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java create mode 100644 spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java create mode 100644 spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java create mode 100644 spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java new file mode 100644 index 0000000000..7cce34a06c --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.shutdownhooks; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +@EnableAutoConfiguration +public class ShutdownHookApplication { + + public static void main(String args[]) { + SpringApplication.run(ShutdownHookApplication.class, args); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java new file mode 100644 index 0000000000..e85b9395d3 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java @@ -0,0 +1,14 @@ +package com.baeldung.shutdownhooks.beans; + +import javax.annotation.PreDestroy; + +import org.springframework.stereotype.Component; + +@Component +public class Bean1 { + + @PreDestroy + public void destroy() { + System.out.println("Shutdown triggered using @PreDestroy."); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java new file mode 100644 index 0000000000..e85d12e791 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java @@ -0,0 +1,14 @@ +package com.baeldung.shutdownhooks.beans; + +import org.springframework.beans.factory.DisposableBean; +import org.springframework.stereotype.Component; + +@Component +public class Bean2 implements DisposableBean { + + @Override + public void destroy() throws Exception { + System.out.println("Shutdown triggered using DisposableBean."); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java new file mode 100644 index 0000000000..bed1d50ee7 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java @@ -0,0 +1,8 @@ +package com.baeldung.shutdownhooks.beans; + +public class Bean3 { + + public void destroy() { + System.out.println("Shutdown triggered using bean destroy method."); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java new file mode 100644 index 0000000000..07d729cb83 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java @@ -0,0 +1,18 @@ +package com.baeldung.shutdownhooks.config; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + +public class ExampleServletContextListener implements ServletContextListener { + + @Override + public void contextDestroyed(ServletContextEvent event) { + System.out.println("Shutdown triggered using ServletContextListener."); + } + + @Override + public void contextInitialized(ServletContextEvent event) { + // Triggers when context initializes + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java new file mode 100644 index 0000000000..2d0712e19b --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java @@ -0,0 +1,25 @@ +package com.baeldung.shutdownhooks.config; + +import javax.servlet.ServletContextListener; + +import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.shutdownhooks.beans.Bean3; + +@Configuration +public class ShutdownHookConfiguration { + + @Bean(destroyMethod = "destroy") + public Bean3 initializeBean3() { + return new Bean3(); + } + + @Bean + ServletListenerRegistrationBean servletListener() { + ServletListenerRegistrationBean srb = new ServletListenerRegistrationBean<>(); + srb.setListener(new ExampleServletContextListener()); + return srb; + } +} From fc14d426c5589bf4caa4ae380759b814bc8a8980 Mon Sep 17 00:00:00 2001 From: Patryk Kucharz Date: Tue, 12 Jun 2018 18:22:32 +0200 Subject: [PATCH 11/11] BAEL-1730: Optimistic Locking in JPA Tests for the article. --- .../com/baeldung/hibernate/HibernateUtil.java | 4 + .../OptimisticLockingCourse.java | 48 +++++++ .../OptimisticLockingStudent.java | 70 +++++++++ .../OptimisticLockingIntegrationTest.java | 134 ++++++++++++++++++ 4 files changed, 256 insertions(+) create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java create mode 100644 hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java index e8fdabebbc..23d7d2e201 100644 --- a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -1,5 +1,7 @@ package com.baeldung.hibernate; +import com.baeldung.hibernate.optimisticlocking.OptimisticLockingCourse; +import com.baeldung.hibernate.optimisticlocking.OptimisticLockingStudent; import com.baeldung.hibernate.pessimisticlocking.Individual; import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse; import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee; @@ -70,6 +72,8 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(PessimisticLockingCourse.class); metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Customer.class); metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Address.class); + metadataSources.addAnnotatedClass(OptimisticLockingCourse.class); + metadataSources.addAnnotatedClass(OptimisticLockingStudent.class); Metadata metadata = metadataSources.buildMetadata(); return metadata.getSessionFactoryBuilder() diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java new file mode 100644 index 0000000000..1af3e3e21b --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java @@ -0,0 +1,48 @@ +package com.baeldung.hibernate.optimisticlocking; + +import javax.persistence.*; + +@Entity +public class OptimisticLockingCourse { + + @Id + private Long id; + + private String name; + + @ManyToOne + @JoinTable(name = "optimistic_student_course") + private OptimisticLockingStudent student; + + public OptimisticLockingCourse(Long id, String name) { + this.id = id; + this.name = name; + } + + public OptimisticLockingCourse() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public OptimisticLockingStudent getStudent() { + return student; + } + + public void setStudent(OptimisticLockingStudent student) { + this.student = student; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java new file mode 100644 index 0000000000..b79212ae8d --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java @@ -0,0 +1,70 @@ +package com.baeldung.hibernate.optimisticlocking; + +import javax.persistence.*; +import java.util.List; + +@Entity +public class OptimisticLockingStudent { + + @Id + private Long id; + + private String name; + + private String lastName; + @Version + private Integer version; + + @OneToMany(mappedBy = "student") + private List courses; + + public OptimisticLockingStudent(Long id, String name, String lastName, List courses) { + this.id = id; + this.name = name; + this.lastName = lastName; + this.courses = courses; + } + + public OptimisticLockingStudent() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Integer getVersion() { + return version; + } + + public void setVersion(Integer version) { + this.version = version; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public List getCourses() { + return courses; + } + + public void setCourses(List courses) { + this.courses = courses; + } +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java new file mode 100644 index 0000000000..68b51764e4 --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java @@ -0,0 +1,134 @@ +package com.baeldung.hibernate.optimisticlocking; + +import com.baeldung.hibernate.HibernateUtil; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import javax.persistence.EntityManager; +import javax.persistence.LockModeType; +import javax.persistence.OptimisticLockException; +import java.io.IOException; +import java.util.Arrays; + +public class OptimisticLockingIntegrationTest { + + @Before + public void setUp() throws IOException { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + OptimisticLockingCourse course = new OptimisticLockingCourse(1L, "MATH"); + OptimisticLockingStudent student = new OptimisticLockingStudent(1L, "John", "Doe", Arrays.asList(course)); + course.setStudent(student); + entityManager.persist(course); + entityManager.persist(student); + entityManager.getTransaction() + .commit(); + entityManager.close(); + } + + @After + public void clean() throws IOException { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + OptimisticLockingCourse course = entityManager.find(OptimisticLockingCourse.class, 1L); + OptimisticLockingStudent student = entityManager.find(OptimisticLockingStudent.class, 1L); + entityManager.remove(course); + entityManager.remove(student); + entityManager.getTransaction() + .commit(); + entityManager.close(); + } + + @Test(expected = OptimisticLockException.class) + public void givenVersionedEntities_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L); + + EntityManager em2 = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L); + student2.setName("RICHARD"); + em2.persist(student2); + em2.getTransaction() + .commit(); + em2.close(); + + student.setName("JOHN"); + em.persist(student); + em.getTransaction() + .commit(); + em.close(); + } + + @Test(expected = OptimisticLockException.class) + public void givenVersionedEntitiesWithLockByFindMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L, LockModeType.OPTIMISTIC); + + EntityManager em2 = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L, LockModeType.OPTIMISTIC_FORCE_INCREMENT); + student2.setName("RICHARD"); + em2.persist(student2); + em2.getTransaction() + .commit(); + em2.close(); + + student.setName("JOHN"); + em.persist(student); + em.getTransaction() + .commit(); + em.close(); + } + + @Test(expected = OptimisticLockException.class) + public void givenVersionedEntitiesWithLockByRefreshMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L); + em.refresh(student, LockModeType.OPTIMISTIC); + + EntityManager em2 = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L); + em.refresh(student, LockModeType.OPTIMISTIC_FORCE_INCREMENT); + student2.setName("RICHARD"); + em2.persist(student2); + em2.getTransaction() + .commit(); + em2.close(); + + student.setName("JOHN"); + em.persist(student); + em.getTransaction() + .commit(); + em.close(); + } + + @Test(expected = OptimisticLockException.class) + public void givenVersionedEntitiesWithLockByLockMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L); + em.lock(student, LockModeType.OPTIMISTIC); + + EntityManager em2 = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L); + em.lock(student, LockModeType.OPTIMISTIC_FORCE_INCREMENT); + student2.setName("RICHARD"); + em2.persist(student2); + em2.getTransaction() + .commit(); + em2.close(); + + student.setName("JOHN"); + em.persist(student); + em.getTransaction() + .commit(); + em.close(); + } + + protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException { + String propertyFileName = "hibernate-pessimistic-locking.properties"; + EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName) + .openSession(); + entityManager.getTransaction() + .begin(); + + return entityManager; + } +}