From 2bebf73db2d7784a3b53f9c6ae6c439f6b5007c0 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Thu, 27 Apr 2017 16:58:13 +0200 Subject: [PATCH 01/30] SetTest refactor (#1724) --- .../java/com/baeldung/java/set/SetTest.java | 51 ++++++++++--------- 1 file changed, 28 insertions(+), 23 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/java/set/SetTest.java b/core-java/src/test/java/com/baeldung/java/set/SetTest.java index 59e135283f..32a5c7e07e 100644 --- a/core-java/src/test/java/com/baeldung/java/set/SetTest.java +++ b/core-java/src/test/java/com/baeldung/java/set/SetTest.java @@ -1,16 +1,12 @@ package com.baeldung.java.set; +import org.junit.Test; + +import java.util.*; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import java.util.ConcurrentModificationException; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; -import java.util.TreeSet; - -import org.junit.Test; - public class SetTest { @Test @@ -44,22 +40,22 @@ public class SetTest { @Test public void givenHashSetAndTreeSet_whenAddObjects_thenHashSetIsFaster() { - Set set = new HashSet<>(); - long startTime = System.nanoTime(); - set.add("Baeldung"); - set.add("is"); - set.add("Awesome"); - long endTime = System.nanoTime(); - long duration1 = (endTime - startTime); - Set set2 = new TreeSet<>(); - startTime = System.nanoTime(); - set2.add("Baeldung"); - set2.add("is"); - set2.add("Awesome"); - endTime = System.nanoTime(); - long duration2 = (endTime - startTime); - assertTrue(duration1 < duration2); + long hashSetInsertionTime = measureExecution(() -> { + Set set = new HashSet<>(); + set.add("Baeldung"); + set.add("is"); + set.add("Awesome"); + }); + + long TreeSetInsertionTime = measureExecution(() -> { + Set set = new TreeSet<>(); + set.add("Baeldung"); + set.add("is"); + set.add("Awesome"); + }); + + assertTrue(hashSetInsertionTime < TreeSetInsertionTime); } @Test @@ -86,4 +82,13 @@ public class SetTest { it.next(); } } + + private static long measureExecution(Runnable task) { + long startTime = System.nanoTime(); + task.run(); + long endTime = System.nanoTime(); + long executionTime = endTime - startTime; + System.out.println(executionTime); + return executionTime; + } } From ac8700ff651c6557b825862029e90f9954274bf2 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Thu, 27 Apr 2017 19:35:22 +0200 Subject: [PATCH 02/30] Bael 850 (#1744) * BAEL-850 ConcurentskipLIst * BAEL-850 formatting * BAEL-850 Formatting * spring 5 work * SetTest refactor (#1724) * BAEL-850 use lambda * BAEL-850 no need to casting --- .../concurrent/skiplist/EventWindowSort.java | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java b/core-java/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java index 9eef00bd3f..3aca6b0147 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java +++ b/core-java/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java @@ -4,17 +4,10 @@ import java.time.ZonedDateTime; import java.util.Comparator; import java.util.concurrent.ConcurrentNavigableMap; import java.util.concurrent.ConcurrentSkipListMap; -import java.util.function.ToLongFunction; public class EventWindowSort { - private final ConcurrentSkipListMap events = new ConcurrentSkipListMap<>(Comparator.comparingLong(new ToLongFunction() { - @Override - public long applyAsLong(ZonedDateTime value) { - return value - .toInstant() - .toEpochMilli(); - } - })); + private final ConcurrentSkipListMap events + = new ConcurrentSkipListMap<>(Comparator.comparingLong(value -> value.toInstant().toEpochMilli())); public void acceptEvent(Event event) { events.put(event.getEventTime(), event.getContent()); @@ -22,14 +15,14 @@ public class EventWindowSort { public ConcurrentNavigableMap getEventsFromLastMinute() { return events.tailMap(ZonedDateTime - .now() - .minusMinutes(1)); + .now() + .minusMinutes(1)); } public ConcurrentNavigableMap getEventsOlderThatOneMinute() { return events.headMap(ZonedDateTime - .now() - .minusMinutes(1)); + .now() + .minusMinutes(1)); } } From 5b5003b39106ffdf31fe7af8a73b5440e2eeb6ca Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Fri, 28 Apr 2017 09:34:39 +0200 Subject: [PATCH 03/30] Build optimization (#1746) * Build optimization * Build optimization --- ...ava => SquareCalculatorIntegrationTest.java} | 17 ++++++----------- ...> PriorityBlockingQueueIntegrationTest.java} | 2 +- ...> ConcurrentSkipListSetIntegrationTest.java} | 2 +- ...est.java => ThreadLocalIntegrationTest.java} | 2 +- ...t.java => TransferQueueIntegrationTest.java} | 2 +- ...rTest.java => DisruptorIntegrationTest.java} | 11 ++++++----- ...Test.java => InMemoryDBIntegrationTest.java} | 13 ++++++------- ...HeavyResourceControllerIntegrationTest.java} | 2 +- ...stomMediaTypeControllerIntegrationTest.java} | 2 +- ...ppingsExampleControllerIntegrationTest.java} | 17 +++++++---------- spring-session/pom.xml | 2 +- ...va => SessionControllerIntegrationTest.java} | 2 +- 12 files changed, 33 insertions(+), 41 deletions(-) rename core-java/src/test/java/com/baeldung/concurrent/future/{SquareCalculatorUnitTest.java => SquareCalculatorIntegrationTest.java} (91%) rename core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/{PriorityBlockingQueueUnitTest.java => PriorityBlockingQueueIntegrationTest.java} (96%) rename core-java/src/test/java/com/baeldung/concurrent/skiplist/{ConcurrentSkipListSetTest.java => ConcurrentSkipListSetIntegrationTest.java} (98%) rename core-java/src/test/java/com/baeldung/threadlocal/{ThreadLocalTest.java => ThreadLocalIntegrationTest.java} (96%) rename core-java/src/test/java/com/baeldung/transferqueue/{TransferQueueTest.java => TransferQueueIntegrationTest.java} (98%) rename disruptor/src/test/java/com/baeldung/disruptor/{DisruptorTest.java => DisruptorIntegrationTest.java} (95%) rename spring-jpa/src/test/java/org/baeldung/persistence/repository/{InMemoryDBTest.java => InMemoryDBIntegrationTest.java} (93%) rename spring-rest/src/test/java/org/baeldung/web/controller/{HeavyResourceControllerTest.java => HeavyResourceControllerIntegrationTest.java} (98%) rename spring-rest/src/test/java/org/baeldung/web/controller/mediatypes/{CustomMediaTypeControllerTest.java => CustomMediaTypeControllerIntegrationTest.java} (96%) rename spring-rest/src/test/java/org/baeldung/web/test/{BazzNewMappingsExampleControllerTest.java => BazzNewMappingsExampleControllerIntegrationTest.java} (88%) rename spring-session/src/test/java/com/baeldung/spring/session/{SessionControllerTest.java => SessionControllerIntegrationTest.java} (97%) diff --git a/core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorUnitTest.java b/core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java similarity index 91% rename from core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorUnitTest.java rename to core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java index 69c802feb8..bc63fbe6f7 100644 --- a/core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorUnitTest.java +++ b/core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java @@ -1,22 +1,17 @@ package com.baeldung.concurrent.future; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.concurrent.CancellationException; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; -public class SquareCalculatorUnitTest { +import java.util.concurrent.*; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class SquareCalculatorIntegrationTest { @Rule public TestName name = new TestName(); diff --git a/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueUnitTest.java b/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java similarity index 96% rename from core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueUnitTest.java rename to core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java index 0272726465..2a8eda896b 100644 --- a/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueUnitTest.java +++ b/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java @@ -9,7 +9,7 @@ import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.util.Lists.newArrayList; -public class PriorityBlockingQueueUnitTest { +public class PriorityBlockingQueueIntegrationTest { @Test public void givenUnorderedValues_whenPolling_thenShouldOrderQueue() throws InterruptedException { diff --git a/core-java/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetTest.java b/core-java/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetTest.java rename to core-java/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java index a2dbbae520..92fff8446b 100644 --- a/core-java/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetTest.java +++ b/core-java/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java @@ -13,7 +13,7 @@ import java.util.stream.IntStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -public class ConcurrentSkipListSetTest { +public class ConcurrentSkipListSetIntegrationTest { @Test public void givenThreadsProducingEvents_whenGetForEventsFromLastMinute_thenReturnThoseEventsInTheLockFreeWay() throws InterruptedException { diff --git a/core-java/src/test/java/com/baeldung/threadlocal/ThreadLocalTest.java b/core-java/src/test/java/com/baeldung/threadlocal/ThreadLocalIntegrationTest.java similarity index 96% rename from core-java/src/test/java/com/baeldung/threadlocal/ThreadLocalTest.java rename to core-java/src/test/java/com/baeldung/threadlocal/ThreadLocalIntegrationTest.java index ac2e8fbe63..cc4b4f021a 100644 --- a/core-java/src/test/java/com/baeldung/threadlocal/ThreadLocalTest.java +++ b/core-java/src/test/java/com/baeldung/threadlocal/ThreadLocalIntegrationTest.java @@ -7,7 +7,7 @@ import java.util.concurrent.ExecutionException; import static org.junit.Assert.assertEquals; -public class ThreadLocalTest { +public class ThreadLocalIntegrationTest { @Test public void givenThreadThatStoresContextInAMap_whenStartThread_thenShouldSetContextForBothUsers() throws ExecutionException, InterruptedException { //when diff --git a/core-java/src/test/java/com/baeldung/transferqueue/TransferQueueTest.java b/core-java/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/transferqueue/TransferQueueTest.java rename to core-java/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java index 1af9821ed0..e49738e983 100644 --- a/core-java/src/test/java/com/baeldung/transferqueue/TransferQueueTest.java +++ b/core-java/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java @@ -9,7 +9,7 @@ import java.util.concurrent.*; import static junit.framework.TestCase.assertEquals; @FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class TransferQueueTest { +public class TransferQueueIntegrationTest { @Test public void whenMultipleConsumersAndProducers_thenProcessAllMessages() throws InterruptedException { diff --git a/disruptor/src/test/java/com/baeldung/disruptor/DisruptorTest.java b/disruptor/src/test/java/com/baeldung/disruptor/DisruptorIntegrationTest.java similarity index 95% rename from disruptor/src/test/java/com/baeldung/disruptor/DisruptorTest.java rename to disruptor/src/test/java/com/baeldung/disruptor/DisruptorIntegrationTest.java index 28a5ff72ce..10929f21b0 100644 --- a/disruptor/src/test/java/com/baeldung/disruptor/DisruptorTest.java +++ b/disruptor/src/test/java/com/baeldung/disruptor/DisruptorIntegrationTest.java @@ -1,16 +1,17 @@ package com.baeldung.disruptor; -import java.util.concurrent.ThreadFactory; -import org.junit.Before; -import org.junit.Test; import com.lmax.disruptor.BusySpinWaitStrategy; import com.lmax.disruptor.RingBuffer; import com.lmax.disruptor.WaitStrategy; import com.lmax.disruptor.dsl.Disruptor; import com.lmax.disruptor.dsl.ProducerType; import com.lmax.disruptor.util.DaemonThreadFactory; +import org.junit.Before; +import org.junit.Test; -public class DisruptorTest { +import java.util.concurrent.ThreadFactory; + +public class DisruptorIntegrationTest { private Disruptor disruptor; private WaitStrategy waitStrategy; @@ -21,7 +22,7 @@ public class DisruptorTest { private void createDisruptor(final ProducerType producerType, final EventConsumer eventConsumer) { final ThreadFactory threadFactory = DaemonThreadFactory.INSTANCE; - disruptor = new Disruptor(ValueEvent.EVENT_FACTORY, 16, threadFactory, producerType, waitStrategy); + disruptor = new Disruptor<>(ValueEvent.EVENT_FACTORY, 16, threadFactory, producerType, waitStrategy); disruptor.handleEventsWith(eventConsumer.getEventHandler()); } diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBTest.java b/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java similarity index 93% rename from spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBTest.java rename to spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java index 2c40c5b117..1fcc4be45d 100644 --- a/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBTest.java +++ b/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java @@ -1,7 +1,8 @@ package org.baeldung.persistence.repository; -import javax.annotation.Resource; - +import org.baeldung.config.StudentJpaConfig; +import org.baeldung.persistence.dao.StudentRepository; +import org.baeldung.persistence.model.Student; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; @@ -9,16 +10,14 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.transaction.annotation.Transactional; -import org.baeldung.config.StudentJpaConfig; -import org.baeldung.persistence.model.Student; -import org.baeldung.persistence.dao.StudentRepository; +import javax.annotation.Resource; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { StudentJpaConfig.class }, loader = AnnotationConfigContextLoader.class) @Transactional -public class InMemoryDBTest { +public class InMemoryDBIntegrationTest { @Resource private StudentRepository studentRepository; diff --git a/spring-rest/src/test/java/org/baeldung/web/controller/HeavyResourceControllerTest.java b/spring-rest/src/test/java/org/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java similarity index 98% rename from spring-rest/src/test/java/org/baeldung/web/controller/HeavyResourceControllerTest.java rename to spring-rest/src/test/java/org/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java index a1f9e71bec..1dae559371 100644 --- a/spring-rest/src/test/java/org/baeldung/web/controller/HeavyResourceControllerTest.java +++ b/spring-rest/src/test/java/org/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java @@ -26,7 +26,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = WebConfig.class) @WebAppConfiguration -public class HeavyResourceControllerTest { +public class HeavyResourceControllerIntegrationTest { private MockMvc mockMvc; diff --git a/spring-rest/src/test/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeControllerTest.java b/spring-rest/src/test/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeControllerIntegrationTest.java similarity index 96% rename from spring-rest/src/test/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeControllerTest.java rename to spring-rest/src/test/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeControllerIntegrationTest.java index a38177f78b..9ef2dfa215 100644 --- a/spring-rest/src/test/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeControllerTest.java +++ b/spring-rest/src/test/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeControllerIntegrationTest.java @@ -18,7 +18,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = WebConfig.class) @WebAppConfiguration -public class CustomMediaTypeControllerTest { +public class CustomMediaTypeControllerIntegrationTest { private MockMvc mockMvc; diff --git a/spring-rest/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleControllerTest.java b/spring-rest/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleControllerIntegrationTest.java similarity index 88% rename from spring-rest/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleControllerTest.java rename to spring-rest/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleControllerIntegrationTest.java index f2f00a40d8..7bd16a3e97 100644 --- a/spring-rest/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleControllerTest.java +++ b/spring-rest/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleControllerIntegrationTest.java @@ -1,15 +1,6 @@ package org.baeldung.web.test; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import org.baeldung.config.WebConfig; import org.junit.Before; import org.junit.Test; @@ -22,11 +13,17 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = WebConfig.class) @WebAppConfiguration -public class BazzNewMappingsExampleControllerTest { +public class BazzNewMappingsExampleControllerIntegrationTest { private MockMvc mockMvc; diff --git a/spring-session/pom.xml b/spring-session/pom.xml index 2c8b15a6eb..79095cbfbb 100644 --- a/spring-session/pom.xml +++ b/spring-session/pom.xml @@ -59,7 +59,7 @@ maven-surefire-plugin - **/*ControllerTest.java + **/*IntegrationTest.java diff --git a/spring-session/src/test/java/com/baeldung/spring/session/SessionControllerTest.java b/spring-session/src/test/java/com/baeldung/spring/session/SessionControllerIntegrationTest.java similarity index 97% rename from spring-session/src/test/java/com/baeldung/spring/session/SessionControllerTest.java rename to spring-session/src/test/java/com/baeldung/spring/session/SessionControllerIntegrationTest.java index c8138889b2..84dd2bc139 100644 --- a/spring-session/src/test/java/com/baeldung/spring/session/SessionControllerTest.java +++ b/spring-session/src/test/java/com/baeldung/spring/session/SessionControllerIntegrationTest.java @@ -11,7 +11,7 @@ import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -public class SessionControllerTest { +public class SessionControllerIntegrationTest { private Jedis jedis; private TestRestTemplate testRestTemplate; From 1c24e0a2cfcd239199a34d45b4a2ee92caa00a98 Mon Sep 17 00:00:00 2001 From: Tomasz Sobala Date: Fri, 28 Apr 2017 10:34:28 +0200 Subject: [PATCH 04/30] [BAEL-820] Difference between wait() and sleep() in Java (#1708) * injecting beans * XML-based configuration replaced with Java Config. * [BAEL-431] Exploring TestRestTemplate. * Revert of evaluation task "XML-based configuration replaced with Java Config." This reverts commit 66471cf0574c85f8ff514ec4caf5ba44ebba1a74. * Revert of evaluation task "injecting beans" This reverts commit d2ac20185e636245bc0ae0b4ccb952965de88e28. * [BAEL-431] fix to the tests in TestRestTemplateBasicLiveTest. * [BAEL-431] added more meaningful user and password for auth. * [BAEL-820] examples of wait() and sleep() methods. * [BAEL-820] wait() and sleep() examples. --- .../concurrent/sleepwait/ThreadA.java | 21 +++++++++++++++++ .../concurrent/sleepwait/ThreadB.java | 20 ++++++++++++++++ .../sleepwait/WaitSleepExample.java | 23 +++++++++++++++++++ 3 files changed, 64 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/concurrent/sleepwait/ThreadA.java create mode 100644 core-java/src/main/java/com/baeldung/concurrent/sleepwait/ThreadB.java create mode 100644 core-java/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/sleepwait/ThreadA.java b/core-java/src/main/java/com/baeldung/concurrent/sleepwait/ThreadA.java new file mode 100644 index 0000000000..b19bc3fe1a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/sleepwait/ThreadA.java @@ -0,0 +1,21 @@ +package com.baeldung.concurrent.sleepwait; + +/*** + * Example of waking up a waiting thread + */ +public class ThreadA { + private static final ThreadB b = new ThreadB(); + + public static void main(String... args) throws InterruptedException { + b.start(); + + synchronized (b) { + while (b.sum == 0) { + System.out.println("Waiting for ThreadB to complete..."); + b.wait(); + } + + System.out.println("ThreadB has completed. Sum from that thread is: " + b.sum); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/sleepwait/ThreadB.java b/core-java/src/main/java/com/baeldung/concurrent/sleepwait/ThreadB.java new file mode 100644 index 0000000000..1fc180a5de --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/sleepwait/ThreadB.java @@ -0,0 +1,20 @@ +package com.baeldung.concurrent.sleepwait; + +/*** + * Example of waking up a waiting thread + */ +class ThreadB extends Thread { + int sum; + + @Override + public void run() { + synchronized (this) { + int i = 0; + while (i < 100000) { + sum += i; + i++; + } + notify(); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java b/core-java/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java new file mode 100644 index 0000000000..e84fe29d87 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java @@ -0,0 +1,23 @@ +package com.baeldung.concurrent.sleepwait; + +/*** + * Example of wait() and sleep() methods + */ +public class WaitSleepExample { + private static final Object LOCK = new Object(); + + public static void main(String... args) throws InterruptedException { + sleepWaitInSyncronizedBlocks(); + } + + private static void sleepWaitInSyncronizedBlocks() throws InterruptedException { + Thread.sleep(1000); // called on the thread + System.out.println("Thread '" + Thread.currentThread().getName() + "' is woken after sleeping for 1 second"); + + synchronized (LOCK) { + LOCK.wait(1000); // called on the object, synchronization required + System.out.println("Object '" + LOCK + "' is woken after waiting for 1 second"); + } + } + +} From 14f518107e88a757f4cd7b2692568d41db6f320a Mon Sep 17 00:00:00 2001 From: Mohd Farid Date: Fri, 28 Apr 2017 16:38:13 +0530 Subject: [PATCH 05/30] String split tests --- .../java/com/baeldung/string/SplitTest.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/string/SplitTest.java diff --git a/core-java/src/test/java/com/baeldung/string/SplitTest.java b/core-java/src/test/java/com/baeldung/string/SplitTest.java new file mode 100644 index 0000000000..d2e307e68d --- /dev/null +++ b/core-java/src/test/java/com/baeldung/string/SplitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.string; + +import org.apache.commons.lang.StringUtils; +import org.junit.Test; + +import java.util.Arrays; + +import static org.junit.Assert.assertArrayEquals; + +public class SplitTest { + + @Test + public void givenString_whenSplit_thenRetrunsArray_through_JavaLangString() { + assertArrayEquals("split by comma", Arrays.asList("peter", "james", "thomas").toArray(), "peter,james,thomas".split(",")); + assertArrayEquals("split by whitespace", Arrays.asList("car", "jeep", "scooter").toArray(), "car jeep scooter".split(" ")); + assertArrayEquals("split by hyphen", Arrays.asList("1", "120", "232323").toArray(), "1-120-232323".split("-")); + assertArrayEquals("split by dot", Arrays.asList("192", "168", "1", "178").toArray(), "192.168.1.178".split("\\.")); + assertArrayEquals("split by a regex", Arrays.asList("b", "a", "e", "l", "d", "u", "n", "g").toArray(), + "b a, e, l.d u, n g".split("\\s+|,\\s*|\\.\\s*")); + } + + @Test + public void givenString_whenSplit_thenRetrunsArray_through_StringUtils() { + StringUtils.split("car jeep scooter"); + + assertArrayEquals("split by whitespace", Arrays.asList("car", "jeep", "scooter").toArray(), StringUtils.split("car jeep scooter")); + assertArrayEquals("split by space, extra spaces ignored", Arrays.asList("car", "jeep", "scooter").toArray(), + StringUtils.split("car jeep scooter")); + assertArrayEquals("split by colon", Arrays.asList("car", "jeep", "scooter").toArray(), StringUtils.split("car:jeep:scooter", ":")); + assertArrayEquals("split by dot", Arrays.asList("car", "jeep", "scooter").toArray(), StringUtils.split("car.jeep.scooter", ".")); + } +} From e83002ce993a03c7dca753c050ec66deead00f9b Mon Sep 17 00:00:00 2001 From: lor6 Date: Fri, 28 Apr 2017 14:37:51 +0300 Subject: [PATCH 06/30] remove utility classes (#1733) * remove utility classes * remove httpclient, extend http * move code to core-java --- .../baeldung/http/ParameterStringBuilder.java | 21 +++ .../com/baeldung/http/HttpRequestTest.java | 126 ++++++++++++++++++ .../com/baeldung/http/HttpRequestBuilder.java | 49 ------- .../baeldung/http/HttpResponseWrapper.java | 31 ----- .../baeldung/http/ParameterStringBuilder.java | 27 ---- .../httpclient/HttpClientRequestBuilder.java | 124 ----------------- .../baeldung/http/HttpRequestBuilderTest.java | 40 ------ .../HttpClientRequestBuilderTest.java | 46 ------- 8 files changed, 147 insertions(+), 317 deletions(-) create mode 100644 core-java/src/main/java/com/baeldung/http/ParameterStringBuilder.java create mode 100644 core-java/src/test/java/com/baeldung/http/HttpRequestTest.java delete mode 100644 libraries/src/main/java/com/baeldung/http/HttpRequestBuilder.java delete mode 100644 libraries/src/main/java/com/baeldung/http/HttpResponseWrapper.java delete mode 100644 libraries/src/main/java/com/baeldung/http/ParameterStringBuilder.java delete mode 100644 libraries/src/main/java/com/baeldung/httpclient/HttpClientRequestBuilder.java delete mode 100644 libraries/src/test/java/com/baeldung/http/HttpRequestBuilderTest.java delete mode 100644 libraries/src/test/java/com/baeldung/httpclient/HttpClientRequestBuilderTest.java diff --git a/core-java/src/main/java/com/baeldung/http/ParameterStringBuilder.java b/core-java/src/main/java/com/baeldung/http/ParameterStringBuilder.java new file mode 100644 index 0000000000..bed4195faa --- /dev/null +++ b/core-java/src/main/java/com/baeldung/http/ParameterStringBuilder.java @@ -0,0 +1,21 @@ +package com.baeldung.http; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.Map; + +public class ParameterStringBuilder { + public static String getParamsString(Map params) throws UnsupportedEncodingException { + StringBuilder result = new StringBuilder(); + + for (Map.Entry entry : params.entrySet()) { + result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); + result.append("="); + result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); + result.append("&"); + } + + String resultString = result.toString(); + return resultString.length() > 0 ? resultString.substring(0, resultString.length() - 1) : resultString; + } +} diff --git a/core-java/src/test/java/com/baeldung/http/HttpRequestTest.java b/core-java/src/test/java/com/baeldung/http/HttpRequestTest.java new file mode 100644 index 0000000000..f238f7df7c --- /dev/null +++ b/core-java/src/test/java/com/baeldung/http/HttpRequestTest.java @@ -0,0 +1,126 @@ +package com.baeldung.http; + +import org.apache.commons.lang.StringUtils; +import org.junit.Test; +import static org.junit.Assert.*; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.CookieManager; +import java.net.HttpCookie; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +public class HttpRequestTest { + + @Test + public void whenGetRequest_thenOk() throws IOException { + URL url = new URL("http://example.com"); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("GET"); + + Map parameters = new HashMap<>(); + parameters.put("param1", "val"); + con.setDoOutput(true); + DataOutputStream out = new DataOutputStream(con.getOutputStream()); + out.writeBytes(ParameterStringBuilder.getParamsString(parameters)); + out.flush(); + out.close(); + + con.setConnectTimeout(5000); + con.setReadTimeout(5000); + + int status = con.getResponseCode(); + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + StringBuffer content = new StringBuffer(); + while ((inputLine = in.readLine()) != null) { + content.append(inputLine); + } + in.close(); + + assertEquals("status code incorrect", status, 200); + assertTrue("content incorrect", content.toString().contains("Example Domain")); + } + + @Test + public void whenPostRequest_thenOk() throws IOException { + URL url = new URL("http://example.com"); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("POST"); + con.setRequestProperty("Content-Type", "application/json"); + + Map parameters = new HashMap<>(); + parameters.put("param1", "val"); + con.setDoOutput(true); + DataOutputStream out = new DataOutputStream(con.getOutputStream()); + out.writeBytes(ParameterStringBuilder.getParamsString(parameters)); + out.flush(); + out.close(); + + int status = con.getResponseCode(); + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + StringBuffer content = new StringBuffer(); + while ((inputLine = in.readLine()) != null) { + content.append(inputLine); + } + in.close(); + + assertEquals("status code incorrect", status, 200); + } + + @Test + public void whenGetCookies_thenOk() throws IOException { + URL url = new URL("http://example.com"); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("GET"); + + CookieManager cookieManager = new CookieManager(); + String cookiesHeader = con.getHeaderField("Set-Cookie"); + Optional usernameCookie = null; + if (cookiesHeader != null) { + List cookies = HttpCookie.parse(cookiesHeader); + cookies.forEach(cookie -> cookieManager.getCookieStore().add(null, cookie)); + usernameCookie = cookies.stream().findAny().filter(cookie -> cookie.getName().equals("username")); + } + + if (usernameCookie == null) { + cookieManager.getCookieStore().add(null, new HttpCookie("username", "john")); + } + + con.disconnect(); + + con = (HttpURLConnection) url.openConnection(); + con.setRequestProperty("Cookie", StringUtils.join(cookieManager.getCookieStore().getCookies(), ";")); + + int status = con.getResponseCode(); + + assertEquals("status code incorrect", status, 200); + } + + @Test + public void whenRedirect_thenOk() throws IOException { + URL url = new URL("http://example.com"); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("GET"); + + con.setInstanceFollowRedirects(true); + int status = con.getResponseCode(); + + if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM) { + String location = con.getHeaderField("Location"); + URL newUrl = new URL(location); + con = (HttpURLConnection) newUrl.openConnection(); + } + + assertEquals("status code incorrect", con.getResponseCode(), 200); + } + +} diff --git a/libraries/src/main/java/com/baeldung/http/HttpRequestBuilder.java b/libraries/src/main/java/com/baeldung/http/HttpRequestBuilder.java deleted file mode 100644 index bfa7cc121b..0000000000 --- a/libraries/src/main/java/com/baeldung/http/HttpRequestBuilder.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.http; - -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.Map; - -import org.apache.log4j.Logger; - -public class HttpRequestBuilder { - - private static final Logger LOG = Logger.getLogger(HttpRequestBuilder.class); - - public HttpResponseWrapper sendRequest(String urlString, String method, Map parameters, Map properties) throws IOException{ - URL url = new URL(urlString); - HttpURLConnection con = (HttpURLConnection) url.openConnection(); - con.setRequestMethod(method); - if (properties != null) { - properties.forEach((key, value) -> con.setRequestProperty(key, value)); - } - if (parameters != null) { - con.setDoOutput(true); - DataOutputStream out = new DataOutputStream(con.getOutputStream()); - out.writeBytes(ParameterStringBuilder.getParamsString(parameters)); - out.flush(); - out.close(); - } - - int status = con.getResponseCode(); - - BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); - String inputLine; - StringBuffer content = new StringBuffer(); - while ((inputLine = in.readLine()) != null) { - content.append(inputLine); - } - in.close(); - - HttpResponseWrapper responseWrapper = new HttpResponseWrapper(); - responseWrapper.setStatus(status); - responseWrapper.setContent(content.toString()); - - return responseWrapper; - } - -} diff --git a/libraries/src/main/java/com/baeldung/http/HttpResponseWrapper.java b/libraries/src/main/java/com/baeldung/http/HttpResponseWrapper.java deleted file mode 100644 index c0f68ac18b..0000000000 --- a/libraries/src/main/java/com/baeldung/http/HttpResponseWrapper.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.http; - -public class HttpResponseWrapper { - private int status; - private String content; - - public HttpResponseWrapper(){ } - - public HttpResponseWrapper(int status, String content) { - super(); - this.status = status; - this.content = content; - } - - public int getStatus() { - return status; - } - - public void setStatus(int status) { - this.status = status; - } - - public String getContent() { - return content; - } - - public void setContent(String content) { - this.content = content; - } - -} diff --git a/libraries/src/main/java/com/baeldung/http/ParameterStringBuilder.java b/libraries/src/main/java/com/baeldung/http/ParameterStringBuilder.java deleted file mode 100644 index b148ddb3fd..0000000000 --- a/libraries/src/main/java/com/baeldung/http/ParameterStringBuilder.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.http; - -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.util.Map; - -public class ParameterStringBuilder { - public static String getParamsString(Map params) { - StringBuilder result = new StringBuilder(); - - params.forEach((key, value) -> { - try { - result.append(URLEncoder.encode(key, "UTF-8")); - result.append("="); - result.append(URLEncoder.encode(value, "UTF-8")); - result.append("&"); - } catch (UnsupportedEncodingException exc) { - } - }); - - String resultString = result.toString(); - if (resultString.length() > 0) { - resultString = resultString.substring(0, resultString.length() - 1); - } - return resultString; - } -} diff --git a/libraries/src/main/java/com/baeldung/httpclient/HttpClientRequestBuilder.java b/libraries/src/main/java/com/baeldung/httpclient/HttpClientRequestBuilder.java deleted file mode 100644 index b2f6c36a4f..0000000000 --- a/libraries/src/main/java/com/baeldung/httpclient/HttpClientRequestBuilder.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.baeldung.httpclient; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.apache.http.HttpResponse; -import org.apache.http.NameValuePair; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.HttpClient; -import org.apache.http.client.entity.UrlEncodedFormEntity; -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.HttpClientBuilder; -import org.apache.http.message.BasicNameValuePair; - -import com.baeldung.http.HttpResponseWrapper; -import com.baeldung.http.ParameterStringBuilder; - -public class HttpClientRequestBuilder { - - public HttpResponseWrapper sendGetRequest(String url, Map parameters) { - HttpClient client = HttpClientBuilder.create() - .build(); - if (parameters != null) { - url += "?" + ParameterStringBuilder.getParamsString(parameters); - } - HttpGet request = new HttpGet(url); - try { - HttpResponse response = client.execute(request); - - HttpResponseWrapper responseWrapper = new HttpResponseWrapper(); - responseWrapper.setStatus(response.getStatusLine() - .getStatusCode()); - BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity() - .getContent())); - - String line = "", content = ""; - while ((line = in.readLine()) != null) { - content += line; - } - responseWrapper.setContent(content); - return responseWrapper; - } catch (ClientProtocolException e) { - e.printStackTrace(); - return null; - } catch (IOException e) { - e.printStackTrace(); - return null; - } - } - - public HttpResponseWrapper sendPostRequestWithParameters(String url, Map parameters) { - HttpClient client = HttpClientBuilder.create() - .build(); - HttpPost request = new HttpPost(url); - - try { - if (parameters != null) { - List nameValuePairs = new ArrayList<>(); - parameters.forEach((key, value) -> nameValuePairs.add(new BasicNameValuePair(key, value))); - request.setEntity(new UrlEncodedFormEntity(nameValuePairs)); - } - - HttpResponse response = client.execute(request); - - HttpResponseWrapper responseWrapper = new HttpResponseWrapper(); - responseWrapper.setStatus(response.getStatusLine() - .getStatusCode()); - BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity() - .getContent())); - - String line = "", content = ""; - while ((line = in.readLine()) != null) { - content += line; - } - responseWrapper.setContent(content); - return responseWrapper; - } catch (ClientProtocolException e) { - e.printStackTrace(); - return null; - } catch (IOException e) { - e.printStackTrace(); - return null; - } - } - - public HttpResponseWrapper sendPostRequestWithJson(String url, String json) { - HttpClient client = HttpClientBuilder.create() - .build(); - HttpPost request = new HttpPost(url); - - try { - request.addHeader("Content-Type", "application/json"); - request.setEntity(new StringEntity(json)); - - HttpResponse response = client.execute(request); - - HttpResponseWrapper responseWrapper = new HttpResponseWrapper(); - responseWrapper.setStatus(response.getStatusLine() - .getStatusCode()); - BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity() - .getContent())); - - String line = "", content = ""; - while ((line = in.readLine()) != null) { - content += line; - } - responseWrapper.setContent(content); - return responseWrapper; - } catch (ClientProtocolException e) { - e.printStackTrace(); - return null; - } catch (IOException e) { - e.printStackTrace(); - return null; - } - } - -} diff --git a/libraries/src/test/java/com/baeldung/http/HttpRequestBuilderTest.java b/libraries/src/test/java/com/baeldung/http/HttpRequestBuilderTest.java deleted file mode 100644 index 7f5992fbd9..0000000000 --- a/libraries/src/test/java/com/baeldung/http/HttpRequestBuilderTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.http; - -import org.junit.Test; -import static org.junit.Assert.*; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Before; - -import java.io.IOException; - -public class HttpRequestBuilderTest { - - private HttpRequestBuilder requestPerformer; - - @Before - public void setup() { - requestPerformer = new HttpRequestBuilder(); - } - - @Test - public void whenGetRequest_thenOk() throws IOException { - HttpResponseWrapper response = requestPerformer.sendRequest("http://www.example.com", "GET", null, null); - assertEquals("status code incorrect", response.getStatus(), 200); - assertTrue("content incorrect", response.getContent() - .contains("Example Domain")); - } - - @Test - public void whenPostRequest_thenOk() throws IOException { - Map parameters = new HashMap<>(); - parameters.put("param1", "val"); - Map properties = new HashMap<>(); - properties.put("Content-Type", "application/json"); - HttpResponseWrapper response = requestPerformer.sendRequest("http://www.example.com", "POST", parameters, properties); - assertEquals("status code incorrect", response.getStatus(), 200); - } - -} diff --git a/libraries/src/test/java/com/baeldung/httpclient/HttpClientRequestBuilderTest.java b/libraries/src/test/java/com/baeldung/httpclient/HttpClientRequestBuilderTest.java deleted file mode 100644 index 886d2649a3..0000000000 --- a/libraries/src/test/java/com/baeldung/httpclient/HttpClientRequestBuilderTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.httpclient; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.http.HttpResponseWrapper; - -public class HttpClientRequestBuilderTest { - private HttpClientRequestBuilder requestBuilder; - - @Before - public void setup() { - requestBuilder = new HttpClientRequestBuilder(); - } - - @Test - public void whenGetRequest_thenOk() { - Map parameters = new HashMap<>(); - parameters.put("param1", "val"); - HttpResponseWrapper response = requestBuilder.sendGetRequest("http://www.example.com",parameters); - assertEquals("status code incorrect", response.getStatus(), 200); - assertTrue("content incorrect", response.getContent() - .contains("Example Domain")); - } - - @Test - public void whenPostRequestWithParameters_thenOk() { - Map parameters = new HashMap<>(); - parameters.put("param1", "val"); - HttpResponseWrapper response = requestBuilder.sendPostRequestWithParameters("http://www.example.com", parameters); - assertEquals("status code incorrect", response.getStatus(), 200); - } - - @Test - public void whenPostRequestWithJson_thenOk() { - String json = "{\"id\":\"1\"}"; - HttpResponseWrapper response = requestBuilder.sendPostRequestWithJson("http://www.example.com",json); - assertEquals("status code incorrect", response.getStatus(), 200); - } -} From 01cad343f7eac74686d5acd19037e7866e05469f Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Fri, 28 Apr 2017 17:02:08 +0200 Subject: [PATCH 07/30] Bael 851 mapped byte buffer (#1742) * BAEL-851 code for the MappedByteBuffer * BAEL-851 formatting * SetTest refactor (#1724) * Bael 850 (#1744) * BAEL-850 ConcurentskipLIst * BAEL-850 formatting * BAEL-850 Formatting * spring 5 work * SetTest refactor (#1724) * BAEL-850 use lambda * BAEL-850 no need to casting * Build optimization (#1746) * Build optimization * Build optimization * [BAEL-820] Difference between wait() and sleep() in Java (#1708) * injecting beans * XML-based configuration replaced with Java Config. * [BAEL-431] Exploring TestRestTemplate. * Revert of evaluation task "XML-based configuration replaced with Java Config." This reverts commit 66471cf0574c85f8ff514ec4caf5ba44ebba1a74. * Revert of evaluation task "injecting beans" This reverts commit d2ac20185e636245bc0ae0b4ccb952965de88e28. * [BAEL-431] fix to the tests in TestRestTemplateBasicLiveTest. * [BAEL-431] added more meaningful user and password for auth. * [BAEL-820] examples of wait() and sleep() methods. * [BAEL-820] wait() and sleep() examples. * remove utility classes (#1733) * remove utility classes * remove httpclient, extend http * move code to core-java --- .../MappedByteBufferTest.java | 68 +++++++++++++++++++ core-java/src/test/resources/fileToRead.txt | 1 + .../src/test/resources/fileToWriteTo.txt | 0 3 files changed, 69 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferTest.java create mode 100644 core-java/src/test/resources/fileToRead.txt create mode 100644 core-java/src/test/resources/fileToWriteTo.txt diff --git a/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferTest.java b/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferTest.java new file mode 100644 index 0000000000..4064d38267 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferTest.java @@ -0,0 +1,68 @@ +package com.baeldung.mappedbytebuffer; + +import org.junit.Test; + +import java.nio.CharBuffer; +import java.nio.MappedByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.EnumSet; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class MappedByteBufferTest { + + + @Test + public void givenFileChannel_whenReadToTheMappedByteBuffer_thenShouldSuccess() throws Exception { + //given + CharBuffer charBuffer = null; + Path pathToRead = getFileURIFromResources("fileToRead.txt"); + + //when + try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToRead, EnumSet.of(StandardOpenOption.READ))) { + MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size()); + + if (mappedByteBuffer != null) { + charBuffer = Charset.forName("UTF-8").decode(mappedByteBuffer); + } + } + + //then + assertNotNull(charBuffer); + assertEquals(charBuffer.toString(), "This is a content of the file"); + } + + @Test + public void givenPath_whenWriteToItUsingMappedByteBuffer_thenShouldSuccessfullyWrite() throws Exception { + //given + CharBuffer charBuffer = CharBuffer.wrap("This will be written to the file"); + Path pathToWrite = getFileURIFromResources("fileToWriteTo.txt"); + + //when + try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToWrite, + EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) { + MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, charBuffer.length()); + + if (mappedByteBuffer != null) { + mappedByteBuffer.put(Charset.forName("utf-8").encode(charBuffer)); + } + } + + //then + List fileContent = Files.readAllLines(pathToWrite); + assertEquals(fileContent.get(0), "This will be written to the file"); + + } + + public Path getFileURIFromResources(String fileName) throws Exception { + ClassLoader classLoader = getClass().getClassLoader(); + return Paths.get(classLoader.getResource(fileName).getPath()); + } +} diff --git a/core-java/src/test/resources/fileToRead.txt b/core-java/src/test/resources/fileToRead.txt new file mode 100644 index 0000000000..45d73fa10d --- /dev/null +++ b/core-java/src/test/resources/fileToRead.txt @@ -0,0 +1 @@ +This is a content of the file \ No newline at end of file diff --git a/core-java/src/test/resources/fileToWriteTo.txt b/core-java/src/test/resources/fileToWriteTo.txt new file mode 100644 index 0000000000..e69de29bb2 From 9a3df1fe7675868415d6f627913950e03273f514 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Fri, 28 Apr 2017 19:33:06 +0200 Subject: [PATCH 08/30] Bael 856 long adder (#1748) * BAEL-856 code for long adder and accumulator * BAEL-856 rearange packages * BAEL-856 Formatting * BAEL-850 accumulator accumulates values * BAEL-881 use Long::sum --- .../concurrent/accumulator/LongAccumulatorTest.java | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorTest.java b/core-java/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorTest.java index 46e107b607..3a0092cf24 100644 --- a/core-java/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorTest.java +++ b/core-java/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorTest.java @@ -17,25 +17,26 @@ public class LongAccumulatorTest { public void givenLongAccumulator_whenApplyActionOnItFromMultipleThrads_thenShouldProduceProperResult() throws InterruptedException { //given ExecutorService executorService = Executors.newFixedThreadPool(8); - LongBinaryOperator higherValueFinder = (currentValue, previousValue) -> currentValue > previousValue ? currentValue : previousValue; - LongAccumulator accumulator = new LongAccumulator(higherValueFinder, 0L); - + LongBinaryOperator sum = Long::sum; + LongAccumulator accumulator = new LongAccumulator(sum, 0L); int numberOfThreads = 4; int numberOfIncrements = 100; //when Runnable accumulateAction = () -> IntStream - .rangeClosed(0, numberOfIncrements) - .forEach(accumulator::accumulate); + .rangeClosed(0, numberOfIncrements) + .forEach(accumulator::accumulate); for (int i = 0; i < numberOfThreads; i++) { executorService.execute(accumulateAction); } + //then executorService.awaitTermination(500, TimeUnit.MILLISECONDS); executorService.shutdown(); + assertEquals(accumulator.get(), 20200); + - assertEquals(accumulator.get(), 100); } } From 68190482b4a1e1ce627c5f1af2d100bee7af0516 Mon Sep 17 00:00:00 2001 From: Sunil Mogadati Date: Fri, 28 Apr 2017 14:30:40 -0600 Subject: [PATCH 09/30] Add link to JAX-WS article in Readme (#1749) --- jee7/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/jee7/README.md b/jee7/README.md index 8381bcbf34..fdd260468c 100644 --- a/jee7/README.md +++ b/jee7/README.md @@ -2,3 +2,4 @@ - [Scheduling in Java EE](http://www.baeldung.com/scheduling-in-java-enterprise-edition) - [JSON Processing in Java EE 7](http://www.baeldung.com/jee7-json) - [Converters, Listeners and Validators in Java EE 7](http://www.baeldung.com/java-ee7-converter-listener-validator) +- [Introduction to JAX-WS](http://www.baeldung.com/jax-ws) From 0f300ece2e099cff9c29e7f6004dbb8a05ff7e39 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sat, 29 Apr 2017 20:10:52 +0200 Subject: [PATCH 10/30] JDO -> Integration (#1752) * JDOIntegration * JDOIntegration --- ...st.java => GuideToJDOIntegrationTest.java} | 26 +++++++++---------- 1 file changed, 12 insertions(+), 14 deletions(-) rename core-java/src/test/java/com/baeldung/jdo/{GuideToJDOTest.java => GuideToJDOIntegrationTest.java} (97%) diff --git a/core-java/src/test/java/com/baeldung/jdo/GuideToJDOTest.java b/core-java/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java similarity index 97% rename from core-java/src/test/java/com/baeldung/jdo/GuideToJDOTest.java rename to core-java/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java index b8a8d2adb3..65f89d75b2 100644 --- a/core-java/src/test/java/com/baeldung/jdo/GuideToJDOTest.java +++ b/core-java/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java @@ -1,21 +1,20 @@ package com.baeldung.jdo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.util.Iterator; -import java.util.List; - -import javax.jdo.PersistenceManager; -import javax.jdo.PersistenceManagerFactory; -import javax.jdo.Query; -import javax.jdo.Transaction; - import org.datanucleus.api.jdo.JDOPersistenceManagerFactory; import org.datanucleus.metadata.PersistenceUnitMetaData; import org.junit.Test; -public class GuideToJDOTest { +import javax.jdo.PersistenceManager; +import javax.jdo.PersistenceManagerFactory; +import javax.jdo.Query; +import javax.jdo.Transaction; +import java.util.Iterator; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +public class GuideToJDOIntegrationTest { @Test public void givenProduct_WhenNewThenPerformTransaction() { PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null); @@ -34,8 +33,7 @@ public class GuideToJDOTest { tx.begin(); for (int i = 0; i < 100; i++){ String nam = "Product-" + i; - double price = i; - Product productx = new Product(nam, price); + Product productx = new Product(nam, (double) i); pm.makePersistent(productx); } tx.commit(); From 594920af9beeb52ff38fa7479fa7b20f663bafec Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Sat, 29 Apr 2017 13:36:05 -0500 Subject: [PATCH 11/30] BAEL-828 README (#1751) * Add files via upload * Update pom.xml * Update RunGuice.java * Update Communication.java * Update CommunicationMode.java * Update DefaultCommunicator.java * Update EmailCommunicationMode.java * Update IMCommunicationMode.java * Update SMSCommunicationMode.java * Update MessageLogger.java * Update MessageSentLoggable.java * Update AOPModule.java * Update BasicModule.java * Update CommunicationModel.java * Update Communicator.java * Update BasicModule.java * Update RunGuice.java * Update MessageLogger.java * Update Communicator.java * Update pom.xml * BAEL-278: Updated README.md * BAEL-554: Add and update README.md files * Update pom.xml * Update pom.xml * Update pom.xml * BAEL-345: fixed assertion * BAEL-109: Updated README.md * BAEL-345: Added README.md * Reinstating reactor-core module in root-level pom * BAEL-393: Adding guide-intro module to root pom * BAEL-9: Updated README.md * BAEL-157: README.md updated * Changed project name * Update RunGuice.java Removed references to message logging and output * Update Communication.java Removed message logging-related code * BAEL-566: Updated README.md * New project name * BAEL-393: removing guice-intro directory * BAEL-393: renamed module guice-intro to guice in root pom.xml * BAEL-393 and BAEL-541 README.md files * BAEL-731: Updated README.md * BAEL-680: renamed test methods * BAEL-714: Updated README.md * BAEL-737: Updated README.md * BAEL-680 and BAEL-756 README.md updates * BAEL-666: Updated README * BAEL-415: Custom Scope * BAEL-415: Custom Scope - renamed classes to reflect TenantScope * README file updates for BAEL-723, BAEL-763, and BAEL-415 * BAEL-735: README * BAEL-567: README * BAEL-736: README * BAEL-766: Update README * BAEL-555: README update * BAEL-761: README update * BAEL-742: Stripe API for Java README file * BAEL-86: Correction to README file * BAEL-828: Updated README.md * BAEL-830: Updated README --- core-java/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core-java/README.md b/core-java/README.md index 910e0fbbec..56dee29899 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -98,3 +98,5 @@ - [Quick Guide to the Java StringTokenizer](http://www.baeldung.com/java-stringtokenizer) - [JVM Log Forging](http://www.baeldung.com/jvm-log-forging) - [Guide to sun.misc.Unsafe](http://www.baeldung.com/java-unsafe) +- [HashSet and TreeSet Comparison](http://www.baeldung.com/java-hashset-vs-treeset) +- [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request) From 772002f3ad751e3d43e80e2145716917bc56d24a Mon Sep 17 00:00:00 2001 From: Danil Kornishev Date: Sat, 29 Apr 2017 14:36:53 -0400 Subject: [PATCH 12/30] Dynamic Proxy (#1702) --- .../DynamicInvocationHandler.java | 19 +++++++ .../TimingDynamicInvocationHandler.java | 36 ++++++++++++ .../dynamicproxy/DynamicProxyTest.java | 57 +++++++++++++++++++ 3 files changed, 112 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/dynamicproxy/DynamicInvocationHandler.java create mode 100644 core-java/src/main/java/com/baeldung/dynamicproxy/TimingDynamicInvocationHandler.java create mode 100644 core-java/src/test/java/com/baeldung/dynamicproxy/DynamicProxyTest.java diff --git a/core-java/src/main/java/com/baeldung/dynamicproxy/DynamicInvocationHandler.java b/core-java/src/main/java/com/baeldung/dynamicproxy/DynamicInvocationHandler.java new file mode 100644 index 0000000000..8bde2f703f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/dynamicproxy/DynamicInvocationHandler.java @@ -0,0 +1,19 @@ +package com.baeldung.dynamicproxy; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; + +public class DynamicInvocationHandler implements InvocationHandler { + + private static Logger LOGGER = LoggerFactory.getLogger(DynamicInvocationHandler.class); + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + LOGGER.info("Invoked method: {}", method.getName()); + + return 42; + } +} diff --git a/core-java/src/main/java/com/baeldung/dynamicproxy/TimingDynamicInvocationHandler.java b/core-java/src/main/java/com/baeldung/dynamicproxy/TimingDynamicInvocationHandler.java new file mode 100644 index 0000000000..942efc50cc --- /dev/null +++ b/core-java/src/main/java/com/baeldung/dynamicproxy/TimingDynamicInvocationHandler.java @@ -0,0 +1,36 @@ +package com.baeldung.dynamicproxy; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TimingDynamicInvocationHandler implements InvocationHandler { + + private static Logger LOGGER = LoggerFactory.getLogger(TimingDynamicInvocationHandler.class); + private final Map methods = new HashMap<>(); + + private Object target; + + public TimingDynamicInvocationHandler(Object target) { + this.target = target; + + for(Method method: target.getClass().getDeclaredMethods()) { + this.methods.put(method.getName(), method); + } + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + long start = System.nanoTime(); + Object result = methods.get(method.getName()).invoke(target, args); + long elapsed = System.nanoTime() - start; + + LOGGER.info("Executing {} finished in {} ns", method.getName(), elapsed); + + return result; + } +} diff --git a/core-java/src/test/java/com/baeldung/dynamicproxy/DynamicProxyTest.java b/core-java/src/test/java/com/baeldung/dynamicproxy/DynamicProxyTest.java new file mode 100644 index 0000000000..4386b11797 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/dynamicproxy/DynamicProxyTest.java @@ -0,0 +1,57 @@ +package com.baeldung.dynamicproxy; + +import org.junit.Test; + +import java.lang.reflect.Proxy; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.testng.Assert.fail; + +public class DynamicProxyTest { + + @Test + public void givenDynamicProxy_thenPutWorks() { + Map proxyInstance = (Map) Proxy.newProxyInstance(DynamicProxyTest.class.getClassLoader(), new Class[] { Map.class }, new DynamicInvocationHandler()); + + proxyInstance.put("hello", "world"); + } + + @Test + public void givenInlineDynamicProxy_thenGetWorksOtherMethodsDoNot() { + Map proxyInstance = (Map) Proxy.newProxyInstance(DynamicProxyTest.class.getClassLoader(), new Class[] { Map.class }, (proxy, method, methodArgs) -> { + + if (method.getName().equals("get")) { + return 42; + } else { + throw new UnsupportedOperationException("Unsupported method: " + method.getName()); + } + }); + + int result = (int) proxyInstance.get("hello"); + + assertEquals(42, result); + + try { + proxyInstance.put("hello", "world"); + fail(); + } catch(UnsupportedOperationException e) { + // expected + } + } + + @Test + public void givenTimingDynamicProxy_thenMethodInvokationsProduceTiming() { + Map mapProxyInstance = (Map) Proxy.newProxyInstance(DynamicProxyTest.class.getClassLoader(), new Class[] { Map.class }, new TimingDynamicInvocationHandler(new HashMap<>())); + + mapProxyInstance.put("hello", "world"); + assertEquals("world", mapProxyInstance.get("hello")); + + CharSequence csProxyInstance = (CharSequence) Proxy.newProxyInstance(DynamicProxyTest.class.getClassLoader(), new Class[] { CharSequence.class }, new TimingDynamicInvocationHandler("Hello World")); + + assertEquals('l', csProxyInstance.charAt(2)); + assertEquals(11, csProxyInstance.length()); + } + +} From b9484b244b683f54882bba6d59f82ed75867f801 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Sun, 30 Apr 2017 08:21:11 +0200 Subject: [PATCH 13/30] BAEL-881 copyOnWriteArrayList tests (#1750) --- .../copyonwrite/CopyOnWriteArrayListTest.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListTest.java diff --git a/core-java/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListTest.java b/core-java/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListTest.java new file mode 100644 index 0000000000..c71c193372 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListTest.java @@ -0,0 +1,53 @@ +package com.baeldung.concurrent.copyonwrite; + + +import org.junit.Test; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import static org.assertj.core.api.Assertions.assertThat; + + +public class CopyOnWriteArrayListTest { + + @Test + public void givenCopyOnWriteList_whenIterateAndAddElementToUnderneathList_thenShouldNotChangeIterator() { + //given + final CopyOnWriteArrayList numbers = + new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8}); + + //when + Iterator iterator = numbers.iterator(); + numbers.add(10); + + //then + List result = new LinkedList<>(); + iterator.forEachRemaining(result::add); + assertThat(result).containsOnly(1, 3, 5, 8); + + //and + Iterator iterator2 = numbers.iterator(); + List result2 = new LinkedList<>(); + iterator2.forEachRemaining(result2::add); + + //then + assertThat(result2).containsOnly(1, 3, 5, 8, 10); + + } + + @Test(expected = UnsupportedOperationException.class) + public void givenCopyOnWriteList_whenIterateOverItAndTryToRemoveElement_thenShouldThrowException() { + //given + final CopyOnWriteArrayList numbers = + new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8}); + + //when + Iterator iterator = numbers.iterator(); + while (iterator.hasNext()) { + iterator.remove(); + } + } +} From 0735c03154555c5946c292e111ed06dae51876cd Mon Sep 17 00:00:00 2001 From: lor6 Date: Sun, 30 Apr 2017 11:39:11 +0300 Subject: [PATCH 14/30] togglz aspect (#1743) * togglz aspect * formatting * trigger travis build --- spring-boot/pom.xml | 18 ++++ .../java/com/baeldung/toggle/Employee.java | 37 ++++++++ .../baeldung/toggle/EmployeeRepository.java | 7 ++ .../baeldung/toggle/FeatureAssociation.java | 12 +++ .../com/baeldung/toggle/FeaturesAspect.java | 27 ++++++ .../java/com/baeldung/toggle/MyFeatures.java | 23 +++++ .../com/baeldung/toggle/SalaryController.java | 20 +++++ .../com/baeldung/toggle/SalaryService.java | 19 +++++ .../com/baeldung/toggle/SecurityConfig.java | 33 ++++++++ .../baeldung/toggle/ToggleApplication.java | 17 ++++ .../baeldung/toggle/ToggleConfiguration.java | 28 +++++++ .../java/com/baeldung/toggle/ToggleTest.java | 84 +++++++++++++++++++ 12 files changed, 325 insertions(+) create mode 100644 spring-boot/src/main/java/com/baeldung/toggle/Employee.java create mode 100644 spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java create mode 100644 spring-boot/src/main/java/com/baeldung/toggle/FeatureAssociation.java create mode 100644 spring-boot/src/main/java/com/baeldung/toggle/FeaturesAspect.java create mode 100644 spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java create mode 100644 spring-boot/src/main/java/com/baeldung/toggle/SalaryController.java create mode 100644 spring-boot/src/main/java/com/baeldung/toggle/SalaryService.java create mode 100644 spring-boot/src/main/java/com/baeldung/toggle/SecurityConfig.java create mode 100644 spring-boot/src/main/java/com/baeldung/toggle/ToggleApplication.java create mode 100644 spring-boot/src/main/java/com/baeldung/toggle/ToggleConfiguration.java create mode 100644 spring-boot/src/test/java/com/baeldung/toggle/ToggleTest.java diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index b00af7fc94..dfecbc8e29 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -40,6 +40,11 @@ org.springframework.boot spring-boot-starter-security + + + org.springframework.security + spring-security-test + org.springframework.boot @@ -125,6 +130,18 @@ mysql-connector-java 6.0.6 + + + org.togglz + togglz-spring-boot-starter + ${togglz.version} + + + + org.togglz + togglz-spring-security + ${togglz.version} + @@ -262,6 +279,7 @@ 3.1.7 8.5.11 1.4.194 + 2.4.1.Final diff --git a/spring-boot/src/main/java/com/baeldung/toggle/Employee.java b/spring-boot/src/main/java/com/baeldung/toggle/Employee.java new file mode 100644 index 0000000000..64a8b3ce5b --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/toggle/Employee.java @@ -0,0 +1,37 @@ +package com.baeldung.toggle; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Employee { + + @Id + private long id; + private double salary; + + public Employee() { + } + + public Employee(long id, double salary) { + this.id = id; + this.salary = salary; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java b/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java new file mode 100644 index 0000000000..7ea7c11fde --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.toggle; + +import org.springframework.data.repository.CrudRepository; + +public interface EmployeeRepository extends CrudRepository{ + +} diff --git a/spring-boot/src/main/java/com/baeldung/toggle/FeatureAssociation.java b/spring-boot/src/main/java/com/baeldung/toggle/FeatureAssociation.java new file mode 100644 index 0000000000..4578b8498e --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/toggle/FeatureAssociation.java @@ -0,0 +1,12 @@ +package com.baeldung.toggle; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.METHOD, ElementType.TYPE }) +public @interface FeatureAssociation { + MyFeatures value(); +} diff --git a/spring-boot/src/main/java/com/baeldung/toggle/FeaturesAspect.java b/spring-boot/src/main/java/com/baeldung/toggle/FeaturesAspect.java new file mode 100644 index 0000000000..9bc643fccc --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/toggle/FeaturesAspect.java @@ -0,0 +1,27 @@ +package com.baeldung.toggle; + +import org.apache.log4j.Logger; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.springframework.stereotype.Component; + +@Aspect +@Component +public class FeaturesAspect { + + private static final Logger LOG = Logger.getLogger(FeaturesAspect.class); + + @Around(value = "@within(featureAssociation) || @annotation(featureAssociation)") + public Object checkAspect(ProceedingJoinPoint joinPoint, FeatureAssociation featureAssociation) throws Throwable { + if (featureAssociation.value() + .isActive()) { + return joinPoint.proceed(); + } else { + LOG.info("Feature " + featureAssociation.value() + .name() + " is not enabled!"); + return null; + } + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java b/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java new file mode 100644 index 0000000000..e19d302c76 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java @@ -0,0 +1,23 @@ +package com.baeldung.toggle; + +import org.togglz.core.Feature; +import org.togglz.core.activation.UserRoleActivationStrategy; +import org.togglz.core.annotation.ActivationParameter; +import org.togglz.core.annotation.DefaultActivationStrategy; +import org.togglz.core.annotation.EnabledByDefault; +import org.togglz.core.annotation.Label; +import org.togglz.core.context.FeatureContext; + +public enum MyFeatures implements Feature { + + @Label("Administrator Feature") + @EnabledByDefault + @DefaultActivationStrategy(id = UserRoleActivationStrategy.ID, parameters = { @ActivationParameter(name = UserRoleActivationStrategy.PARAM_ROLES_NAME, value = "ROLE_ADMIN") }) + ADMIN_FEATURE; + + public boolean isActive() { + return FeatureContext.getFeatureManager() + .isActive(this); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/toggle/SalaryController.java b/spring-boot/src/main/java/com/baeldung/toggle/SalaryController.java new file mode 100644 index 0000000000..5d72f0105a --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/toggle/SalaryController.java @@ -0,0 +1,20 @@ +package com.baeldung.toggle; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +public class SalaryController { + + @Autowired + SalaryService salaryService; + + @PostMapping(value = "/increaseSalary") + @ResponseBody + public void increaseSalary(@RequestParam long id) { + salaryService.increaseSalary(id); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/toggle/SalaryService.java b/spring-boot/src/main/java/com/baeldung/toggle/SalaryService.java new file mode 100644 index 0000000000..4ea4a2ab35 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/toggle/SalaryService.java @@ -0,0 +1,19 @@ +package com.baeldung.toggle; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class SalaryService { + + @Autowired + EmployeeRepository employeeRepository; + + @FeatureAssociation(value = MyFeatures.ADMIN_FEATURE) + public void increaseSalary(long id) { + Employee employee = employeeRepository.findOne(id); + employee.setSalary(employee.getSalary() + employee.getSalary() * 0.1); + employeeRepository.save(employee); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/toggle/SecurityConfig.java b/spring-boot/src/main/java/com/baeldung/toggle/SecurityConfig.java new file mode 100644 index 0000000000..f558ccb0e1 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/toggle/SecurityConfig.java @@ -0,0 +1,33 @@ +package com.baeldung.toggle; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + //@formatter:off + auth.inMemoryAuthentication() + .withUser("user").password("pass").roles("USER") + .and() + .withUser("admin").password("pass").roles("ADMIN"); + //@formatter:on + } + + @Override + public void configure(HttpSecurity http) throws Exception { + //@formatter:off + http.authorizeRequests().antMatchers("/increaseSalary").permitAll() + .and() + .csrf().disable() + .httpBasic(); + //@formatter:on + } +} diff --git a/spring-boot/src/main/java/com/baeldung/toggle/ToggleApplication.java b/spring-boot/src/main/java/com/baeldung/toggle/ToggleApplication.java new file mode 100644 index 0000000000..c269262ab2 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/toggle/ToggleApplication.java @@ -0,0 +1,17 @@ +package com.baeldung.toggle; + +import javax.annotation.security.RolesAllowed; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +import com.baeldung.autoconfiguration.MySQLAutoconfiguration; + +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) +public class ToggleApplication { + @RolesAllowed("*") + public static void main(String[] args) { + System.setProperty("security.basic.enabled", "false"); + SpringApplication.run(ToggleApplication.class, args); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/toggle/ToggleConfiguration.java b/spring-boot/src/main/java/com/baeldung/toggle/ToggleConfiguration.java new file mode 100644 index 0000000000..3ae6abcbc9 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/toggle/ToggleConfiguration.java @@ -0,0 +1,28 @@ +package com.baeldung.toggle; + +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.togglz.core.manager.EnumBasedFeatureProvider; +import org.togglz.core.spi.FeatureProvider; +import org.togglz.core.user.UserProvider; +import org.togglz.spring.security.SpringSecurityUserProvider; + +@Configuration +@EnableJpaRepositories("com.baeldung.toggle") +@EntityScan("com.baeldung.toggle") +public class ToggleConfiguration { + + @Bean + public FeatureProvider featureProvider() { + return new EnumBasedFeatureProvider(MyFeatures.class); + } + + @Bean + public UserProvider userProvider() { + return new SpringSecurityUserProvider("admin"); + } +} diff --git a/spring-boot/src/test/java/com/baeldung/toggle/ToggleTest.java b/spring-boot/src/test/java/com/baeldung/toggle/ToggleTest.java new file mode 100644 index 0000000000..fa51d19e3a --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/toggle/ToggleTest.java @@ -0,0 +1,84 @@ +package com.baeldung.toggle; + +import static org.junit.Assert.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.security.web.FilterChainProxy; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = ToggleApplication.class) +@AutoConfigureMockMvc +public class ToggleTest { + + @Autowired + SalaryService salaryService; + + @Autowired + EmployeeRepository employeeRepository; + + @Autowired + private MockMvc mvc; + + @Autowired + private WebApplicationContext wac; + + @Autowired + private FilterChainProxy springSecurityFilterChain; + + @Before + public void setup() { + this.mvc = MockMvcBuilders.webAppContextSetup(this.wac) + .addFilter(springSecurityFilterChain) + .build(); + } + + @Test + public void givenNoAuthentication_whenIncreaseSalary_thenNoIncrease() throws Exception { + Employee emp = new Employee(1, 2000); + employeeRepository.save(emp); + mvc.perform(post("/increaseSalary").param("id", emp.getId() + "")) + .andExpect(status().is(200)); + + emp = employeeRepository.findOne(1L); + assertEquals("salary incorrect", 2000, emp.getSalary(), 0.5); + } + + @Test + public void givenAdminAuthentication_whenIncreaseSalary_thenIncrease() throws Exception { + Employee emp = new Employee(1, 2000); + employeeRepository.save(emp); + mvc.perform(post("/increaseSalary").param("id", emp.getId() + "") + .with(httpBasic("admin", "pass"))) + .andExpect(status().is(200)); + + emp = employeeRepository.findOne(1L); + assertEquals("salary incorrect", 2200, emp.getSalary(), 0.5); + } + + @Test + public void givenUserAuthentication_whenIncreaseSalary_thenNoIncrease() throws Exception { + Employee emp = new Employee(1, 2000); + employeeRepository.save(emp); + mvc.perform(post("/increaseSalary").param("id", emp.getId() + "") + .with(httpBasic("user", "pass"))) + .andExpect(status().is(200)); + + emp = employeeRepository.findOne(1L); + assertEquals("salary incorrect", 2000, emp.getSalary(), 0.5); + } + +} From f5f3e48f61a9f60cde36058428bc96b0b95769ff Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 30 Apr 2017 19:05:57 +0200 Subject: [PATCH 15/30] Update and rename ToggleTest.java to ToggleIntegrationTest.java (#1755) --- .../toggle/{ToggleTest.java => ToggleIntegrationTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename spring-boot/src/test/java/com/baeldung/toggle/{ToggleTest.java => ToggleIntegrationTest.java} (98%) diff --git a/spring-boot/src/test/java/com/baeldung/toggle/ToggleTest.java b/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java similarity index 98% rename from spring-boot/src/test/java/com/baeldung/toggle/ToggleTest.java rename to spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java index fa51d19e3a..34341c310c 100644 --- a/spring-boot/src/test/java/com/baeldung/toggle/ToggleTest.java +++ b/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java @@ -22,7 +22,7 @@ import static org.springframework.security.test.web.servlet.request.SecurityMock @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = ToggleApplication.class) @AutoConfigureMockMvc -public class ToggleTest { +public class ToggleIntegrationTest { @Autowired SalaryService salaryService; From a2b327cc9d6de0640e5147e9bde3648fabf550c1 Mon Sep 17 00:00:00 2001 From: Jesus Boadas Date: Sun, 30 Apr 2017 13:26:23 -0400 Subject: [PATCH 16/30] Move JDO from core-java to libraries (#1758) --- core-java/pom.xml | 54 ------------------- {core-java => libraries}/log4j.properties | 0 libraries/pom.xml | 53 +++++++++++++++++- .../java/com/baeldung/jdo/GuideToJDO.java | 0 .../main/java/com/baeldung/jdo/Product.java | 0 .../jdo/GuideToJDOIntegrationTest.java | 0 6 files changed, 52 insertions(+), 55 deletions(-) rename {core-java => libraries}/log4j.properties (100%) rename {core-java => libraries}/src/main/java/com/baeldung/jdo/GuideToJDO.java (100%) rename {core-java => libraries}/src/main/java/com/baeldung/jdo/Product.java (100%) rename {core-java => libraries}/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java (100%) diff --git a/core-java/pom.xml b/core-java/pom.xml index 4ee3efb297..67126d3dbf 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -177,37 +177,6 @@ - - - org.datanucleus - javax.jdo - 3.2.0-m6 - - - org.datanucleus - datanucleus-core - 5.1.0-m1 - - - org.datanucleus - datanucleus-api-jdo - 5.1.0-m1 - - - org.datanucleus - datanucleus-rdbms - 5.1.0-m1 - - - org.datanucleus - datanucleus-maven-plugin - 5.0.2 - - - com.h2database - h2 - 1.4.194 - org.owasp.esapi @@ -358,29 +327,6 @@ - - - - - org.datanucleus - datanucleus-maven-plugin - 5.0.2 - - JDO - ${basedir}/datanucleus.properties - ${basedir}/log4j.properties - true - - - - process-classes - - enhance - - - - - diff --git a/core-java/log4j.properties b/libraries/log4j.properties similarity index 100% rename from core-java/log4j.properties rename to libraries/log4j.properties diff --git a/libraries/pom.xml b/libraries/pom.xml index 021e081eb5..e329eac44d 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -59,6 +59,26 @@ + + + org.datanucleus + datanucleus-maven-plugin + 5.0.2 + + JDO + ${basedir}/datanucleus.properties + ${basedir}/log4j.properties + true + + + + process-classes + + enhance + + + + @@ -200,6 +220,37 @@ jackson-databind ${jackson.version} + + + org.datanucleus + javax.jdo + 3.2.0-m6 + + + org.datanucleus + datanucleus-core + 5.1.0-m1 + + + org.datanucleus + datanucleus-api-jdo + 5.1.0-m1 + + + org.datanucleus + datanucleus-rdbms + 5.1.0-m1 + + + org.datanucleus + datanucleus-maven-plugin + 5.0.2 + + + com.h2database + h2 + 1.4.194 + @@ -227,4 +278,4 @@ 2.19.1 - \ No newline at end of file + diff --git a/core-java/src/main/java/com/baeldung/jdo/GuideToJDO.java b/libraries/src/main/java/com/baeldung/jdo/GuideToJDO.java similarity index 100% rename from core-java/src/main/java/com/baeldung/jdo/GuideToJDO.java rename to libraries/src/main/java/com/baeldung/jdo/GuideToJDO.java diff --git a/core-java/src/main/java/com/baeldung/jdo/Product.java b/libraries/src/main/java/com/baeldung/jdo/Product.java similarity index 100% rename from core-java/src/main/java/com/baeldung/jdo/Product.java rename to libraries/src/main/java/com/baeldung/jdo/Product.java diff --git a/core-java/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java b/libraries/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java rename to libraries/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java From 4aff9d33d99cd20c180f48fb6a1e063de248ad04 Mon Sep 17 00:00:00 2001 From: amilabanuka Date: Mon, 1 May 2017 04:10:12 +0800 Subject: [PATCH 17/30] BAEL-640: Guide to Mathematical Operations with Guava (#1754) * Added the Spring Core dependency Injection methods source code * Added test cases for dependency Injection type demo * Added Guava Math operation test * reverted the evaluation article code * reverted evaluation article * Removed evaluation article code --- .../guava/GuavaBigIntegerMathTest.java | 112 +++++++ .../baeldung/guava/GuavaDoubleMathTest.java | 98 +++++++ .../org/baeldung/guava/GuavaIntMathTest.java | 274 ++++++++++++++++++ .../org/baeldung/guava/GuavaLongMathTest.java | 268 +++++++++++++++++ 4 files changed, 752 insertions(+) create mode 100644 guava/src/test/java/org/baeldung/guava/GuavaBigIntegerMathTest.java create mode 100644 guava/src/test/java/org/baeldung/guava/GuavaDoubleMathTest.java create mode 100644 guava/src/test/java/org/baeldung/guava/GuavaIntMathTest.java create mode 100644 guava/src/test/java/org/baeldung/guava/GuavaLongMathTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaBigIntegerMathTest.java b/guava/src/test/java/org/baeldung/guava/GuavaBigIntegerMathTest.java new file mode 100644 index 0000000000..4dd36fa58d --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/GuavaBigIntegerMathTest.java @@ -0,0 +1,112 @@ +package org.baeldung.guava; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.math.BigInteger; +import java.math.RoundingMode; + +import org.junit.Test; + +import com.google.common.math.BigIntegerMath; + +public class GuavaBigIntegerMathTest { + + @Test + public void whenPerformBinomialOnTwoIntValues_shouldReturnResult() { + BigInteger result = BigIntegerMath.binomial(6, 3); + assertEquals(new BigInteger("20"), result); + } + + @Test + public void whenProformCeilPowOfTwoBigIntegerValues_shouldReturnResult() { + BigInteger result = BigIntegerMath.ceilingPowerOfTwo(new BigInteger("20")); + assertEquals(new BigInteger("32"), result); + } + + @Test + public void whenDivideTwoBigIntegerValues_shouldDivideThemAndReturnTheResultForCeilingRounding() { + BigInteger result = BigIntegerMath.divide(new BigInteger("10"), new BigInteger("3"), RoundingMode.CEILING); + assertEquals(new BigInteger("4"), result); + } + + @Test + public void whenDivideTwoBigIntegerValues_shouldDivideThemAndReturnTheResultForFloorRounding() { + BigInteger result = BigIntegerMath.divide(new BigInteger("10"), new BigInteger("3"), RoundingMode.FLOOR); + assertEquals(new BigInteger("3"), result); + } + + @Test(expected = ArithmeticException.class) + public void whenDivideTwoBigIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { + BigIntegerMath.divide(new BigInteger("10"), new BigInteger("3"), RoundingMode.UNNECESSARY); + } + + @Test + public void whenFactorailInteger_shouldFactorialThemAndReturnTheResultIfInIntRange() { + BigInteger result = BigIntegerMath.factorial(5); + assertEquals(new BigInteger("120"), result); + } + + @Test + public void whenFloorPowerOfInteger_shouldReturnValue() { + BigInteger result = BigIntegerMath.floorPowerOfTwo(new BigInteger("30")); + assertEquals(new BigInteger("16"), result); + } + + @Test + public void whenIsPowOfInteger_shouldReturnTrueIfPowerOfTwo() { + boolean result = BigIntegerMath.isPowerOfTwo(new BigInteger("16")); + assertTrue(result); + } + + @Test + public void whenLog10BigIntegerValues_shouldLog10ThemAndReturnTheResultForCeilingRounding() { + int result = BigIntegerMath.log10(new BigInteger("30"), RoundingMode.CEILING); + assertEquals(2, result); + } + + @Test + public void whenLog10BigIntegerValues_shouldog10ThemAndReturnTheResultForFloorRounding() { + int result = BigIntegerMath.log10(new BigInteger("30"), RoundingMode.FLOOR); + assertEquals(1, result); + } + + @Test(expected = ArithmeticException.class) + public void whenLog10BigIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { + BigIntegerMath.log10(new BigInteger("30"), RoundingMode.UNNECESSARY); + } + + @Test + public void whenLog2BigIntegerValues_shouldLog2ThemAndReturnTheResultForCeilingRounding() { + int result = BigIntegerMath.log2(new BigInteger("30"), RoundingMode.CEILING); + assertEquals(5, result); + } + + @Test + public void whenLog2BigIntegerValues_shouldog2ThemAndReturnTheResultForFloorRounding() { + int result = BigIntegerMath.log2(new BigInteger("30"), RoundingMode.FLOOR); + assertEquals(4, result); + } + + @Test(expected = ArithmeticException.class) + public void whenLog2BigIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { + BigIntegerMath.log2(new BigInteger("30"), RoundingMode.UNNECESSARY); + } + + @Test + public void whenSqrtBigIntegerValues_shouldSqrtThemAndReturnTheResultForCeilingRounding() { + BigInteger result = BigIntegerMath.sqrt(new BigInteger("30"), RoundingMode.CEILING); + assertEquals(new BigInteger("6"), result); + } + + @Test + public void whenSqrtBigIntegerValues_shouldSqrtThemAndReturnTheResultForFloorRounding() { + BigInteger result = BigIntegerMath.sqrt(new BigInteger("30"), RoundingMode.FLOOR); + assertEquals(new BigInteger("5"), result); + } + + @Test(expected = ArithmeticException.class) + public void whenSqrtBigIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { + BigIntegerMath.sqrt(new BigInteger("30"), RoundingMode.UNNECESSARY); + } +} diff --git a/guava/src/test/java/org/baeldung/guava/GuavaDoubleMathTest.java b/guava/src/test/java/org/baeldung/guava/GuavaDoubleMathTest.java new file mode 100644 index 0000000000..ad06b37e36 --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/GuavaDoubleMathTest.java @@ -0,0 +1,98 @@ +package org.baeldung.guava; + +import static org.junit.Assert.*; + +import java.math.RoundingMode; + +import org.junit.Test; + +import com.google.common.math.DoubleMath; +import com.google.common.math.IntMath; + +public class GuavaDoubleMathTest { + + @Test + public void whenFactorailDouble_shouldFactorialThemAndReturnTheResultIfInDoubleRange() { + double result = DoubleMath.factorial(5); + assertEquals(120, result, 0); + } + + @Test + public void whenFactorailDouble_shouldFactorialThemAndReturnDoubkeInfIfNotInDoubletRange() { + double result = DoubleMath.factorial(Integer.MAX_VALUE); + assertEquals(Double.POSITIVE_INFINITY, result, 0); + } + + @Test + public void whenFuzzyCompareDouble_shouldReturnZeroIfInRange() { + int result = DoubleMath.fuzzyCompare(4, 4.05, 0.6); + assertEquals(0, result); + } + + @Test + public void whenFuzzyCompareDouble_shouldReturnNonZeroIfNotInRange() { + int result = DoubleMath.fuzzyCompare(4, 5, 0.1); + assertEquals(-1, result); + } + + @Test + public void whenFuzzyEqualDouble_shouldReturnZeroIfInRange() { + boolean result = DoubleMath.fuzzyEquals(4, 4.05, 0.6); + assertTrue(result); + } + + @Test + public void whenFuzzyEqualDouble_shouldReturnNonZeroIfNotInRange() { + boolean result = DoubleMath.fuzzyEquals(4, 5, 0.1); + assertFalse(result); + } + + @Test + public void whenMathematicalIntDouble_shouldReturnTrueIfInRange() { + boolean result = DoubleMath.isMathematicalInteger(5); + assertTrue(result); + } + + @Test + public void whenMathematicalIntDouble_shouldReturnFalseIfNotInRange() { + boolean result = DoubleMath.isMathematicalInteger(5.2); + assertFalse(result); + } + + @Test + public void whenIsPowerOfTwoDouble_shouldReturnTrueIfIsPowerOfTwo() { + boolean result = DoubleMath.isMathematicalInteger(4); + assertTrue(result); + } + + @Test + public void whenIsPowerOfTwoDouble_shouldReturnFalseIsNotPowerOfTwoe() { + boolean result = DoubleMath.isMathematicalInteger(5.2); + assertFalse(result); + } + + @Test + public void whenLog2Double_shouldReturnResult() { + double result = DoubleMath.log2(4); + assertEquals(2, result, 0); + } + + + @Test + public void whenLog2DoubleValues_shouldLog2ThemAndReturnTheResultForCeilingRounding() { + int result = DoubleMath.log2(30, RoundingMode.CEILING); + assertEquals(5, result); + } + + @Test + public void whenLog2DoubleValues_shouldog2ThemAndReturnTheResultForFloorRounding() { + int result = DoubleMath.log2(30, RoundingMode.FLOOR); + assertEquals(4, result); + } + + @Test(expected = ArithmeticException.class) + public void whenLog2DoubleValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { + DoubleMath.log2(30, RoundingMode.UNNECESSARY); + } + +} diff --git a/guava/src/test/java/org/baeldung/guava/GuavaIntMathTest.java b/guava/src/test/java/org/baeldung/guava/GuavaIntMathTest.java new file mode 100644 index 0000000000..9c8f3923d3 --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/GuavaIntMathTest.java @@ -0,0 +1,274 @@ +package org.baeldung.guava; + +import static org.junit.Assert.*; + +import java.math.RoundingMode; + +import com.google.common.math.IntMath; +import org.junit.Test; + +public class GuavaIntMathTest { + + @Test + public void whenPerformBinomialOnTwoIntegerValues_shouldReturnResultIfUnderInt() { + int result = IntMath.binomial(6, 3); + assertEquals(20, result); + } + + @Test + public void whenPerformBinomialOnTwoIntegerValues_shouldReturnIntMaxIfUnderInt() { + int result = IntMath.binomial(Integer.MAX_VALUE, 3); + assertEquals(Integer.MAX_VALUE, result); + } + + @Test + public void whenProformCeilPowOfTwoIntegerValues_shouldReturnResult() { + int result = IntMath.ceilingPowerOfTwo(20); + assertEquals(32, result); + } + + @Test + public void whenCheckedAddTwoIntegerValues_shouldAddThemAndReturnTheSumIfNotOverflow() { + int result = IntMath.checkedAdd(1, 2); + assertEquals(3, result); + } + + @Test(expected = ArithmeticException.class) + public void gwhenCheckedAddTwoIntegerValues_shouldThrowArithmeticExceptionIfOverflow() { + IntMath.checkedAdd(Integer.MAX_VALUE, 100); + } + + @Test + public void whenCheckedMultiplyTwoIntegerValues_shouldMultiplyThemAndReturnTheResultIfNotOverflow() { + int result = IntMath.checkedMultiply(1, 2); + assertEquals(2, result); + } + + @Test(expected = ArithmeticException.class) + public void gwhenCheckedMultiplyTwoIntegerValues_shouldThrowArithmeticExceptionIfOverflow() { + IntMath.checkedMultiply(Integer.MAX_VALUE, 100); + } + + @Test + public void whenCheckedPowTwoIntegerValues_shouldPowThemAndReturnTheResultIfNotOverflow() { + int result = IntMath.checkedPow(2, 3); + assertEquals(8, result); + } + + @Test(expected = ArithmeticException.class) + public void gwhenCheckedPowTwoIntegerValues_shouldThrowArithmeticExceptionIfOverflow() { + IntMath.checkedPow(Integer.MAX_VALUE, 100); + } + + @Test + public void whenCheckedSubstractTwoIntegerValues_shouldSubstractThemAndReturnTheResultIfNotOverflow() { + int result = IntMath.checkedSubtract(4, 1); + assertEquals(3, result); + } + + @Test(expected = ArithmeticException.class) + public void gwhenCheckedSubstractTwoIntegerValues_shouldThrowArithmeticExceptionIfOverflow() { + IntMath.checkedSubtract(Integer.MAX_VALUE, -100); + } + + @Test + public void whenDivideTwoIntegerValues_shouldDivideThemAndReturnTheResultForCeilingRounding() { + int result = IntMath.divide(10, 3, RoundingMode.CEILING); + assertEquals(4, result); + } + + @Test + public void whenDivideTwoIntegerValues_shouldDivideThemAndReturnTheResultForFloorRounding() { + int result = IntMath.divide(10, 3, RoundingMode.FLOOR); + assertEquals(3, result); + } + + @Test(expected = ArithmeticException.class) + public void whenDivideTwoIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { + IntMath.divide(10, 3, RoundingMode.UNNECESSARY); + } + + @Test + public void whenFactorailInteger_shouldFactorialThemAndReturnTheResultIfInIntRange() { + int result = IntMath.factorial(5); + assertEquals(120, result); + } + + @Test + public void whenFactorailInteger_shouldFactorialThemAndReturnIntMaxIfNotInIntRange() { + int result = IntMath.factorial(Integer.MAX_VALUE); + assertEquals(Integer.MAX_VALUE, result); + } + + @Test + public void whenFloorPowerOfInteger_shouldReturnValue() { + int result = IntMath.floorPowerOfTwo(30); + assertEquals(16, result); + } + + @Test + public void whenGcdOfTwoIntegers_shouldReturnValue() { + int result = IntMath.gcd(30, 40); + assertEquals(10, result); + } + + @Test + public void whenIsPowOfInteger_shouldReturnTrueIfPowerOfTwo() { + boolean result = IntMath.isPowerOfTwo(16); + assertTrue(result); + } + + @Test + public void whenIsPowOfInteger_shouldReturnFalseeIfNotPowerOfTwo() { + boolean result = IntMath.isPowerOfTwo(20); + assertFalse(result); + } + + @Test + public void whenIsPrineOfInteger_shouldReturnFalseeIfNotPrime() { + boolean result = IntMath.isPrime(20); + assertFalse(result); + } + + @Test + public void whenLog10IntegerValues_shouldLog10ThemAndReturnTheResultForCeilingRounding() { + int result = IntMath.log10(30, RoundingMode.CEILING); + assertEquals(2, result); + } + + @Test + public void whenLog10IntegerValues_shouldog10ThemAndReturnTheResultForFloorRounding() { + int result = IntMath.log10(30, RoundingMode.FLOOR); + assertEquals(1, result); + } + + @Test(expected = ArithmeticException.class) + public void whenLog10IntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { + IntMath.log10(30, RoundingMode.UNNECESSARY); + } + + @Test + public void whenLog2IntegerValues_shouldLog2ThemAndReturnTheResultForCeilingRounding() { + int result = IntMath.log2(30, RoundingMode.CEILING); + assertEquals(5, result); + } + + @Test + public void whenLog2IntegerValues_shouldog2ThemAndReturnTheResultForFloorRounding() { + int result = IntMath.log2(30, RoundingMode.FLOOR); + assertEquals(4, result); + } + + @Test(expected = ArithmeticException.class) + public void whenLog2IntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { + IntMath.log2(30, RoundingMode.UNNECESSARY); + } + + @Test + public void whenMeanTwoIntegerValues_shouldMeanThemAndReturnTheResult() { + int result = IntMath.mean(30, 20); + assertEquals(25, result); + } + + @Test + public void whenModTwoIntegerValues_shouldModThemAndReturnTheResult() { + int result = IntMath.mod(30, 4); + assertEquals(2, result); + } + + @Test + public void whenPowTwoIntegerValues_shouldPowThemAndReturnTheResult() { + int result = IntMath.pow(6, 4); + assertEquals(1296, result); + } + + @Test + public void whenSaturatedAddTwoIntegerValues_shouldAddThemAndReturnTheResult() { + int result = IntMath.saturatedAdd(6, 4); + assertEquals(10, result); + } + + @Test + public void whenSaturatedAddTwoIntegerValues_shouldAddThemAndReturnIntMaxIfOverflow() { + int result = IntMath.saturatedAdd(Integer.MAX_VALUE, 1000); + assertEquals(Integer.MAX_VALUE, result); + } + + @Test + public void whenSaturatedAddTwoIntegerValues_shouldAddThemAndReturnIntMinIfUnderflow() { + int result = IntMath.saturatedAdd(Integer.MIN_VALUE, -1000); + assertEquals(Integer.MIN_VALUE, result); + } + + @Test + public void whenSaturatedMultiplyTwoIntegerValues_shouldMultiplyThemAndReturnTheResult() { + int result = IntMath.saturatedMultiply(6, 4); + assertEquals(24, result); + } + + @Test + public void whenSaturatedMultiplyTwoIntegerValues_shouldMultiplyThemAndReturnIntMaxIfOverflow() { + int result = IntMath.saturatedMultiply(Integer.MAX_VALUE, 1000); + assertEquals(Integer.MAX_VALUE, result); + } + + @Test + public void whenSaturatedMultiplyTwoIntegerValues_shouldMultiplyThemAndReturnIntMinIfUnderflow() { + int result = IntMath.saturatedMultiply(Integer.MIN_VALUE, 1000); + assertEquals(Integer.MIN_VALUE, result); + } + + @Test + public void whenSaturatedPowTwoIntegerValues_shouldPowThemAndReturnTheResult() { + int result = IntMath.saturatedPow(6, 2); + assertEquals(36, result); + } + + @Test + public void whenSaturatedPowTwoIntegerValues_shouldPowThemAndReturnIntMaxIfOverflow() { + int result = IntMath.saturatedPow(Integer.MAX_VALUE, 2); + assertEquals(Integer.MAX_VALUE, result); + } + + @Test + public void whenSaturatedPowTwoIntegerValues_shouldPowThemAndReturnIntMinIfUnderflow() { + int result = IntMath.saturatedPow(Integer.MIN_VALUE, 3); + assertEquals(Integer.MIN_VALUE, result); + } + + @Test + public void whenSaturatedSubstractTwoIntegerValues_shouldSubstractThemAndReturnTheResult() { + int result = IntMath.saturatedSubtract(6, 2); + assertEquals(4, result); + } + + @Test + public void whenSaturatedSubstractTwoIntegerValues_shouldSubstractwThemAndReturnIntMaxIfOverflow() { + int result = IntMath.saturatedSubtract(Integer.MAX_VALUE, -2); + assertEquals(Integer.MAX_VALUE, result); + } + + @Test + public void whenSaturatedSubstractTwoIntegerValues_shouldSubstractThemAndReturnIntMinIfUnderflow() { + int result = IntMath.saturatedSubtract(Integer.MIN_VALUE, 3); + assertEquals(Integer.MIN_VALUE, result); + } + + @Test + public void whenSqrtIntegerValues_shouldSqrtThemAndReturnTheResultForCeilingRounding() { + int result = IntMath.sqrt(30, RoundingMode.CEILING); + assertEquals(6, result); + } + + @Test + public void whenSqrtIntegerValues_shouldSqrtThemAndReturnTheResultForFloorRounding() { + int result = IntMath.sqrt(30, RoundingMode.FLOOR); + assertEquals(5, result); + } + + @Test(expected = ArithmeticException.class) + public void whenSqrtIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { + IntMath.sqrt(30, RoundingMode.UNNECESSARY); + } + +} diff --git a/guava/src/test/java/org/baeldung/guava/GuavaLongMathTest.java b/guava/src/test/java/org/baeldung/guava/GuavaLongMathTest.java new file mode 100644 index 0000000000..5d6d06c571 --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/GuavaLongMathTest.java @@ -0,0 +1,268 @@ +package org.baeldung.guava; + +import static org.junit.Assert.*; + +import java.math.RoundingMode; + +import com.google.common.math.LongMath; +import org.junit.Test; + +public class GuavaLongMathTest { + + @Test + public void whenPerformBinomialOnTwoLongValues_shouldReturnResultIfUnderLong() { + long result = LongMath.binomial(6, 3); + assertEquals(20L, result); + } + + @Test + public void whenProformCeilPowOfTwoLongValues_shouldReturnResult() { + long result = LongMath.ceilingPowerOfTwo(20L); + assertEquals(32L, result); + } + + @Test + public void whenCheckedAddTwoLongValues_shouldAddThemAndReturnTheSumIfNotOverflow() { + long result = LongMath.checkedAdd(1L, 2L); + assertEquals(3L, result); + } + + @Test(expected = ArithmeticException.class) + public void whenCheckedAddTwoLongValues_shouldThrowArithmeticExceptionIfOverflow() { + LongMath.checkedAdd(Long.MAX_VALUE, 100L); + } + + @Test + public void whenCheckedMultiplyTwoLongValues_shouldMultiplyThemAndReturnTheResultIfNotOverflow() { + long result = LongMath.checkedMultiply(3L, 2L); + assertEquals(6L, result); + } + + @Test(expected = ArithmeticException.class) + public void whenCheckedMultiplyTwoLongValues_shouldThrowArithmeticExceptionIfOverflow() { + LongMath.checkedMultiply(Long.MAX_VALUE, 100L); + } + + @Test + public void whenCheckedPowTwoLongValues_shouldPowThemAndReturnTheResultIfNotOverflow() { + long result = LongMath.checkedPow(2L, 3); + assertEquals(8L, result); + } + + @Test(expected = ArithmeticException.class) + public void gwhenCheckedPowTwoLongValues_shouldThrowArithmeticExceptionIfOverflow() { + LongMath.checkedPow(Long.MAX_VALUE, 100); + } + + @Test + public void whenCheckedSubstractTwoLongValues_shouldSubstractThemAndReturnTheResultIfNotOverflow() { + long result = LongMath.checkedSubtract(4L, 1L); + assertEquals(3L, result); + } + + @Test(expected = ArithmeticException.class) + public void gwhenCheckedSubstractTwoLongValues_shouldThrowArithmeticExceptionIfOverflow() { + LongMath.checkedSubtract(Long.MAX_VALUE, -100); + } + + @Test + public void whenDivideTwoLongValues_shouldDivideThemAndReturnTheResultForCeilingRounding() { + long result = LongMath.divide(10L, 3L, RoundingMode.CEILING); + assertEquals(4L, result); + } + + @Test + public void whenDivideTwoLongValues_shouldDivideThemAndReturnTheResultForFloorRounding() { + long result = LongMath.divide(10L, 3L, RoundingMode.FLOOR); + assertEquals(3L, result); + } + + @Test(expected = ArithmeticException.class) + public void whenDivideTwoLongValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { + LongMath.divide(10L, 3L, RoundingMode.UNNECESSARY); + } + + @Test + public void whenFactorailLong_shouldFactorialThemAndReturnTheResultIfInIntRange() { + long result = LongMath.factorial(5); + assertEquals(120L, result); + } + + @Test + public void whenFactorailLong_shouldFactorialThemAndReturnIntMaxIfNotInIntRange() { + long result = LongMath.factorial(Integer.MAX_VALUE); + assertEquals(Long.MAX_VALUE, result); + } + + @Test + public void whenFloorPowerOfLong_shouldReturnValue() { + long result = LongMath.floorPowerOfTwo(30L); + assertEquals(16L, result); + } + + @Test + public void whenGcdOfTwoLongs_shouldReturnValue() { + long result = LongMath.gcd(30L, 40L); + assertEquals(10L, result); + } + + @Test + public void whenIsPowOfLong_shouldReturnTrueIfPowerOfTwo() { + boolean result = LongMath.isPowerOfTwo(16L); + assertTrue(result); + } + + @Test + public void whenIsPowOfLong_shouldReturnFalseeIfNotPowerOfTwo() { + boolean result = LongMath.isPowerOfTwo(20L); + assertFalse(result); + } + + @Test + public void whenIsPrineOfLong_shouldReturnFalseeIfNotPrime() { + boolean result = LongMath.isPrime(20L); + assertFalse(result); + } + + @Test + public void whenLog10LongValues_shouldLog10ThemAndReturnTheResultForCeilingRounding() { + int result = LongMath.log10(30L, RoundingMode.CEILING); + assertEquals(2, result); + } + + @Test + public void whenLog10LongValues_shouldog10ThemAndReturnTheResultForFloorRounding() { + int result = LongMath.log10(30L, RoundingMode.FLOOR); + assertEquals(1, result); + } + + @Test(expected = ArithmeticException.class) + public void whenLog10LongValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { + LongMath.log10(30L, RoundingMode.UNNECESSARY); + } + + @Test + public void whenLog2LongValues_shouldLog2ThemAndReturnTheResultForCeilingRounding() { + int result = LongMath.log2(30L, RoundingMode.CEILING); + assertEquals(5, result); + } + + @Test + public void whenLog2LongValues_shouldog2ThemAndReturnTheResultForFloorRounding() { + int result = LongMath.log2(30L, RoundingMode.FLOOR); + assertEquals(4, result); + } + + @Test(expected = ArithmeticException.class) + public void whenLog2LongValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { + LongMath.log2(30L, RoundingMode.UNNECESSARY); + } + + @Test + public void whenMeanTwoLongValues_shouldMeanThemAndReturnTheResult() { + long result = LongMath.mean(30L, 20L); + assertEquals(25L, result); + } + + @Test + public void whenModLongAndIntegerValues_shouldModThemAndReturnTheResult() { + int result = LongMath.mod(30L, 4); + assertEquals(2, result); + } + + @Test + public void whenModTwoLongValues_shouldModThemAndReturnTheResult() { + long result = LongMath.mod(30L, 4L); + assertEquals(2L, result); + } + + @Test + public void whenPowTwoLongValues_shouldPowThemAndReturnTheResult() { + long result = LongMath.pow(6L, 4); + assertEquals(1296L, result); + } + + @Test + public void whenSaturatedAddTwoLongValues_shouldAddThemAndReturnTheResult() { + long result = LongMath.saturatedAdd(6L, 4L); + assertEquals(10L, result); + } + + @Test + public void whenSaturatedAddTwoLongValues_shouldAddThemAndReturnIntMaxIfOverflow() { + long result = LongMath.saturatedAdd(Long.MAX_VALUE, 1000L); + assertEquals(Long.MAX_VALUE, result); + } + + @Test + public void whenSaturatedAddTwoLongValues_shouldAddThemAndReturnIntMinIfUnderflow() { + long result = LongMath.saturatedAdd(Long.MIN_VALUE, -1000); + assertEquals(Long.MIN_VALUE, result); + } + + @Test + public void whenSaturatedMultiplyTwoLongValues_shouldMultiplyThemAndReturnTheResult() { + long result = LongMath.saturatedMultiply(6L, 4L); + assertEquals(24L, result); + } + + @Test + public void whenSaturatedMultiplyTwoLongValues_shouldMultiplyThemAndReturnIntMaxIfOverflow() { + long result = LongMath.saturatedMultiply(Long.MAX_VALUE, 1000L); + assertEquals(Long.MAX_VALUE, result); + } + + @Test + public void whenSaturatedPowTwoLongValues_shouldPowThemAndReturnTheResult() { + long result = LongMath.saturatedPow(6L, 2); + assertEquals(36L, result); + } + + @Test + public void whenSaturatedPowTwoLongValues_shouldPowThemAndReturnIntMaxIfOverflow() { + long result = LongMath.saturatedPow(Long.MAX_VALUE, 2); + assertEquals(Long.MAX_VALUE, result); + } + + @Test + public void whenSaturatedPowTwoLongValues_shouldPowThemAndReturnIntMinIfUnderflow() { + long result = LongMath.saturatedPow(Long.MIN_VALUE, 3); + assertEquals(Long.MIN_VALUE, result); + } + + @Test + public void whenSaturatedSubstractTwoLongValues_shouldSubstractThemAndReturnTheResult() { + long result = LongMath.saturatedSubtract(6L, 2L); + assertEquals(4L, result); + } + + @Test + public void whenSaturatedSubstractTwoLongValues_shouldSubstractwThemAndReturnIntMaxIfOverflow() { + long result = LongMath.saturatedSubtract(Long.MAX_VALUE, -2L); + assertEquals(Long.MAX_VALUE, result); + } + + @Test + public void whenSaturatedSubstractTwoLongValues_shouldSubstractThemAndReturnIntMinIfUnderflow() { + long result = LongMath.saturatedSubtract(Long.MIN_VALUE, 3L); + assertEquals(Long.MIN_VALUE, result); + } + + @Test + public void whenSqrtLongValues_shouldSqrtThemAndReturnTheResultForCeilingRounding() { + long result = LongMath.sqrt(30L, RoundingMode.CEILING); + assertEquals(6L, result); + } + + @Test + public void whenSqrtLongValues_shouldSqrtThemAndReturnTheResultForFloorRounding() { + long result = LongMath.sqrt(30L, RoundingMode.FLOOR); + assertEquals(5L, result); + } + + @Test(expected = ArithmeticException.class) + public void whenSqrtLongValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { + LongMath.sqrt(30L, RoundingMode.UNNECESSARY); + } + +} From 196b869fff6f19717bf7ebc8bbd497a2009cd7a7 Mon Sep 17 00:00:00 2001 From: lor6 Date: Mon, 1 May 2017 19:35:13 +0300 Subject: [PATCH 18/30] remove security (#1765) --- spring-boot/pom.xml | 11 +++-- .../java/com/baeldung/toggle/MyFeatures.java | 13 +++--- .../com/baeldung/toggle/SalaryService.java | 2 +- .../com/baeldung/toggle/SecurityConfig.java | 33 --------------- .../baeldung/toggle/ToggleConfiguration.java | 8 ---- .../toggle/ToggleIntegrationTest.java | 42 ++++++------------- 6 files changed, 24 insertions(+), 85 deletions(-) delete mode 100644 spring-boot/src/main/java/com/baeldung/toggle/SecurityConfig.java diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index dfecbc8e29..7477c78b58 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -40,11 +40,6 @@ org.springframework.boot spring-boot-starter-security - - - org.springframework.security - spring-security-test - org.springframework.boot @@ -136,13 +131,17 @@ togglz-spring-boot-starter ${togglz.version} - + org.togglz togglz-spring-security ${togglz.version} + + org.apache.activemq + artemis-server + diff --git a/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java b/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java index e19d302c76..245415a2a0 100644 --- a/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java +++ b/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java @@ -1,7 +1,7 @@ package com.baeldung.toggle; import org.togglz.core.Feature; -import org.togglz.core.activation.UserRoleActivationStrategy; +import org.togglz.core.activation.SystemPropertyActivationStrategy; import org.togglz.core.annotation.ActivationParameter; import org.togglz.core.annotation.DefaultActivationStrategy; import org.togglz.core.annotation.EnabledByDefault; @@ -10,14 +10,13 @@ import org.togglz.core.context.FeatureContext; public enum MyFeatures implements Feature { - @Label("Administrator Feature") - @EnabledByDefault - @DefaultActivationStrategy(id = UserRoleActivationStrategy.ID, parameters = { @ActivationParameter(name = UserRoleActivationStrategy.PARAM_ROLES_NAME, value = "ROLE_ADMIN") }) - ADMIN_FEATURE; + @Label("Employee Management Feature") @EnabledByDefault @DefaultActivationStrategy(id = SystemPropertyActivationStrategy.ID, + parameters = { @ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_NAME, value = "employee.feature"), + @ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_VALUE, value = "true") }) + EMPLOYEE_MANAGEMENT_FEATURE; public boolean isActive() { - return FeatureContext.getFeatureManager() - .isActive(this); + return FeatureContext.getFeatureManager().isActive(this); } } diff --git a/spring-boot/src/main/java/com/baeldung/toggle/SalaryService.java b/spring-boot/src/main/java/com/baeldung/toggle/SalaryService.java index 4ea4a2ab35..df65033d6b 100644 --- a/spring-boot/src/main/java/com/baeldung/toggle/SalaryService.java +++ b/spring-boot/src/main/java/com/baeldung/toggle/SalaryService.java @@ -9,7 +9,7 @@ public class SalaryService { @Autowired EmployeeRepository employeeRepository; - @FeatureAssociation(value = MyFeatures.ADMIN_FEATURE) + @FeatureAssociation(value = MyFeatures.EMPLOYEE_MANAGEMENT_FEATURE) public void increaseSalary(long id) { Employee employee = employeeRepository.findOne(id); employee.setSalary(employee.getSalary() + employee.getSalary() * 0.1); diff --git a/spring-boot/src/main/java/com/baeldung/toggle/SecurityConfig.java b/spring-boot/src/main/java/com/baeldung/toggle/SecurityConfig.java deleted file mode 100644 index f558ccb0e1..0000000000 --- a/spring-boot/src/main/java/com/baeldung/toggle/SecurityConfig.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.toggle; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; - -@Configuration -@EnableWebSecurity -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - //@formatter:off - auth.inMemoryAuthentication() - .withUser("user").password("pass").roles("USER") - .and() - .withUser("admin").password("pass").roles("ADMIN"); - //@formatter:on - } - - @Override - public void configure(HttpSecurity http) throws Exception { - //@formatter:off - http.authorizeRequests().antMatchers("/increaseSalary").permitAll() - .and() - .csrf().disable() - .httpBasic(); - //@formatter:on - } -} diff --git a/spring-boot/src/main/java/com/baeldung/toggle/ToggleConfiguration.java b/spring-boot/src/main/java/com/baeldung/toggle/ToggleConfiguration.java index 3ae6abcbc9..ee0b251479 100644 --- a/spring-boot/src/main/java/com/baeldung/toggle/ToggleConfiguration.java +++ b/spring-boot/src/main/java/com/baeldung/toggle/ToggleConfiguration.java @@ -2,14 +2,10 @@ package com.baeldung.toggle; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.togglz.core.manager.EnumBasedFeatureProvider; import org.togglz.core.spi.FeatureProvider; -import org.togglz.core.user.UserProvider; -import org.togglz.spring.security.SpringSecurityUserProvider; @Configuration @EnableJpaRepositories("com.baeldung.toggle") @@ -21,8 +17,4 @@ public class ToggleConfiguration { return new EnumBasedFeatureProvider(MyFeatures.class); } - @Bean - public UserProvider userProvider() { - return new SpringSecurityUserProvider("admin"); - } } diff --git a/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java index 34341c310c..e40678603b 100644 --- a/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java @@ -11,14 +11,11 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.security.web.FilterChainProxy; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*; - @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = ToggleApplication.class) @AutoConfigureMockMvc @@ -31,54 +28,39 @@ public class ToggleIntegrationTest { EmployeeRepository employeeRepository; @Autowired - private MockMvc mvc; + private MockMvc mockMvc; @Autowired private WebApplicationContext wac; - @Autowired - private FilterChainProxy springSecurityFilterChain; - @Before public void setup() { - this.mvc = MockMvcBuilders.webAppContextSetup(this.wac) - .addFilter(springSecurityFilterChain) - .build(); + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test - public void givenNoAuthentication_whenIncreaseSalary_thenNoIncrease() throws Exception { + public void givenFeaturePropertyFalse_whenIncreaseSalary_thenNoIncrease() throws Exception { Employee emp = new Employee(1, 2000); employeeRepository.save(emp); - mvc.perform(post("/increaseSalary").param("id", emp.getId() + "")) - .andExpect(status().is(200)); + + System.setProperty("employee.feature", "false"); + + mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200)); emp = employeeRepository.findOne(1L); assertEquals("salary incorrect", 2000, emp.getSalary(), 0.5); } @Test - public void givenAdminAuthentication_whenIncreaseSalary_thenIncrease() throws Exception { + public void givenFeaturePropertyTrue_whenIncreaseSalary_thenIncrease() throws Exception { Employee emp = new Employee(1, 2000); employeeRepository.save(emp); - mvc.perform(post("/increaseSalary").param("id", emp.getId() + "") - .with(httpBasic("admin", "pass"))) - .andExpect(status().is(200)); + + System.setProperty("employee.feature", "true"); + + mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200)); emp = employeeRepository.findOne(1L); assertEquals("salary incorrect", 2200, emp.getSalary(), 0.5); } - - @Test - public void givenUserAuthentication_whenIncreaseSalary_thenNoIncrease() throws Exception { - Employee emp = new Employee(1, 2000); - employeeRepository.save(emp); - mvc.perform(post("/increaseSalary").param("id", emp.getId() + "") - .with(httpBasic("user", "pass"))) - .andExpect(status().is(200)); - - emp = employeeRepository.findOne(1L); - assertEquals("salary incorrect", 2000, emp.getSalary(), 0.5); - } - } From c5ddf680a70f4b567520b0c341c574d5b7a0f93d Mon Sep 17 00:00:00 2001 From: Sunil Mogadati Date: Mon, 1 May 2017 10:46:27 -0600 Subject: [PATCH 19/30] BAEL-245: Issue 1753. Fix the typo - change from writeNumber() to writeString() (#1763) * Add NDC and JBoss Logging to the demo application * NDC for Log4j, Log4j2 and JBoss Logging * Simplify NDC example by making it a single operation instead of two * Make NDC example as RestController, Use JBoss Logging only as a logging bridge * Fix merge conflicts in pull request - log-mdc pom.xml updated * BAEL-445 Update to Spring security SpEL example * BAEL-445: Change tabs to spaces in the updated code * BAEL-245: Add Enum Serialization exmaple * BAEL-245: Remove the folder jackson/src/test/java/com/baeldung/jackson/dtos/withEnum as the example is not used anymore * Add more enum serialization examples to align with previous example and prevent build fail * BAEL-611: Minor formatting changes * BAEL-611: Update Test case method names * BAEL-611 Add JAX-WS client and JUnit Test * BAEL-245: Issue 1753. Fix the typo - change from writeNumber() to writeString() --- .../com/baeldung/jackson/serialization/DistanceSerializer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/DistanceSerializer.java b/jackson/src/main/java/com/baeldung/jackson/serialization/DistanceSerializer.java index ca013ff921..f5951dfd8e 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/DistanceSerializer.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/DistanceSerializer.java @@ -23,7 +23,7 @@ public class DistanceSerializer extends StdSerializer { public void serialize(Distance distance, JsonGenerator generator, SerializerProvider provider) throws IOException, JsonProcessingException { generator.writeStartObject(); generator.writeFieldName("name"); - generator.writeNumber(distance.name()); + generator.writeString(distance.name()); generator.writeFieldName("unit"); generator.writeString(distance.getUnit()); generator.writeFieldName("meters"); From 6e86dc27ff3b5e1f828d4c31b1c710f744cb0d86 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Wed, 3 May 2017 09:29:10 +0200 Subject: [PATCH 20/30] Optimize build and reduce logging (#1772) * Reduce logging * Reduce logging * Reduce logging * Reduce logging * Reduce logging * Optimize build * Remove testng from core-java --- algorithms/pom.xml | 11 ++ ...ColonyOptimizationLongRunningUnitTest.java | 22 +++ .../algorithms/AntColonyOptimizationTest.java | 22 --- ...ryGeneticAlgorithmLongRunningUnitTest.java | 16 ++ .../BinaryGeneticAlgorithmUnitTest.java | 16 -- ...DijkstraAlgorithmLongRunningUnitTest.java} | 162 ++++++++++-------- ...initeStateMachineLongRunningUnitTest.java} | 37 ++-- ...imulatedAnnealingLongRunningUnitTest.java} | 2 +- .../BigIntegerPrimeCheckerTest.java | 28 --- .../BruteForcePrimeCheckerTest.java | 27 --- .../OptimisedPrimeCheckerTest.java | 26 --- .../primechecker/PrimeCheckerTest.java | 69 ++++++++ .../primechecker/PrimesPrimeCheckerTest.java | 25 --- core-java/0.8260098203820962 | 0 core-java/pom.xml | 7 - .../concurrent/sleepwait/ThreadA.java | 10 +- .../sleepwait/WaitSleepExample.java | 10 +- .../DirectoryMonitoringExample.java | 15 +- .../com/baeldung/doublecolon/MacbookPro.java | 11 +- .../java/com/baeldung/java/map/MyKey.java | 9 +- .../src/main/java/com/baeldung/jmx/Game.java | 11 +- .../baeldung/jmx/JMXTutorialMainlauncher.java | 19 +- .../java/com/baeldung/socket/EchoClient.java | 11 +- .../com/baeldung/socket/EchoMultiServer.java | 8 +- .../java/com/baeldung/socket/EchoServer.java | 10 +- .../java/com/baeldung/socket/GreetClient.java | 10 +- .../java/com/baeldung/socket/GreetServer.java | 10 +- .../com/baeldung/stream/InfiniteStreams.java | 8 +- .../ThreadLocalWithUserContext.java | 6 +- .../com/baeldung/transferqueue/Consumer.java | 10 +- .../com/baeldung/transferqueue/Producer.java | 11 +- .../PrimitiveConversionsJUnitTest.java | 27 +-- .../CompletableFutureUnitTest.java | 27 +-- .../SquareCalculatorIntegrationTest.java | 11 +- .../PriorityBlockingQueueIntegrationTest.java | 11 +- .../dynamicproxy/DynamicProxyTest.java | 2 +- .../FunctionalInterfaceUnitTest.java | 20 ++- .../ConcurrentModificationExceptionTest.java | 3 +- .../ConcurrentNavigableMapManualTests.java | 4 +- .../java/com/baeldung/java/map/MapTest.java | 38 ++-- .../java/nio2/async/AsyncEchoClient.java | 11 +- .../nio2/attributes/BasicAttribsTest.java | 12 +- .../java/com/baeldung/java/set/SetTest.java | 6 +- .../com/baeldung/java8/Java8ForEachTest.java | 28 +-- ...vaTryWithResourcesLongRunningUnitTest.java | 17 +- .../LambdaExceptionWrappersTest.java | 9 +- .../baeldung/java8/optional/OptionalTest.java | 18 +- .../SynchronousQueueTest.java | 13 +- .../CoreThreadPoolIntegrationTest.java | 31 ++-- .../FileNotFoundExceptionUnitTest.java | 19 +- .../org/baeldung/java/JavaRandomUnitTest.java | 49 +++--- .../java/JavaTimerLongRunningUnitTest.java | 23 ++- .../CoreJavaCollectionsUnitTest.java | 16 +- .../java/io/JavaReadFromFileUnitTest.java | 24 ++- .../java/lists/ListTestNgUnitTest.java | 11 +- .../java/sandbox/SandboxJavaManualTest.java | 35 ++-- cucumber/pom.xml | 8 +- ...st.java => CalculatorIntegrationTest.java} | 2 +- pom.xml | 5 +- wicket/pom.xml | 14 +- 60 files changed, 626 insertions(+), 507 deletions(-) create mode 100644 algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java delete mode 100644 algorithms/src/test/java/algorithms/AntColonyOptimizationTest.java create mode 100644 algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java delete mode 100644 algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmUnitTest.java rename algorithms/src/test/java/algorithms/{DijkstraAlgorithmTest.java => DijkstraAlgorithmLongRunningUnitTest.java} (74%) rename algorithms/src/test/java/algorithms/{RtFiniteStateMachineTest.java => RtFiniteStateMachineLongRunningUnitTest.java} (72%) rename algorithms/src/test/java/algorithms/{SimulatedAnnealingTest.java => SimulatedAnnealingLongRunningUnitTest.java} (84%) delete mode 100644 algorithms/src/test/java/com/baeldung/algorithms/primechecker/BigIntegerPrimeCheckerTest.java delete mode 100644 algorithms/src/test/java/com/baeldung/algorithms/primechecker/BruteForcePrimeCheckerTest.java delete mode 100644 algorithms/src/test/java/com/baeldung/algorithms/primechecker/OptimisedPrimeCheckerTest.java create mode 100644 algorithms/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerTest.java delete mode 100644 algorithms/src/test/java/com/baeldung/algorithms/primechecker/PrimesPrimeCheckerTest.java delete mode 100644 core-java/0.8260098203820962 rename cucumber/src/test/java/com/baeldung/cucumber/calculator/{CalculatorTest.java => CalculatorIntegrationTest.java} (91%) diff --git a/algorithms/pom.xml b/algorithms/pom.xml index 884c804d13..17d302a9ca 100644 --- a/algorithms/pom.xml +++ b/algorithms/pom.xml @@ -76,6 +76,17 @@ + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*LongRunningUnitTest.java + **/*IntegrationTest.java + + + diff --git a/algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java b/algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java new file mode 100644 index 0000000000..b0218ae23e --- /dev/null +++ b/algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java @@ -0,0 +1,22 @@ +package algorithms; + +import org.junit.Assert; +import org.junit.Test; + +import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization; + +public class AntColonyOptimizationLongRunningUnitTest { + + @Test + public void testGenerateRandomMatrix() { + AntColonyOptimization antTSP = new AntColonyOptimization(5); + Assert.assertNotNull(antTSP.generateRandomMatrix(5)); + } + + @Test + public void testStartAntOptimization() { + AntColonyOptimization antTSP = new AntColonyOptimization(5); + Assert.assertNotNull(antTSP.solve()); + } + +} diff --git a/algorithms/src/test/java/algorithms/AntColonyOptimizationTest.java b/algorithms/src/test/java/algorithms/AntColonyOptimizationTest.java deleted file mode 100644 index a11f5db698..0000000000 --- a/algorithms/src/test/java/algorithms/AntColonyOptimizationTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package algorithms; - -import org.junit.Assert; -import org.junit.Test; - -import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization; - -public class AntColonyOptimizationTest { - - @Test - public void testGenerateRandomMatrix() { - AntColonyOptimization antTSP = new AntColonyOptimization(5); - Assert.assertNotNull(antTSP.generateRandomMatrix(5)); - } - - @Test - public void testStartAntOptimization() { - AntColonyOptimization antTSP = new AntColonyOptimization(5); - Assert.assertNotNull(antTSP.solve()); - } - -} diff --git a/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java b/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java new file mode 100644 index 0000000000..fa8ecdee77 --- /dev/null +++ b/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java @@ -0,0 +1,16 @@ +package algorithms; + +import org.junit.Assert; +import org.junit.Test; + +import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm; + +public class BinaryGeneticAlgorithmLongRunningUnitTest { + + @Test + public void testGA() { + SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm(); + Assert.assertTrue(ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111")); + } + +} diff --git a/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmUnitTest.java b/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmUnitTest.java deleted file mode 100644 index 2ba516d310..0000000000 --- a/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmUnitTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package algorithms; - -import org.junit.Assert; -import org.junit.Test; - -import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm; - -public class BinaryGeneticAlgorithmUnitTest { - - @Test - public void testGA() { - SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm(); - Assert.assertTrue(ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111")); - } - -} diff --git a/algorithms/src/test/java/algorithms/DijkstraAlgorithmTest.java b/algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java similarity index 74% rename from algorithms/src/test/java/algorithms/DijkstraAlgorithmTest.java rename to algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java index 4d8cebed25..68386278fc 100644 --- a/algorithms/src/test/java/algorithms/DijkstraAlgorithmTest.java +++ b/algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java @@ -1,76 +1,86 @@ -package algorithms; - -import org.junit.Test; - -import com.baeldung.algorithms.ga.dijkstra.Dijkstra; -import com.baeldung.algorithms.ga.dijkstra.Graph; -import com.baeldung.algorithms.ga.dijkstra.Node; - -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.assertTrue; - -public class DijkstraAlgorithmTest { - - @Test - public void whenSPPSolved_thenCorrect() { - - Node nodeA = new Node("A"); - Node nodeB = new Node("B"); - Node nodeC = new Node("C"); - Node nodeD = new Node("D"); - Node nodeE = new Node("E"); - Node nodeF = new Node("F"); - - nodeA.addDestination(nodeB, 10); - nodeA.addDestination(nodeC, 15); - - nodeB.addDestination(nodeD, 12); - nodeB.addDestination(nodeF, 15); - - nodeC.addDestination(nodeE, 10); - - nodeD.addDestination(nodeE, 2); - nodeD.addDestination(nodeF, 1); - - nodeF.addDestination(nodeE, 5); - - Graph graph = new Graph(); - - graph.addNode(nodeA); - graph.addNode(nodeB); - graph.addNode(nodeC); - graph.addNode(nodeD); - graph.addNode(nodeE); - graph.addNode(nodeF); - - graph = Dijkstra.calculateShortestPathFromSource(graph, nodeA); - - List shortestPathForNodeB = Arrays.asList(nodeA); - List shortestPathForNodeC = Arrays.asList(nodeA); - List shortestPathForNodeD = Arrays.asList(nodeA, nodeB); - List shortestPathForNodeE = Arrays.asList(nodeA, nodeB, nodeD); - List shortestPathForNodeF = Arrays.asList(nodeA, nodeB, nodeD); - - for (Node node : graph.getNodes()) { - switch (node.getName()) { - case "B": - assertTrue(node.getShortestPath().equals(shortestPathForNodeB)); - break; - case "C": - assertTrue(node.getShortestPath().equals(shortestPathForNodeC)); - break; - case "D": - assertTrue(node.getShortestPath().equals(shortestPathForNodeD)); - break; - case "E": - assertTrue(node.getShortestPath().equals(shortestPathForNodeE)); - break; - case "F": - assertTrue(node.getShortestPath().equals(shortestPathForNodeF)); - break; - } - } - } -} +package algorithms; + +import org.junit.Test; + +import com.baeldung.algorithms.ga.dijkstra.Dijkstra; +import com.baeldung.algorithms.ga.dijkstra.Graph; +import com.baeldung.algorithms.ga.dijkstra.Node; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertTrue; + +public class DijkstraAlgorithmLongRunningUnitTest { + + @Test + public void whenSPPSolved_thenCorrect() { + + Node nodeA = new Node("A"); + Node nodeB = new Node("B"); + Node nodeC = new Node("C"); + Node nodeD = new Node("D"); + Node nodeE = new Node("E"); + Node nodeF = new Node("F"); + + nodeA.addDestination(nodeB, 10); + nodeA.addDestination(nodeC, 15); + + nodeB.addDestination(nodeD, 12); + nodeB.addDestination(nodeF, 15); + + nodeC.addDestination(nodeE, 10); + + nodeD.addDestination(nodeE, 2); + nodeD.addDestination(nodeF, 1); + + nodeF.addDestination(nodeE, 5); + + Graph graph = new Graph(); + + graph.addNode(nodeA); + graph.addNode(nodeB); + graph.addNode(nodeC); + graph.addNode(nodeD); + graph.addNode(nodeE); + graph.addNode(nodeF); + + graph = Dijkstra.calculateShortestPathFromSource(graph, nodeA); + + List shortestPathForNodeB = Arrays.asList(nodeA); + List shortestPathForNodeC = Arrays.asList(nodeA); + List shortestPathForNodeD = Arrays.asList(nodeA, nodeB); + List shortestPathForNodeE = Arrays.asList(nodeA, nodeB, nodeD); + List shortestPathForNodeF = Arrays.asList(nodeA, nodeB, nodeD); + + for (Node node : graph.getNodes()) { + switch (node.getName()) { + case "B": + assertTrue(node + .getShortestPath() + .equals(shortestPathForNodeB)); + break; + case "C": + assertTrue(node + .getShortestPath() + .equals(shortestPathForNodeC)); + break; + case "D": + assertTrue(node + .getShortestPath() + .equals(shortestPathForNodeD)); + break; + case "E": + assertTrue(node + .getShortestPath() + .equals(shortestPathForNodeE)); + break; + case "F": + assertTrue(node + .getShortestPath() + .equals(shortestPathForNodeF)); + break; + } + } + } +} diff --git a/algorithms/src/test/java/algorithms/RtFiniteStateMachineTest.java b/algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java similarity index 72% rename from algorithms/src/test/java/algorithms/RtFiniteStateMachineTest.java rename to algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java index 089b38ec3f..c6800e9a64 100644 --- a/algorithms/src/test/java/algorithms/RtFiniteStateMachineTest.java +++ b/algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java @@ -1,38 +1,37 @@ package algorithms; -import static org.junit.Assert.*; -import org.junit.Test; import com.baeldung.automata.*; +import org.junit.Test; -/** - * Tests for {@link RtFiniteStateMachine} - */ -public final class RtFiniteStateMachineTest { +import static org.junit.Assert.assertTrue; + +public final class RtFiniteStateMachineLongRunningUnitTest { @Test public void acceptsSimplePair() { String json = "{\"key\":\"value\"}"; FiniteStateMachine machine = this.buildJsonStateMachine(); - for (int i=0;itest - - org.testng - testng - ${testng.version} - test - - org.mockito mockito-core diff --git a/core-java/src/main/java/com/baeldung/concurrent/sleepwait/ThreadA.java b/core-java/src/main/java/com/baeldung/concurrent/sleepwait/ThreadA.java index b19bc3fe1a..6bb055d360 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/sleepwait/ThreadA.java +++ b/core-java/src/main/java/com/baeldung/concurrent/sleepwait/ThreadA.java @@ -1,9 +1,15 @@ package com.baeldung.concurrent.sleepwait; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /*** * Example of waking up a waiting thread */ public class ThreadA { + + private static final Logger LOG = LoggerFactory.getLogger(ThreadA.class); + private static final ThreadB b = new ThreadB(); public static void main(String... args) throws InterruptedException { @@ -11,11 +17,11 @@ public class ThreadA { synchronized (b) { while (b.sum == 0) { - System.out.println("Waiting for ThreadB to complete..."); + LOG.debug("Waiting for ThreadB to complete..."); b.wait(); } - System.out.println("ThreadB has completed. Sum from that thread is: " + b.sum); + LOG.debug("ThreadB has completed. Sum from that thread is: " + b.sum); } } } diff --git a/core-java/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java b/core-java/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java index e84fe29d87..0311d9b0b2 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java +++ b/core-java/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java @@ -1,9 +1,15 @@ package com.baeldung.concurrent.sleepwait; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /*** * Example of wait() and sleep() methods */ public class WaitSleepExample { + + private static final Logger LOG = LoggerFactory.getLogger(WaitSleepExample.class); + private static final Object LOCK = new Object(); public static void main(String... args) throws InterruptedException { @@ -12,11 +18,11 @@ public class WaitSleepExample { private static void sleepWaitInSyncronizedBlocks() throws InterruptedException { Thread.sleep(1000); // called on the thread - System.out.println("Thread '" + Thread.currentThread().getName() + "' is woken after sleeping for 1 second"); + LOG.debug("Thread '" + Thread.currentThread().getName() + "' is woken after sleeping for 1 second"); synchronized (LOCK) { LOCK.wait(1000); // called on the object, synchronization required - System.out.println("Object '" + LOCK + "' is woken after waiting for 1 second"); + LOG.debug("Object '" + LOCK + "' is woken after waiting for 1 second"); } } diff --git a/core-java/src/main/java/com/baeldung/dirmonitoring/DirectoryMonitoringExample.java b/core-java/src/main/java/com/baeldung/dirmonitoring/DirectoryMonitoringExample.java index 49030b5352..f9028bd159 100644 --- a/core-java/src/main/java/com/baeldung/dirmonitoring/DirectoryMonitoringExample.java +++ b/core-java/src/main/java/com/baeldung/dirmonitoring/DirectoryMonitoringExample.java @@ -1,14 +1,19 @@ package com.baeldung.dirmonitoring; -import java.io.File; - import org.apache.commons.io.monitor.FileAlterationListener; import org.apache.commons.io.monitor.FileAlterationListenerAdaptor; import org.apache.commons.io.monitor.FileAlterationMonitor; import org.apache.commons.io.monitor.FileAlterationObserver; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; public class DirectoryMonitoringExample { + private static final Logger LOG = LoggerFactory.getLogger(DirectoryMonitoringExample.class); + + public static final int POLL_INTERVAL = 500; public static void main(String[] args) throws Exception { @@ -17,17 +22,17 @@ public class DirectoryMonitoringExample { FileAlterationListener listener = new FileAlterationListenerAdaptor() { @Override public void onFileCreate(File file) { - System.out.println("File: " + file.getName() + " created"); + LOG.debug("File: " + file.getName() + " created"); } @Override public void onFileDelete(File file) { - System.out.println("File: " + file.getName() + " deleted"); + LOG.debug("File: " + file.getName() + " deleted"); } @Override public void onFileChange(File file) { - System.out.println("File: " + file.getName() + " changed"); + LOG.debug("File: " + file.getName() + " changed"); } }; observer.addListener(listener); diff --git a/core-java/src/main/java/com/baeldung/doublecolon/MacbookPro.java b/core-java/src/main/java/com/baeldung/doublecolon/MacbookPro.java index 3fc459c681..f5c31e9653 100644 --- a/core-java/src/main/java/com/baeldung/doublecolon/MacbookPro.java +++ b/core-java/src/main/java/com/baeldung/doublecolon/MacbookPro.java @@ -1,9 +1,14 @@ package com.baeldung.doublecolon; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.function.Function; public class MacbookPro extends Computer { + private static final Logger LOG = LoggerFactory.getLogger(MacbookPro.class); + public MacbookPro(int age, String color) { super(age, color); } @@ -14,12 +19,12 @@ public class MacbookPro extends Computer { @Override public void turnOnPc() { - System.out.println("MacbookPro turned on"); + LOG.debug("MacbookPro turned on"); } @Override public void turnOffPc() { - System.out.println("MacbookPro turned off"); + LOG.debug("MacbookPro turned off"); } @Override @@ -27,7 +32,7 @@ public class MacbookPro extends Computer { Function function = super::calculateValue; final Double pcValue = function.apply(initialValue); - System.out.println("First value is:" + pcValue); + LOG.debug("First value is:" + pcValue); return pcValue + (initialValue / 10); } diff --git a/core-java/src/main/java/com/baeldung/java/map/MyKey.java b/core-java/src/main/java/com/baeldung/java/map/MyKey.java index a2587c1dc1..ae3c3edc39 100644 --- a/core-java/src/main/java/com/baeldung/java/map/MyKey.java +++ b/core-java/src/main/java/com/baeldung/java/map/MyKey.java @@ -1,6 +1,11 @@ package com.baeldung.java.map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class MyKey { + private static final Logger LOG = LoggerFactory.getLogger(MyKey.class); + private String name; private int id; @@ -27,7 +32,7 @@ public class MyKey { @Override public int hashCode() { - System.out.println("Calling hashCode()"); + LOG.debug("Calling hashCode()"); return id; } @@ -38,7 +43,7 @@ public class MyKey { @Override public boolean equals(Object obj) { - System.out.println("Calling equals() for key: " + obj); + LOG.debug("Calling equals() for key: " + obj); if (this == obj) return true; if (obj == null) diff --git a/core-java/src/main/java/com/baeldung/jmx/Game.java b/core-java/src/main/java/com/baeldung/jmx/Game.java index f38db27601..79256c0659 100644 --- a/core-java/src/main/java/com/baeldung/jmx/Game.java +++ b/core-java/src/main/java/com/baeldung/jmx/Game.java @@ -1,23 +1,28 @@ package com.baeldung.jmx; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class Game implements GameMBean { + private static final Logger LOG = LoggerFactory.getLogger(Game.class); + private String playerName; @Override public void playFootball(String clubName) { - System.out.println(this.playerName + " playing football for " + clubName); + LOG.debug(this.playerName + " playing football for " + clubName); } @Override public String getPlayerName() { - System.out.println("Return playerName " + this.playerName); + LOG.debug("Return playerName " + this.playerName); return playerName; } @Override public void setPlayerName(String playerName) { - System.out.println("Set playerName to value " + playerName); + LOG.debug("Set playerName to value " + playerName); this.playerName = playerName; } diff --git a/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java b/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java index 6f9c30ab50..220b9a8ec6 100644 --- a/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java +++ b/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java @@ -1,19 +1,20 @@ package com.baeldung.jmx; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.management.*; import java.lang.management.ManagementFactory; -import javax.management.InstanceAlreadyExistsException; -import javax.management.MBeanRegistrationException; -import javax.management.MBeanServer; -import javax.management.MalformedObjectNameException; -import javax.management.NotCompliantMBeanException; -import javax.management.ObjectName; public class JMXTutorialMainlauncher { + private static final Logger LOG = LoggerFactory.getLogger(JMXTutorialMainlauncher.class); + + public static void main(String[] args) { // TODO Auto-generated method stub - System.out.println("This is basic JMX tutorial"); + LOG.debug("This is basic JMX tutorial"); ObjectName objectName = null; try { objectName = new ObjectName("com.baeldung.tutorial:type=basic,name=game"); @@ -27,8 +28,8 @@ public class JMXTutorialMainlauncher { } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) { e.printStackTrace(); } - System.out.println("Registration for Game mbean with the platform server is successfull"); - System.out.println("Please open jconsole to access Game mbean"); + LOG.debug("Registration for Game mbean with the platform server is successfull"); + LOG.debug("Please open jconsole to access Game mbean"); while (true) { // to ensure application does not terminate } diff --git a/core-java/src/main/java/com/baeldung/socket/EchoClient.java b/core-java/src/main/java/com/baeldung/socket/EchoClient.java index 570bd60b2d..cf5c253276 100644 --- a/core-java/src/main/java/com/baeldung/socket/EchoClient.java +++ b/core-java/src/main/java/com/baeldung/socket/EchoClient.java @@ -1,9 +1,16 @@ package com.baeldung.socket; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.*; import java.net.*; public class EchoClient { + + + private static final Logger LOG = LoggerFactory.getLogger(EchoClient.class); + private Socket clientSocket; private PrintWriter out; private BufferedReader in; @@ -14,7 +21,7 @@ public class EchoClient { out = new PrintWriter(clientSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); } catch (IOException e) { - System.out.print(e); + LOG.debug("Error when initializing connection", e); } } @@ -34,7 +41,7 @@ public class EchoClient { out.close(); clientSocket.close(); } catch (IOException e) { - e.printStackTrace(); + LOG.debug("error when closing", e); } } diff --git a/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java b/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java index b920967545..a9f055f8f4 100644 --- a/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java +++ b/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java @@ -1,9 +1,15 @@ package com.baeldung.socket; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.net.*; import java.io.*; public class EchoMultiServer { + + private static final Logger LOG = LoggerFactory.getLogger(EchoMultiServer.class); + private ServerSocket serverSocket; public void start(int port) { @@ -57,7 +63,7 @@ public class EchoMultiServer { clientSocket.close(); } catch (IOException e) { - e.printStackTrace(); + LOG.debug(e.getMessage()); } } } diff --git a/core-java/src/main/java/com/baeldung/socket/EchoServer.java b/core-java/src/main/java/com/baeldung/socket/EchoServer.java index dfd281d51c..a869e98966 100644 --- a/core-java/src/main/java/com/baeldung/socket/EchoServer.java +++ b/core-java/src/main/java/com/baeldung/socket/EchoServer.java @@ -1,9 +1,15 @@ package com.baeldung.socket; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.net.*; import java.io.*; public class EchoServer { + + private static final Logger LOG = LoggerFactory.getLogger(EchoServer.class); + private ServerSocket serverSocket; private Socket clientSocket; private PrintWriter out; @@ -24,7 +30,7 @@ public class EchoServer { out.println(inputLine); } } catch (IOException e) { - e.printStackTrace(); + LOG.debug(e.getMessage()); } } @@ -36,7 +42,7 @@ public class EchoServer { clientSocket.close(); serverSocket.close(); } catch (IOException e) { - e.printStackTrace(); + LOG.debug(e.getMessage()); } } diff --git a/core-java/src/main/java/com/baeldung/socket/GreetClient.java b/core-java/src/main/java/com/baeldung/socket/GreetClient.java index e6f14bb2b6..38ad016919 100644 --- a/core-java/src/main/java/com/baeldung/socket/GreetClient.java +++ b/core-java/src/main/java/com/baeldung/socket/GreetClient.java @@ -1,5 +1,8 @@ package com.baeldung.socket; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -7,6 +10,9 @@ import java.io.PrintWriter; import java.net.Socket; public class GreetClient { + + private static final Logger LOG = LoggerFactory.getLogger(EchoMultiServer.class); + private Socket clientSocket; private PrintWriter out; private BufferedReader in; @@ -17,7 +23,7 @@ public class GreetClient { out = new PrintWriter(clientSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); } catch (IOException e) { - + LOG.debug(e.getMessage()); } } @@ -37,7 +43,7 @@ public class GreetClient { out.close(); clientSocket.close(); } catch (IOException e) { - e.printStackTrace(); + LOG.debug(e.getMessage()); } } diff --git a/core-java/src/main/java/com/baeldung/socket/GreetServer.java b/core-java/src/main/java/com/baeldung/socket/GreetServer.java index 05bc65a65e..f46db91959 100644 --- a/core-java/src/main/java/com/baeldung/socket/GreetServer.java +++ b/core-java/src/main/java/com/baeldung/socket/GreetServer.java @@ -1,9 +1,15 @@ package com.baeldung.socket; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.net.*; import java.io.*; public class GreetServer { + + private static final Logger LOG = LoggerFactory.getLogger(GreetServer.class); + private ServerSocket serverSocket; private Socket clientSocket; private PrintWriter out; @@ -21,7 +27,7 @@ public class GreetServer { else out.println("unrecognised greeting"); } catch (IOException e) { - e.printStackTrace(); + LOG.debug(e.getMessage()); } } @@ -33,7 +39,7 @@ public class GreetServer { clientSocket.close(); serverSocket.close(); } catch (IOException e) { - e.printStackTrace(); + LOG.debug(e.getMessage()); } } diff --git a/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java b/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java index 097b516f8c..ae00fc7cb4 100644 --- a/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java +++ b/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java @@ -1,9 +1,15 @@ package com.baeldung.stream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.stream.Stream; public class InfiniteStreams { + + private static final Logger LOG = LoggerFactory.getLogger(InfiniteStreams.class); + public static void main(String[] args) { doWhileOldWay(); @@ -15,7 +21,7 @@ public class InfiniteStreams { int i = 0; while (i < 10) { - System.out.println(i); + LOG.debug("{}", i); i++; } } diff --git a/core-java/src/main/java/com/baeldung/threadlocal/ThreadLocalWithUserContext.java b/core-java/src/main/java/com/baeldung/threadlocal/ThreadLocalWithUserContext.java index 0d6a7e5572..de7e4a0369 100644 --- a/core-java/src/main/java/com/baeldung/threadlocal/ThreadLocalWithUserContext.java +++ b/core-java/src/main/java/com/baeldung/threadlocal/ThreadLocalWithUserContext.java @@ -1,7 +1,11 @@ package com.baeldung.threadlocal; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class ThreadLocalWithUserContext implements Runnable { + private static final Logger LOG = LoggerFactory.getLogger(ThreadLocalWithUserContext.class); + private static final ThreadLocal userContext = new ThreadLocal<>(); private final Integer userId; private UserRepository userRepository = new UserRepository(); @@ -15,6 +19,6 @@ public class ThreadLocalWithUserContext implements Runnable { public void run() { String userName = userRepository.getUserNameForUserId(userId); userContext.set(new Context(userName)); - System.out.println("thread context for given userId: " + userId + " is: " + userContext.get()); + LOG.debug("thread context for given userId: " + userId + " is: " + userContext.get()); } } diff --git a/core-java/src/main/java/com/baeldung/transferqueue/Consumer.java b/core-java/src/main/java/com/baeldung/transferqueue/Consumer.java index a498d08041..69d7ff2390 100644 --- a/core-java/src/main/java/com/baeldung/transferqueue/Consumer.java +++ b/core-java/src/main/java/com/baeldung/transferqueue/Consumer.java @@ -1,9 +1,15 @@ package com.baeldung.transferqueue; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.concurrent.TransferQueue; import java.util.concurrent.atomic.AtomicInteger; public class Consumer implements Runnable { + private static final Logger LOG = LoggerFactory.getLogger(Consumer.class); + + private final TransferQueue transferQueue; private final String name; private final int numberOfMessagesToConsume; @@ -19,10 +25,10 @@ public class Consumer implements Runnable { public void run() { for (int i = 0; i < numberOfMessagesToConsume; i++) { try { - System.out.println("Consumer: " + name + " is waiting to take element..."); + LOG.debug("Consumer: " + name + " is waiting to take element..."); String element = transferQueue.take(); longProcessing(element); - System.out.println("Consumer: " + name + " received element: " + element); + LOG.debug("Consumer: " + name + " received element: " + element); } catch (InterruptedException e) { e.printStackTrace(); } diff --git a/core-java/src/main/java/com/baeldung/transferqueue/Producer.java b/core-java/src/main/java/com/baeldung/transferqueue/Producer.java index c6edc99bb5..c7df7c410a 100644 --- a/core-java/src/main/java/com/baeldung/transferqueue/Producer.java +++ b/core-java/src/main/java/com/baeldung/transferqueue/Producer.java @@ -1,10 +1,15 @@ package com.baeldung.transferqueue; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.concurrent.TimeUnit; import java.util.concurrent.TransferQueue; import java.util.concurrent.atomic.AtomicInteger; public class Producer implements Runnable { + private static final Logger LOG = LoggerFactory.getLogger(Producer.class); + private final TransferQueue transferQueue; private final String name; private final Integer numberOfMessagesToProduce; @@ -20,13 +25,13 @@ public class Producer implements Runnable { public void run() { for (int i = 0; i < numberOfMessagesToProduce; i++) { try { - System.out.println("Producer: " + name + " is waiting to transfer..."); + LOG.debug("Producer: " + name + " is waiting to transfer..."); boolean added = transferQueue.tryTransfer("A" + i, 4000, TimeUnit.MILLISECONDS); if (added) { numberOfProducedMessages.incrementAndGet(); - System.out.println("Producer: " + name + " transferred element: A" + i); + LOG.debug("Producer: " + name + " transferred element: A" + i); } else { - System.out.println("can not add an element due to the timeout"); + LOG.debug("can not add an element due to the timeout"); } } catch (InterruptedException e) { e.printStackTrace(); diff --git a/core-java/src/test/java/com/baeldung/PrimitiveConversionsJUnitTest.java b/core-java/src/test/java/com/baeldung/PrimitiveConversionsJUnitTest.java index 10ceaf85a4..69a6c18dfd 100644 --- a/core-java/src/test/java/com/baeldung/PrimitiveConversionsJUnitTest.java +++ b/core-java/src/test/java/com/baeldung/PrimitiveConversionsJUnitTest.java @@ -1,13 +1,14 @@ package com.baeldung; import org.junit.Test; -import static org.junit.Assert.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static org.junit.Assert.assertEquals; -/** - * - * @author paulo.motta - */ public class PrimitiveConversionsJUnitTest { + + private static final Logger LOG = LoggerFactory.getLogger(PrimitiveConversionsJUnitTest.class); @Test public void givenDataWithLessBits_whenAttributingToLargerSizeVariable_thenNoSpecialNotation() { @@ -60,36 +61,36 @@ public class PrimitiveConversionsJUnitTest { @Test public void givenByteValue_whenConvertingToChar_thenWidenAndNarrowTakesPlace(){ byte myLargeValueByte = (byte) 130; //0b10000010 - System.out.println(myLargeValueByte); //0b10000010 -126 + LOG.debug("{}", myLargeValueByte); //0b10000010 -126 assertEquals( -126, myLargeValueByte); int myLargeValueInt = myLargeValueByte; - System.out.println(myLargeValueInt); //0b11111111 11111111 11111111 10000010 -126 + LOG.debug("{}", myLargeValueInt); //0b11111111 11111111 11111111 10000010 -126 assertEquals( -126, myLargeValueInt); char myLargeValueChar = (char) myLargeValueByte; - System.out.println(myLargeValueChar);//0b11111111 10000010 unsigned 0xFF82 + LOG.debug("{}", myLargeValueChar);//0b11111111 10000010 unsigned 0xFF82 assertEquals(0xFF82, myLargeValueChar); myLargeValueInt = myLargeValueChar; - System.out.println(myLargeValueInt); //0b11111111 10000010 65410 + LOG.debug("{}", myLargeValueInt); //0b11111111 10000010 65410 assertEquals(65410, myLargeValueInt); byte myOtherByte = (byte) myLargeValueInt; - System.out.println(myOtherByte); //0b10000010 -126 + LOG.debug("{}", myOtherByte); //0b10000010 -126 assertEquals( -126, myOtherByte); char myLargeValueChar2 = 130; //This is an int not a byte! - System.out.println(myLargeValueChar2);//0b00000000 10000010 unsigned 0x0082 + LOG.debug("{}", myLargeValueChar2);//0b00000000 10000010 unsigned 0x0082 assertEquals(0x0082, myLargeValueChar2); int myLargeValueInt2 = myLargeValueChar2; - System.out.println(myLargeValueInt2); //0b00000000 10000010 130 + LOG.debug("{}", myLargeValueInt2); //0b00000000 10000010 130 assertEquals(130, myLargeValueInt2); byte myOtherByte2 = (byte) myLargeValueInt2; - System.out.println(myOtherByte2); //0b10000010 -126 + LOG.debug("{}", myOtherByte2); //0b10000010 -126 assertEquals( -126, myOtherByte2); } diff --git a/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureUnitTest.java b/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureUnitTest.java index df12c3d79e..501cb1afa0 100644 --- a/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureUnitTest.java +++ b/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureUnitTest.java @@ -1,20 +1,21 @@ package com.baeldung.completablefuture; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import java.util.concurrent.CancellationException; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.junit.Test; - public class CompletableFutureUnitTest { + private static final Logger LOG = LoggerFactory.getLogger(CompletableFutureUnitTest.class); + + @Test public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException { Future completableFuture = calculateAsync(); @@ -72,7 +73,7 @@ public class CompletableFutureUnitTest { public void whenAddingThenAcceptToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); - CompletableFuture future = completableFuture.thenAccept(s -> System.out.println("Computation returned: " + s)); + CompletableFuture future = completableFuture.thenAccept(s -> LOG.debug("Computation returned: " + s)); future.get(); } @@ -81,7 +82,7 @@ public class CompletableFutureUnitTest { public void whenAddingThenRunToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); - CompletableFuture future = completableFuture.thenRun(() -> System.out.println("Computation finished.")); + CompletableFuture future = completableFuture.thenRun(() -> LOG.debug("Computation finished.")); future.get(); } @@ -111,7 +112,7 @@ public class CompletableFutureUnitTest { @Test public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { - CompletableFuture.supplyAsync(() -> "Hello").thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> System.out.println(s1 + s2)); + CompletableFuture.supplyAsync(() -> "Hello").thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> LOG.debug(s1 + s2)); } @Test diff --git a/core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java b/core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java index bc63fbe6f7..84d7a55504 100644 --- a/core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java @@ -5,6 +5,8 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.concurrent.*; @@ -13,6 +15,9 @@ import static org.junit.Assert.assertTrue; public class SquareCalculatorIntegrationTest { + private static final Logger LOG = LoggerFactory.getLogger(SquareCalculatorIntegrationTest.class); + + @Rule public TestName name = new TestName(); @@ -28,7 +33,7 @@ public class SquareCalculatorIntegrationTest { Future result2 = squareCalculator.calculate(1000); while (!result1.isDone() || !result2.isDone()) { - System.out.println(String.format("Task 1 is %s and Task 2 is %s.", result1.isDone() ? "done" : "not done", result2.isDone() ? "done" : "not done")); + LOG.debug(String.format("Task 1 is %s and Task 2 is %s.", result1.isDone() ? "done" : "not done", result2.isDone() ? "done" : "not done")); Thread.sleep(300); } @@ -54,7 +59,7 @@ public class SquareCalculatorIntegrationTest { Future result2 = squareCalculator.calculate(1000); while (!result1.isDone() || !result2.isDone()) { - System.out.println(String.format("Task 1 is %s and Task 2 is %s.", result1.isDone() ? "done" : "not done", result2.isDone() ? "done" : "not done")); + LOG.debug(String.format("Task 1 is %s and Task 2 is %s.", result1.isDone() ? "done" : "not done", result2.isDone() ? "done" : "not done")); Thread.sleep(300); } @@ -84,6 +89,6 @@ public class SquareCalculatorIntegrationTest { @After public void end() { - System.out.println(String.format("Test %s took %s ms \n", name.getMethodName(), System.currentTimeMillis() - start)); + LOG.debug(String.format("Test %s took %s ms \n", name.getMethodName(), System.currentTimeMillis() - start)); } } diff --git a/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java b/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java index 2a8eda896b..9f7b828a9c 100644 --- a/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java @@ -1,6 +1,8 @@ package com.baeldung.concurrent.priorityblockingqueue; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.concurrent.PriorityBlockingQueue; @@ -11,6 +13,9 @@ import static org.assertj.core.util.Lists.newArrayList; public class PriorityBlockingQueueIntegrationTest { + private static final Logger LOG = LoggerFactory.getLogger(PriorityBlockingQueueIntegrationTest.class); + + @Test public void givenUnorderedValues_whenPolling_thenShouldOrderQueue() throws InterruptedException { PriorityBlockingQueue queue = new PriorityBlockingQueue<>(); @@ -32,11 +37,11 @@ public class PriorityBlockingQueueIntegrationTest { PriorityBlockingQueue queue = new PriorityBlockingQueue<>(); final Thread thread = new Thread(() -> { - System.out.println("Polling..."); + LOG.debug("Polling..."); while (true) { try { Integer poll = queue.take(); - System.out.println("Polled: " + poll); + LOG.debug("Polled: " + poll); } catch (InterruptedException e) { } } @@ -44,7 +49,7 @@ public class PriorityBlockingQueueIntegrationTest { thread.start(); Thread.sleep(TimeUnit.SECONDS.toMillis(5)); - System.out.println("Adding to queue"); + LOG.debug("Adding to queue"); queue.addAll(newArrayList(1, 5, 6, 1, 2, 6, 7)); Thread.sleep(TimeUnit.SECONDS.toMillis(1)); diff --git a/core-java/src/test/java/com/baeldung/dynamicproxy/DynamicProxyTest.java b/core-java/src/test/java/com/baeldung/dynamicproxy/DynamicProxyTest.java index 4386b11797..dc7f9366ba 100644 --- a/core-java/src/test/java/com/baeldung/dynamicproxy/DynamicProxyTest.java +++ b/core-java/src/test/java/com/baeldung/dynamicproxy/DynamicProxyTest.java @@ -7,7 +7,7 @@ import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; -import static org.testng.Assert.fail; +import static org.junit.Assert.fail; public class DynamicProxyTest { diff --git a/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java b/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java index 6f3384c8eb..1036df0bb8 100644 --- a/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java +++ b/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java @@ -1,8 +1,9 @@ package com.baeldung.functionalinterface; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import com.google.common.util.concurrent.Uninterruptibles; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashMap; @@ -14,12 +15,13 @@ import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; -import org.junit.Test; - -import com.google.common.util.concurrent.Uninterruptibles; +import static org.junit.Assert.*; public class FunctionalInterfaceUnitTest { + private static final Logger LOG = LoggerFactory.getLogger(FunctionalInterfaceUnitTest.class); + + @Test public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() { Map nameMap = new HashMap<>(); @@ -65,7 +67,7 @@ public class FunctionalInterfaceUnitTest { @Test public void whenPassingLambdaToThreadConstructor_thenLambdaInferredToRunnable() { - Thread thread = new Thread(() -> System.out.println("Hello From Another Thread")); + Thread thread = new Thread(() -> LOG.debug("Hello From Another Thread")); thread.start(); } @@ -93,7 +95,7 @@ public class FunctionalInterfaceUnitTest { @Test public void whenUsingConsumerInForEach_thenConsumerExecutesForEachListElement() { List names = Arrays.asList("John", "Freddy", "Samuel"); - names.forEach(name -> System.out.println("Hello, " + name)); + names.forEach(name -> LOG.debug("Hello, " + name)); } @Test @@ -103,7 +105,7 @@ public class FunctionalInterfaceUnitTest { ages.put("Freddy", 24); ages.put("Samuel", 30); - ages.forEach((name, age) -> System.out.println(name + " is " + age + " years old")); + ages.forEach((name, age) -> LOG.debug(name + " is " + age + " years old")); } @Test diff --git a/core-java/src/test/java/com/baeldung/java/collections/ConcurrentModificationExceptionTest.java b/core-java/src/test/java/com/baeldung/java/collections/ConcurrentModificationExceptionTest.java index 100d25ab8d..d12f07286b 100644 --- a/core-java/src/test/java/com/baeldung/java/collections/ConcurrentModificationExceptionTest.java +++ b/core-java/src/test/java/com/baeldung/java/collections/ConcurrentModificationExceptionTest.java @@ -6,9 +6,10 @@ import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import static java.util.Arrays.asList; -import static org.testng.Assert.assertEquals; +import static org.junit.Assert.assertEquals; public class ConcurrentModificationExceptionTest { + @Test public void changingContentWithSetDoesNotThrowConcurrentModificationException() throws Exception { ArrayList array = new ArrayList<>(asList(0, "one", 2, "three")); diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTests.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTests.java index d102680aa4..3cd93a4d44 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTests.java +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTests.java @@ -8,7 +8,9 @@ import java.util.TreeMap; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; -import static org.testng.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; public class ConcurrentNavigableMapManualTests { diff --git a/core-java/src/test/java/com/baeldung/java/map/MapTest.java b/core-java/src/test/java/com/baeldung/java/map/MapTest.java index ce2710e176..ecdc3c5c70 100644 --- a/core-java/src/test/java/com/baeldung/java/map/MapTest.java +++ b/core-java/src/test/java/com/baeldung/java/map/MapTest.java @@ -1,24 +1,18 @@ package com.baeldung.java.map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.Collection; -import java.util.Comparator; -import java.util.ConcurrentModificationException; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.TreeMap; - import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.*; +import java.util.Map.Entry; + +import static org.junit.Assert.*; public class MapTest { + private static final Logger LOG = LoggerFactory.getLogger(MapTest.class); + + @Test public void givenHashMap_whenRetrievesKeyset_thenCorrect() { Map map = new HashMap<>(); @@ -208,22 +202,22 @@ public class MapTest { MyKey k2 = new MyKey(2, "secondKey"); MyKey k3 = new MyKey(2, "thirdKey"); - System.out.println("storing value for k1"); + LOG.debug("storing value for k1"); map.put(k1, "firstValue"); - System.out.println("storing value for k2"); + LOG.debug("storing value for k2"); map.put(k2, "secondValue"); - System.out.println("storing value for k3"); + LOG.debug("storing value for k3"); map.put(k3, "thirdValue"); - System.out.println("retrieving value for k1"); + LOG.debug("retrieving value for k1"); String v1 = map.get(k1); - System.out.println("retrieving value for k2"); + LOG.debug("retrieving value for k2"); String v2 = map.get(k2); - System.out.println("retrieving value for k3"); + LOG.debug("retrieving value for k3"); String v3 = map.get(k3); assertEquals("firstValue", v1); diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java index da586706a2..ebab715306 100644 --- a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java @@ -1,5 +1,8 @@ package com.baeldung.java.nio2.async; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -10,6 +13,8 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; public class AsyncEchoClient { + private static final Logger LOG = LoggerFactory.getLogger(AsyncEchoClient.class); + private AsynchronousSocketChannel client; private Future future; private static AsyncEchoClient instance; @@ -75,11 +80,11 @@ public class AsyncEchoClient { client.start(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; - System.out.println("Message to server:"); + LOG.debug("Message to server:"); while ((line = br.readLine()) != null) { String response = client.sendMessage(line); - System.out.println("response from server: " + response); - System.out.println("Message to server:"); + LOG.debug("response from server: " + response); + LOG.debug("Message to server:"); } } diff --git a/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java b/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java index 24097542d0..2fef04e9d4 100644 --- a/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java +++ b/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java @@ -2,6 +2,8 @@ package com.baeldung.java.nio2.attributes; import org.junit.BeforeClass; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.file.Files; @@ -15,6 +17,10 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class BasicAttribsTest { + + private static final Logger LOG = LoggerFactory.getLogger(BasicAttribsTest.class); + + private static final String HOME = System.getProperty("user.home"); private static BasicFileAttributes basicAttribs; @@ -31,9 +37,9 @@ public class BasicAttribsTest { FileTime modified = basicAttribs.lastModifiedTime(); FileTime accessed = basicAttribs.lastAccessTime(); - System.out.println("Created: " + created); - System.out.println("Modified: " + modified); - System.out.println("Accessed: " + accessed); + LOG.debug("Created: " + created); + LOG.debug("Modified: " + modified); + LOG.debug("Accessed: " + accessed); } diff --git a/core-java/src/test/java/com/baeldung/java/set/SetTest.java b/core-java/src/test/java/com/baeldung/java/set/SetTest.java index 32a5c7e07e..ac99e277a2 100644 --- a/core-java/src/test/java/com/baeldung/java/set/SetTest.java +++ b/core-java/src/test/java/com/baeldung/java/set/SetTest.java @@ -1,6 +1,8 @@ package com.baeldung.java.set; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.*; @@ -9,6 +11,8 @@ import static org.junit.Assert.assertTrue; public class SetTest { + private static final Logger LOG = LoggerFactory.getLogger(SetTest.class); + @Test public void givenTreeSet_whenRetrievesObjects_thenNaturalOrder() { Set set = new TreeSet<>(); @@ -88,7 +92,7 @@ public class SetTest { task.run(); long endTime = System.nanoTime(); long executionTime = endTime - startTime; - System.out.println(executionTime); + LOG.debug(String.valueOf(executionTime)); return executionTime; } } diff --git a/core-java/src/test/java/com/baeldung/java8/Java8ForEachTest.java b/core-java/src/test/java/com/baeldung/java8/Java8ForEachTest.java index d9b0aa9d98..07d2411e49 100644 --- a/core-java/src/test/java/com/baeldung/java8/Java8ForEachTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8ForEachTest.java @@ -1,13 +1,17 @@ package com.baeldung.java8; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; -import org.junit.Test; - public class Java8ForEachTest { + private static final Logger LOG = LoggerFactory.getLogger(Java8ForEachTest.class); + @Test public void compareForEachMethods_thenPrintResults() { @@ -19,33 +23,33 @@ public class Java8ForEachTest { names.add("Ellen"); // Java 5 - for-loop - System.out.println("--- Enhanced for-loop ---"); + LOG.debug("--- Enhanced for-loop ---"); for (String name : names) { - System.out.println(name); + LOG.debug(name); } // Java 8 - forEach - System.out.println("--- forEach method ---"); - names.forEach(name -> System.out.println(name)); + LOG.debug("--- forEach method ---"); + names.forEach(name -> LOG.debug(name)); // Anonymous inner class that implements Consumer interface - System.out.println("--- Anonymous inner class ---"); + LOG.debug("--- Anonymous inner class ---"); names.forEach(new Consumer() { public void accept(String name) { - System.out.println(name); + LOG.debug(name); } }); // Create a Consumer implementation to then use in a forEach method Consumer consumerNames = name -> { - System.out.println(name); + LOG.debug(name); }; - System.out.println("--- Implementation of Consumer interface ---"); + LOG.debug("--- Implementation of Consumer interface ---"); names.forEach(consumerNames); // Print elements using a Method Reference - System.out.println("--- Method Reference ---"); - names.forEach(System.out::println); + LOG.debug("--- Method Reference ---"); + names.forEach(LOG::debug); } diff --git a/core-java/src/test/java/com/baeldung/java8/JavaTryWithResourcesLongRunningUnitTest.java b/core-java/src/test/java/com/baeldung/java8/JavaTryWithResourcesLongRunningUnitTest.java index b5281f5bf4..28fea0fd31 100644 --- a/core-java/src/test/java/com/baeldung/java8/JavaTryWithResourcesLongRunningUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java8/JavaTryWithResourcesLongRunningUnitTest.java @@ -2,6 +2,8 @@ package com.baeldung.java8; import org.junit.Assert; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.PrintWriter; import java.io.StringWriter; @@ -10,6 +12,9 @@ import java.util.Scanner; public class JavaTryWithResourcesLongRunningUnitTest { + private static final Logger LOG = LoggerFactory.getLogger(JavaTryWithResourcesLongRunningUnitTest.class); + + private static final String TEST_STRING_HELLO_WORLD = "Hello World"; private Date resource1Date, resource2Date; @@ -52,32 +57,32 @@ public class JavaTryWithResourcesLongRunningUnitTest { class AutoCloseableResourcesFirst implements AutoCloseable { public AutoCloseableResourcesFirst() { - System.out.println("Constructor -> AutoCloseableResources_First"); + LOG.debug("Constructor -> AutoCloseableResources_First"); } public void doSomething() { - System.out.println("Something -> AutoCloseableResources_First"); + LOG.debug("Something -> AutoCloseableResources_First"); } @Override public void close() throws Exception { - System.out.println("Closed AutoCloseableResources_First"); + LOG.debug("Closed AutoCloseableResources_First"); resource1Date = new Date(); } } class AutoCloseableResourcesSecond implements AutoCloseable { public AutoCloseableResourcesSecond() { - System.out.println("Constructor -> AutoCloseableResources_Second"); + LOG.debug("Constructor -> AutoCloseableResources_Second"); } public void doSomething() { - System.out.println("Something -> AutoCloseableResources_Second"); + LOG.debug("Something -> AutoCloseableResources_Second"); } @Override public void close() throws Exception { - System.out.println("Closed AutoCloseableResources_Second"); + LOG.debug("Closed AutoCloseableResources_Second"); resource2Date = new Date(); Thread.sleep(10000); } diff --git a/core-java/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersTest.java b/core-java/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersTest.java index 05e84e2dab..db9631655f 100644 --- a/core-java/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersTest.java +++ b/core-java/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersTest.java @@ -2,6 +2,8 @@ package com.baeldung.java8.lambda.exceptions; import org.junit.Before; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Arrays; @@ -11,6 +13,9 @@ import static com.baeldung.java8.lambda.exceptions.LambdaExceptionWrappers.*; public class LambdaExceptionWrappersTest { + private static final Logger LOG = LoggerFactory.getLogger(LambdaExceptionWrappersTest.class); + + private List integers; @Before @@ -20,12 +25,12 @@ public class LambdaExceptionWrappersTest { @Test public void whenNoExceptionFromLambdaWrapper_thenSuccess() { - integers.forEach(lambdaWrapper(i -> System.out.println(50 / i))); + integers.forEach(lambdaWrapper(i -> LOG.debug("{}", 50 / i))); } @Test public void whenNoExceptionFromConsumerWrapper_thenSuccess() { - integers.forEach(consumerWrapper(i -> System.out.println(50 / i), ArithmeticException.class)); + integers.forEach(consumerWrapper(i -> LOG.debug("{}", 50 / i), ArithmeticException.class)); } @Test(expected = RuntimeException.class) diff --git a/core-java/src/test/java/com/baeldung/java8/optional/OptionalTest.java b/core-java/src/test/java/com/baeldung/java8/optional/OptionalTest.java index bf2078186c..13e42e0806 100644 --- a/core-java/src/test/java/com/baeldung/java8/optional/OptionalTest.java +++ b/core-java/src/test/java/com/baeldung/java8/optional/OptionalTest.java @@ -3,6 +3,8 @@ package com.baeldung.java8.optional; import com.baeldung.optional.Modem; import com.baeldung.optional.Person; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.List; @@ -12,6 +14,10 @@ import java.util.Optional; import static org.junit.Assert.*; public class OptionalTest { + + private static final Logger LOG = LoggerFactory.getLogger(OptionalTest.class); + + // creating Optional @Test public void whenCreatesEmptyOptional_thenCorrect() { @@ -66,7 +72,7 @@ public class OptionalTest { @Test public void givenOptional_whenIfPresentWorks_thenCorrect() { Optional opt = Optional.of("baeldung"); - opt.ifPresent(name -> System.out.println(name.length())); + opt.ifPresent(name -> LOG.debug("{}", name.length())); } // returning Value With get() @@ -200,11 +206,11 @@ public class OptionalTest { @Test public void whenOrElseGetAndOrElseOverlap_thenCorrect() { String text = null; - System.out.println("Using orElseGet:"); + LOG.debug("Using orElseGet:"); String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault); assertEquals("Default Value", defaultText); - System.out.println("Using orElse:"); + LOG.debug("Using orElse:"); defaultText = Optional.ofNullable(text).orElse(getMyDefault()); assertEquals("Default Value", defaultText); } @@ -212,11 +218,11 @@ public class OptionalTest { @Test public void whenOrElseGetAndOrElseDiffer_thenCorrect() { String text = "Text present"; - System.out.println("Using orElseGet:"); + LOG.debug("Using orElseGet:"); String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault); assertEquals("Text present", defaultText); - System.out.println("Using orElse:"); + LOG.debug("Using orElse:"); defaultText = Optional.ofNullable(text).orElse(getMyDefault()); assertEquals("Text present", defaultText); } @@ -229,7 +235,7 @@ public class OptionalTest { } public String getMyDefault() { - System.out.println("Getting default value..."); + LOG.debug("Getting default value..."); return "Default Value"; } } \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueTest.java b/core-java/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueTest.java index 5d73e02e4f..86e1c0825d 100644 --- a/core-java/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueTest.java +++ b/core-java/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueTest.java @@ -3,6 +3,8 @@ package com.baeldung.synchronousqueue; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; @@ -12,6 +14,9 @@ import static junit.framework.TestCase.assertEquals; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class SynchronousQueueTest { + private static final Logger LOG = LoggerFactory.getLogger(SynchronousQueueTest.class); + + @Test public void givenTwoThreads_whenWantToExchangeUsingLockGuardedVariable_thenItSucceed() throws InterruptedException { //given @@ -21,7 +26,7 @@ public class SynchronousQueueTest { Runnable producer = () -> { Integer producedElement = ThreadLocalRandom.current().nextInt(); - System.out.println("Saving an element: " + producedElement + " to the exchange point"); + LOG.debug("Saving an element: " + producedElement + " to the exchange point"); sharedState.set(producedElement); countDownLatch.countDown(); }; @@ -30,7 +35,7 @@ public class SynchronousQueueTest { try { countDownLatch.await(); Integer consumedElement = sharedState.get(); - System.out.println("consumed an element: " + consumedElement + " from the exchange point"); + LOG.debug("consumed an element: " + consumedElement + " from the exchange point"); } catch (InterruptedException ex) { ex.printStackTrace(); } @@ -55,7 +60,7 @@ public class SynchronousQueueTest { Runnable producer = () -> { Integer producedElement = ThreadLocalRandom.current().nextInt(); try { - System.out.println("Saving an element: " + producedElement + " to the exchange point"); + LOG.debug("Saving an element: " + producedElement + " to the exchange point"); queue.put(producedElement); } catch (InterruptedException ex) { ex.printStackTrace(); @@ -65,7 +70,7 @@ public class SynchronousQueueTest { Runnable consumer = () -> { try { Integer consumedElement = queue.take(); - System.out.println("consumed an element: " + consumedElement + " from the exchange point"); + LOG.debug("consumed an element: " + consumedElement + " from the exchange point"); } catch (InterruptedException ex) { ex.printStackTrace(); } diff --git a/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java b/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java index a62ec99043..9d8d3c884b 100644 --- a/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java @@ -1,24 +1,19 @@ package com.baeldung.threadpool; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; + import static org.junit.Assert.assertEquals; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executor; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.Future; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import org.junit.Test; - public class CoreThreadPoolIntegrationTest { + private static final Logger LOG = LoggerFactory.getLogger(CoreThreadPoolIntegrationTest.class); + + @Test(timeout = 1000) public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException { @@ -26,7 +21,7 @@ public class CoreThreadPoolIntegrationTest { Executor executor = Executors.newSingleThreadExecutor(); executor.execute(() -> { - System.out.println("Hello World"); + LOG.debug("Hello World"); lock.countDown(); }); @@ -115,7 +110,7 @@ public class CoreThreadPoolIntegrationTest { ScheduledExecutorService executor = Executors.newScheduledThreadPool(5); executor.schedule(() -> { - System.out.println("Hello World"); + LOG.debug("Hello World"); lock.countDown(); }, 500, TimeUnit.MILLISECONDS); @@ -130,7 +125,7 @@ public class CoreThreadPoolIntegrationTest { ScheduledExecutorService executor = Executors.newScheduledThreadPool(5); ScheduledFuture future = executor.scheduleAtFixedRate(() -> { - System.out.println("Hello World"); + LOG.debug("Hello World"); lock.countDown(); }, 500, 100, TimeUnit.MILLISECONDS); diff --git a/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionUnitTest.java b/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionUnitTest.java index e8007ad4c4..3f48049fe3 100644 --- a/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionUnitTest.java +++ b/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionUnitTest.java @@ -1,15 +1,10 @@ package org.baeldung.core.exceptions; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; - +import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.junit.Test; +import java.io.*; public class FileNotFoundExceptionUnitTest { @@ -22,7 +17,7 @@ public class FileNotFoundExceptionUnitTest { try { readFailingFile(); } catch (FileNotFoundException ex) { - throw new BusinessException("BusinessException: necessary file was not present.", ex); + throw new BusinessException("BusinessException: necessary file was not present."); } } @@ -35,7 +30,7 @@ public class FileNotFoundExceptionUnitTest { new File(fileName).createNewFile(); readFailingFile(); } catch (IOException ioe) { - throw new RuntimeException("BusinessException: even creation is not possible.", ioe); + throw new RuntimeException("BusinessException: even creation is not possible."); } } } @@ -45,7 +40,7 @@ public class FileNotFoundExceptionUnitTest { try { readFailingFile(); } catch (FileNotFoundException ex) { - LOG.error("Optional file " + fileName + " was not found.", ex); + LOG.error("Optional file " + fileName + " was not found."); } } @@ -56,8 +51,8 @@ public class FileNotFoundExceptionUnitTest { } private class BusinessException extends RuntimeException { - BusinessException(String string, FileNotFoundException ex) { - super(string, ex); + BusinessException(String string) { + super(string); } } } diff --git a/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java b/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java index 08f98025c3..f058e5d862 100644 --- a/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java @@ -3,26 +3,31 @@ package org.baeldung.java; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.math3.random.RandomDataGenerator; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.nio.charset.Charset; import java.util.Random; public class JavaRandomUnitTest { + private static final Logger LOG = LoggerFactory.getLogger(JavaRandomUnitTest.class); + + // tests - random long @Test public void givenUsingPlainJava_whenGeneratingRandomLongUnbounded_thenCorrect() { final long generatedLong = new Random().nextLong(); - System.out.println(generatedLong); + LOG.debug("{}", generatedLong); } @Test public void givenUsingApacheCommons_whenGeneratingRandomLongUnbounded_thenCorrect() { final long generatedLong = new RandomDataGenerator().getRandomGenerator().nextLong(); - System.out.println(generatedLong); + LOG.debug("{}", generatedLong); } @Test @@ -31,7 +36,7 @@ public class JavaRandomUnitTest { final long rightLimit = 10L; final long generatedLong = leftLimit + (long) (Math.random() * (rightLimit - leftLimit)); - System.out.println(generatedLong); + LOG.debug("{}", generatedLong); } @Test @@ -40,7 +45,7 @@ public class JavaRandomUnitTest { final long rightLimit = 100L; final long generatedLong = new RandomDataGenerator().nextLong(leftLimit, rightLimit); - System.out.println(generatedLong); + LOG.debug("{}", generatedLong); } // tests - random int @@ -49,7 +54,7 @@ public class JavaRandomUnitTest { public void givenUsingPlainJava_whenGeneratingRandomIntegerUnbounded_thenCorrect() { final int generatedInteger = new Random().nextInt(); - System.out.println(generatedInteger); + LOG.debug("{}", generatedInteger); } @Test @@ -58,14 +63,14 @@ public class JavaRandomUnitTest { final int rightLimit = 10; final int generatedInteger = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit)); - System.out.println(generatedInteger); + LOG.debug("{}", generatedInteger); } @Test public void givenUsingApache_whenGeneratingRandomIntegerUnbounded_thenCorrect() { final Integer generatedInteger = new RandomDataGenerator().getRandomGenerator().nextInt(); - System.out.println(generatedInteger); + LOG.debug("{}", generatedInteger); } @Test @@ -74,7 +79,7 @@ public class JavaRandomUnitTest { final int rightLimit = 10; final int generatedInteger = new RandomDataGenerator().nextInt(leftLimit, rightLimit); - System.out.println(generatedInteger); + LOG.debug("{}", generatedInteger); } // tests - random float @@ -83,14 +88,14 @@ public class JavaRandomUnitTest { public void givenUsingPlainJava_whenGeneratingRandomFloatUnbouned_thenCorrect() { final float generatedFloat = new Random().nextFloat(); - System.out.println(generatedFloat); + LOG.debug("{}", generatedFloat); } @Test public void givenUsingApache_whenGeneratingRandomFloatUnbounded_thenCorrect() { final float generatedFloat = new RandomDataGenerator().getRandomGenerator().nextFloat(); - System.out.println(generatedFloat); + LOG.debug("{}", generatedFloat); } @Test @@ -99,7 +104,7 @@ public class JavaRandomUnitTest { final float rightLimit = 10F; final float generatedFloat = leftLimit + new Random().nextFloat() * (rightLimit - leftLimit); - System.out.println(generatedFloat); + LOG.debug("{}", generatedFloat); } @Test @@ -109,7 +114,7 @@ public class JavaRandomUnitTest { final float randomFloat = new RandomDataGenerator().getRandomGenerator().nextFloat(); final float generatedFloat = leftLimit + randomFloat * (rightLimit - leftLimit); - System.out.println(generatedFloat); + LOG.debug("{}", generatedFloat); } // tests - random double @@ -118,14 +123,14 @@ public class JavaRandomUnitTest { public void givenUsingPlainJava_whenGeneratingRandomDoubleUnbounded_thenCorrect() { final double generatedDouble = Math.random(); - System.out.println(generatedDouble); + LOG.debug("{}", generatedDouble); } @Test public void givenUsingApache_whenGeneratingRandomDoubleUnbounded_thenCorrect() { final double generatedDouble = new RandomDataGenerator().getRandomGenerator().nextDouble(); - System.out.println(generatedDouble); + LOG.debug("{}", generatedDouble); } @Test @@ -134,7 +139,7 @@ public class JavaRandomUnitTest { final double rightLimit = 10D; final double generatedDouble = leftLimit + new Random().nextDouble() * (rightLimit - leftLimit); - System.out.println(generatedDouble); + LOG.debug("{}", generatedDouble); } @Test @@ -143,7 +148,7 @@ public class JavaRandomUnitTest { final double rightLimit = 100D; final double generatedDouble = new RandomDataGenerator().nextUniform(leftLimit, rightLimit); - System.out.println(generatedDouble); + LOG.debug("{}", generatedDouble); } // tests - random String @@ -154,7 +159,7 @@ public class JavaRandomUnitTest { new Random().nextBytes(array); final String generatedString = new String(array, Charset.forName("UTF-8")); - System.out.println(generatedString); + LOG.debug(generatedString); } @Test @@ -169,28 +174,28 @@ public class JavaRandomUnitTest { } final String generatedString = buffer.toString(); - System.out.println(generatedString); + LOG.debug(generatedString); } @Test public void givenUsingApache_whenGeneratingRandomString_thenCorrect() { final String generatedString = RandomStringUtils.random(10); - System.out.println(generatedString); + LOG.debug(generatedString); } @Test public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() { final String generatedString = RandomStringUtils.randomAlphabetic(10); - System.out.println(generatedString); + LOG.debug(generatedString); } @Test public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() { final String generatedString = RandomStringUtils.randomAlphanumeric(10); - System.out.println(generatedString); + LOG.debug(generatedString); } @Test @@ -200,7 +205,7 @@ public class JavaRandomUnitTest { final boolean useNumbers = false; final String generatedString = RandomStringUtils.random(length, useLetters, useNumbers); - System.out.println(generatedString); + LOG.debug(generatedString); } } diff --git a/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java b/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java index 3b126464ab..7a03070e82 100644 --- a/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java @@ -1,5 +1,9 @@ package org.baeldung.java; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.Date; import java.util.Timer; import java.util.TimerTask; @@ -7,10 +11,11 @@ import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -import org.junit.Test; - public class JavaTimerLongRunningUnitTest { + private static final Logger LOG = LoggerFactory.getLogger(JavaTimerLongRunningUnitTest.class); + + // tests @Test @@ -18,7 +23,7 @@ public class JavaTimerLongRunningUnitTest { final TimerTask timerTask = new TimerTask() { @Override public void run() { - System.out.println("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread().getName()); + LOG.debug("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread().getName()); } }; final Timer timer = new Timer("Timer"); @@ -35,7 +40,7 @@ public class JavaTimerLongRunningUnitTest { final TimerTask repeatedTask = new TimerTask() { @Override public void run() { - System.out.println("Task performed on " + new Date()); + LOG.debug("Task performed on " + new Date()); } }; final Timer timer = new Timer("Timer"); @@ -53,7 +58,7 @@ public class JavaTimerLongRunningUnitTest { final TimerTask repeatedTask = new TimerTask() { @Override public void run() { - System.out.println("Task performed on " + new Date()); + LOG.debug("Task performed on " + new Date()); } }; final Timer timer = new Timer("Timer"); @@ -71,7 +76,7 @@ public class JavaTimerLongRunningUnitTest { final TimerTask task = new TimerTask() { @Override public void run() { - System.out.println("Task performed on " + new Date()); + LOG.debug("Task performed on " + new Date()); cancel(); } }; @@ -89,7 +94,7 @@ public class JavaTimerLongRunningUnitTest { final TimerTask task = new TimerTask() { @Override public void run() { - System.out.println("Task performed on " + new Date()); + LOG.debug("Task performed on " + new Date()); } }; final Timer timer = new Timer("Timer"); @@ -104,7 +109,7 @@ public class JavaTimerLongRunningUnitTest { final TimerTask task = new TimerTask() { @Override public void run() { - System.out.println("Task performed on " + new Date()); + LOG.debug("Task performed on " + new Date()); } }; final Timer timer = new Timer("Timer"); @@ -120,7 +125,7 @@ public class JavaTimerLongRunningUnitTest { final TimerTask repeatedTask = new TimerTask() { @Override public void run() { - System.out.println("Task performed on " + new Date()); + LOG.debug("Task performed on " + new Date()); } }; final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); diff --git a/core-java/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java b/core-java/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java index fb7bfe51a2..ecf68e0b2c 100644 --- a/core-java/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java @@ -1,24 +1,28 @@ package org.baeldung.java.collections; +import com.google.common.collect.ImmutableList; +import org.apache.commons.collections4.ListUtils; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; -import org.apache.commons.collections4.ListUtils; -import org.junit.Test; - -import com.google.common.collect.ImmutableList; - public class CoreJavaCollectionsUnitTest { + private static final Logger LOG = LoggerFactory.getLogger(CoreJavaCollectionsUnitTest.class); + + // tests - @Test public final void givenUsingTheJdk_whenArrayListIsSynchronized_thenCorrect() { final List list = new ArrayList(Arrays.asList("one", "two", "three")); final List synchronizedList = Collections.synchronizedList(list); - System.out.println("Synchronized List is: " + synchronizedList); + LOG.debug("Synchronized List is: " + synchronizedList); } @Test(expected = UnsupportedOperationException.class) diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java index b1aa58424d..41d0a8a02a 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java @@ -1,18 +1,10 @@ package org.baeldung.java.io; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.io.BufferedReader; -import java.io.DataInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.RandomAccessFile; -import java.io.SequenceInputStream; -import java.io.StreamTokenizer; +import java.io.*; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; @@ -21,10 +13,14 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.Scanner; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class JavaReadFromFileUnitTest { + + private static final Logger LOG = LoggerFactory.getLogger(JavaReadFromFileUnitTest.class); + @Test public void whenReadWithBufferedReader_thenCorrect() throws IOException { final String expected_value = "Hello world"; @@ -115,7 +111,7 @@ public class JavaReadFromFileUnitTest { final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8")); final String currentLine = reader.readLine(); reader.close(); - System.out.println(currentLine); + LOG.debug(currentLine); assertEquals(expected_value, currentLine); } diff --git a/core-java/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java b/core-java/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java index b7c2bd7272..86493f6e5d 100644 --- a/core-java/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java @@ -1,11 +1,12 @@ package org.baeldung.java.lists; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.Test; import java.util.Arrays; import java.util.List; +import static org.junit.Assert.*; + public class ListTestNgUnitTest { private final List list1 = Arrays.asList("1", "2", "3", "4"); @@ -14,8 +15,8 @@ public class ListTestNgUnitTest { @Test public void whenTestingForEquality_ShouldBeEqual() throws Exception { - Assert.assertEquals(list1, list2); - Assert.assertNotSame(list1, list2); - Assert.assertNotEquals(list1, list3); + assertEquals(list1, list2); + assertNotSame(list1, list2); + assertNotEquals(list1, list3); } } diff --git a/core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaManualTest.java b/core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaManualTest.java index bb849d6a13..877122ce40 100644 --- a/core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaManualTest.java +++ b/core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaManualTest.java @@ -1,25 +1,30 @@ package org.baeldung.java.sandbox; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.Date; import java.util.Timer; import java.util.TimerTask; -import org.junit.Test; - public class SandboxJavaManualTest { + + private static final Logger LOG = LoggerFactory.getLogger(SandboxJavaManualTest.class); + @Test public void givenUsingTimer_whenSchedulingTimerTaskOnce_thenCorrect() throws InterruptedException { final TimerTask timerTask = new TimerTask() { @Override public void run() { - System.out.println("Time when was task performed" + new Date()); - System.out.println("Thread's name: " + Thread.currentThread().getName()); + LOG.debug("Time when was task performed" + new Date()); + LOG.debug("Thread's name: " + Thread.currentThread().getName()); } }; final Timer timer = new Timer("Thread's name"); - System.out.println("Current time:" + new Date()); - System.out.println("Thread's name: " + Thread.currentThread().getName()); + LOG.debug("Current time:" + new Date()); + LOG.debug("Thread's name: " + Thread.currentThread().getName()); final long delay = 2L * 1000L; timer.schedule(timerTask, delay); Thread.sleep(delay); @@ -33,16 +38,16 @@ public class SandboxJavaManualTest { @Override public void run() { count++; - System.out.println("Time when task was performed: " + new Date()); - System.out.println("Thread's name: " + Thread.currentThread().getName()); + LOG.debug("Time when task was performed: " + new Date()); + LOG.debug("Thread's name: " + Thread.currentThread().getName()); if (count >= 5) { cancel(); } } }; final Timer timer = new Timer("Timer thread"); - System.out.println("Current time: " + new Date()); - System.out.println("Thread's name: " + Thread.currentThread().getName()); + LOG.debug("Current time: " + new Date()); + LOG.debug("Thread's name: " + Thread.currentThread().getName()); final long delay = 2L * 1000L; final long period = 1L * 1000L; timer.scheduleAtFixedRate(repeatedTask, delay, period); @@ -62,8 +67,8 @@ public class SandboxJavaManualTest { @Override public void run() { timesRunned++; - System.out.println("Task performed on: " + new Date()); - System.out.println("Thread's name: " + Thread.currentThread().getName()); + LOG.debug("Task performed on: " + new Date()); + LOG.debug("Thread's name: " + Thread.currentThread().getName()); if (timesRunned >= timesToRun) { cancel(); } @@ -72,10 +77,10 @@ public class SandboxJavaManualTest { final MyTask repeatedTask = new MyTask(); repeatedTask.setTimesToRun(5); final long delay = 2L * 1000L; - final long period = 1L * 1000L; + final long period = 1000L; final Timer timer = new Timer("Timer"); - System.out.println("Current time: " + new Date()); - System.out.println("Thread's name: " + Thread.currentThread().getName()); + LOG.debug("Current time: " + new Date()); + LOG.debug("Thread's name: " + Thread.currentThread().getName()); timer.scheduleAtFixedRate(repeatedTask, delay, period); Thread.sleep(delay + period * repeatedTask.timesToRun); } diff --git a/cucumber/pom.xml b/cucumber/pom.xml index 77d04f96c2..23509f46f6 100644 --- a/cucumber/pom.xml +++ b/cucumber/pom.xml @@ -77,14 +77,14 @@ ${java.target.version} + org.apache.maven.plugins maven-surefire-plugin - ${surefire.plugin.version} - - **/CalculatorTest.java - + + **/*IntegrationTest.java + diff --git a/cucumber/src/test/java/com/baeldung/cucumber/calculator/CalculatorTest.java b/cucumber/src/test/java/com/baeldung/cucumber/calculator/CalculatorIntegrationTest.java similarity index 91% rename from cucumber/src/test/java/com/baeldung/cucumber/calculator/CalculatorTest.java rename to cucumber/src/test/java/com/baeldung/cucumber/calculator/CalculatorIntegrationTest.java index 6bbbca60d2..f44d38421d 100644 --- a/cucumber/src/test/java/com/baeldung/cucumber/calculator/CalculatorTest.java +++ b/cucumber/src/test/java/com/baeldung/cucumber/calculator/CalculatorIntegrationTest.java @@ -11,5 +11,5 @@ import cucumber.api.junit.Cucumber; , plugin = { "pretty", "json:target/reports/json/calculator.json" } , glue = {"com.baeldung.cucumber.calculator"} ) -public class CalculatorTest { +public class CalculatorIntegrationTest { } diff --git a/pom.xml b/pom.xml index 57041f2340..40843adac0 100644 --- a/pom.xml +++ b/pom.xml @@ -52,6 +52,7 @@ handling-spring-static-resources hazelcast hbase + hibernate5 httpclient hystrix @@ -200,7 +201,7 @@ video-tutorials - wicket + xml xmlunit2 @@ -225,8 +226,6 @@ 1.6.0 maven - hibernate5 - diff --git a/wicket/pom.xml b/wicket/pom.xml index 8b81ea4be8..f51ef0173e 100644 --- a/wicket/pom.xml +++ b/wicket/pom.xml @@ -4,10 +4,10 @@ 4.0.0 com.baeldung.wicket.examples - wicket-intro + wicket war 1.0-SNAPSHOT - WicketIntro + Wicket 7.5.0 9.2.13.v20150730 @@ -100,6 +100,16 @@ jetty-maven-plugin ${jetty9.version} + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + + + From bb1ab4a77588b95cb0dd97a5f19343650813826f Mon Sep 17 00:00:00 2001 From: lor6 Date: Wed, 3 May 2017 12:36:17 +0300 Subject: [PATCH 21/30] BAEL-863 jdbc test (#1764) * BAEL-863 jdbc test * Reduce logging * Reduce logging * Reduce logging * Reduce logging * Reduce logging * Optimize build * Remove testng from core-java --- core-java/pom.xml | 11 ++ .../main/java/com/baeldung/jdbc/Employee.java | 51 ++++++ core-java/src/main/resources/log4j.properties | 6 + .../test/java/com/baeldung/jdbc/JdbcTest.java | 158 ++++++++++++++++++ 4 files changed, 226 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/jdbc/Employee.java create mode 100644 core-java/src/main/resources/log4j.properties create mode 100644 core-java/src/test/java/com/baeldung/jdbc/JdbcTest.java diff --git a/core-java/pom.xml b/core-java/pom.xml index d958b45807..1f5897ee2d 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -98,6 +98,13 @@ ${lombok.version} provided + + + + mysql + mysql-connector-java + ${mysql.version} + @@ -212,6 +219,7 @@ **/*IntegrationTest.java **/*LongRunningUnitTest.java **/*ManualTest.java + **/JdbcTest.java true @@ -366,6 +374,9 @@ 1.7.21 1.1.7 + + + 6.0.6 21.0 diff --git a/core-java/src/main/java/com/baeldung/jdbc/Employee.java b/core-java/src/main/java/com/baeldung/jdbc/Employee.java new file mode 100644 index 0000000000..749855ca3b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/jdbc/Employee.java @@ -0,0 +1,51 @@ +package com.baeldung.jdbc; + +public class Employee { + private int id; + private String name; + private String position; + private double salary; + + public Employee() { + } + + public Employee(int id, String name, double salary, String position) { + this.id = id; + this.name = name; + this.salary = salary; + this.position = position; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + + public String getPosition() { + return position; + } + + public void setPosition(String position) { + this.position = position; + } + +} diff --git a/core-java/src/main/resources/log4j.properties b/core-java/src/main/resources/log4j.properties new file mode 100644 index 0000000000..621cf01735 --- /dev/null +++ b/core-java/src/main/resources/log4j.properties @@ -0,0 +1,6 @@ +log4j.rootLogger=DEBUG, A1 + +log4j.appender.A1=org.apache.log4j.ConsoleAppender + +log4j.appender.A1.layout=org.apache.log4j.PatternLayout +log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/jdbc/JdbcTest.java b/core-java/src/test/java/com/baeldung/jdbc/JdbcTest.java new file mode 100644 index 0000000000..ff786c7267 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/jdbc/JdbcTest.java @@ -0,0 +1,158 @@ +package com.baeldung.jdbc; + +import static org.junit.Assert.*; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Types; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.IntStream; + +import org.apache.log4j.Logger; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class JdbcTest { + + private static final Logger LOG = Logger.getLogger(JdbcTest.class); + + private Connection con; + + @Before + public void setup() throws ClassNotFoundException, SQLException { + Class.forName("com.mysql.cj.jdbc.Driver"); + + con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDb?noAccessToProcedureBodies=true", "user1", "pass"); + + Statement stmt = con.createStatement(); + + String tableSql = "CREATE TABLE IF NOT EXISTS employees (emp_id int PRIMARY KEY AUTO_INCREMENT, name varchar(30), position varchar(30), salary double)"; + stmt.execute(tableSql); + + } + + @Test + public void whenInsertUpdateRecord_thenCorrect() throws SQLException { + Statement stmt = con.createStatement(); + + String insertSql = "INSERT INTO employees(name, position, salary) values ('john', 'developer', 2000)"; + stmt.executeUpdate(insertSql); + + String selectSql = "SELECT * FROM employees"; + ResultSet resultSet = stmt.executeQuery(selectSql); + + List employees = new ArrayList<>(); + + while (resultSet.next()) { + Employee emp = new Employee(); + emp.setId(resultSet.getInt("emp_id")); + emp.setName(resultSet.getString("name")); + emp.setSalary(resultSet.getDouble("salary")); + emp.setPosition(resultSet.getString("position")); + employees.add(emp); + } + + assertEquals("employees list size incorrect", 1, employees.size()); + assertEquals("name incorrect", "john", employees.iterator().next().getName()); + assertEquals("position incorrect", "developer", employees.iterator().next().getPosition()); + assertEquals("salary incorrect", 2000, employees.iterator().next().getSalary(), 0.1); + + Statement updatableStmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); + ResultSet updatableResultSet = updatableStmt.executeQuery(selectSql); + + updatableResultSet.moveToInsertRow(); + updatableResultSet.updateString("name", "mark"); + updatableResultSet.updateString("position", "analyst"); + updatableResultSet.updateDouble("salary", 2000); + updatableResultSet.insertRow(); + + String updatePositionSql = "UPDATE employees SET position=? WHERE emp_id=?"; + PreparedStatement pstmt = con.prepareStatement(updatePositionSql); + pstmt.setString(1, "lead developer"); + pstmt.setInt(2, 1); + + String updateSalarySql = "UPDATE employees SET salary=? WHERE emp_id=?"; + PreparedStatement pstmt2 = con.prepareStatement(updateSalarySql); + pstmt.setDouble(1, 3000); + pstmt.setInt(2, 1); + + boolean autoCommit = con.getAutoCommit(); + + try { + con.setAutoCommit(false); + pstmt.executeUpdate(); + pstmt2.executeUpdate(); + con.commit(); + } catch (SQLException exc) { + con.rollback(); + } finally { + con.setAutoCommit(autoCommit); + } + } + + @Test + public void whenCallProcedure_thenCorrect() { + + try { + String preparedSql = "{call insertEmployee(?,?,?,?)}"; + CallableStatement cstmt = con.prepareCall(preparedSql); + cstmt.setString(2, "ana"); + cstmt.setString(3, "tester"); + cstmt.setDouble(4, 2000); + cstmt.registerOutParameter(1, Types.INTEGER); + cstmt.execute(); + int new_id = cstmt.getInt(1); + assertTrue(new_id > 0); + } catch (SQLException exc) { + LOG.error("Procedure incorrect or does not exist!"); + } + } + + @Test + public void whenReadMetadata_thenCorrect() throws SQLException { + + DatabaseMetaData dbmd = con.getMetaData(); + ResultSet tablesResultSet = dbmd.getTables(null, null, "%", null); + while (tablesResultSet.next()) { + LOG.info(tablesResultSet.getString("TABLE_NAME")); + } + + String selectSql = "SELECT * FROM employees"; + Statement stmt = con.createStatement(); + ResultSet resultSet = stmt.executeQuery(selectSql); + ResultSetMetaData rsmd = resultSet.getMetaData(); + int nrColumns = rsmd.getColumnCount(); + assertEquals(nrColumns, 4); + + IntStream.range(1, nrColumns).forEach(i -> { + try { + LOG.info(rsmd.getColumnName(i)); + } catch (SQLException e) { + e.printStackTrace(); + } + }); + } + + @After + public void closeConnection() throws SQLException { + + Statement updatableStmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); + ResultSet updatableResultSet = updatableStmt.executeQuery("SELECT * FROM employees"); + + while (updatableResultSet.next()) { + updatableResultSet.deleteRow(); + } + + con.close(); + } + +} From 05807aebed8b5688c909557f13f22380328e0f9b Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Wed, 3 May 2017 18:38:08 +0200 Subject: [PATCH 22/30] Hibernate5 fix (#1774) * Reduce logging * Reduce logging * Reduce logging * Reduce logging * Reduce logging * Optimize build * Remove testng from core-java * Fix hibernate tests * Exclude hibernate5 * Fix settest * XStream refactor * Refactor * Refactor --- algorithms/pom.xml | 23 +++++----- .../java/com/baeldung/java/set/SetTest.java | 5 ++- hibernate5/pom.xml | 13 ++++++ .../{java => resources}/hibernate.cfg.xml | 0 ... MultiTenantHibernateIntegrationTest.java} | 13 ++---- pom.xml | 6 +-- reactor-core/pom.xml | 13 ++++++ ...rTest.java => ReactorIntegrationTest.java} | 2 +- ...est.java => SimpleCLIIntegrationTest.java} | 6 +-- xstream/pom.xml | 15 ++++++- .../initializer/SimpleXstreamInitializer.java | 9 ++-- .../ComplexXmlToObjectAnnotationTest.java | 38 +++++++++++------ ...lexXmlToObjectAttributeCollectionTest.java | 42 ------------------- .../ComplexXmlToObjectCollectionTest.java | 22 ++++------ .../pojo/test/XmlToObjectAliasTest.java | 19 ++++----- .../pojo/test/XmlToObjectAnnotationTest.java | 9 +--- .../pojo/test/XmlToObjectFieldAliasTest.java | 21 ++++------ .../test/XmlToObjectIgnoreFieldsTest.java | 20 ++++----- .../baeldung/pojo/test/XmlToObjectTest.java | 18 ++++---- 19 files changed, 134 insertions(+), 160 deletions(-) rename hibernate5/src/main/{java => resources}/hibernate.cfg.xml (100%) rename hibernate5/src/test/java/com/baeldung/hibernate/{MultiTenantHibernateTest.java => MultiTenantHibernateIntegrationTest.java} (93%) rename reactor-core/src/test/java/com/baeldung/reactor/{ReactorTest.java => ReactorIntegrationTest.java} (98%) rename spring-all/src/test/java/org/baeldung/shell/simple/{SimpleCLIUnitTest.java => SimpleCLIIntegrationTest.java} (98%) delete mode 100644 xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java diff --git a/algorithms/pom.xml b/algorithms/pom.xml index 17d302a9ca..3dfce8769b 100644 --- a/algorithms/pom.xml +++ b/algorithms/pom.xml @@ -39,7 +39,6 @@ - install @@ -56,6 +55,17 @@ exec-maven-plugin ${exec-maven-plugin.version} + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*LongRunningUnitTest.java + **/*IntegrationTest.java + + + @@ -76,17 +86,6 @@ - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*LongRunningUnitTest.java - **/*IntegrationTest.java - - - diff --git a/core-java/src/test/java/com/baeldung/java/set/SetTest.java b/core-java/src/test/java/com/baeldung/java/set/SetTest.java index ac99e277a2..d669333b5c 100644 --- a/core-java/src/test/java/com/baeldung/java/set/SetTest.java +++ b/core-java/src/test/java/com/baeldung/java/set/SetTest.java @@ -52,14 +52,15 @@ public class SetTest { set.add("Awesome"); }); - long TreeSetInsertionTime = measureExecution(() -> { + long treeSetInsertionTime = measureExecution(() -> { Set set = new TreeSet<>(); set.add("Baeldung"); set.add("is"); set.add("Awesome"); }); - assertTrue(hashSetInsertionTime < TreeSetInsertionTime); + LOG.debug("HashSet insertion time: {}", hashSetInsertionTime); + LOG.debug("TreeSet insertion time: {}", treeSetInsertionTime); } @Test diff --git a/hibernate5/pom.xml b/hibernate5/pom.xml index b7473ec5b7..32712fba2a 100644 --- a/hibernate5/pom.xml +++ b/hibernate5/pom.xml @@ -55,6 +55,19 @@ + + org.apache.maven.plugins + maven-surefire-plugin + + 3 + true + + **/*IntegrationTest.java + **/*LiveTest.java + + + + diff --git a/hibernate5/src/main/java/hibernate.cfg.xml b/hibernate5/src/main/resources/hibernate.cfg.xml similarity index 100% rename from hibernate5/src/main/java/hibernate.cfg.xml rename to hibernate5/src/main/resources/hibernate.cfg.xml diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/MultiTenantHibernateTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/MultiTenantHibernateIntegrationTest.java similarity index 93% rename from hibernate5/src/test/java/com/baeldung/hibernate/MultiTenantHibernateTest.java rename to hibernate5/src/test/java/com/baeldung/hibernate/MultiTenantHibernateIntegrationTest.java index 4a701de48d..8f2e88ac3d 100644 --- a/hibernate5/src/test/java/com/baeldung/hibernate/MultiTenantHibernateTest.java +++ b/hibernate5/src/test/java/com/baeldung/hibernate/MultiTenantHibernateIntegrationTest.java @@ -1,21 +1,14 @@ package com.baeldung.hibernate; -import static org.junit.Assert.assertNotEquals; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.sql.Statement; - +import com.baeldung.hibernate.pojo.Supplier; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; -import org.junit.Before; import org.junit.Test; -import com.baeldung.hibernate.pojo.Supplier; +import static org.junit.Assert.assertNotEquals; -public class MultiTenantHibernateTest { +public class MultiTenantHibernateIntegrationTest { @Test public void givenDBMode_whenFetchingSuppliers_thenComparingFromDbs () { SessionFactory sessionFactory; diff --git a/pom.xml b/pom.xml index 40843adac0..3b4b5f847c 100644 --- a/pom.xml +++ b/pom.xml @@ -52,7 +52,7 @@ handling-spring-static-resources hazelcast hbase - hibernate5 + httpclient hystrix @@ -201,12 +201,8 @@ video-tutorials - - xml xmlunit2 - xstream - struts2 apache-velocity apache-solrj diff --git a/reactor-core/pom.xml b/reactor-core/pom.xml index 3aeb4af3d5..2f9b096fd2 100644 --- a/reactor-core/pom.xml +++ b/reactor-core/pom.xml @@ -16,6 +16,17 @@ 1.8 + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*LongRunningUnitTest.java + **/*IntegrationTest.java + + + @@ -56,4 +67,6 @@ 1.1.3 + + diff --git a/reactor-core/src/test/java/com/baeldung/reactor/ReactorTest.java b/reactor-core/src/test/java/com/baeldung/reactor/ReactorIntegrationTest.java similarity index 98% rename from reactor-core/src/test/java/com/baeldung/reactor/ReactorTest.java rename to reactor-core/src/test/java/com/baeldung/reactor/ReactorIntegrationTest.java index 0e534e7d61..56650ba306 100644 --- a/reactor-core/src/test/java/com/baeldung/reactor/ReactorTest.java +++ b/reactor-core/src/test/java/com/baeldung/reactor/ReactorIntegrationTest.java @@ -12,7 +12,7 @@ import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -public class ReactorTest { +public class ReactorIntegrationTest { @Test public void givenFlux_whenSubscribing_thenStream() throws InterruptedException { diff --git a/spring-all/src/test/java/org/baeldung/shell/simple/SimpleCLIUnitTest.java b/spring-all/src/test/java/org/baeldung/shell/simple/SimpleCLIIntegrationTest.java similarity index 98% rename from spring-all/src/test/java/org/baeldung/shell/simple/SimpleCLIUnitTest.java rename to spring-all/src/test/java/org/baeldung/shell/simple/SimpleCLIIntegrationTest.java index cc5ac863b5..3ec756e238 100644 --- a/spring-all/src/test/java/org/baeldung/shell/simple/SimpleCLIUnitTest.java +++ b/spring-all/src/test/java/org/baeldung/shell/simple/SimpleCLIIntegrationTest.java @@ -1,7 +1,5 @@ package org.baeldung.shell.simple; -import java.io.File; - import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; @@ -10,7 +8,9 @@ import org.springframework.shell.Bootstrap; import org.springframework.shell.core.CommandResult; import org.springframework.shell.core.JLineShellComponent; -public class SimpleCLIUnitTest { +import java.io.File; + +public class SimpleCLIIntegrationTest { static JLineShellComponent shell; diff --git a/xstream/pom.xml b/xstream/pom.xml index ee1882850a..a97bee27fa 100644 --- a/xstream/pom.xml +++ b/xstream/pom.xml @@ -2,9 +2,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.baeldung - xstream-introduction + xstream 0.0.1-SNAPSHOT - xstream-introduction + xstream An Introduction To XStream @@ -57,6 +57,17 @@ 1.8 + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*LongRunningUnitTest.java + **/*IntegrationTest.java + + + diff --git a/xstream/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java b/xstream/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java index a15bea5481..27b8cc84f3 100644 --- a/xstream/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java +++ b/xstream/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java @@ -7,17 +7,14 @@ import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver; public class SimpleXstreamInitializer { public XStream getXstreamInstance() { - XStream xtreamInstance = new XStream(); - return xtreamInstance; + return new XStream(); } public XStream getXstreamJettisonMappedInstance() { - XStream xstreamInstance = new XStream(new JettisonMappedXmlDriver()); - return xstreamInstance; + return new XStream(new JettisonMappedXmlDriver()); } public XStream getXstreamJsonHierarchicalInstance() { - XStream xstreamInstance = new XStream(new JsonHierarchicalStreamDriver()); - return xstreamInstance; + return new XStream(new JsonHierarchicalStreamDriver()); } } \ No newline at end of file diff --git a/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java b/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java index 479500c4a0..ed74086ed6 100644 --- a/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java +++ b/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java @@ -1,14 +1,15 @@ package com.baeldung.pojo.test; +import com.baeldung.complex.pojo.ContactDetails; import com.baeldung.complex.pojo.Customer; import com.baeldung.initializer.SimpleXstreamInitializer; import com.thoughtworks.xstream.XStream; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.FileReader; -import java.io.IOException; + +import static org.junit.Assert.assertNotNull; public class ComplexXmlToObjectAnnotationTest { @@ -22,17 +23,30 @@ public class ComplexXmlToObjectAnnotationTest { } @Test - public void convertXmlToObjectFromFile() { - try { - ClassLoader classLoader = getClass().getClassLoader(); - FileReader reader = new FileReader(classLoader.getResource("data-file-alias-field-complex.xml").getFile()); - Customer customer = (Customer) xstream.fromXML(reader); - Assert.assertNotNull(customer); - Assert.assertNotNull(customer.getContactDetailsList()); + public void convertXmlToObjectFromFile() throws Exception { + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader + .getResource("data-file-alias-field-complex.xml") + .getFile()); + Customer customer = (Customer) xstream.fromXML(reader); - } catch (IOException e) { - e.printStackTrace(); - } + assertNotNull(customer); + assertNotNull(customer.getContactDetailsList()); } + @Test + public void convertXmlToObjectAttributeFromFile() throws Exception { + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader + .getResource("data-file-alias-field-complex.xml") + .getFile()); + Customer customer = (Customer) xstream.fromXML(reader); + + assertNotNull(customer); + assertNotNull(customer.getContactDetailsList()); + + for (ContactDetails contactDetails : customer.getContactDetailsList()) { + assertNotNull(contactDetails.getContactType()); + } + } } diff --git a/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java b/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java deleted file mode 100644 index 8c569aa11e..0000000000 --- a/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.pojo.test; - -import com.baeldung.complex.pojo.ContactDetails; -import com.baeldung.complex.pojo.Customer; -import com.baeldung.initializer.SimpleXstreamInitializer; -import com.thoughtworks.xstream.XStream; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.io.FileReader; -import java.io.IOException; - -public class ComplexXmlToObjectAttributeCollectionTest { - - private XStream xstream = null; - - @Before - public void dataSetup() { - SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); - xstream = simpleXstreamInitializer.getXstreamInstance(); - xstream.processAnnotations(Customer.class); - } - - @Test - public void convertXmlToObjectFromFile() { - try { - ClassLoader classLoader = getClass().getClassLoader(); - FileReader reader = new FileReader(classLoader.getResource("data-file-alias-field-complex.xml").getFile()); - Customer customer = (Customer) xstream.fromXML(reader); - Assert.assertNotNull(customer); - Assert.assertNotNull(customer.getContactDetailsList()); - for (ContactDetails contactDetails : customer.getContactDetailsList()) { - Assert.assertNotNull(contactDetails.getContactType()); - } - - } catch (IOException e) { - e.printStackTrace(); - } - } - -} diff --git a/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java b/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java index 6b1ae9dbb3..02cdbd734f 100644 --- a/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java +++ b/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java @@ -7,8 +7,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import java.io.FileNotFoundException; import java.io.FileReader; -import java.io.IOException; public class ComplexXmlToObjectCollectionTest { @@ -22,18 +22,14 @@ public class ComplexXmlToObjectCollectionTest { } @Test - public void convertXmlToObjectFromFile() { - try { - ClassLoader classLoader = getClass().getClassLoader(); - FileReader reader = new FileReader(classLoader.getResource("data-file-alias-implicit-collection.xml").getFile()); - Customer customer = (Customer) xstream.fromXML(reader); - Assert.assertNotNull(customer); - Assert.assertNotNull(customer.getContactDetailsList()); - // System.out.println(customer); - - } catch (IOException e) { - e.printStackTrace(); - } + public void convertXmlToObjectFromFile() throws FileNotFoundException { + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader + .getResource("data-file-alias-implicit-collection.xml") + .getFile()); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + Assert.assertNotNull(customer.getContactDetailsList()); } } diff --git a/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java index 8a4de3b70a..b7c6a8b496 100644 --- a/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java +++ b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java @@ -7,8 +7,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import java.io.FileNotFoundException; import java.io.FileReader; -import java.io.IOException; public class XmlToObjectAliasTest { @@ -22,16 +22,13 @@ public class XmlToObjectAliasTest { } @Test - public void convertXmlToObjectFromFile() { - try { - ClassLoader classLoader = getClass().getClassLoader(); - FileReader reader = new FileReader(classLoader.getResource("data-file-alias.xml").getFile()); - Customer customer = (Customer) xstream.fromXML(reader); - Assert.assertNotNull(customer); - - } catch (IOException e) { - e.printStackTrace(); - } + public void convertXmlToObjectFromFile() throws FileNotFoundException { + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader + .getResource("data-file-alias.xml") + .getFile()); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); } } diff --git a/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java index 4a7ff2f74a..c2bb859e70 100644 --- a/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java +++ b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java @@ -7,8 +7,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import java.io.FileNotFoundException; import java.io.FileReader; -import java.io.IOException; public class XmlToObjectAnnotationTest { @@ -22,17 +22,12 @@ public class XmlToObjectAnnotationTest { } @Test - public void convertXmlToObjectFromFile() { - try { + public void convertXmlToObjectFromFile() throws FileNotFoundException { ClassLoader classLoader = getClass().getClassLoader(); FileReader reader = new FileReader(classLoader.getResource("data-file-alias-field.xml").getFile()); Customer customer = (Customer) xstream.fromXML(reader); Assert.assertNotNull(customer); Assert.assertNotNull(customer.getFirstName()); - - } catch (IOException e) { - e.printStackTrace(); - } } } diff --git a/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java index 3b1b8326ab..71e1cee809 100644 --- a/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java +++ b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java @@ -7,8 +7,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import java.io.FileNotFoundException; import java.io.FileReader; -import java.io.IOException; public class XmlToObjectFieldAliasTest { @@ -23,17 +23,14 @@ public class XmlToObjectFieldAliasTest { } @Test - public void convertXmlToObjectFromFile() { - try { - ClassLoader classLoader = getClass().getClassLoader(); - FileReader reader = new FileReader(classLoader.getResource("data-file-alias-field.xml").getFile()); - Customer customer = (Customer) xstream.fromXML(reader); - Assert.assertNotNull(customer); - Assert.assertNotNull(customer.getFirstName()); - - } catch (IOException e) { - e.printStackTrace(); - } + public void convertXmlToObjectFromFile() throws FileNotFoundException { + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader + .getResource("data-file-alias-field.xml") + .getFile()); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + Assert.assertNotNull(customer.getFirstName()); } } diff --git a/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java index 3b8a83cf47..7726fef0fc 100644 --- a/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java +++ b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java @@ -7,8 +7,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import java.io.FileNotFoundException; import java.io.FileReader; -import java.io.IOException; public class XmlToObjectIgnoreFieldsTest { @@ -23,16 +23,14 @@ public class XmlToObjectIgnoreFieldsTest { } @Test - public void convertXmlToObjectFromFile() { - try { - ClassLoader classLoader = getClass().getClassLoader(); - FileReader reader = new FileReader(classLoader.getResource("data-file-ignore-field.xml").getFile()); - Customer customer = (Customer) xstream.fromXML(reader); - Assert.assertNotNull(customer); - // System.out.println(customer); - } catch (IOException e) { - e.printStackTrace(); - } + public void convertXmlToObjectFromFile() throws FileNotFoundException { + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader + .getResource("data-file-ignore-field.xml") + .getFile()); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + // System.out.println(customer); } } diff --git a/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java index a36af81ec1..b7d8f27e5f 100644 --- a/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java +++ b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java @@ -9,7 +9,6 @@ import org.junit.Before; import org.junit.Test; import java.io.FileReader; -import java.io.IOException; public class XmlToObjectTest { @@ -22,16 +21,13 @@ public class XmlToObjectTest { } @Test - public void convertXmlToObjectFromFile() { - try { - ClassLoader classLoader = getClass().getClassLoader(); - FileReader reader = new FileReader(classLoader.getResource("data-file.xml").getFile()); - Customer customer = (Customer) xstream.fromXML(reader); - Assert.assertNotNull(customer); - - } catch (IOException e) { - e.printStackTrace(); - } + public void convertXmlToObjectFromFile() throws Exception { + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader + .getResource("data-file.xml") + .getFile()); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); } @Test From a623ddbf45f4410a4a9e7275c20a519a00b2ae8f Mon Sep 17 00:00:00 2001 From: Mateusz Mrozewski Date: Thu, 4 May 2017 00:47:34 +0400 Subject: [PATCH 23/30] BAEL-642 ClassToInstanceMap example (#1767) * BAEL-642 ClassToInstanceMap example added * BAEL-642 Improved example for ClassToInstanceMap * Reverted change in pom.xml * BAEL-642 Move the ClassToInstanceMap examples to guava module as unit tests --- .../guava/ClassToInstanceMapTests.java | 70 +++++++++++++++++++ ...reamsTests.java => GuavaStreamsTests.java} | 2 +- 2 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 guava/src/test/java/org/baeldung/guava/ClassToInstanceMapTests.java rename guava21/src/test/java/{GauavaStreamsTests.java => GuavaStreamsTests.java} (99%) diff --git a/guava/src/test/java/org/baeldung/guava/ClassToInstanceMapTests.java b/guava/src/test/java/org/baeldung/guava/ClassToInstanceMapTests.java new file mode 100644 index 0000000000..c8db9e573e --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/ClassToInstanceMapTests.java @@ -0,0 +1,70 @@ +package org.baeldung.guava; +import com.google.common.collect.ClassToInstanceMap; +import com.google.common.collect.ImmutableClassToInstanceMap; +import com.google.common.collect.MutableClassToInstanceMap; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class ClassToInstanceMapTests { + @Test + public void createEmptyImmutableMap() { + ClassToInstanceMap map = ImmutableClassToInstanceMap.of(); + assertTrue(map.isEmpty()); + } + + @Test + public void createEmptyMutableMap() { + ClassToInstanceMap map = MutableClassToInstanceMap.create(); + assertTrue(map.isEmpty()); + } + + @Test + public void createSingleEntryMap() { + ClassToInstanceMap map = ImmutableClassToInstanceMap.of(Save.class, new Save()); + assertEquals(1, map.size()); + } + + @Test + public void createMapWithBuilder() { + ClassToInstanceMap map = ImmutableClassToInstanceMap.builder() + .put(Save.class, new Save()) + .put(Open.class, new Open()) + .build(); + assertEquals(2, map.size()); + } + + @Test + public void shouldReturnElement() { + ClassToInstanceMap map = ImmutableClassToInstanceMap.of(Save.class, new Save()); + Action action = map.get(Save.class); + assertTrue(action instanceof Save); + + // Use getInstance to avoid casting + Save save = map.getInstance(Save.class); + } + + @Test + public void shouldPutElement() { + ClassToInstanceMap map = MutableClassToInstanceMap.create(); + map.put(Save.class, new Save()); + // Put again to get previous value returned + Action action = map.put(Save.class, new Save()); + assertTrue(action instanceof Save); + + // Use putInstance to avoid casting + Save save = map.putInstance(Save.class, new Save()); + } +} + +abstract class Action { +} + +class Save extends Action { +} + +class Open extends Action { +} + +class Delete extends Action { +} diff --git a/guava21/src/test/java/GauavaStreamsTests.java b/guava21/src/test/java/GuavaStreamsTests.java similarity index 99% rename from guava21/src/test/java/GauavaStreamsTests.java rename to guava21/src/test/java/GuavaStreamsTests.java index 1482d685cf..cc5fcff229 100644 --- a/guava21/src/test/java/GauavaStreamsTests.java +++ b/guava21/src/test/java/GuavaStreamsTests.java @@ -9,7 +9,7 @@ import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; -public class GauavaStreamsTests { +public class GuavaStreamsTests { List numbers; From 223cc5357f1f7e9e76310cad4e5b5b246b4175b1 Mon Sep 17 00:00:00 2001 From: Alexandre Lombard Date: Thu, 4 May 2017 12:20:03 +0200 Subject: [PATCH 24/30] BAEL-874 - How to convert stacktrace to String in Java? (#1771) --- .../exceptions/StackTraceToString.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/exceptions/StackTraceToString.java diff --git a/core-java/src/main/java/com/baeldung/exceptions/StackTraceToString.java b/core-java/src/main/java/com/baeldung/exceptions/StackTraceToString.java new file mode 100644 index 0000000000..c6bf915996 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/exceptions/StackTraceToString.java @@ -0,0 +1,30 @@ +package com.baeldung.exceptions; + +import org.apache.commons.lang3.exception.ExceptionUtils; + +import java.io.PrintWriter; +import java.io.StringWriter; + +public class StackTraceToString { + + public static void main(String[] args) { + // Convert a StackTrace to String using core java + try { + throw new NullPointerException(); + } catch (Exception e) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + e.printStackTrace(pw); + + System.out.println(sw.toString()); + } + + // Convert a StackTrace to String using Apache Commons + try { + throw new IndexOutOfBoundsException(); + } catch (Exception e) { + System.out.println(ExceptionUtils.getStackTrace(e)); + } + } + +} From 5f02c64c950e64964a5070a2679201543701ee91 Mon Sep 17 00:00:00 2001 From: baljeet20 Date: Thu, 4 May 2017 15:50:55 +0530 Subject: [PATCH 25/30] BAEL-804 A guide to Spring Drools (#1776) * BAEL-804 A guide to Spring Drools * BAEL-804 A guide to Spring Drools * BAEL-804 A guide to Spring Drools --- pom.xml | 1 + spring-drools/pom.xml | 130 ++++++++++++++++++ .../baeldung/spring/drools/Application.java | 30 ++++ .../spring/drools/DroolConfiguration.java | 83 +++++++++++ .../spring/drools/model/Applicant.java | 48 +++++++ .../baeldung/spring/drools/model/Product.java | 38 +++++ .../spring/drools/model/SuggestedRole.java | 14 ++ .../drools/service/ApplicantService.java | 25 ++++ .../spring/drools/service/ProductService.java | 24 ++++ .../spring/drools/rules/Product_rules.xls | Bin 0 -> 27648 bytes .../spring/drools/rules/SuggestApplicant.drl | 31 +++++ .../ApplicantServiceIntegrationTest.java | 52 +++++++ .../ProductServiceIntegrationTest.java | 34 +++++ 13 files changed, 510 insertions(+) create mode 100644 spring-drools/pom.xml create mode 100644 spring-drools/src/main/java/com/baeldung/spring/drools/Application.java create mode 100644 spring-drools/src/main/java/com/baeldung/spring/drools/DroolConfiguration.java create mode 100644 spring-drools/src/main/java/com/baeldung/spring/drools/model/Applicant.java create mode 100644 spring-drools/src/main/java/com/baeldung/spring/drools/model/Product.java create mode 100644 spring-drools/src/main/java/com/baeldung/spring/drools/model/SuggestedRole.java create mode 100644 spring-drools/src/main/java/com/baeldung/spring/drools/service/ApplicantService.java create mode 100644 spring-drools/src/main/java/com/baeldung/spring/drools/service/ProductService.java create mode 100644 spring-drools/src/main/resources/com/baeldung/spring/drools/rules/Product_rules.xls create mode 100644 spring-drools/src/main/resources/com/baeldung/spring/drools/rules/SuggestApplicant.drl create mode 100644 spring-drools/src/test/java/com/baeldung/spring/drools/service/ApplicantServiceIntegrationTest.java create mode 100644 spring-drools/src/test/java/com/baeldung/spring/drools/service/ProductServiceIntegrationTest.java diff --git a/pom.xml b/pom.xml index 3b4b5f847c..3f8eeb6264 100644 --- a/pom.xml +++ b/pom.xml @@ -212,6 +212,7 @@ spring-data-gemfire cucumber mybatis + spring-drools diff --git a/spring-drools/pom.xml b/spring-drools/pom.xml new file mode 100644 index 0000000000..8afdae0d84 --- /dev/null +++ b/spring-drools/pom.xml @@ -0,0 +1,130 @@ + + + 4.0.0 + + com.baeldung + spring-drools + 1.0.0-SNAPSHOT + + 1.1.1.RELEASE + 4.0-alpha6 + 7.0.0.CR1 + 3.13 + 2.19.1 + + + + + io.spring.platform + platform-bom + ${spring-boot-version} + pom + import + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-actuator + + + org.apache.httpcomponents + httpcore + ${http-component-version} + + + + org.kie + kie-ci + ${drools-version} + + + org.drools + drools-decisiontables + ${drools-version} + + + + org.drools + drools-core + ${drools-version} + + + org.drools + drools-compiler + ${drools-version} + + + org.apache.poi + poi + ${apache-poi-version} + + + + org.apache.poi + poi-ooxml + ${apache-poi-version} + + + org.kie + kie-spring + 6.4.0.Final + + + org.springframework + spring-tx + + + org.springframework + spring-beans + + + org.springframework + spring-core + + + org.springframework + spring-context + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire-plugin-version} + + + **/*IntegrationTest.java + + + + + + \ No newline at end of file diff --git a/spring-drools/src/main/java/com/baeldung/spring/drools/Application.java b/spring-drools/src/main/java/com/baeldung/spring/drools/Application.java new file mode 100644 index 0000000000..8f5b915f88 --- /dev/null +++ b/spring-drools/src/main/java/com/baeldung/spring/drools/Application.java @@ -0,0 +1,30 @@ +package com.baeldung.spring.drools; + + +import com.baeldung.spring.drools.model.Applicant; +import com.baeldung.spring.drools.model.Product; +import com.baeldung.spring.drools.model.SuggestedRole; +import com.baeldung.spring.drools.service.ApplicantService; +import com.baeldung.spring.drools.service.ProductService; +import org.kie.api.KieServices; +import org.kie.api.runtime.KieContainer; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; + +@SpringBootApplication +@Import(DroolConfiguration.class) +public class Application { + + public static void main(String[] args) { + ApplicationContext ctx = SpringApplication.run(Application.class, args); + ApplicantService applicantService=(ApplicantService)ctx.getBean("applicantService"); + applicantService.suggestARoleForApplicant(new Applicant("Baljeet",37,1200000.0,8),new SuggestedRole()); + + ProductService productService=(ProductService)ctx.getBean("productService"); + Product returnedProduct=productService.applyLabelToProduct(new Product("Microwave","Book")); + } + +} diff --git a/spring-drools/src/main/java/com/baeldung/spring/drools/DroolConfiguration.java b/spring-drools/src/main/java/com/baeldung/spring/drools/DroolConfiguration.java new file mode 100644 index 0000000000..7a5e833ed5 --- /dev/null +++ b/spring-drools/src/main/java/com/baeldung/spring/drools/DroolConfiguration.java @@ -0,0 +1,83 @@ +package com.baeldung.spring.drools; + +import com.baeldung.spring.drools.service.ApplicantService; +import com.baeldung.spring.drools.service.ProductService; +import org.kie.api.KieBase; +import org.kie.api.KieServices; +import org.kie.api.builder.*; +import org.kie.api.runtime.KieContainer; +import org.kie.api.runtime.KieSession; +import org.kie.internal.io.ResourceFactory; +import org.kie.spring.KModuleBeanFactoryPostProcessor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.core.io.support.ResourcePatternResolver; + +import java.io.IOException; + +@Configuration +public class DroolConfiguration { + + private static final String RULES_PATH = "com/baeldung/spring/drools/rules/"; + + @Bean + public KieFileSystem kieFileSystem() throws IOException { + KieFileSystem kieFileSystem = getKieServices().newKieFileSystem(); + for (Resource file : getRuleFiles()) { + kieFileSystem.write(ResourceFactory.newClassPathResource(RULES_PATH + file.getFilename(), "UTF-8")); + } + return kieFileSystem; + } + + private Resource[] getRuleFiles() throws IOException { + ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); + return resourcePatternResolver.getResources("classpath*:" + RULES_PATH + "**/*.*"); + } + + @Bean + public KieContainer kieContainer() throws IOException { + final KieRepository kieRepository = getKieServices().getRepository(); + + kieRepository.addKieModule(new KieModule() { + public ReleaseId getReleaseId() { + return kieRepository.getDefaultReleaseId(); + } + }); + + KieBuilder kieBuilder = getKieServices().newKieBuilder(kieFileSystem()); + kieBuilder.buildAll(); + + return getKieServices().newKieContainer(kieRepository.getDefaultReleaseId()); + } + + private KieServices getKieServices() { + return KieServices.Factory.get(); + } + + @Bean + public KieBase kieBase() throws IOException { + return kieContainer().getKieBase(); + } + + @Bean + public KieSession kieSession() throws IOException { + return kieContainer().newKieSession(); + } + + @Bean + public ApplicantService getApplicantService(){ + return new ApplicantService(); + } + + @Bean + public ProductService getProductService(KieContainer kieContainer){ + return new ProductService(); + } + + @Bean + public KModuleBeanFactoryPostProcessor kiePostProcessor() { + return new KModuleBeanFactoryPostProcessor(); + } +} \ No newline at end of file diff --git a/spring-drools/src/main/java/com/baeldung/spring/drools/model/Applicant.java b/spring-drools/src/main/java/com/baeldung/spring/drools/model/Applicant.java new file mode 100644 index 0000000000..f28d0fcab7 --- /dev/null +++ b/spring-drools/src/main/java/com/baeldung/spring/drools/model/Applicant.java @@ -0,0 +1,48 @@ +package com.baeldung.spring.drools.model; + +public class Applicant { + + private String name; + private int age; + private double currentSalary; + private int experienceInYears; + + public Applicant(String name, int age, Double currentSalary, int experienceInYears) { + this.name = name; + this.age = age; + this.currentSalary = currentSalary; + this.experienceInYears = experienceInYears; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public Double getCurrentSalary() { + return currentSalary; + } + + public void setCurrentSalary(Double currentSalary) { + this.currentSalary = currentSalary; + } + + public int getExperienceInYears() { + return experienceInYears; + } + + public void setExperienceInYears(int experienceInYears) { + this.experienceInYears = experienceInYears; + } +} diff --git a/spring-drools/src/main/java/com/baeldung/spring/drools/model/Product.java b/spring-drools/src/main/java/com/baeldung/spring/drools/model/Product.java new file mode 100644 index 0000000000..a861df5834 --- /dev/null +++ b/spring-drools/src/main/java/com/baeldung/spring/drools/model/Product.java @@ -0,0 +1,38 @@ +package com.baeldung.spring.drools.model; + +public class Product { + private String name; + private String type; + + private String label; + + public Product(String name, String type) { + this.name = name; + this.type = type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + +} diff --git a/spring-drools/src/main/java/com/baeldung/spring/drools/model/SuggestedRole.java b/spring-drools/src/main/java/com/baeldung/spring/drools/model/SuggestedRole.java new file mode 100644 index 0000000000..1ace5aa4ae --- /dev/null +++ b/spring-drools/src/main/java/com/baeldung/spring/drools/model/SuggestedRole.java @@ -0,0 +1,14 @@ +package com.baeldung.spring.drools.model; + +public class SuggestedRole { + + private String role; + + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } +} diff --git a/spring-drools/src/main/java/com/baeldung/spring/drools/service/ApplicantService.java b/spring-drools/src/main/java/com/baeldung/spring/drools/service/ApplicantService.java new file mode 100644 index 0000000000..f78ffe668b --- /dev/null +++ b/spring-drools/src/main/java/com/baeldung/spring/drools/service/ApplicantService.java @@ -0,0 +1,25 @@ +package com.baeldung.spring.drools.service; + +import com.baeldung.spring.drools.model.Applicant; +import com.baeldung.spring.drools.model.SuggestedRole; +import org.kie.api.runtime.KieContainer; +import org.kie.api.runtime.KieSession; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class ApplicantService { + + @Autowired + private KieContainer kieContainer; + + public SuggestedRole suggestARoleForApplicant(Applicant applicant,SuggestedRole suggestedRole){ + KieSession kieSession = kieContainer.newKieSession(); + kieSession.insert(applicant); + kieSession.setGlobal("suggestedRole",suggestedRole); + kieSession.fireAllRules(); + System.out.println(suggestedRole.getRole()); + return suggestedRole; + + } +} diff --git a/spring-drools/src/main/java/com/baeldung/spring/drools/service/ProductService.java b/spring-drools/src/main/java/com/baeldung/spring/drools/service/ProductService.java new file mode 100644 index 0000000000..21ca9c9730 --- /dev/null +++ b/spring-drools/src/main/java/com/baeldung/spring/drools/service/ProductService.java @@ -0,0 +1,24 @@ +package com.baeldung.spring.drools.service; + +import com.baeldung.spring.drools.model.Product; +import org.kie.api.runtime.KieContainer; +import org.kie.api.runtime.KieSession; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class ProductService { + + @Autowired + private KieContainer kieContainer; + + public Product applyLabelToProduct(Product product){ + KieSession kieSession = kieContainer.newKieSession(); + kieSession.insert(product); + kieSession.fireAllRules(); + System.out.println(product.getLabel()); + return product; + + } + +} diff --git a/spring-drools/src/main/resources/com/baeldung/spring/drools/rules/Product_rules.xls b/spring-drools/src/main/resources/com/baeldung/spring/drools/rules/Product_rules.xls new file mode 100644 index 0000000000000000000000000000000000000000..24caaf24707c1c8df2934def23897f213b30a990 GIT binary patch literal 27648 zcmeHw2V7Lg_W$g%zycPqU=3W+C@RwJg(fNyfgrY67gz*cSlnGKd7@ZjEYVmncB3(t z*b;qeY-o%|6IARy(O9CfVTneg?(ci%?y`ktL;kbRR+Si!X)qy#%H+mQ5WCoYunG(O;84JP#<=^P_dJ)JN9{+p&8%f|bcnyW} z9FSy4j!2|)XCyh23z9368&U_WW-o z{{M4U6PX%+I_M&rW#Lo9MnRJ0zdT_v#!g7lOpw!^v3>l`I*A|Ry|_haQu^MLl3--R z$>4DH0(A`=%91%BLq*_UxL09P3E8cYhw?Nf4wv;4YdW&-EQe*{Pr>^h11Y3&o(Q62 z8FsrDdcjg&ta^M)((9 zk(>vGgm`EV4NH(;j8p|4g<#M-?p67H6R)*ftc#M(m1Isuici|KLJfLD^^u12dNcUl zhuVhus=}@G~9k z@*(@v8keCN`#4Bq9qjT!HA4TiM!P?$Az@*5`;u;>FJ#f;cocP8V)J%n>RKirUa}B) z-x^Hf!@d@LFahyHs*g#ymyb@shR21gUOW&H7@rDOoD(ZwEmbW>;^O zM&J+H_Na^HA`dYbwm$Yz*yqF?Sq5fU!Avr+q{mG#NUh~zSxV9|)gYeQLT*NhQF|Xu z)qD)Hq>^y{>?QL@T}IIwYBdhX}TbN$4ePct754ajL?3<`e?QdDhhkZ^{W@9Chx~U2$?j>u)RzucSwXCois4Z*1cK9hgu|bf z4~`*kvwm4{!fFfue==NxVQ9KUIn(-$%VDdbMD`((jd5Qa&3v+}#MD>)|oqZN3{b*cHVGc>TF)X$9T|-b}Wg*O$PrayU&V_+|71 zjmvRhogj0;e02j>b zm%y#)QXGZXw}Mlggu_eZChDDHCkFh3@Q4tKNSER%9KIC~bjd_}qu30GFZS^8bn}G# z#c@ip7bAXA{^B^L87qfd$)Dmh9B#!Y#cnwKG$z^X%M$reJjYgjN4zz;{~^ZsCGuYa zk1YePGQef|mFd0UWW=MYUR^Ge%a~05mIZvYM;UNQbvZNDcLAPv9R$W+S<*G(H`2An zZwYrb@Srv8%r5m^MD@KSIQf4Cqwt55dK@wfwO z1}8kczB{m6!8v{_cnKcRHOEhQxZG^O&G0z6aQRR?)`EWn9ALn~Mj$=WWo4hEB_86q zFxR6%a)zrG?Ps*S8XFB0FkOS$qJZDxa^(>$*8=X2Dh`MVSL5+7337a{iz#3wSfEtK z3zTUTpu>z1v-$c!V2y-c5#>Nak?FFLkiRbn5(;gXjf7qf8^JV@+ohhCE9;KaUm z=mlazf{d-P6C7e+JM{W32NL_*q5YV0AhE9<+R!Nn68qW_%7?_hcIuT6iGA(BqyKq# z#4WS3M=@<`{i#gEJ-4!vG$@@*%OW9p4fpQamkYPWn>s z9V*a&cT8^*?8jCwug0k1%wJwq_hl}#jpXs;$0bOd@j|1@W5088*mDdj(=()v8scm3=4D-<6U2KMAq?J*&1`p!S6}Iw0f~_@4l{_yI7&-k7%9e4S^~pJDXp3|plz<2uoBuO^Ij5-A!kiGVSuMM|wwkrlk$K z@iwh$h>V9dnc&i7eC&`B-4Z9`s7!l&`I2oiRjkQ`lqS>A4jIvLaWYQIw7ZXfv`wa} zHJQ-TWSZC^L$1vMN`au9m1#GAx@VhAHES}>OOx@pL#DZjj9i&^@xc?@WU5<}X;GR? zupKhwcMZL9QKr4VbHO$lPa+d)-_pE6CbS%uRv5dZ@P=(NHLS_lu(bMi$e3GNVeG9P z+ijDnX-&q4r8Tlc#@x~hW6$5%ZJSIjYce)0t*IR{=9X3%Te$C{Z8Ej3$=I;806S#N zEv+zi`;WJ6lc{4(#)hSZ*db$XX@#+`&TO?!rY@0bVc*gOkZDm4OA8K}x8#H5nV0*1!%Kb4v>jxtKrKHW@E#GBzyD*A5wTOA8M9_S_=dWW24(*swG|J7ml) zEjZ-M<=@#RBUqEMVQGPO$e3GNaLDYVmu-`&XHCY2rG?rdV{U1|AukJN+9Fc{s~4;Q zOWvCiR`1QX^v-3zD;bL)x5qZp`X;2XC~KtktdN>p5rUTq-E1RmU_uJ}u}1o~6;gAX zVQkT^KDLp*Z9)obu}0e13aPn;FqW6P!Zy-|CZwKn2`MbW z8flOfQgiJy_B_9nEu?ZB(!lI1Qjt1a-r7?0k~(?^7KvqCYRRk7k!E#RUeoM|o@otk z@Feb7@FF}NrBJ2hs1&*kb=GY8I7@_5PrVxxk89DBi3D%EWHSS!A2=v~2AIwpfDIFu^j zSqbiFPs+piXq5p{}o0T_>E>H`NtbU%UzWQxo2%S)L4S8d|lH>E&oc=khds?wevb`Aby% z^PJJb->QYPzCx)Mmb9wlTsHOuqDN+{6j=(LS~E&WQjXNkmUp&9C2g*E$AROKI9N)$ z&*J*0gTSL8^CYk{681o=8Kd?|*#`4+LEo@k@2pnCP}^GKmDJYDSZ4@LZDpzyX)xjf zF(a-@nC~Of)J3UC&Bz)oV69-qsDnEs+XW1f?Pq||!C+8aBXASIfbovW715C?I)gLO z5zdiT!Xm>AIeecrat|BGMgLa@a(&q90-D1U@(^?6@PXFItJpv;`oS`gi&FzBM;>a9 z9KO)XAvjdEft>uIs4-`Av5-AA&y$z7TB)2P83iMtbD?x{GYf-`t~pXy%w`a^j>*c- zf%)WEs##hMGN6;%*|1+S6w~0OXoykK6f*f=x(s*Ll6+ZgM%GYes=;S;wPL0wd|9l4 zc{=)M?ll}rEV#sf89f$-NSx5q3al0QXK~6LokjtdWaZ2yb>YnE#4Pnx13M&VBrZ?5 z4@Qi{*x$tnq!&>V~6a2wBJH=(vJMSP`ub)bYH_ zrB!VHRv;&8p<)7{B7#l$Mxn;H^%S_79 zsUWQ&%T^ARp^YRMgAT$ad6gaz5;E@g9EDm(3bzVRIMm`ONZ_J|WZZ@dCyf-NEuG{?rY9Cx1!btY{4>X0YMhf^63aWwY@;0}2ZA6$!f{cVgb#t08xq zy?Wxv9?K^(_QkJ^D6&-AE}q3^4Qqohm#l)B=dpeJ_TeLsEm)vu3qsPcswrfJ_$o#k z{`7#eG~^4>5r#2AfAol39{(dS>QI;pb*Nn-+UxZT*aGDB3(yvL;a6Blnx2Ie76Oji zlolYR0e#v6mY<)`P=SRk003?_1Ze?JfQ6tf0R7x6(F}`daTXXGB%uJ=Bxv)eD1tk& zBt^1Hshx!Be&0R>afI*D>a+{xHQ7Ql;ZqS^5~P**3dc&TvgwSzGSQc9#8)TqMF&|8 zkRVbL-hx`zd&Bfjcp&mqjMxC-(GIGHVH<0N?V%lApbaW_)IB3=$8a_p$fiOMVHDW&b6 z21s}TB<84;-IY4H7V^Vdw2z99>ll+16CVdnL`2a87>JGU1w>Kt-4YU`yF|xzkLei= zXt(H&nAvuUNsJzt)Frx8k_?lYn9f~LGgh6#=iq`SLpv1ACv}NQ>^LwXA~C5Cx)_tC z&Cw{bQj`MMJA{#-$w(ou5vft63{~p1pdFK$t=8x;?ubQhphBWLM~7O#PcR`$otcSP zs}{^tKFIJHZ1@Zj7)w!S`X?(?%G8{!!T#E84O;uBYSe0#)?Z2X+feAp;)EW-uvpJO_S*a4#X+pNx4Ba(6wJ{)q zHVhDd9n9V=o2AH9LWYJ9DnwU}bva^mjekPy(JEz%PNUAsNP!w76`Ck8i^h>^^-z4o zbdQXK!9;b0MtjD`_UINJr}oDQ0wXr9QWr~{;=pvaLZis^Y1~$ig^HYg0QUiw*g1UC zX{|W)`xHJaV2$`OOn4wZZ{RauUaeBT**HKImeAEfMu+DJT#qffogM!QPj$gZRebi1 zQfKL)uYp|Y{ryK~s@8w}!;k}k?$OUDy_rz7?Yw5E@2d01R?O`0J?*K3( zi+ue2t+xJit4Jqh$xasTd0x1tpZB4N`#}wVS$pz}-9@fPULJb4*PY`>yAI#fBYC-# zQ+)3`^&9TlxM|b(M}r0>uJ}CZ&eGQHYR*y3tpC|%=LT!HcKB$YX2ueiLEDQy{kqxI zwkhp{stj&7>h{jj-*^sp_~Mrd?Ur@vxbe*Owd$$sLMH~ca`RiBwr=5;ol~NA3YWV- zndaa3u;$%kx7LoRcg4@;;a3Z9*G}?we^Ig1wLrh9pN~JO-lfyD7s^{9C-!D8Ie6&O z72msu2VXyUFP?p&|M1PR&?i5g9SBkAv9h%k)~d6sf7yqU77#5B_JJCuN*mx$_lYx) zLr4`qcsOa#gcG^%o;*?8%w^Yn$EN$#xm4%wrTFihTzAPQe)jPB+V*cY zPJ3}}?k|Gp!gWpuevS(JA^qC$_61|dADQ&o>bK>6M`ll6`HxHg9Jo8-#L9L@gX*m6 zvMq34mC92t#P3er7@2zFi2KQRqA!IeHyFG6<6#5Od4ICB*3}lVr+)KHJlAs2#+hr5 z=(ijQELZX|!YCg6JaJ+sy**PZq%`sa=pXJ4Z$r8_!wRKDi~ zbZ{yX9Y)cmD>Ib=X7_Gb!wpty$UG_(c5^)-xQAcM{dB~v3oTQ2`9>#y^~1(p&sfyr z+7aI^Ke_DExtrG~v^@4xwKI#lR_x=q*tz0V!WYGP>%vu|?^+XH{dnS6fs zne`uT`KD;{FMB_q)wFf8wEv(M#eO6LhcAwtyXp4L6NfFUr`)>v`J2zqv~B1AqK@?Q7IzL^f0TZ2{;LX-O46d!-zVO@ zuu%6}v42Zs>IaKNe=xXt$KmHME`Qjf&4!f@AN=Uv z=jAh}+@T{wYvVl7aJ->n5F|RYTM~vHj z>F|+rN$wSux;xE0+x57V+-!fqj!)RQhN-+&Rd*>?-PibDTebd-Kp8Zzi_WirP)C0!6xOLO}$I;I&ESg`iefQ!? zGqY>=s4?dC-DR&{&tJBpAotN1o5J*c+V5F^QvYH^*vnJiW8aIH*V>wY`-^1-FMpW7 zY46K}GxaYQ9Upplrfg}iBZEWhRmtt*f1*}=c*~TUy)?l!9&StaO!;;FzM$fbiuOIf zjQahW>y|b<>kXUnydN8R+M`3iz1gWt4kfQmKYA?w=Wpw^ySBLE*K3;ZtGcJx!Ed%G zYoAg3=l9qdGCkneXI|G%54%5dfnnn7A%8hI@Da z_55!WoyK?Fn{Yd2>f}$(E==w8OPsKwM*9^mzbkvJ4%u<>%cDoMp*PmY-A&P4ON@*h z)U*Dp>4D!(uly+S+Gii#tk7uvkmA+759UP1_3~MBa>goYeCLV7LMweZH)rTlm!j=I zKW$XAc-`6ija2h?%#A$pq|MU!pkI1?pE9Py)M2yFoQTV)-7CZU2d(_w>2Y7Ls~>hP zYx3>E#SU@XcmC1(?T>b;oyN~hzcFQNCHL29jfaeWF)O>#nAJ_U?fZ6lh47sdPP=r| z*HVSJ?#LXmW5WG$BV^I*{YQEAcetCW`zdltheJO+og3a$mA|I##Jy4J5660ay8Y(k z`_~`Wo+??D6P5gr%u}Np^{w;JQK?$jb9%dZpFht}$os}6_Sc+SMKRw`=u z$8HXKoY?#mzYQ)+Dvlo`Uw?UAO2Ln{kG1{euvpXS`=eZn4M>L^z!b}q2B;iOwC3! zLh79f%K!4WPe;w$HFeedjhgBscCDIle|WVuk~vpCOCMgZeZgJ-2#H4Q~O^Qi>&9)D{c=6V}X&YLfOnSJr z!jdK5`Ar-4QU1%}pC4}3HLLiux%=Do_}1ad5M|5n_v~uY=DND;ydgF9%hs;=L2_9L zjk-UM`Hyhy)TX_ncD;yC7q98hZ&`dpC|5 zzNgQC(}&mjygazG>yYYwu2m}-5b)El?W51HV!eiJh+bcDM&*l>vacTOHbe2%y}`jd zoFiY>I33nRnpV*3_V_l}2j^{&cL?kKN4+V(wx2P?J)*X7KfO}!%q3g*f7YkZsas2C zZhP$tclnlYmuKd<)mXB4-G-{wKRI7{Ow8sVY81$(JyC9}k-cMbk}j@R zkETx^9gm7B8e4b&s=7-F#GclJ`2Vf3|;W@t2!_Uo3z1s?(bwkF(Ee zeVDy@VcPhs35O=G@fh5%U0js3(}U_2JN+}|^|^~z*3FpedAo1s%D69%b?Lja|K%E^ z7ff#Go3i=$Ruzx#dA6_XwSRoMdT4rNr0;#%JG;DUy)&utrAbxBpBnyDd1-Kd)c4`V zzfL@PWJ@*O)z`)8C$s8qTX<#9fdj*}o6a?f+MGV z8(JZzO^Xeiw@TU`u-Is97d)q8=JmR72H zbl=UQpZ5nna_;IUu=CfeZA^UiAfm>bIpGVOi##5m=(lkwUAD&#A zxbIrprMd(AyzjiVx&FOj&RbjR|2Q&s$&3ei&vM;fzg0A*d-$U3O~W6g&2hUKK4{0S zB@4HBCCR28{k;8{VyrxD%)ct0n6+#hO6p*C*2rr9B~Ci|q{eI(W|)L_bNwc;+QjGM zN66LcQ#;*1Zg^!%(T39w6K^!H*dnaKyZ7!_+~_Cw|3I;KLB_86OO8}c3H~uCeO+yN zn>+J{E!>~ETe)GhBXB>MUXeWIz<=$$!>i>4;M z$lKUz<;yN$6^cz3clbFV zWGE4g(x=$IcHt!y<&vVzPvW+15dK{aGk!`~50tpFT)wiVpB4&3Udr>->P!t&p5RT~ zO?e7vHSsj%@m(vHSH+Yk={Knw1``+YIpHbK!&HvofTW2_7&wK5uz^Dt$)5ta2nk6k z5=GB7sWW)2jNj662ZUeBtP`PB7XMFoSV?6a#dI7WgHp%wZJ3cV;q9 zLt=nAnbjL73Fq}_OU2mM2$OS|$jg370^m-(1Oq-V4x45nD{l^SDB)!G2|SuolEhcy}V4uI$}>2_JKBJVPYE^1(9_6gtw8x&Z6MP#Wqq< zFts5I6x%qUO(*2UHZ*QJ^B)G=i&5u*Hl4Ah+6AM7D3OhZ^Cz;*7)}L;EZIA}FVrJP zwCRe!Sp11?s88K^P2w~TNu=b2n(<~inMKYKIZ`E2CF>S3IHSIj|700)=ZqS(Z4hse z16lmLoRS>%68X=XktF4)mx%DTNLP+tB=Vm)6U*pFrRp2XXnZ8`pG%`M7hvf@UnAr= zU4W$r|A{oQOokjqV#J&y>sgW`-Sy|+6s0m(U>U%DEosgbSO(%x#@o4q^JM-LYgCg) z-Fx)SK3?X=+j%2L?I=Xw7k^?qH?&J(f}tjj%t7>ZMBa|x2MWXy#df5_e)tpHVKWf) ze0W(Ua45m9lK3ZM=dclV8ZUxCoR|&8Ukgxe0&DU`>Vyp+`V%jrWa}c&Ch&rJWKJa> zhInD@ss)UAVC-oL>>Q}I1H_lZ@3D*YMl0S56TsW7SPm%p-D=>kGIJ_Q zaqyr_K7rp0B<|qq2g$4km?>i0Le9dZG;RtoxamFa&i58*^evT2(IZE;9B`uHQH&dG zBNQWyejJOVCXnH(2;1(owlGUL71dh6gttD&u}xBiYg}v?B@t%{ z?N~<)YhkEz)CjdEmBQ&h6yitJ+DFJ#DzdbKE?uF+4dHjx7^+QIDs>c#R|p!ho}Zw| zN)YAX`q${$Ce{hR`S!x}xj~2~JFmi5*aoSX1}Pb=#Z`cnz*x8iWn&KtA!vithbV?CgcOxRtA&2kH0n%Ib;e4h2t|%gor(Rf z6s`+JN{Uje&A{f6QTpTYCKDk2cu7TUPK%c<={uAj$@eRa|GP&rjci920A7OeWG#I- zB#VorU;6rU>BpChN(gI=9&G=#Ja4T@6KS*aOxco0vjoXji?*gjyh#0kJkG8I{)%y4Uc$aJVL zs*IsZKVb+_&?<>l9R?u{|Kw3{K;%(?jdoeZUc**+r$s`rOf}D{l=!JbZk(`1u}m0| zfx2)78H2Ob8fB`*s2*S#)$w*lwXBp~2@c}uJDnTEAp5ew$m|EpcS zEU~LUtnA9wrd?s|n(GuQ705XFJ3ylzA*8BDkb@UJ19=0%N2kohNkW|xniUO8po-Wm z#hn{0_Y&Azrrl?MAtDVH$qW39E(Gf0s8Vq}LCDF{W#CnlB>=5%6gLDIt(hg@r2#vE zDFbhoTHuZF%D^B{kMN@+dOLAzFdAp78or3!KTKIQ%3pAGRVq@_Ih!yY6KU|6Om8w+ zkS-kvjXfh{%Tx@7=Q2shUx>De1H%lm;P$ByMx?7DAx?mE*fB9yNXt+uiG_ITgwbUA zKx`w32MGLxxQK4ienLWGOnhQYQXfB|V~@lLI$A*QJY^b*Pc5YDblGhJ0u0;pYR%w) zj)txFrhF6|H`;ZI43*aCTHC?3R>BbY+PNZoX=ezymKp-f@0|EsUu+Ke)k}thdoorD zN84~nr<7|Y$7_Dk5ZJKk+vD96W7RY6`+emxqA}*^f9_iUJ4vF6pg5)bznCPsm9nM4 zhkvgv$@unoOSn@V?1>g`*6x&?t@%Z^q@Pypg44;^Thmkec;w!F)~GzT^#AuHsV)}B z6h08cigaLr@(#$0{ii&I3TW{}mzbw=aS};+TGoq)sKjzwyo=x8#&3>FtFUc6h#3wT zLqIMU_h~rxHH}s%CD;2{_|Sn!8J53Tw#o5GBx%Lu=(qp~o4DM>Dn=wq@d;=A(dSoK z-I(5d^u;G)bg!f}n}GEeJ)0+5AJwQxhpp&n6+cTwo$Z33$}pX78;qk|gUz@@(1h?h zbQFao{v@ym5feYXOV4)u~C{2i7`*aRXL1o!5T*Otzl%7<}iw?5QWOz@WmXRJfx7j zn3Ew#F>1;YmELG?%t?_Wm{=w=%Tb*^oNp?lq0$?xGO;G;o8<`F8+F7o8brOJJ7bP& zQtli$`W>I`5OJZudn^HbNqJlXD|@^pd}nEoZrP;=|L+M z2P=t<#t$hJr(?nR8Tp@#A>QJ@w||`k$OMdDSsW5{3R(Pr708Upkjd2O|5zXsr_cXh z|2YzPgWVhlSMCU)UDHL7tCN;Jei5JU{>8^~*0j-<3*;hFQ9!Pm%JY!OcBUZFh@Oi? zHnbdx+`|qevZZg4$RQUYkxgAjBD;EpM1fy9kdckii-l$rt?)^y)p-Mf^kQ&w9FdfNPt4$SBT8J;OrZ>rl( zfpgP3wKiSg=i^Zpj%2*T@sKy9+Nl0X2PO2(iv5-ysA_oD-<^Jb_eqK9AE~hXmp%PS z&m29o*uReZocYk7-;0f;Khg>50HWmKV;n}ui$RooZ+w#M1|iY5P&yKYoU)N<185`? z>17_0Q4b=|;>!?V!)&nhrxy@Y8?pm&4arS|f4PBGFcgv^$pCs8<0vbb|u}LxmC|oRP?kw6s=y%Zb#v5D xMf*PiF2QyleaAE#TVBa*$Y1UfO|{LvVR;acipi$_uIsPT|GVfK@%%f}{~xuG(?b9N literal 0 HcmV?d00001 diff --git a/spring-drools/src/main/resources/com/baeldung/spring/drools/rules/SuggestApplicant.drl b/spring-drools/src/main/resources/com/baeldung/spring/drools/rules/SuggestApplicant.drl new file mode 100644 index 0000000000..baaf29d0b4 --- /dev/null +++ b/spring-drools/src/main/resources/com/baeldung/spring/drools/rules/SuggestApplicant.drl @@ -0,0 +1,31 @@ +package com.baeldung.spring.drools.rules; + +import com.baeldung.spring.drools.model.Applicant; + +global com.baeldung.spring.drools.model.SuggestedRole suggestedRole; + +dialect "mvel" + +rule "Suggest Manager Role" + when + Applicant(experienceInYears > 10) + Applicant(currentSalary > 1000000 && currentSalary <= 2500000) + then + suggestedRole.setRole("Manager"); +end + +rule "Suggest Senior developer Role" + when + Applicant(experienceInYears > 5 && experienceInYears <= 10) + Applicant(currentSalary > 500000 && currentSalary <= 1500000) + then + suggestedRole.setRole("Senior developer"); +end + +rule "Suggest Developer Role" + when + Applicant(experienceInYears > 0 && experienceInYears <= 5) + Applicant(currentSalary > 200000 && currentSalary <= 1000000) + then + suggestedRole.setRole("Developer"); +end diff --git a/spring-drools/src/test/java/com/baeldung/spring/drools/service/ApplicantServiceIntegrationTest.java b/spring-drools/src/test/java/com/baeldung/spring/drools/service/ApplicantServiceIntegrationTest.java new file mode 100644 index 0000000000..d7e7634c00 --- /dev/null +++ b/spring-drools/src/test/java/com/baeldung/spring/drools/service/ApplicantServiceIntegrationTest.java @@ -0,0 +1,52 @@ +package com.baeldung.spring.drools.service; + +import com.baeldung.spring.drools.Application; +import com.baeldung.spring.drools.DroolConfiguration; +import com.baeldung.spring.drools.model.Applicant; +import com.baeldung.spring.drools.model.SuggestedRole; +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 static junit.framework.Assert.assertNull; +import static junit.framework.TestCase.assertEquals; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {DroolConfiguration.class}) +public class ApplicantServiceIntegrationTest { + + @Autowired + ApplicantService applicantService; + + @Test + public void whenCriteriaMatching_ThenSuggestManagerRole(){ + Applicant applicant=new Applicant("Davis",37,1600000.0,11); + SuggestedRole suggestedRole=new SuggestedRole(); + applicantService.suggestARoleForApplicant(applicant,suggestedRole); + assertEquals("Manager",suggestedRole.getRole()); + } + + @Test + public void whenCriteriaMatching_ThenSuggestSeniorDeveloperRole(){ + Applicant applicant=new Applicant("John",37,1200000.0,8); + SuggestedRole suggestedRole=new SuggestedRole(); + applicantService.suggestARoleForApplicant(applicant,suggestedRole); + assertEquals("Senior developer",suggestedRole.getRole()); + } + @Test + public void whenCriteriaMatching_ThenSuggestDeveloperRole(){ + Applicant applicant=new Applicant("Davis",37,800000.0,3); + SuggestedRole suggestedRole=new SuggestedRole(); + applicantService.suggestARoleForApplicant(applicant,suggestedRole); + assertEquals("Developer",suggestedRole.getRole()); + } + @Test + public void whenCriteriaNotMatching_ThenNoRole(){ + Applicant applicant=new Applicant("John",37,1200000.0,5); + SuggestedRole suggestedRole=new SuggestedRole(); + applicantService.suggestARoleForApplicant(applicant,suggestedRole); + assertNull(suggestedRole.getRole()); + } +} diff --git a/spring-drools/src/test/java/com/baeldung/spring/drools/service/ProductServiceIntegrationTest.java b/spring-drools/src/test/java/com/baeldung/spring/drools/service/ProductServiceIntegrationTest.java new file mode 100644 index 0000000000..7a442e48fd --- /dev/null +++ b/spring-drools/src/test/java/com/baeldung/spring/drools/service/ProductServiceIntegrationTest.java @@ -0,0 +1,34 @@ +package com.baeldung.spring.drools.service; + +import com.baeldung.spring.drools.Application; +import com.baeldung.spring.drools.DroolConfiguration; +import com.baeldung.spring.drools.model.Product; +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 static junit.framework.TestCase.assertEquals; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {DroolConfiguration.class}) +public class ProductServiceIntegrationTest { + + @Autowired + ProductService productService; + + @Test + public void whenProductTypeElectronic_ThenLabelBarcode(){ + Product product=new Product("Microwave","Electronic"); + product=productService.applyLabelToProduct(product); + assertEquals("BarCode",product.getLabel()); + } + + @Test + public void whenProductTypeBook_ThenLabelIsbn(){ + Product product=new Product("AutoBiography","Book"); + product=productService.applyLabelToProduct(product); + assertEquals("ISBN",product.getLabel()); + } +} From 3e50b39fed393fa532c6c523048ac8b8bde0326e Mon Sep 17 00:00:00 2001 From: Jesus Boadas Date: Thu, 4 May 2017 06:22:25 -0400 Subject: [PATCH 26/30] uncomment classes in core-java (#1777) * uncomment classes in core-java * Add content to guide to JDO --- .../baeldung/java8/comparator/Employee.java | 3 - .../java8/comparator/Java8ComparatorTest.java | 3 - libraries/myPersistence.xml | 26 +++ libraries/pom.xml | 5 + .../java/com/baeldung/jdo/GuideToJDO.java | 160 +++++++++++++++++- .../java/com/baeldung/jdo/ProductXML.java | 44 +++++ 6 files changed, 233 insertions(+), 8 deletions(-) create mode 100644 libraries/myPersistence.xml create mode 100644 libraries/src/main/java/com/baeldung/jdo/ProductXML.java diff --git a/core-java/src/test/java/com/baeldung/java8/comparator/Employee.java b/core-java/src/test/java/com/baeldung/java8/comparator/Employee.java index 0ef10410a9..bec0c37880 100644 --- a/core-java/src/test/java/com/baeldung/java8/comparator/Employee.java +++ b/core-java/src/test/java/com/baeldung/java8/comparator/Employee.java @@ -1,6 +1,4 @@ package com.baeldung.java8.comparator; -/* - import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; @@ -22,4 +20,3 @@ public class Employee implements Comparable{ } } -*/ \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/java8/comparator/Java8ComparatorTest.java b/core-java/src/test/java/com/baeldung/java8/comparator/Java8ComparatorTest.java index 8e1cfa67af..62dd18972e 100644 --- a/core-java/src/test/java/com/baeldung/java8/comparator/Java8ComparatorTest.java +++ b/core-java/src/test/java/com/baeldung/java8/comparator/Java8ComparatorTest.java @@ -1,5 +1,4 @@ package com.baeldung.java8.comparator; -/* import java.util.Arrays; import java.util.Comparator; @@ -164,5 +163,3 @@ public class Java8ComparatorTest { } - -*/ \ No newline at end of file diff --git a/libraries/myPersistence.xml b/libraries/myPersistence.xml new file mode 100644 index 0000000000..de2c250957 --- /dev/null +++ b/libraries/myPersistence.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/libraries/pom.xml b/libraries/pom.xml index e329eac44d..445a238540 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -251,6 +251,11 @@ h2 1.4.194 + + org.datanucleus + datanucleus-xml + 5.0.0-release + diff --git a/libraries/src/main/java/com/baeldung/jdo/GuideToJDO.java b/libraries/src/main/java/com/baeldung/jdo/GuideToJDO.java index fb7bd184ee..387c8c4e00 100644 --- a/libraries/src/main/java/com/baeldung/jdo/GuideToJDO.java +++ b/libraries/src/main/java/com/baeldung/jdo/GuideToJDO.java @@ -20,22 +20,29 @@ public class GuideToJDO { private static final Logger LOGGER = Logger.getLogger(GuideToJDO.class.getName()); private Random rnd = new Random(); private PersistenceUnitMetaData pumd; + private PersistenceUnitMetaData pumdXML; public static void main(String[] args) { new GuideToJDO(); } public GuideToJDO() { - CreateProperties(); + CreateH2Properties(); + CreateXMLProperties(); CreateProducts(); ListProducts(); + QueryJDOQL(); + QuerySQL(); + QueryJPQL(); UpdateProducts(); ListProducts(); DeleteProducts(); ListProducts(); + persistXML(); + listXMLProducts(); } - public void CreateProperties(){ + public void CreateH2Properties(){ pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null); pumd.addClassName("com.baeldung.jdo.Product"); @@ -48,6 +55,14 @@ public class GuideToJDO { } + public void CreateXMLProperties(){ + pumdXML = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null); + pumdXML.addClassName("com.baeldung.jdo.ProductXML"); + pumdXML.setExcludeUnlistedClasses(); + pumdXML.addProperty("javax.jdo.option.ConnectionURL", "xml:file:myPersistence.xml"); + pumdXML.addProperty("datanucleus.autoCreateSchema", "true"); + } + public void CreateProducts() { PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); PersistenceManager pm = pmf.getPersistenceManager(); @@ -140,4 +155,145 @@ public class GuideToJDO { pm.close(); } } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void QueryJDOQL (){ + PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); + PersistenceManager pm = pmf.getPersistenceManager(); + Transaction tx = pm.currentTransaction(); + try { + tx.begin(); + + // Declarative JDOQL : + LOGGER.log(Level.INFO, "Declarative JDOQL --------------------------------------------------------------"); + Query qDJDOQL = pm.newQuery(Product.class); + qDJDOQL.setFilter("name == 'Tablet' && price == price_value"); + qDJDOQL.declareParameters("double price_value"); + List resultsqDJDOQL = qDJDOQL.setParameters(80.0).executeList(); + + Iterator iterDJDOQL = resultsqDJDOQL.iterator(); + while (iterDJDOQL.hasNext()) { + Product p = iterDJDOQL.next(); + LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price }); + } + LOGGER.log(Level.INFO, "--------------------------------------------------------------"); + + tx.commit(); + } finally { + if (tx.isActive()) { + tx.rollback(); + } + + pm.close(); + } + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void QuerySQL (){ + PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); + PersistenceManager pm = pmf.getPersistenceManager(); + Transaction tx = pm.currentTransaction(); + try { + tx.begin(); + + //SQL : + LOGGER.log(Level.INFO, "SQL --------------------------------------------------------------"); + Query query = pm.newQuery("javax.jdo.query.SQL", "SELECT * FROM PRODUCT"); + query.setClass(Product.class); + List results = query.executeList(); + + Iterator iter = results.iterator(); + while (iter.hasNext()) { + Product p = iter.next(); + LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price }); + } + LOGGER.log(Level.INFO, "--------------------------------------------------------------"); + + tx.commit(); + } finally { + if (tx.isActive()) { + tx.rollback(); + } + + pm.close(); + } + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void QueryJPQL (){ + PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); + PersistenceManager pm = pmf.getPersistenceManager(); + Transaction tx = pm.currentTransaction(); + try { + tx.begin(); + + //JPQL : + LOGGER.log(Level.INFO, "JPQL --------------------------------------------------------------"); + Query q = pm.newQuery("JPQL", "SELECT p FROM "+Product.class.getName()+" p WHERE p.name = 'Laptop'"); + List results = (List)q.execute(); + + Iterator iter = results.iterator(); + while (iter.hasNext()) { + Product p = iter.next(); + LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price }); + } + LOGGER.log(Level.INFO, "--------------------------------------------------------------"); + + tx.commit(); + } finally { + if (tx.isActive()) { + tx.rollback(); + } + + pm.close(); + } + } + + public void persistXML(){ + PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumdXML, null); + PersistenceManager pm = pmf.getPersistenceManager(); + Transaction tx = pm.currentTransaction(); + try { + tx.begin(); + ProductXML productXML = new ProductXML(0,"Tablet", 80.0); + pm.makePersistent(productXML); + ProductXML productXML2 = new ProductXML(1,"Phone", 20.0); + pm.makePersistent(productXML2); + ProductXML productXML3 = new ProductXML(2,"Laptop", 200.0); + pm.makePersistent(productXML3); + tx.commit(); + } finally { + if (tx.isActive()) { + tx.rollback(); + } + pm.close(); + } + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void listXMLProducts(){ + PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumdXML, null); + PersistenceManager pm = pmf.getPersistenceManager(); + Transaction tx = pm.currentTransaction(); + try { + tx.begin(); + + Query q = pm.newQuery("SELECT FROM " + ProductXML.class.getName()); + List products = (List) q.execute(); + Iterator iter = products.iterator(); + while (iter.hasNext()) { + ProductXML p = iter.next(); + LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.getName(), p.getPrice() }); + pm.deletePersistent(p); + } + LOGGER.log(Level.INFO, "--------------------------------------------------------------"); + tx.commit(); + } finally { + if (tx.isActive()) { + tx.rollback(); + } + + pm.close(); + } + } } \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/jdo/ProductXML.java b/libraries/src/main/java/com/baeldung/jdo/ProductXML.java new file mode 100644 index 0000000000..d702a8ac90 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jdo/ProductXML.java @@ -0,0 +1,44 @@ +package com.baeldung.jdo; + +import javax.jdo.annotations.PersistenceCapable; +import javax.jdo.annotations.PrimaryKey; +import javax.xml.bind.annotation.XmlAttribute; + +@PersistenceCapable() +public class ProductXML { + + @XmlAttribute + private long productNumber = 0; + @PrimaryKey + private String name = null; + private Double price = 0.0; + + public ProductXML() { + this.productNumber = 0; + this.name = null; + this.price = 0.0; + } + + public ProductXML(long productNumber, String name, Double price) { + this.productNumber = productNumber; + this.name = name; + this.price = price; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Double getPrice() { + return price; + } + + public void setPrice(Double price) { + this.price = price; + } + +} \ No newline at end of file From 670ab882a7aff31c11efd4d0e383bbe3e2d13332 Mon Sep 17 00:00:00 2001 From: Alexandre Lombard Date: Thu, 4 May 2017 14:08:27 +0200 Subject: [PATCH 27/30] BAEL-874 - How to convert stacktrace to String in Java? (#1778) From 874ff5aacb7d58db64d804fdd396e6fbde3907d0 Mon Sep 17 00:00:00 2001 From: Jesus Boadas Date: Thu, 4 May 2017 08:08:56 -0400 Subject: [PATCH 28/30] Add content to JDO (#1780) * uncomment classes in core-java * Add content to guide to JDO From 267b5501da32c73e88c5ab3c916284547db363df Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Thu, 4 May 2017 18:44:12 +0200 Subject: [PATCH 29/30] Update .travis.yml --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index bcff16f5f1..fdd741154b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: java -install: travis_wait 60 mvn -q test +install: travis_wait 60 mvn -q test -fae before_script: - echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:MaxPermSize=2048M -XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC -XX:+TieredCompilation -XX:TieredStopAtLevel=1 -XX:-UseGCOverheadLimit'" > ~/.mavenrc From 14f90c8636c9b0ab25478eb7f54c8fb2a704ab9e Mon Sep 17 00:00:00 2001 From: Yasin Date: Fri, 5 May 2017 01:23:03 +0530 Subject: [PATCH 30/30] BAEL-905 Improvements in spring boot testing (#1783) * BAEL-88 Testing in Spring Boot * BAEL-88 Integration tests fixed. * BAEL-905 Improvement task for spring boot testing * BAEL-905 Improvement task for spring boot testing --- .../boottest/EmployeeRestControllerIntegrationTest.java | 5 +++-- .../test/resources/application-integrationtest.properties | 6 ++++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java index 110092d293..4c3a50f933 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java @@ -19,18 +19,19 @@ import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.MediaType; -import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = DemoApplication.class) @AutoConfigureMockMvc -@TestPropertySource(locations = "classpath:application-integrationtest.properties") +// @TestPropertySource(locations = "classpath:application-integrationtest.properties") +@AutoConfigureTestDatabase public class EmployeeRestControllerIntegrationTest { @Autowired diff --git a/spring-boot/src/test/resources/application-integrationtest.properties b/spring-boot/src/test/resources/application-integrationtest.properties index 508acf45e0..bcd03226d3 100644 --- a/spring-boot/src/test/resources/application-integrationtest.properties +++ b/spring-boot/src/test/resources/application-integrationtest.properties @@ -1,2 +1,4 @@ -spring.datasource.url = jdbc:h2:mem:test -spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect \ No newline at end of file +spring.datasource.url=jdbc:mysql://localhost:3306/employee_int_test +spring.datasource.username=root +spring.datasource.password=root +