From c9072e54d1fe27cf63b6ff6fb269cca2cf82c07d Mon Sep 17 00:00:00 2001 From: alincojanu Date: Sun, 24 Sep 2017 20:30:09 +0300 Subject: [PATCH 1/8] rxjava schedulers (#2668) * rxjava utility operators test * rxjava schedulers --- rxjava/pom.xml | 6 + .../com/baeldung/rxjava/SchedulersTest.java | 238 ++++++++++++++++++ 2 files changed, 244 insertions(+) create mode 100644 rxjava/src/test/java/com/baeldung/rxjava/SchedulersTest.java diff --git a/rxjava/pom.xml b/rxjava/pom.xml index ac2b923068..96d49e0d3c 100644 --- a/rxjava/pom.xml +++ b/rxjava/pom.xml @@ -47,6 +47,12 @@ assertj-core ${assertj.version} + + com.google.guava + guava + 22.0 + test + diff --git a/rxjava/src/test/java/com/baeldung/rxjava/SchedulersTest.java b/rxjava/src/test/java/com/baeldung/rxjava/SchedulersTest.java new file mode 100644 index 0000000000..1d36501fed --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/SchedulersTest.java @@ -0,0 +1,238 @@ +package com.baeldung.rxjava; + + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; +import rx.Observable; +import rx.Scheduler; +import rx.observers.TestSubscriber; +import rx.schedulers.Schedulers; +import rx.schedulers.TestScheduler; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; + +import static java.util.concurrent.Executors.newFixedThreadPool; +import static org.hamcrest.Matchers.hasItems; +import static org.junit.Assert.assertThat; + +public class SchedulersTest { + String result = ""; + String result1 = ""; + String result2 = ""; + + @Test + public void givenScheduledWorker_whenScheduleAnAction_thenResultAction() throws InterruptedException { + System.out.println("scheduling"); + Scheduler scheduler = Schedulers.immediate(); + Scheduler.Worker worker = scheduler.createWorker(); + worker.schedule(() -> result += "action"); + Assert.assertTrue(result.equals("action")); + } + + @Test + public void givenScheduledWorker_whenUnsubscribeOnWorker_thenResultFirstAction() throws InterruptedException { + System.out.println("canceling"); + Scheduler scheduler = Schedulers.newThread(); + Scheduler.Worker worker = scheduler.createWorker(); + worker.schedule(() -> { + result += "First_Action"; + worker.unsubscribe(); + }); + worker.schedule(() -> result += "Second_Action"); + Thread.sleep(500); + Assert.assertTrue(result.equals("First_Action")); + } + + @Ignore //it's not safe, not every time is running correctly + @Test + public void givenWorker_whenScheduledOnNewThread_thenResultIsBoundToNewThread() throws InterruptedException { + System.out.println("newThread_1"); + Scheduler scheduler = Schedulers.newThread(); + Scheduler.Worker worker = scheduler.createWorker(); + worker.schedule(() -> { + result += Thread.currentThread().getName() + "_Start"; + worker.schedule(() -> result += "_worker_"); + result += "_End"; + }); + Thread.sleep(2000); + Assert.assertTrue(result.equals("RxNewThreadScheduler-1_Start_End_worker_")); + } + + @Test + public void givenObservable_whenObserveOnNewThread_thenRunOnDifferentThreadEachTime() throws InterruptedException { + System.out.println("newThread_2"); + Observable.just("Hello") + .observeOn(Schedulers.newThread()) + .doOnNext(s -> + result2 += Thread.currentThread().getName() + ) + .observeOn(Schedulers.newThread()) + .subscribe(s -> + result1 += Thread.currentThread().getName() + ); + Thread.sleep(500); + Assert.assertTrue(result1.equals("RxNewThreadScheduler-1")); + Assert.assertTrue(result2.equals("RxNewThreadScheduler-2")); + } + + @Test + public void givenWorker_whenScheduledOnImmediate_thenResultIsBoundToThread() throws InterruptedException { + System.out.println("immediate_1"); + Scheduler scheduler = Schedulers.immediate(); + Scheduler.Worker worker = scheduler.createWorker(); + worker.schedule(() -> { + result += Thread.currentThread().getName() + "_Start"; + worker.schedule(() -> result += "_worker_"); + result += "_End"; + }); + Thread.sleep(500); + Assert.assertTrue(result.equals("main_Start_worker__End")); + } + + @Test + public void givenObservable_whenImmediateScheduled_thenExecuteOnMainThread() throws InterruptedException { + System.out.println("immediate_2"); + Observable.just("Hello") + .subscribeOn(Schedulers.immediate()) + .subscribe(s -> + result += Thread.currentThread().getName() + ); + Thread.sleep(500); + Assert.assertTrue(result.equals("main")); + } + + + @Test + public void givenObservable_whenTrampolineScheduled_thenExecuteOnMainThread() throws InterruptedException { + System.out.println("trampoline_1"); + Observable.just(2, 4, 6, 8) + .subscribeOn(Schedulers.trampoline()) + .subscribe(i -> result += "" + i); + Observable.just(1, 3, 5, 7, 9) + .subscribeOn(Schedulers.trampoline()) + .subscribe(i -> result += "" + i); + Thread.sleep(500); + Assert.assertTrue(result.equals("246813579")); + } + + @Test + public void givenWorker_whenScheduledOnTrampoline_thenComposeResultAsBlocking() throws InterruptedException { + System.out.println("trampoline_2"); + Scheduler scheduler = Schedulers.trampoline(); + Scheduler.Worker worker = scheduler.createWorker(); + worker.schedule(() -> { + result += Thread.currentThread().getName() + "Start"; + worker.schedule(() -> { + result += "_middleStart"; + worker.schedule(() -> + result += "_worker_" + ); + result += "_middleEnd"; + }); + result += "_mainEnd"; + }); + Thread.sleep(500); + Assert.assertTrue(result + .equals("mainStart_mainEnd_middleStart_middleEnd_worker_")); + } + + private ThreadFactory threadFactory(String pattern) { + return new ThreadFactoryBuilder() + .setNameFormat(pattern) + .build(); + } + + @Test + public void givenExecutors_whenSchedulerFromCreatedExecutors_thenReturnElementsOnEacheThread() throws InterruptedException { + System.out.println("from"); + ExecutorService poolA = newFixedThreadPool(10, threadFactory("Sched-A-%d")); + Scheduler schedulerA = Schedulers.from(poolA); + ExecutorService poolB = newFixedThreadPool(10, threadFactory("Sched-B-%d")); + Scheduler schedulerB = Schedulers.from(poolB); + + Observable observable = Observable.create(subscriber -> { + subscriber.onNext("Alfa"); + subscriber.onNext("Beta"); + subscriber.onCompleted(); + });; + + observable + .subscribeOn(schedulerA) + .subscribeOn(schedulerB) + .subscribe( + x -> result += Thread.currentThread().getName() + x + "_", + Throwable::printStackTrace, + () -> result += "_Completed" + ); + Thread.sleep(2000); + Assert.assertTrue(result.equals("Sched-A-0Alfa_Sched-A-0Beta__Completed")); + } + + @Test + public void givenObservable_whenIoScheduling_thenReturnThreadName() throws InterruptedException { + System.out.println("io"); + Observable.just("io") + .subscribeOn(Schedulers.io()) + .subscribe(i -> result += Thread.currentThread().getName()); + Thread.sleep(500); + Assert.assertTrue(result.equals("RxIoScheduler-2")); + } + + @Test + public void givenObservable_whenComputationScheduling_thenReturnThreadName() throws InterruptedException { + System.out.println("computation"); + Observable.just("computation") + .subscribeOn(Schedulers.computation()) + .subscribe(i -> result += Thread.currentThread().getName()); + Thread.sleep(500); + Assert.assertTrue(result.equals("RxComputationScheduler-1")); + } + + @Test + public void givenLetters_whenTestScheduling_thenReturnValuesControllingAdvanceTime() throws InterruptedException { + List letters = Arrays.asList("A", "B", "C"); + TestScheduler scheduler = Schedulers.test(); + TestSubscriber subscriber = new TestSubscriber<>(); + + Observable tick = Observable.interval(1, TimeUnit.SECONDS, scheduler); + + Observable.from(letters) + .zipWith(tick, (string, index) -> index + "-" + string) + .subscribeOn(scheduler) + .subscribe(subscriber); + + subscriber.assertNoValues(); + subscriber.assertNotCompleted(); + + scheduler.advanceTimeBy(1, TimeUnit.SECONDS); + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValues("0-A"); + + scheduler.advanceTimeTo(3, TimeUnit.SECONDS); + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(3); + assertThat(subscriber.getOnNextEvents(), hasItems("0-A", "1-B", "2-C")); + } + + @Test + public void givenLetters_whenDelay_thenReturne() throws InterruptedException { + ExecutorService poolA = newFixedThreadPool(10, threadFactory("Sched1-")); + Scheduler schedulerA = Schedulers.from(poolA); + Observable.just('A', 'B') + .delay(1, TimeUnit.SECONDS, schedulerA) + .subscribe(i -> result+= Thread.currentThread().getName() + i + " "); + + Thread.sleep(2000); + Assert.assertTrue(result.equals("Sched1-A Sched1-B ")); + } + +} From 52ac2ba2d38f86e200033287b4efec3d5c75aac7 Mon Sep 17 00:00:00 2001 From: Dassi orleando Date: Sun, 24 Sep 2017 18:32:50 +0100 Subject: [PATCH 2/8] BAEL-1107: update properties of Author (#2666) * Different types of bean injection in Spring * Difference between two dates in java * Update README.md * Simple clean of difference between dates * Clean my test article * Improve dates diff: for dates and datetimes * Move difference between dates from core-java to libraries * BAEL-890 - Kotlin-Allopen with Spring example * BAEL-1107 - Introduction to Apache Cayenne Orm * BAEL-1107: update formating and version of libs * BAEL-1107: update properties of Author --- .../persistent/auto/_Author.java | 18 +++------ .../src/main/resources/datamap.map.xml | 6 +-- .../apachecayenne/CayenneOperationTests.java | 39 +++++++------------ 3 files changed, 22 insertions(+), 41 deletions(-) diff --git a/apache-cayenne/src/main/java/com/baeldung/apachecayenne/persistent/auto/_Author.java b/apache-cayenne/src/main/java/com/baeldung/apachecayenne/persistent/auto/_Author.java index 3d068423c8..4d3bb090ca 100644 --- a/apache-cayenne/src/main/java/com/baeldung/apachecayenne/persistent/auto/_Author.java +++ b/apache-cayenne/src/main/java/com/baeldung/apachecayenne/persistent/auto/_Author.java @@ -19,22 +19,14 @@ public abstract class _Author extends CayenneDataObject { public static final String ID_PK_COLUMN = "id"; - public static final Property FIRSTNAME = Property.create("firstname", String.class); - public static final Property LASTNAME = Property.create("lastname", String.class); + public static final Property NAME = Property.create("name", String.class); public static final Property> ARTICLES = Property.create("articles", List.class); - public void setFirstname(String firstname) { - writeProperty("firstname", firstname); + public void setName(String name) { + writeProperty("name", name); } - public String getFirstname() { - return (String)readProperty("firstname"); - } - - public void setLastname(String lastname) { - writeProperty("lastname", lastname); - } - public String getLastname() { - return (String)readProperty("lastname"); + public String getName() { + return (String)readProperty("name"); } public void addToArticles(Article obj) { diff --git a/apache-cayenne/src/main/resources/datamap.map.xml b/apache-cayenne/src/main/resources/datamap.map.xml index dc78ad4348..3305649669 100644 --- a/apache-cayenne/src/main/resources/datamap.map.xml +++ b/apache-cayenne/src/main/resources/datamap.map.xml @@ -11,17 +11,15 @@ - - + - - + diff --git a/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationTests.java b/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationTests.java index b92096c0fa..8a0d210d8d 100644 --- a/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationTests.java +++ b/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationTests.java @@ -39,8 +39,7 @@ public class CayenneOperationTests { @Test public void givenAuthor_whenInsert_thenWeGetOneRecordInTheDatabase() { Author author = context.newObject(Author.class); - author.setFirstname("Paul"); - author.setLastname("Smith"); + author.setName("Paul"); context.commitChanges(); @@ -51,28 +50,24 @@ public class CayenneOperationTests { @Test public void givenAuthor_whenInsert_andQueryByFirstName_thenWeGetTheAuthor() { Author author = context.newObject(Author.class); - author.setFirstname("Paul"); - author.setLastname("Smith"); + author.setName("Paul"); context.commitChanges(); Author expectedAuthor = ObjectSelect.query(Author.class) - .where(Author.FIRSTNAME.eq("Paul")) + .where(Author.NAME.eq("Paul")) .selectOne(context); - assertEquals("Paul", expectedAuthor.getFirstname()); - assertEquals("Smith", expectedAuthor.getLastname()); + assertEquals("Paul", expectedAuthor.getName()); } @Test public void givenTwoAuthor_whenInsert_andQueryAll_thenWeGetTwoAuthors() { Author firstAuthor = context.newObject(Author.class); - firstAuthor.setFirstname("Paul"); - firstAuthor.setLastname("Smith"); + firstAuthor.setName("Paul"); Author secondAuthor = context.newObject(Author.class); - secondAuthor.setFirstname("Ludovic"); - secondAuthor.setLastname("Garcia"); + secondAuthor.setName("Ludovic"); context.commitChanges(); @@ -83,44 +78,40 @@ public class CayenneOperationTests { @Test public void givenAuthor_whenUpdating_thenWeGetAnUpatedeAuthor() { Author author = context.newObject(Author.class); - author.setFirstname("Paul"); - author.setLastname("Smith"); + author.setName("Paul"); context.commitChanges(); Author expectedAuthor = ObjectSelect.query(Author.class) - .where(Author.FIRSTNAME.eq("Paul")) + .where(Author.NAME.eq("Paul")) .selectOne(context); - expectedAuthor.setLastname("Smith 2"); + expectedAuthor.setName("Garcia"); context.commitChanges(); - assertEquals(author.getFirstname(), expectedAuthor.getFirstname()); - assertEquals(author.getLastname(), expectedAuthor.getLastname()); + assertEquals(author.getName(), expectedAuthor.getName()); } @Test public void givenAuthor_whenDeleting_thenWeLostHisDetails() { Author author = context.newObject(Author.class); - author.setFirstname("Paul"); - author.setLastname("Smith"); + author.setName("Paul"); context.commitChanges(); Author savedAuthor = ObjectSelect.query(Author.class) - .where(Author.FIRSTNAME.eq("Paul")).selectOne(context); + .where(Author.NAME.eq("Paul")).selectOne(context); if(savedAuthor != null) { context.deleteObjects(author); context.commitChanges(); } Author expectedAuthor = ObjectSelect.query(Author.class) - .where(Author.FIRSTNAME.eq("Paul")).selectOne(context); + .where(Author.NAME.eq("Paul")).selectOne(context); assertNull(expectedAuthor); } @Test public void givenAuthor_whenAttachingToArticle_thenTheRelationIsMade() { Author author = context.newObject(Author.class); - author.setFirstname("Paul"); - author.setLastname("Smith"); + author.setName("Paul"); Article article = context.newObject(Article.class); article.setTitle("My post title"); @@ -130,7 +121,7 @@ public class CayenneOperationTests { context.commitChanges(); Author expectedAuthor = ObjectSelect.query(Author.class) - .where(Author.LASTNAME.eq("Smith")) + .where(Author.NAME.eq("Paul")) .selectOne(context); Article expectedArticle = (expectedAuthor.getArticles()).get(0); From 2beb5f012c203093cf6ff3488fcc44da15a73973 Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Sun, 24 Sep 2017 18:03:34 -0500 Subject: [PATCH 3/8] BAEL-960 and BAEL-1084 README updates (#2670) * BAEL-973: updated README * BAEL-1069: Updated README * BAEL-817: add README file * BAEL-1084: README update * BAEL-960: Update README --- spring-security-mvc-boot/README.MD | 1 + vavr/README.md | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-security-mvc-boot/README.MD b/spring-security-mvc-boot/README.MD index feda6efcd7..32976b0896 100644 --- a/spring-security-mvc-boot/README.MD +++ b/spring-security-mvc-boot/README.MD @@ -8,3 +8,4 @@ The "REST With Spring" Classes: http://github.learnspringsecurity.com - [Two Login Pages with Spring Security](http://www.baeldung.com/spring-security-two-login-pages) - [Multiple Entry Points in Spring Security](http://www.baeldung.com/spring-security-multiple-entry-points) - [Multiple Authentication Providers in Spring Security](http://www.baeldung.com/spring-security-multiple-auth-providers) +- [Granted Authority Versus Role in Spring Security](http://www.baeldung.com/spring-security-granted-authority-vs-role) diff --git a/vavr/README.md b/vavr/README.md index d7816f3f9f..24b8c5a615 100644 --- a/vavr/README.md +++ b/vavr/README.md @@ -5,4 +5,4 @@ - [Property Testing Example With Vavr](http://www.baeldung.com/javaslang-property-testing) - [Exceptions in Lambda Expression Using Vavr](http://www.baeldung.com/exceptions-using-vavr) - [Vavr (ex-Javaslang) Support in Spring Data](http://www.baeldung.com/spring-vavr) - +- [Collection Factory Methods for Vavr](http://www.baeldung.com/vavr-collection-factory-methods) From 8bf825d0462d45b4b8d0704cf8fe365420f69f9f Mon Sep 17 00:00:00 2001 From: adamd1985 Date: Mon, 25 Sep 2017 20:24:24 +0200 Subject: [PATCH 4/8] Code examples for the articl on Apache bags (#2671) --- .../commons/collections4/BagTests.java | 182 ++++++++++-------- 1 file changed, 104 insertions(+), 78 deletions(-) diff --git a/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java b/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java index 4ce250d979..55fadcbf85 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java +++ b/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java @@ -1,85 +1,111 @@ package com.baeldung.commons.collections4; -import java.util.ArrayList; -import java.util.List; - import org.apache.commons.collections4.Bag; -import org.apache.commons.collections4.bag.CollectionBag; -import org.apache.commons.collections4.bag.HashBag; -import org.apache.commons.collections4.bag.TreeBag; -import org.junit.Assert; -import org.junit.Before; +import org.apache.commons.collections4.SortedBag; +import org.apache.commons.collections4.bag.*; import org.junit.Test; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; + public class BagTests { - - Bag baseBag; - TreeBag treeBag; - - @Before - public void before() { - baseBag = new HashBag(); - treeBag = new TreeBag(); - treeBag = new TreeBag(); - } - - @Test - public void whenAdd_thenRemoveFromBaseBag_thenContainsCorrect() { - baseBag.add("apple", 2); - baseBag.add("lemon", 6); - baseBag.add("lime"); - - baseBag.remove("lemon"); - Assert.assertEquals(3, baseBag.size()); - Assert.assertFalse(baseBag.contains("lemon")); - - Assert.assertTrue(baseBag.uniqueSet().contains("apple")); - - List containList = new ArrayList(); - containList.add("apple"); - containList.add("lemon"); - containList.add("lime"); - Assert.assertFalse(baseBag.containsAll(containList)); - } - - @Test - public void whenAdd_thenRemoveFromBaseCollectionBag_thenContainsCorrect() { - baseBag.add("apple", 2); - baseBag.add("lemon", 6); - baseBag.add("lime"); - - CollectionBag baseCollectionBag = new CollectionBag( - baseBag); - - baseCollectionBag.remove("lemon"); - Assert.assertEquals(8, baseCollectionBag.size()); - Assert.assertTrue(baseCollectionBag.contains("lemon")); - - baseCollectionBag.remove("lemon",1); - Assert.assertEquals(7, baseCollectionBag.size()); - - Assert.assertTrue(baseBag.uniqueSet().contains("apple")); - - List containList = new ArrayList(); - containList.add("apple"); - containList.add("lemon"); - containList.add("lime"); - Assert.assertTrue(baseBag.containsAll(containList)); - } - - @Test - public void whenAddtoTreeBag_thenRemove_thenContainsCorrect() { - treeBag.add("banana", 8); - treeBag.add("apple", 2); - treeBag.add("lime"); - - Assert.assertEquals(11, treeBag.size()); - Assert.assertEquals("apple", treeBag.first()); - Assert.assertEquals("lime", treeBag.last()); - - treeBag.remove("apple"); - Assert.assertEquals(9, treeBag.size()); - Assert.assertEquals("banana", treeBag.first()); - - } + + @Test + public void givenMultipleCopies_whenAdded_theCountIsKept() { + Bag bag = new HashBag<>( + Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 })); + + assertThat(bag.getCount(1), equalTo(2)); + } + + @Test + public void givenBag_whenBagAddAPILikeCollectionAPI_thenFalse() { + Collection collection = new ArrayList<>(); + + // Collection contract defines that add() should return true + assertThat(collection.add(9), is(true)); + + // Even when element is already in the collection + collection.add(1); + assertThat(collection.add(1), is(true)); + + Bag bag = new HashBag<>(); + + // Bag returns true on adding a new element + assertThat(bag.add(9), is(true)); + + bag.add(1); + // But breaks the contract with false when it has to increment the count + assertThat(bag.add(1), is(not(true))); + } + + @Test + public void givenDecoratedBag_whenBagAddAPILikeCollectionAPI_thenTrue() { + Bag bag = CollectionBag.collectionBag(new HashBag<>()); + + bag.add(1); + // This time the behavior is compliant to the Java Collection + assertThat(bag.add(1), is((true))); + } + + @Test + public void givenAdd_whenCountOfElementsDefined_thenCountAreAdded() { + Bag bag = new HashBag<>(); + + // Adding 1 for 5 times + bag.add(1, 5); + assertThat(bag.getCount(1), equalTo(5)); + } + + @Test + public void givenMultipleCopies_whenRemove_allAreRemoved() { + Bag bag = new HashBag<>( + Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 })); + + // From 3 we delete 1, 2 remain + bag.remove(3, 1); + assertThat(bag.getCount(3), equalTo(2)); + + // From 2 we delete all + bag.remove(1); + assertThat(bag.getCount(1), equalTo(0)); + } + + @Test + public void givenTree_whenDuplicateElementsAdded_thenSort() { + TreeBag bag = new TreeBag<>( + Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 })); + + assertThat(bag.first(), equalTo(1)); + assertThat(bag.getCount(bag.first()), equalTo(2)); + assertThat(bag.last(), equalTo(7)); + assertThat(bag.getCount(bag.last()), equalTo(3)); + } + + @Test + public void givenDecoratedTree_whenTreeAddAPILikeCollectionAPI_thenTrue() { + SortedBag bag = CollectionSortedBag + .collectionSortedBag(new TreeBag<>()); + + bag.add(1); + assertThat(bag.add(1), is((true))); + } + + @Test + public void givenSortedBag_whenDuplicateElementsAdded_thenSort() { + SynchronizedSortedBag bag = SynchronizedSortedBag + .synchronizedSortedBag(new TreeBag<>( + Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 }))); + + assertThat(bag.first(), equalTo(1)); + assertThat(bag.getCount(bag.first()), equalTo(2)); + assertThat(bag.last(), equalTo(7)); + assertThat(bag.getCount(bag.last()), equalTo(3)); + } } From c9a754f0e4625caf7df0a941515fc7712a28d8df Mon Sep 17 00:00:00 2001 From: eugenp Date: Tue, 26 Sep 2017 01:00:09 +0300 Subject: [PATCH 5/8] cleanup resources --- .../baeldung/java/nio2/watcher/DirectoryWatcherExample.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/core-java/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java b/core-java/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java index ffc58a1c50..35955032dc 100644 --- a/core-java/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java +++ b/core-java/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java @@ -10,6 +10,7 @@ import java.nio.file.WatchKey; import java.nio.file.WatchService; public class DirectoryWatcherExample { + public static void main(String[] args) throws IOException, InterruptedException { WatchService watchService = FileSystems.getDefault().newWatchService(); Path path = Paths.get(System.getProperty("user.home")); @@ -21,5 +22,8 @@ public class DirectoryWatcherExample { } key.reset(); } + + watchService.close(); } + } From d10d758c84f809e9fffd05882b995cfe7906f83e Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Tue, 26 Sep 2017 13:53:23 +0200 Subject: [PATCH 6/8] Build optimization 26.09.2017 (#2676) * Optimize spring-rest * Refactor RxJava * Refactor RxJava --- rxjava/pom.xml | 1 - .../com/baeldung/rxjava/ObservableTest.java | 5 +-- .../rxjava/ResourceManagementTest.java | 16 +++----- ...RxJavaBackpressureLongRunningUnitTest.java | 13 ++----- .../rxjava/RxJavaCustomOperatorUnitTest.java | 36 ++++++++---------- .../com/baeldung/rxjava/RxJavaUnitTest.java | 14 +++++-- .../com/baeldung/rxjava/SchedulersTest.java | 23 +++++------- .../java/com/baeldung/rxjava/SingleTest.java | 1 - .../java/com/baeldung/rxjava/SubjectTest.java | 2 +- .../baeldung/rxjava/UtilityOperatorsTest.java | 34 +++++++---------- ....java => AutomapClassIntegrationTest.java} | 12 +++--- ...a => AutomapInterfaceIntegrationTest.java} | 12 +++--- ...va => BasicQueryTypesIntegrationTest.java} | 32 +++++++--------- ...st.java => InsertBlobIntegrationTest.java} | 28 ++++++-------- ...st.java => InsertClobIntegrationTest.java} | 28 ++++++-------- ...st.java => ReturnKeysIntegrationTest.java} | 27 ++++++-------- ...t.java => TransactionIntegrationTest.java} | 26 +++++-------- .../rxjava/onerror/ExceptionHandlingTest.java | 37 +++++++++---------- .../rxjava/onerror/OnErrorRetryTest.java | 33 ++++++++--------- ...PostControllerRequestIntegrationTest.java} | 2 +- ...ostControllerResponseIntegrationTest.java} | 2 +- .../web/log/test/TestTaxiFareController.java | 33 ----------------- 22 files changed, 164 insertions(+), 253 deletions(-) rename rxjava/src/test/java/com/baeldung/rxjava/jdbc/{AutomapClassTest.java => AutomapClassIntegrationTest.java} (80%) rename rxjava/src/test/java/com/baeldung/rxjava/jdbc/{AutomapInterfaceTest.java => AutomapInterfaceIntegrationTest.java} (80%) rename rxjava/src/test/java/com/baeldung/rxjava/jdbc/{BasicQueryTypesTest.java => BasicQueryTypesIntegrationTest.java} (63%) rename rxjava/src/test/java/com/baeldung/rxjava/jdbc/{InsertBlobTest.java => InsertBlobIntegrationTest.java} (81%) rename rxjava/src/test/java/com/baeldung/rxjava/jdbc/{InsertClobTest.java => InsertClobIntegrationTest.java} (80%) rename rxjava/src/test/java/com/baeldung/rxjava/jdbc/{ReturnKeysTest.java => ReturnKeysIntegrationTest.java} (54%) rename rxjava/src/test/java/com/baeldung/rxjava/jdbc/{TransactionTest.java => TransactionIntegrationTest.java} (71%) rename spring-rest/src/test/java/com/baeldung/controllers/{ExamplePostControllerRequestUnitTest.java => ExamplePostControllerRequestIntegrationTest.java} (97%) rename spring-rest/src/test/java/com/baeldung/controllers/{ExamplePostControllerResponseUnitTest.java => ExamplePostControllerResponseIntegrationTest.java} (97%) delete mode 100644 spring-rest/src/test/java/com/baeldung/web/log/test/TestTaxiFareController.java diff --git a/rxjava/pom.xml b/rxjava/pom.xml index 96d49e0d3c..783833243b 100644 --- a/rxjava/pom.xml +++ b/rxjava/pom.xml @@ -3,7 +3,6 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung rxjava 1.0-SNAPSHOT diff --git a/rxjava/src/test/java/com/baeldung/rxjava/ObservableTest.java b/rxjava/src/test/java/com/baeldung/rxjava/ObservableTest.java index 08fccfb238..3d3bb021d2 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/ObservableTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/ObservableTest.java @@ -8,7 +8,7 @@ import static junit.framework.Assert.assertTrue; public class ObservableTest { - String result = ""; + private String result = ""; @Test public void givenString_whenJustAndSubscribe_thenEmitsSingleItem() { @@ -85,7 +85,7 @@ public class ObservableTest { .groupBy(i -> 0 == (i % 2) ? "EVEN" : "ODD") .subscribe(group -> group.subscribe((number) -> { - if (group.getKey().toString().equals("EVEN")) { + if (group.getKey().equals("EVEN")) { EVEN[0] += number; } else { ODD[0] += number; @@ -141,5 +141,4 @@ public class ObservableTest { assertTrue(sum[0] == 10); } - } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementTest.java b/rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementTest.java index 9c52af61d0..81be84fd0d 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementTest.java @@ -12,16 +12,12 @@ public class ResourceManagementTest { String[] result = {""}; Observable values = Observable.using( - () -> { - return "MyResource"; - }, - r -> { - return Observable.create(o -> { - for (Character c : r.toCharArray()) - o.onNext(c); - o.onCompleted(); - }); - }, + () -> "MyResource", + r -> Observable.create(o -> { + for (Character c : r.toCharArray()) + o.onNext(c); + o.onCompleted(); + }), r -> System.out.println("Disposed: " + r) ); diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java index 458091fd1c..e9dbb48b92 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java @@ -27,7 +27,6 @@ public class RxJavaBackpressureLongRunningUnitTest { // then testSubscriber.awaitTerminalEvent(); assertTrue(testSubscriber.getOnErrorEvents().size() == 0); - } @Test @@ -60,7 +59,6 @@ public class RxJavaBackpressureLongRunningUnitTest { // then testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS); assertTrue(testSubscriber.getOnErrorEvents().size() == 0); - } @Test @@ -77,7 +75,6 @@ public class RxJavaBackpressureLongRunningUnitTest { // then testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS); assertTrue(testSubscriber.getOnErrorEvents().size() == 0); - } @Test @@ -88,15 +85,14 @@ public class RxJavaBackpressureLongRunningUnitTest { // when source.sample(100, TimeUnit.MILLISECONDS) - // .throttleFirst(100, TimeUnit.MILLISECONDS) - .observeOn(Schedulers.computation()).subscribe(testSubscriber); + // .throttleFirst(100, TimeUnit.MILLISECONDS) + .observeOn(Schedulers.computation()).subscribe(testSubscriber); IntStream.range(0, 1_000).forEach(source::onNext); // then testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS); assertTrue(testSubscriber.getOnErrorEvents().size() == 0); - } @Test @@ -111,7 +107,6 @@ public class RxJavaBackpressureLongRunningUnitTest { // then testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS); assertTrue(testSubscriber.getOnErrorEvents().size() == 0); - } @Test @@ -120,11 +115,11 @@ public class RxJavaBackpressureLongRunningUnitTest { TestSubscriber testSubscriber = new TestSubscriber<>(); // when - Observable.range(1, 1_000_000).onBackpressureDrop().observeOn(Schedulers.computation()).subscribe(testSubscriber); + Observable.range(1, 1_000_000).onBackpressureDrop().observeOn(Schedulers.computation()) + .subscribe(testSubscriber); // then testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS); assertTrue(testSubscriber.getOnErrorEvents().size() == 0); - } } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java index a49103196c..bba891da88 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java @@ -1,5 +1,15 @@ package com.baeldung.rxjava; +import org.junit.Test; +import rx.Observable; +import rx.Observable.Operator; +import rx.Observable.Transformer; +import rx.Subscriber; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + import static com.baelding.rxjava.operator.ToCleanString.toCleanString; import static com.baelding.rxjava.operator.ToLength.toLength; import static org.hamcrest.Matchers.hasItems; @@ -7,20 +17,6 @@ import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.junit.Test; - -import rx.Observable; -import rx.Observable.Operator; -import rx.Observable.Transformer; -import rx.Subscriber; - -import com.baelding.rxjava.operator.ToCleanString; -import com.baelding.rxjava.operator.ToLength; - public class RxJavaCustomOperatorUnitTest { @Test @@ -29,7 +25,7 @@ public class RxJavaCustomOperatorUnitTest { final List results = new ArrayList<>(); final Observable observable = Observable.from(list) - .lift(toCleanString()); + .lift(toCleanString()); // when observable.subscribe(results::add); @@ -46,7 +42,7 @@ public class RxJavaCustomOperatorUnitTest { final List results = new ArrayList<>(); final Observable observable = Observable.from(list) - .compose(toLength()); + .compose(toLength()); // when observable.subscribe(results::add); @@ -85,8 +81,8 @@ public class RxJavaCustomOperatorUnitTest { final List results = new ArrayList<>(); Observable.from(Arrays.asList("ap_p-l@e", "or-an?ge")) - .lift(cleanStringFn) - .subscribe(results::add); + .lift(cleanStringFn) + .subscribe(results::add); assertThat(results, notNullValue()); assertThat(results, hasSize(2)); @@ -99,8 +95,8 @@ public class RxJavaCustomOperatorUnitTest { final List results = new ArrayList<>(); Observable.from(Arrays.asList("apple", "orange")) - .compose(toLengthFn) - .subscribe(results::add); + .compose(toLengthFn) + .subscribe(results::add); assertThat(results, notNullValue()); assertThat(results, hasSize(2)); diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaUnitTest.java b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaUnitTest.java index 1e59b8c2d9..31ec473dc6 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaUnitTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaUnitTest.java @@ -10,7 +10,9 @@ import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; public class RxJavaUnitTest { @@ -19,7 +21,8 @@ public class RxJavaUnitTest { // given List letters = Arrays.asList("A", "B", "C", "D", "E"); List results = new ArrayList<>(); - Observable observable = Observable.from(letters).zipWith(Observable.range(1, Integer.MAX_VALUE), (string, index) -> index + "-" + string); + Observable observable = Observable.from(letters) + .zipWith(Observable.range(1, Integer.MAX_VALUE), (string, index) -> index + "-" + string); // when observable.subscribe(results::add); @@ -36,7 +39,8 @@ public class RxJavaUnitTest { List letters = Arrays.asList("A", "B", "C", "D", "E"); TestSubscriber subscriber = new TestSubscriber<>(); - Observable observable = Observable.from(letters).zipWith(Observable.range(1, Integer.MAX_VALUE), ((string, index) -> index + "-" + string)); + Observable observable = Observable.from(letters) + .zipWith(Observable.range(1, Integer.MAX_VALUE), ((string, index) -> index + "-" + string)); // when observable.subscribe(subscriber); @@ -54,7 +58,9 @@ public class RxJavaUnitTest { List letters = Arrays.asList("A", "B", "C", "D", "E"); TestSubscriber subscriber = new TestSubscriber<>(); - Observable observable = Observable.from(letters).zipWith(Observable.range(1, Integer.MAX_VALUE), ((string, index) -> index + "-" + string)).concatWith(Observable.error(new RuntimeException("error in Observable"))); + Observable observable = Observable.from(letters) + .zipWith(Observable.range(1, Integer.MAX_VALUE), ((string, index) -> index + "-" + string)) + .concatWith(Observable.error(new RuntimeException("error in Observable"))); // when observable.subscribe(subscriber); diff --git a/rxjava/src/test/java/com/baeldung/rxjava/SchedulersTest.java b/rxjava/src/test/java/com/baeldung/rxjava/SchedulersTest.java index 1d36501fed..35714566ca 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/SchedulersTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/SchedulersTest.java @@ -1,8 +1,6 @@ package com.baeldung.rxjava; - import com.google.common.util.concurrent.ThreadFactoryBuilder; -import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; @@ -23,9 +21,9 @@ import static org.hamcrest.Matchers.hasItems; import static org.junit.Assert.assertThat; public class SchedulersTest { - String result = ""; - String result1 = ""; - String result2 = ""; + private String result = ""; + private String result1 = ""; + private String result2 = ""; @Test public void givenScheduledWorker_whenScheduleAnAction_thenResultAction() throws InterruptedException { @@ -108,7 +106,6 @@ public class SchedulersTest { Assert.assertTrue(result.equals("main")); } - @Test public void givenObservable_whenTrampolineScheduled_thenExecuteOnMainThread() throws InterruptedException { System.out.println("trampoline_1"); @@ -161,7 +158,8 @@ public class SchedulersTest { subscriber.onNext("Alfa"); subscriber.onNext("Beta"); subscriber.onCompleted(); - });; + }); + ; observable .subscribeOn(schedulerA) @@ -203,10 +201,10 @@ public class SchedulersTest { Observable tick = Observable.interval(1, TimeUnit.SECONDS, scheduler); - Observable.from(letters) - .zipWith(tick, (string, index) -> index + "-" + string) - .subscribeOn(scheduler) - .subscribe(subscriber); + Observable.from(letters) + .zipWith(tick, (string, index) -> index + "-" + string) + .subscribeOn(scheduler) + .subscribe(subscriber); subscriber.assertNoValues(); subscriber.assertNotCompleted(); @@ -229,10 +227,9 @@ public class SchedulersTest { Scheduler schedulerA = Schedulers.from(poolA); Observable.just('A', 'B') .delay(1, TimeUnit.SECONDS, schedulerA) - .subscribe(i -> result+= Thread.currentThread().getName() + i + " "); + .subscribe(i -> result += Thread.currentThread().getName() + i + " "); Thread.sleep(2000); Assert.assertTrue(result.equals("Sched1-A Sched1-B ")); } - } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/SingleTest.java b/rxjava/src/test/java/com/baeldung/rxjava/SingleTest.java index 6d428d856b..1352841ed9 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/SingleTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/SingleTest.java @@ -20,5 +20,4 @@ public class SingleTest { single.subscribe(); assertTrue(result[0].equals("Hello")); } - } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/SubjectTest.java b/rxjava/src/test/java/com/baeldung/rxjava/SubjectTest.java index 429a7fe231..210ceaa636 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/SubjectTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/SubjectTest.java @@ -9,7 +9,7 @@ import static junit.framework.Assert.assertTrue; public class SubjectTest { @Test - public void givenSubjectAndTwoSubscribers_whenSubscribeOnSubject_thenSubscriberBeginsToAdd(){ + public void givenSubjectAndTwoSubscribers_whenSubscribeOnSubject_thenSubscriberBeginsToAdd() { PublishSubject subject = PublishSubject.create(); subject.subscribe(SubjectImpl.getFirstObserver()); diff --git a/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsTest.java index 8ce370e356..a4fc62aaf1 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsTest.java @@ -7,6 +7,7 @@ import rx.Observable; import rx.Observer; import rx.exceptions.OnErrorNotImplementedException; import rx.schedulers.Schedulers; +import rx.schedulers.Timestamped; import java.util.concurrent.TimeUnit; @@ -14,9 +15,9 @@ import static org.junit.Assert.assertTrue; public class UtilityOperatorsTest { - int emittedTotal = 0; - int receivedTotal = 0; - String result = ""; + private int emittedTotal = 0; + private int receivedTotal = 0; + private String result = ""; @Rule public ExpectedException thrown = ExpectedException.none(); @@ -44,7 +45,6 @@ public class UtilityOperatorsTest { assertTrue(receivedTotal == 15000); } - @Test public void givenObservable_whenObserveOnBeforeOnNext_thenEmitsEventsOnComputeScheduler() throws InterruptedException { @@ -68,7 +68,6 @@ public class UtilityOperatorsTest { assertTrue(receivedTotal == 15000); } - @Test public void givenObservable_whenSubscribeOn_thenEmitsEventsOnComputeScheduler() throws InterruptedException { @@ -92,7 +91,6 @@ public class UtilityOperatorsTest { assertTrue(receivedTotal == 15000); } - @Test public void givenObservableWithOneEvent_whenSingle_thenEmitEvent() { @@ -197,15 +195,13 @@ public class UtilityOperatorsTest { @Test public void givenObservables_whenDelay_thenEventsStartAppearAfterATime() throws InterruptedException { - Observable source - = Observable.interval(1, TimeUnit.SECONDS) + Observable> source = Observable.interval(1, TimeUnit.SECONDS) .take(5) .timestamp(); - Observable delay - = source.delaySubscription(2, TimeUnit.SECONDS); + Observable> delay = source.delaySubscription(2, TimeUnit.SECONDS); - source.subscribe( + source.subscribe( value -> System.out.println("source :" + value), t -> System.out.println("source error"), () -> System.out.println("source completed")); @@ -231,14 +227,12 @@ public class UtilityOperatorsTest { Observable values = Observable.using( () -> "resource", - r -> { - return Observable.create(o -> { - for (Character c : r.toCharArray()) { - o.onNext(c); - } - o.onCompleted(); - }); - }, + r -> Observable.create(o -> { + for (Character c : r.toCharArray()) { + o.onNext(c); + } + o.onCompleted(); + }), r -> System.out.println("Disposed: " + r) ); values.subscribe( @@ -248,7 +242,6 @@ public class UtilityOperatorsTest { assertTrue(result.equals("resource")); } - @Test public void givenObservableCached_whenSubscribesWith2Actions_thenEmitsCachedValues() { @@ -269,5 +262,4 @@ public class UtilityOperatorsTest { }); assertTrue(receivedTotal == 8); } - } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapClassTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapClassIntegrationTest.java similarity index 80% rename from rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapClassTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapClassIntegrationTest.java index f44d4ac6b8..51e163db1f 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapClassTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapClassIntegrationTest.java @@ -8,18 +8,16 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -import com.github.davidmoten.rx.jdbc.ConnectionProvider; import com.github.davidmoten.rx.jdbc.Database; import rx.Observable; -public class AutomapClassTest { +public class AutomapClassIntegrationTest { - ConnectionProvider connectionProvider = Connector.connectionProvider; - Database db = Database.from(connectionProvider); + private Database db = Database.from(Connector.connectionProvider); - Observable create = null; - Observable insert1, insert2 = null; + private Observable create = null; + private Observable insert1, insert2 = null; @Before public void setup() { @@ -58,6 +56,6 @@ public class AutomapClassTest { public void close() { db.update("DROP TABLE MANAGER") .dependsOn(create); - connectionProvider.close(); + Connector.connectionProvider.close(); } } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java similarity index 80% rename from rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java index 79bae281eb..f1182952b1 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java @@ -8,18 +8,16 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -import com.github.davidmoten.rx.jdbc.ConnectionProvider; import com.github.davidmoten.rx.jdbc.Database; import rx.Observable; -public class AutomapInterfaceTest { +public class AutomapInterfaceIntegrationTest { - ConnectionProvider connectionProvider = Connector.connectionProvider; - Database db = Database.from(connectionProvider); + private Database db = Database.from(Connector.connectionProvider); - Observable create = null; - Observable insert1, insert2 = null; + private Observable create = null; + private Observable insert1, insert2 = null; @Before public void setup() { @@ -58,7 +56,7 @@ public class AutomapInterfaceTest { public void close() { db.update("DROP TABLE EMPLOYEE") .dependsOn(create); - connectionProvider.close(); + Connector.connectionProvider.close(); } } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java similarity index 63% rename from rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java index 7677b2375d..5bbe175cb0 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java @@ -1,42 +1,38 @@ package com.baeldung.rxjava.jdbc; -import static org.junit.Assert.assertEquals; +import com.github.davidmoten.rx.jdbc.Database; +import org.junit.After; +import org.junit.Test; +import rx.Observable; import java.util.Arrays; import java.util.List; -import org.junit.After; -import org.junit.Test; +import static org.junit.Assert.assertEquals; -import com.github.davidmoten.rx.jdbc.ConnectionProvider; -import com.github.davidmoten.rx.jdbc.Database; +public class BasicQueryTypesIntegrationTest { -import rx.Observable; + private Database db = Database.from(Connector.connectionProvider); -public class BasicQueryTypesTest { - - ConnectionProvider connectionProvider = Connector.connectionProvider; - Database db = Database.from(connectionProvider); - - Observable create, insert1, insert2, insert3, update, delete = null; + private Observable create; @Test public void whenCreateTableAndInsertRecords_thenCorrect() { create = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int primary key, name varchar(255))") .count(); - insert1 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(1, 'John')") + Observable insert1 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(1, 'John')") .dependsOn(create) .count(); - update = db.update("UPDATE EMPLOYEE SET name = 'Alan' WHERE id = 1") + Observable update = db.update("UPDATE EMPLOYEE SET name = 'Alan' WHERE id = 1") .dependsOn(create) .count(); - insert2 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(2, 'Sarah')") + Observable insert2 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(2, 'Sarah')") .dependsOn(create) .count(); - insert3 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(3, 'Mike')") + Observable insert3 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(3, 'Mike')") .dependsOn(create) .count(); - delete = db.update("DELETE FROM EMPLOYEE WHERE id = 2") + Observable delete = db.update("DELETE FROM EMPLOYEE WHERE id = 2") .dependsOn(create) .count(); List names = db.select("select name from EMPLOYEE where id < ?") @@ -59,6 +55,6 @@ public class BasicQueryTypesTest { public void close() { db.update("DROP TABLE EMPLOYEE") .dependsOn(create); - connectionProvider.close(); + Connector.connectionProvider.close(); } } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertBlobTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertBlobIntegrationTest.java similarity index 81% rename from rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertBlobTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertBlobIntegrationTest.java index fb3018ede4..70fc7cf984 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertBlobTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertBlobIntegrationTest.java @@ -1,30 +1,26 @@ package com.baeldung.rxjava.jdbc; -import static org.junit.Assert.assertEquals; +import com.github.davidmoten.rx.jdbc.Database; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import rx.Observable; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertEquals; -import com.github.davidmoten.rx.jdbc.ConnectionProvider; -import com.github.davidmoten.rx.jdbc.Database; +public class InsertBlobIntegrationTest { -import rx.Observable; + private Database db = Database.from(Connector.connectionProvider); -public class InsertBlobTest { + private String expectedDocument = null; + private String actualDocument = null; - ConnectionProvider connectionProvider = Connector.connectionProvider; - Database db = Database.from(connectionProvider); - - String expectedDocument = null; - String actualDocument = null; - - Observable create, insert = null; + private Observable create, insert = null; @Before public void setup() throws IOException { @@ -60,6 +56,6 @@ public class InsertBlobTest { public void close() { db.update("DROP TABLE SERVERLOG") .dependsOn(create); - connectionProvider.close(); + Connector.connectionProvider.close(); } } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java similarity index 80% rename from rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java index d29c2e3de2..aea68426ec 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java @@ -1,29 +1,25 @@ package com.baeldung.rxjava.jdbc; -import static org.junit.Assert.assertEquals; +import com.github.davidmoten.rx.jdbc.Database; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import rx.Observable; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertEquals; -import com.github.davidmoten.rx.jdbc.ConnectionProvider; -import com.github.davidmoten.rx.jdbc.Database; +public class InsertClobIntegrationTest { -import rx.Observable; + private Database db = Database.from(Connector.connectionProvider); -public class InsertClobTest { + private String expectedDocument = null; + private String actualDocument = null; - ConnectionProvider connectionProvider = Connector.connectionProvider; - Database db = Database.from(connectionProvider); - - String expectedDocument = null; - String actualDocument = null; - - Observable create, insert = null; + private Observable create, insert = null; @Before public void setup() throws IOException { @@ -58,6 +54,6 @@ public class InsertClobTest { public void close() { db.update("DROP TABLE SERVERLOG") .dependsOn(create); - connectionProvider.close(); + Connector.connectionProvider.close(); } } \ No newline at end of file diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java similarity index 54% rename from rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java index 87604b6c5f..cc5a9fe3be 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java @@ -1,28 +1,24 @@ package com.baeldung.rxjava.jdbc; -import static org.assertj.core.api.Assertions.assertThat; - +import com.github.davidmoten.rx.jdbc.Database; import org.junit.After; import org.junit.Before; import org.junit.Test; - -import com.github.davidmoten.rx.jdbc.ConnectionProvider; -import com.github.davidmoten.rx.jdbc.Database; - import rx.Observable; -public class ReturnKeysTest { +import static org.assertj.core.api.Assertions.assertThat; - Observable begin, commit = null; - Observable createStatement, insertStatement, updateStatement = null; +public class ReturnKeysIntegrationTest { - ConnectionProvider connectionProvider = Connector.connectionProvider; - Database db = Database.from(connectionProvider); + private Observable createStatement; + + private Database db = Database.from(Connector.connectionProvider); @Before public void setup() { - begin = db.beginTransaction(); - createStatement = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int auto_increment primary key, name varchar(255))") + Observable begin = db.beginTransaction(); + createStatement = db + .update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int auto_increment primary key, name varchar(255))") .dependsOn(begin) .count(); } @@ -41,8 +37,7 @@ public class ReturnKeysTest { @After public void close() { - db.update("DROP TABLE EMPLOYEE") - .dependsOn(createStatement); - connectionProvider.close(); + db.update("DROP TABLE EMPLOYEE"); + Connector.connectionProvider.close(); } } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java similarity index 71% rename from rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java index 9603a11c46..2021dcdbb3 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java @@ -1,22 +1,15 @@ package com.baeldung.rxjava.jdbc; +import com.github.davidmoten.rx.jdbc.Database; +import org.junit.After; +import org.junit.Test; +import rx.Observable; + import static org.junit.Assert.assertEquals; -import org.junit.After; -import org.junit.Test; +public class TransactionIntegrationTest { -import com.github.davidmoten.rx.jdbc.ConnectionProvider; -import com.github.davidmoten.rx.jdbc.Database; - -import rx.Observable; - -public class TransactionTest { - - Observable begin, commit = null; - Observable createStatement, insertStatement, updateStatement = null; - - ConnectionProvider connectionProvider = Connector.connectionProvider; - Database db = Database.from(connectionProvider); + private Database db = Database.from(Connector.connectionProvider); @Test public void whenCommitTransaction_thenRecordUpdated() { @@ -43,8 +36,7 @@ public class TransactionTest { @After public void close() { - db.update("DROP TABLE EMPLOYEE") - .dependsOn(createStatement); - connectionProvider.close(); + db.update("DROP TABLE EMPLOYEE"); + Connector.connectionProvider.close(); } } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingTest.java b/rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingTest.java index 297cfa980b..b1d711ab39 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingTest.java @@ -9,9 +9,6 @@ import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.Assert.assertTrue; -/** - * @author aiet - */ public class ExceptionHandlingTest { private Error UNKNOWN_ERROR = new Error("unknown error"); @@ -19,10 +16,10 @@ public class ExceptionHandlingTest { @Test public void givenSubscriberAndError_whenHandleOnErrorReturn_thenResumed() { - TestObserver testObserver = new TestObserver(); + TestObserver testObserver = new TestObserver<>(); Observable - .error(UNKNOWN_ERROR) + .error(UNKNOWN_ERROR) .onErrorReturn(Throwable::getMessage) .subscribe(testObserver); @@ -34,10 +31,10 @@ public class ExceptionHandlingTest { @Test public void givenSubscriberAndError_whenHandleOnErrorResume_thenResumed() { - TestObserver testObserver = new TestObserver(); + TestObserver testObserver = new TestObserver<>(); Observable - .error(UNKNOWN_ERROR) + .error(UNKNOWN_ERROR) .onErrorResumeNext(Observable.just("one", "two")) .subscribe(testObserver); @@ -49,10 +46,10 @@ public class ExceptionHandlingTest { @Test public void givenSubscriberAndError_whenHandleOnErrorResumeItem_thenResumed() { - TestObserver testObserver = new TestObserver(); + TestObserver testObserver = new TestObserver<>(); Observable - .error(UNKNOWN_ERROR) + .error(UNKNOWN_ERROR) .onErrorReturnItem("singleValue") .subscribe(testObserver); @@ -64,10 +61,10 @@ public class ExceptionHandlingTest { @Test public void givenSubscriberAndError_whenHandleOnErrorResumeFunc_thenResumed() { - TestObserver testObserver = new TestObserver(); + TestObserver testObserver = new TestObserver<>(); Observable - .error(UNKNOWN_ERROR) + .error(UNKNOWN_ERROR) .onErrorResumeNext(throwable -> { return Observable.just(throwable.getMessage(), "nextValue"); }) @@ -81,11 +78,11 @@ public class ExceptionHandlingTest { @Test public void givenSubscriberAndError_whenChangeStateOnError_thenErrorThrown() { - TestObserver testObserver = new TestObserver(); + TestObserver testObserver = new TestObserver<>(); final AtomicBoolean state = new AtomicBoolean(false); Observable - .error(UNKNOWN_ERROR) + .error(UNKNOWN_ERROR) .doOnError(throwable -> state.set(true)) .subscribe(testObserver); @@ -97,10 +94,10 @@ public class ExceptionHandlingTest { @Test public void givenSubscriberAndError_whenExceptionOccurOnError_thenCompositeExceptionThrown() { - TestObserver testObserver = new TestObserver(); + TestObserver testObserver = new TestObserver<>(); Observable - .error(UNKNOWN_ERROR) + .error(UNKNOWN_ERROR) .doOnError(throwable -> { throw new RuntimeException("unexcepted"); }) @@ -113,10 +110,10 @@ public class ExceptionHandlingTest { @Test public void givenSubscriberAndException_whenHandleOnException_thenResumed() { - TestObserver testObserver = new TestObserver(); + TestObserver testObserver = new TestObserver<>(); Observable - .error(UNKNOWN_EXCEPTION) + .error(UNKNOWN_EXCEPTION) .onExceptionResumeNext(Observable.just("exceptionResumed")) .subscribe(testObserver); @@ -128,14 +125,14 @@ public class ExceptionHandlingTest { @Test public void givenSubscriberAndError_whenHandleOnException_thenNotResumed() { - TestObserver testObserver = new TestObserver(); + TestObserver testObserver = new TestObserver<>(); + Observable - .error(UNKNOWN_ERROR) + .error(UNKNOWN_ERROR) .onExceptionResumeNext(Observable.just("exceptionResumed")) .subscribe(testObserver); testObserver.assertError(UNKNOWN_ERROR); testObserver.assertNotComplete(); } - } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryTest.java b/rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryTest.java index 0f9c39ad1b..3cc72056ba 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryTest.java @@ -9,20 +9,17 @@ import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertTrue; -/** - * @author aiet - */ public class OnErrorRetryTest { private Error UNKNOWN_ERROR = new Error("unknown error"); @Test public void givenSubscriberAndError_whenRetryOnError_thenRetryConfirmed() { - TestObserver testObserver = new TestObserver(); + TestObserver testObserver = new TestObserver<>(); AtomicInteger atomicCounter = new AtomicInteger(0); Observable - .error(() -> { + .error(() -> { atomicCounter.incrementAndGet(); return UNKNOWN_ERROR; }) @@ -37,12 +34,12 @@ public class OnErrorRetryTest { @Test public void givenSubscriberAndError_whenRetryConditionallyOnError_thenRetryConfirmed() { - TestObserver testObserver = new TestObserver(); + TestObserver testObserver = new TestObserver<>(); AtomicInteger atomicCounter = new AtomicInteger(0); Observable - .error(() -> { + .error(() -> { atomicCounter.incrementAndGet(); return UNKNOWN_ERROR; }) @@ -57,11 +54,11 @@ public class OnErrorRetryTest { @Test public void givenSubscriberAndError_whenRetryUntilOnError_thenRetryConfirmed() { - TestObserver testObserver = new TestObserver(); + TestObserver testObserver = new TestObserver<>(); AtomicInteger atomicCounter = new AtomicInteger(0); Observable - .error(UNKNOWN_ERROR) + .error(UNKNOWN_ERROR) .retryUntil(() -> atomicCounter.incrementAndGet() > 3) .subscribe(testObserver); @@ -73,12 +70,12 @@ public class OnErrorRetryTest { @Test public void givenSubscriberAndError_whenRetryWhenOnError_thenRetryConfirmed() { - TestObserver testObserver = new TestObserver(); + TestObserver testObserver = new TestObserver<>(); Exception noretryException = new Exception("don't retry"); Observable - .error(UNKNOWN_ERROR) - .retryWhen(throwableObservable -> Observable.error(noretryException)) + .error(UNKNOWN_ERROR) + .retryWhen(throwableObservable -> Observable.error(noretryException)) .subscribe(testObserver); testObserver.assertError(noretryException); @@ -88,11 +85,11 @@ public class OnErrorRetryTest { @Test public void givenSubscriberAndError_whenRetryWhenOnError_thenCompleted() { - TestObserver testObserver = new TestObserver(); + TestObserver testObserver = new TestObserver<>(); AtomicInteger atomicCounter = new AtomicInteger(0); Observable - .error(() -> { + .error(() -> { atomicCounter.incrementAndGet(); return UNKNOWN_ERROR; }) @@ -107,11 +104,11 @@ public class OnErrorRetryTest { @Test public void givenSubscriberAndError_whenRetryWhenOnError_thenResubscribed() { - TestObserver testObserver = new TestObserver(); + TestObserver testObserver = new TestObserver<>(); AtomicInteger atomicCounter = new AtomicInteger(0); Observable - .error(() -> { + .error(() -> { atomicCounter.incrementAndGet(); return UNKNOWN_ERROR; }) @@ -126,11 +123,11 @@ public class OnErrorRetryTest { @Test public void givenSubscriberAndError_whenRetryWhenForMultipleTimesOnError_thenResumed() { - TestObserver testObserver = new TestObserver(); + TestObserver testObserver = new TestObserver<>(); long before = System.currentTimeMillis(); Observable - .error(UNKNOWN_ERROR) + .error(UNKNOWN_ERROR) .retryWhen(throwableObservable -> throwableObservable .zipWith(Observable.range(1, 3), (throwable, integer) -> integer) .flatMap(integer -> { diff --git a/spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerRequestUnitTest.java b/spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerRequestIntegrationTest.java similarity index 97% rename from spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerRequestUnitTest.java rename to spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerRequestIntegrationTest.java index c20f968704..33926d6200 100644 --- a/spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerRequestUnitTest.java +++ b/spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerRequestIntegrationTest.java @@ -21,7 +21,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @SpringBootTest(classes = MainApplication.class) -public class ExamplePostControllerRequestUnitTest { +public class ExamplePostControllerRequestIntegrationTest { MockMvc mockMvc; @Mock private ExampleService exampleService; diff --git a/spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerResponseUnitTest.java b/spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerResponseIntegrationTest.java similarity index 97% rename from spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerResponseUnitTest.java rename to spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerResponseIntegrationTest.java index 3d09622c47..5c5e5c0a64 100644 --- a/spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerResponseUnitTest.java +++ b/spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerResponseIntegrationTest.java @@ -23,7 +23,7 @@ import org.baeldung.config.MainApplication; @RunWith(SpringRunner.class) @SpringBootTest(classes = MainApplication.class) -public class ExamplePostControllerResponseUnitTest { +public class ExamplePostControllerResponseIntegrationTest { MockMvc mockMvc; @Mock private ExampleService exampleService; diff --git a/spring-rest/src/test/java/com/baeldung/web/log/test/TestTaxiFareController.java b/spring-rest/src/test/java/com/baeldung/web/log/test/TestTaxiFareController.java deleted file mode 100644 index 398e3c04e9..0000000000 --- a/spring-rest/src/test/java/com/baeldung/web/log/test/TestTaxiFareController.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.web.log.test; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; - -import org.junit.Test; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; - -import com.baeldung.web.log.data.TaxiRide; - -public class TestTaxiFareController { - - private static final String URL = "http://localhost:" + 8082 + "/spring-rest/taxifare/"; - - @Test - public void givenRequest_whenFetchTaxiFareRateCard_thanOK() { - TestRestTemplate testRestTemplate = new TestRestTemplate(); - ResponseEntity response = testRestTemplate.getForEntity(URL + "get/", String.class); - - assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); - } - - @Test - public void givenTaxiRide_whenCalculatedFare_thanStatus200() { - TestRestTemplate testRestTemplate = new TestRestTemplate(); - TaxiRide taxiRide = new TaxiRide(true, 10l); - String fare = testRestTemplate.postForObject(URL + "calculate/", taxiRide, String.class); - - assertThat(fare, equalTo("200")); - } -} From d79fcae1309ec38961544716b9edf973969a1c45 Mon Sep 17 00:00:00 2001 From: Nikhil Khatwani Date: Tue, 26 Sep 2017 22:51:11 +0530 Subject: [PATCH 7/8] =?UTF-8?q?=C2=96BAEL-866=20Changes=20(#2669)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- animal-sniffer-mvn-plugin/pom.xml | 57 +++++++++++++++++++ .../src/main/java/com/baeldung/App.java | 16 ++++++ .../src/test/java/com/baeldung/AppTest.java | 40 +++++++++++++ 3 files changed, 113 insertions(+) create mode 100644 animal-sniffer-mvn-plugin/pom.xml create mode 100644 animal-sniffer-mvn-plugin/src/main/java/com/baeldung/App.java create mode 100644 animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppTest.java diff --git a/animal-sniffer-mvn-plugin/pom.xml b/animal-sniffer-mvn-plugin/pom.xml new file mode 100644 index 0000000000..3190950d9b --- /dev/null +++ b/animal-sniffer-mvn-plugin/pom.xml @@ -0,0 +1,57 @@ + + 4.0.0 + com.baeldung + animal-sniffer-mvn-plugin + jar + 1.0-SNAPSHOT + example-animal-sniffer-mvn-plugin + http://maven.apache.org + + + 3.6.0 + + + + + junit + junit + 3.8.1 + test + + + + + + maven-compiler-plugin + 3.7.0 + + 1.6 + 1.6 + + + + org.codehaus.mojo + animal-sniffer-maven-plugin + 1.16 + + + org.codehaus.mojo.signature + java16 + 1.0 + + + + + animal-sniffer + verify + + check + + + + + + + + \ No newline at end of file diff --git a/animal-sniffer-mvn-plugin/src/main/java/com/baeldung/App.java b/animal-sniffer-mvn-plugin/src/main/java/com/baeldung/App.java new file mode 100644 index 0000000000..6deaf70cde --- /dev/null +++ b/animal-sniffer-mvn-plugin/src/main/java/com/baeldung/App.java @@ -0,0 +1,16 @@ +package com.baeldung; + +//import java.nio.charset.StandardCharsets; + +/** + * Hello world! + * + */ +public class App +{ + public static void main( String[] args ) + { + System.out.println( "Hello World!" ); + //System.out.println(StandardCharsets.UTF_8.name()); + } +} diff --git a/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppTest.java b/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppTest.java new file mode 100644 index 0000000000..8ecb1bc629 --- /dev/null +++ b/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppTest.java @@ -0,0 +1,40 @@ +package com.baeldung; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * Unit test for simple App. + */ +public class AppTest + extends TestCase +{ + /** + * Create the test case + * + * @param testName name of the test case + */ + public AppTest( String testName ) + { + super( testName ); + } + + /** + * @return the suite of tests being tested + */ + public static Test suite() + { + return new TestSuite( AppTest.class ); + } + + /** + * Rigourous Test :-) + */ + public void testApp() + { + + assertTrue( true ); + + } +} From 692fe315751b6da1373b23450c3b513327395118 Mon Sep 17 00:00:00 2001 From: Parth Karia Date: Wed, 27 Sep 2017 20:20:08 +0530 Subject: [PATCH 8/8] BAEL-815 Introduction to JGraphT (#2653) * BAEL-243 Spring Batch using Partitioner * BAEL-1106 Introduction to javax.measure * Unnecessary Committed * BAEL-1106 Move code to libraries from core-java * BAEL-1106 Move code to libraries from core-java * BAEL-815 Introduction to JGraphT * BAEL-815 Introduction to JGraphT --- libraries/pom.xml | 7 +- .../baeldung/jgrapht/CompleteGraphTest.java | 38 ++++++++ .../baeldung/jgrapht/DirectedGraphTests.java | 95 +++++++++++++++++++ .../baeldung/jgrapht/EulerianCircuitTest.java | 42 ++++++++ 4 files changed, 181 insertions(+), 1 deletion(-) create mode 100644 libraries/src/test/java/com/baeldung/jgrapht/CompleteGraphTest.java create mode 100644 libraries/src/test/java/com/baeldung/jgrapht/DirectedGraphTests.java create mode 100644 libraries/src/test/java/com/baeldung/jgrapht/EulerianCircuitTest.java diff --git a/libraries/pom.xml b/libraries/pom.xml index 01a3e7bd73..03919b9cec 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -585,6 +585,11 @@ fugue 3.0.0-m007 + + org.jgrapht + jgrapht-core + 1.0.1 + @@ -660,4 +665,4 @@ 1.0.0 3.8.4 - \ No newline at end of file + diff --git a/libraries/src/test/java/com/baeldung/jgrapht/CompleteGraphTest.java b/libraries/src/test/java/com/baeldung/jgrapht/CompleteGraphTest.java new file mode 100644 index 0000000000..c085d54689 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/jgrapht/CompleteGraphTest.java @@ -0,0 +1,38 @@ +package com.baeldung.jgrapht; + +import static org.junit.Assert.assertEquals; + +import java.util.List; + +import org.jgrapht.VertexFactory; +import org.jgrapht.alg.HamiltonianCycle; +import org.jgrapht.generate.CompleteGraphGenerator; +import org.jgrapht.graph.DefaultEdge; +import org.jgrapht.graph.SimpleWeightedGraph; +import org.junit.Before; +import org.junit.Test; + +public class CompleteGraphTest { + + static SimpleWeightedGraph completeGraph; + static int size = 10; + + @Before + public void createCompleteGraph() { + completeGraph = new SimpleWeightedGraph<>(DefaultEdge.class); + CompleteGraphGenerator completeGenerator = new CompleteGraphGenerator(size); + VertexFactory vFactory = new VertexFactory() { + private int id = 0; + public String createVertex() { + return "v" + id++; + } + }; + completeGenerator.generateGraph(completeGraph, vFactory, null); + } + + @Test + public void givenCompleteGraph_whenGetHamiltonianCyclePath_thenGetVerticeListInSequence() { + List verticeList = HamiltonianCycle.getApproximateOptimalForCompleteGraph(completeGraph); + assertEquals(verticeList.size(), completeGraph.vertexSet().size()); + } +} diff --git a/libraries/src/test/java/com/baeldung/jgrapht/DirectedGraphTests.java b/libraries/src/test/java/com/baeldung/jgrapht/DirectedGraphTests.java new file mode 100644 index 0000000000..7f4cc99715 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/jgrapht/DirectedGraphTests.java @@ -0,0 +1,95 @@ +package com.baeldung.jgrapht; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.stream.IntStream; + +import org.jgrapht.DirectedGraph; +import org.jgrapht.GraphPath; +import org.jgrapht.alg.CycleDetector; +import org.jgrapht.alg.KosarajuStrongConnectivityInspector; +import org.jgrapht.alg.interfaces.StrongConnectivityAlgorithm; +import org.jgrapht.alg.shortestpath.AllDirectedPaths; +import org.jgrapht.alg.shortestpath.BellmanFordShortestPath; +import org.jgrapht.alg.shortestpath.DijkstraShortestPath; +import org.jgrapht.graph.DefaultDirectedGraph; +import org.jgrapht.graph.DefaultEdge; +import org.jgrapht.graph.DirectedSubgraph; +import org.jgrapht.traverse.BreadthFirstIterator; +import org.jgrapht.traverse.DepthFirstIterator; +import org.junit.Before; +import org.junit.Test; + +public class DirectedGraphTests { + DirectedGraph directedGraph; + + @Before + public void createDirectedGraph() { + directedGraph = new DefaultDirectedGraph(DefaultEdge.class); + IntStream.range(1, 10).forEach(i -> { + directedGraph.addVertex("v" + i); + }); + directedGraph.addEdge("v1", "v2"); + directedGraph.addEdge("v2", "v4"); + directedGraph.addEdge("v4", "v3"); + directedGraph.addEdge("v3", "v1"); + directedGraph.addEdge("v5", "v4"); + directedGraph.addEdge("v5", "v6"); + directedGraph.addEdge("v6", "v7"); + directedGraph.addEdge("v7", "v5"); + directedGraph.addEdge("v8", "v5"); + directedGraph.addEdge("v9", "v8"); + } + + @Test + public void givenDirectedGraph_whenGetStronglyConnectedSubgraphs_thenPathExistsBetweenStronglyconnectedVertices() { + StrongConnectivityAlgorithm scAlg = new KosarajuStrongConnectivityInspector<>(directedGraph); + List> stronglyConnectedSubgraphs = scAlg.stronglyConnectedSubgraphs(); + List stronglyConnectedVertices = new ArrayList<>(stronglyConnectedSubgraphs.get(3).vertexSet()); + + String randomVertex1 = stronglyConnectedVertices.get(0); + String randomVertex2 = stronglyConnectedVertices.get(3); + AllDirectedPaths allDirectedPaths = new AllDirectedPaths<>(directedGraph); + + List> possiblePathList = allDirectedPaths.getAllPaths(randomVertex1, randomVertex2, false, stronglyConnectedVertices.size()); + assertTrue(possiblePathList.size() > 0); + } + + @Test + public void givenDirectedGraphWithCycle_whenCheckCycles_thenDetectCycles() { + CycleDetector cycleDetector = new CycleDetector(directedGraph); + assertTrue(cycleDetector.detectCycles()); + Set cycleVertices = cycleDetector.findCycles(); + assertTrue(cycleVertices.size() > 0); + } + + @Test + public void givenDirectedGraph_whenCreateInstanceDepthFirstIterator_thenGetIterator() { + DepthFirstIterator depthFirstIterator = new DepthFirstIterator<>(directedGraph); + assertNotNull(depthFirstIterator); + } + + @Test + public void givenDirectedGraph_whenCreateInstanceBreadthFirstIterator_thenGetIterator() { + BreadthFirstIterator breadthFirstIterator = new BreadthFirstIterator<>(directedGraph); + assertNotNull(breadthFirstIterator); + } + + @Test + public void givenDirectedGraph_whenGetDijkstraShortestPath_thenGetNotNullPath() { + DijkstraShortestPath dijkstraShortestPath = new DijkstraShortestPath(directedGraph); + List shortestPath = dijkstraShortestPath.getPath("v1", "v4").getVertexList(); + assertNotNull(shortestPath); + } + + @Test + public void givenDirectedGraph_whenGetBellmanFordShortestPath_thenGetNotNullPath() { + BellmanFordShortestPath bellmanFordShortestPath = new BellmanFordShortestPath(directedGraph); + List shortestPath = bellmanFordShortestPath.getPath("v1", "v4").getVertexList(); + assertNotNull(shortestPath); + } +} diff --git a/libraries/src/test/java/com/baeldung/jgrapht/EulerianCircuitTest.java b/libraries/src/test/java/com/baeldung/jgrapht/EulerianCircuitTest.java new file mode 100644 index 0000000000..6f0fb92ab7 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/jgrapht/EulerianCircuitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.jgrapht; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.stream.IntStream; + +import org.jgrapht.GraphPath; +import org.jgrapht.alg.cycle.HierholzerEulerianCycle; +import org.jgrapht.graph.DefaultEdge; +import org.jgrapht.graph.SimpleWeightedGraph; +import org.junit.Before; +import org.junit.Test; + +public class EulerianCircuitTest { + SimpleWeightedGraph simpleGraph; + + @Before + public void createGraphWithEulerianCircuit() { + simpleGraph = new SimpleWeightedGraph<>(DefaultEdge.class); + IntStream.range(1, 6).forEach(i -> { + simpleGraph.addVertex("v" + i); + }); + IntStream.range(1, 6).forEach(i -> { + int endVertexNo = (i + 1) > 5 ? 1 : i + 1; + simpleGraph.addEdge("v" + i, "v" + endVertexNo); + }); + } + + @Test + public void givenGraph_whenCheckEluerianCycle_thenGetResult() { + HierholzerEulerianCycle eulerianCycle = new HierholzerEulerianCycle<>(); + assertTrue(eulerianCycle.isEulerian(simpleGraph)); + } + + @Test + public void givenGraphWithEulerianCircuit_whenGetEulerianCycle_thenGetGraphPath() { + HierholzerEulerianCycle eulerianCycle = new HierholzerEulerianCycle<>(); + GraphPath path = eulerianCycle.getEulerianCycle(simpleGraph); + assertTrue(path.getEdgeList().containsAll(simpleGraph.edgeSet())); + } +}