#BAEL-16633 split Core Java 9 module - improved features

This commit is contained in:
Alessio Stalla
2019-10-29 15:30:01 +01:00
parent 83b5897387
commit fabf0993f6
24 changed files with 95 additions and 37 deletions

View File

@@ -1,13 +0,0 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@@ -4,17 +4,13 @@ This module contains articles about Java 9 core features
### Relevant Articles:
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
- [Method Handles in Java](http://www.baeldung.com/java-method-handles)
- [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue)
- [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional)
- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
- [Immutable Set in Java](https://www.baeldung.com/java-immutable-set)
- [Java 9 Process API Improvements](https://www.baeldung.com/java-9-process-api)
- [Java 9 java.util.Objects Additions](https://www.baeldung.com/java-9-objects-new)
- [Java 9 Optional API Additions](https://www.baeldung.com/java-9-optional)
- [Java 9 CompletableFuture API Improvements](https://www.baeldung.com/java-9-completablefuture)
- [Java 9 Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods)
- [Java 9 Stream API Improvements](https://www.baeldung.com/java-9-stream-api)
- [Filtering a Stream of Optionals in Java](https://www.baeldung.com/java-filter-stream-of-optional)
Note: also contains part of the code for the article
[How to Filter a Collection in Java](https://www.baeldung.com/java-collection-filtering).

View File

@@ -1 +0,0 @@
javac -d mods --module-source-path src/modules $(find src/modules -name "*.java")

View File

@@ -1,15 +0,0 @@
# compile logging module
# javac --module-path mods -d mods/com.baeldung.logging src/modules/com.baeldung.logging/module-info.java src/modules/com.baeldung.logging/com/baeldung/logging/*.java
# compile logging slf4j module
javac --module-path mods -d mods/com.baeldung.logging.slf4j src/modules/com.baeldung.logging.slf4j/module-info.java src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/*.java
# compile logging main app module
javac --module-path mods -d mods/com.baeldung.logging.app src/modules/com.baeldung.logging.app/module-info.java src/modules/com.baeldung.logging.app/com/baeldung/logging/app/*.java
# run logging main app
# java --module-path mods -m com.baeldung.logging.app/com.baeldung.logging.app.MainApp
# run looging main app using logback
java --module-path mods -Dlogback.configurationFile=mods/logback.xml -m com.baeldung.logging.app/com.baeldung.logging.app.MainApp

View File

@@ -1,16 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>
%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} -- %msg%n
</pattern>
</encoder>
</appender>
<root>
<appender-ref ref="STDOUT"/>
</root>
</configuration>

View File

@@ -1,23 +0,0 @@
package com.baeldung.java9.language;
public interface PrivateInterface {
private static String staticPrivate() {
return "static private";
}
private String instancePrivate() {
return "instance private";
}
public default void check() {
String result = staticPrivate();
if (!result.equals("static private"))
throw new AssertionError("Incorrect result for static private interface method");
PrivateInterface pvt = new PrivateInterface() {
};
result = pvt.instancePrivate();
if (!result.equals("instance private"))
throw new AssertionError("Incorrect result for instance private interface method");
}
}

View File

@@ -1,82 +0,0 @@
package com.baeldung.java9.reactive;
import java.util.ArrayList;
import java.util.concurrent.Flow.Subscriber;
import java.util.concurrent.Flow.Subscription;
public class BaeldungBatchSubscriberImpl<T> implements Subscriber<String> {
private Subscription subscription;
private boolean completed = false;
private int counter;
private ArrayList<String> buffer;
public static final int BUFFER_SIZE = 5;
public BaeldungBatchSubscriberImpl() {
buffer = new ArrayList<String>();
}
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
@Override
public void onSubscribe(Subscription subscription) {
this.subscription = subscription;
subscription.request(BUFFER_SIZE);
}
@Override
public void onNext(String item) {
buffer.add(item);
// if buffer is full, process the items.
if (buffer.size() >= BUFFER_SIZE) {
processBuffer();
}
//request more items.
subscription.request(1);
}
private void processBuffer() {
if (buffer.isEmpty())
return;
// Process all items in the buffer. Here, we just print it and sleep for 1 second.
System.out.print("Processed items: ");
buffer.stream()
.forEach(item -> {
System.out.print(" " + item);
});
System.out.println();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter = counter + buffer.size();
buffer.clear();
}
@Override
public void onError(Throwable t) {
t.printStackTrace();
}
@Override
public void onComplete() {
completed = true;
// process any remaining items in buffer before
processBuffer();
subscription.cancel();
}
}

View File

@@ -1,55 +0,0 @@
package com.baeldung.java9.reactive;
import java.util.concurrent.Flow.Subscriber;
import java.util.concurrent.Flow.Subscription;
public class BaeldungSubscriberImpl<T> implements Subscriber<String> {
private Subscription subscription;
private boolean completed = false;
private int counter;
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
@Override
public void onSubscribe(Subscription subscription) {
this.subscription = subscription;
subscription.request(1);
}
@Override
public void onNext(String item) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter++;
System.out.println("Processed item : " + item);
subscription.request(1);
}
@Override
public void onError(Throwable t) {
t.printStackTrace();
}
@Override
public void onComplete() {
completed = true;
subscription.cancel();
}
}

View File

@@ -1,85 +0,0 @@
package com.baeldung.java9;
public class Java9OptionalTest {
@Test
public void givenOptionalOfSome_whenToStream_thenShouldTreatItAsOneElementStream() {
//given
Optional<String> value = Optional.of("a");
//when
List<String> collect = value.stream().map(String::toUpperCase).collect(Collectors.toList());
//then
assertThat(collect).hasSameElementsAs(List.of("A"));
}
@Test
public void givenOptionalOfNone_whenToStream_thenShouldTreatItAsZeroElementStream() {
//given
Optional<String> value = Optional.empty();
//when
List<String> collect = value.stream().map(String::toUpperCase).collect(Collectors.toList());
//then
assertThat(collect).isEmpty();
}
@Test
public void givenOptional_whenPresent_thenShouldExecuteProperCallback() {
//given
Optional<String> value = Optional.of("properValue");
AtomicInteger successCounter = new AtomicInteger(0);
AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0);
//when
value.ifPresentOrElse((v) -> successCounter.incrementAndGet(), onEmptyOptionalCounter::incrementAndGet);
//then
assertThat(successCounter.get()).isEqualTo(1);
assertThat(onEmptyOptionalCounter.get()).isEqualTo(0);
}
@Test
public void givenOptional_whenNotPresent_thenShouldExecuteProperCallback() {
//given
Optional<String> value = Optional.empty();
AtomicInteger successCounter = new AtomicInteger(0);
AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0);
//when
value.ifPresentOrElse((v) -> successCounter.incrementAndGet(), onEmptyOptionalCounter::incrementAndGet);
//then
assertThat(successCounter.get()).isEqualTo(0);
assertThat(onEmptyOptionalCounter.get()).isEqualTo(1);
}
@Test
public void givenOptional_whenPresent_thenShouldTakeAValueFromIt() {
//given
String expected = "properValue";
Optional<String> value = Optional.of(expected);
Optional<String> defaultValue = Optional.of("default");
//when
Optional<String> result = value.or(() -> defaultValue);
//then
assertThat(result.get()).isEqualTo(expected);
}
@Test
public void givenOptional_whenEmpty_thenShouldTakeAValueFromOr() {
//given
String defaultString = "default";
Optional<String> value = Optional.empty();
Optional<String> defaultValue = Optional.of(defaultString);
//when
Optional<String> result = value.or(() -> defaultValue);
//then
assertThat(result.get()).isEqualTo(defaultString);
}
}

View File

@@ -1,2 +0,0 @@
### Relevant Artiles:
- [Filtering a Stream of Optionals in Java](http://www.baeldung.com/java-filter-stream-of-optional)

View File

@@ -1,74 +0,0 @@
package com.baeldung.java9.concurrent.future;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class CompletableFutureUnitTest {
@Test
public void testDelay () throws Exception {
Object input = new Object();
CompletableFuture<Object> future = new CompletableFuture<>();
future.completeAsync(() -> input, CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS));
Thread.sleep(100);
assertFalse(future.isDone());
Thread.sleep(1000);
assertTrue(future.isDone());
assertSame(input, future.get());
}
@Test
public void testTimeoutTriggered () throws Exception {
CompletableFuture<Object> future = new CompletableFuture<>();
future.orTimeout(1, TimeUnit.SECONDS);
Thread.sleep(1100);
assertTrue(future.isDone());
try {
future.get();
} catch (ExecutionException e) {
assertTrue(e.getCause() instanceof TimeoutException);
}
}
@Test
public void testTimeoutNotTriggered () throws Exception {
Object input = new Object();
CompletableFuture<Object> future = new CompletableFuture<>();
future.orTimeout(1, TimeUnit.SECONDS);
Thread.sleep(100);
future.complete(input);
Thread.sleep(1000);
assertTrue(future.isDone());
assertSame(input, future.get());
}
@Test
public void completeOnTimeout () throws Exception {
Object input = new Object();
CompletableFuture<Object> future = new CompletableFuture<>();
future.completeOnTimeout(input, 1, TimeUnit.SECONDS);
Thread.sleep(1100);
assertTrue(future.isDone());
assertSame(input, future.get());
}
}

View File

@@ -1,86 +0,0 @@
package com.baeldung.java9.language;
import org.junit.Test;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
public class Java9ObjectsAPIUnitTest {
private List<String> aMethodReturningNullList(){
return null;
}
@Test
public void givenNullObject_whenRequireNonNullElse_thenElse(){
List<String> aList = Objects.<List>requireNonNullElse(
aMethodReturningNullList(), Collections.EMPTY_LIST);
assertThat(aList, is(Collections.EMPTY_LIST));
}
private List<String> aMethodReturningNonNullList(){
return List.of("item1", "item2");
}
@Test
public void givenObject_whenRequireNonNullElse_thenObject(){
List<String> aList = Objects.<List>requireNonNullElse(
aMethodReturningNonNullList(), Collections.EMPTY_LIST);
assertThat(aList, is(List.of("item1", "item2")));
}
@Test(expected = NullPointerException.class)
public void givenNull_whenRequireNonNullElse_thenException(){
Objects.<List>requireNonNullElse(null, null);
}
@Test
public void givenObject_whenRequireNonNullElseGet_thenObject(){
List<String> aList = Objects.<List>requireNonNullElseGet(null, List::of);
assertThat(aList, is(List.of()));
}
@Test
public void givenNumber_whenInvokeCheckIndex_thenNumber(){
int length = 5;
assertThat(Objects.checkIndex(4, length), is(4));
}
@Test(expected = IndexOutOfBoundsException.class)
public void givenOutOfRangeNumber_whenInvokeCheckIndex_thenException(){
int length = 5;
Objects.checkIndex(5, length);
}
@Test
public void givenSubRange_whenCheckFromToIndex_thenNumber(){
int length = 6;
assertThat(Objects.checkFromToIndex(2,length,length), is(2));
}
@Test(expected = IndexOutOfBoundsException.class)
public void givenInvalidSubRange_whenCheckFromToIndex_thenException(){
int length = 6;
Objects.checkFromToIndex(2,7,length);
}
@Test
public void givenSubRange_whenCheckFromIndexSize_thenNumber(){
int length = 6;
assertThat(Objects.checkFromIndexSize(2,3,length), is(2));
}
@Test(expected = IndexOutOfBoundsException.class)
public void givenInvalidSubRange_whenCheckFromIndexSize_thenException(){
int length = 6;
Objects.checkFromIndexSize(2, 6, length);
}
}

View File

@@ -1,61 +0,0 @@
package com.baeldung.java9.language.collections;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class ListFactoryMethodsUnitTest {
@Test
public void whenListCreated_thenSuccess() {
List<String> traditionlList = new ArrayList<String>();
traditionlList.add("foo");
traditionlList.add("bar");
traditionlList.add("baz");
List<String> factoryCreatedList = List.of("foo", "bar", "baz");
assertEquals(traditionlList, factoryCreatedList);
}
@Test(expected = UnsupportedOperationException.class)
public void onElemAdd_ifUnSupportedOpExpnThrown_thenSuccess() {
List<String> list = List.of("foo", "bar");
list.add("baz");
}
@Test(expected = UnsupportedOperationException.class)
public void onElemModify_ifUnSupportedOpExpnThrown_thenSuccess() {
List<String> list = List.of("foo", "bar");
list.set(0, "baz");
}
@Test(expected = UnsupportedOperationException.class)
public void onElemRemove_ifUnSupportedOpExpnThrown_thenSuccess() {
List<String> list = List.of("foo", "bar");
list.remove("foo");
}
@Test(expected = NullPointerException.class)
public void onNullElem_ifNullPtrExpnThrown_thenSuccess() {
List.of("foo", "bar", null);
}
@Test
public void ifNotArrayList_thenSuccess() {
List<String> list = List.of("foo", "bar");
assertFalse(list instanceof ArrayList);
}
@Test
public void ifListSizeIsOne_thenSuccess() {
int[] arr = { 1, 2, 3, 4 };
List<int[]> list = List.of(arr);
assertEquals(1, list.size());
assertArrayEquals(arr, list.get(0));
}
}

View File

@@ -1,62 +0,0 @@
package com.baeldung.java9.language.collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class MapFactoryMethodsUnitTest {
@Test
public void whenMapCreated_thenSuccess() {
Map<String, String> traditionlMap = new HashMap<String, String>();
traditionlMap.put("foo", "a");
traditionlMap.put("bar", "b");
traditionlMap.put("baz", "c");
Map<String, String> factoryCreatedMap = Map.of("foo", "a", "bar", "b", "baz", "c");
assertEquals(traditionlMap, factoryCreatedMap);
}
@Test(expected = UnsupportedOperationException.class)
public void onElemAdd_ifUnSupportedOpExpnThrown_thenSuccess() {
Map<String, String> map = Map.of("foo", "a", "bar", "b");
map.put("baz", "c");
}
@Test(expected = UnsupportedOperationException.class)
public void onElemModify_ifUnSupportedOpExpnThrown_thenSuccess() {
Map<String, String> map = Map.of("foo", "a", "bar", "b");
map.put("foo", "c");
}
@Test(expected = UnsupportedOperationException.class)
public void onElemRemove_ifUnSupportedOpExpnThrown_thenSuccess() {
Map<String, String> map = Map.of("foo", "a", "bar", "b");
map.remove("foo");
}
@Test(expected = IllegalArgumentException.class)
public void givenDuplicateKeys_ifIllegalArgExp_thenSuccess() {
Map.of("foo", "a", "foo", "b");
}
@Test(expected = NullPointerException.class)
public void onNullKey_ifNullPtrExp_thenSuccess() {
Map.of("foo", "a", null, "b");
}
@Test(expected = NullPointerException.class)
public void onNullValue_ifNullPtrExp_thenSuccess() {
Map.of("foo", "a", "bar", null);
}
@Test
public void ifNotHashMap_thenSuccess() {
Map<String, String> map = Map.of("foo", "a", "bar", "b");
assertFalse(map instanceof HashMap);
}
}

View File

@@ -1,60 +0,0 @@
package com.baeldung.java9.language.collections;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class SetFactoryMethodsUnitTest {
@Test
public void whenSetCreated_thenSuccess() {
Set<String> traditionlSet = new HashSet<String>();
traditionlSet.add("foo");
traditionlSet.add("bar");
traditionlSet.add("baz");
Set<String> factoryCreatedSet = Set.of("foo", "bar", "baz");
assertEquals(traditionlSet, factoryCreatedSet);
}
@Test(expected = IllegalArgumentException.class)
public void onDuplicateElem_IfIllegalArgExp_thenSuccess() {
Set.of("foo", "bar", "baz", "foo");
}
@Test(expected = UnsupportedOperationException.class)
public void onElemAdd_ifUnSupportedOpExpnThrown_thenSuccess() {
Set<String> set = Set.of("foo", "bar");
set.add("baz");
}
@Test(expected = UnsupportedOperationException.class)
public void onElemRemove_ifUnSupportedOpExpnThrown_thenSuccess() {
Set<String> set = Set.of("foo", "bar", "baz");
set.remove("foo");
}
@Test(expected = NullPointerException.class)
public void onNullElem_ifNullPtrExpnThrown_thenSuccess() {
Set.of("foo", "bar", null);
}
@Test
public void ifNotHashSet_thenSuccess() {
Set<String> list = Set.of("foo", "bar");
assertFalse(list instanceof HashSet);
}
@Test
public void ifSetSizeIsOne_thenSuccess() {
int[] arr = { 1, 2, 3, 4 };
Set<int[]> set = Set.of(arr);
assertEquals(1, set.size());
assertArrayEquals(arr, set.iterator().next());
}
}

View File

@@ -1,61 +0,0 @@
package com.baeldung.java9.language.stream;
import org.junit.Test;
import java.util.*;
import java.util.stream.Collectors;
import java.util.function.Function;
import static org.junit.Assert.assertEquals;
public class CollectorImprovementUnitTest {
@Test
public void givenList_whenSatifyPredicate_thenMapValueWithOccurences() {
List<Integer> numbers = List.of(1, 2, 3, 5, 5);
Map<Integer, Long> result = numbers.stream().filter(val -> val > 3).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
assertEquals(1, result.size());
result = numbers.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.filtering(val -> val > 3, Collectors.counting())));
assertEquals(4, result.size());
}
@Test
public void givenListOfBlogs_whenAuthorName_thenMapAuthorWithComments() {
Blog blog1 = new Blog("1", "Nice", "Very Nice");
Blog blog2 = new Blog("2", "Disappointing", "Ok", "Could be better");
List<Blog> blogs = List.of(blog1, blog2);
Map<String, List<List<String>>> authorComments1 = blogs.stream().collect(Collectors.groupingBy(Blog::getAuthorName, Collectors.mapping(Blog::getComments, Collectors.toList())));
assertEquals(2, authorComments1.size());
assertEquals(2, authorComments1.get("1").get(0).size());
assertEquals(3, authorComments1.get("2").get(0).size());
Map<String, List<String>> authorComments2 = blogs.stream().collect(Collectors.groupingBy(Blog::getAuthorName, Collectors.flatMapping(blog -> blog.getComments().stream(), Collectors.toList())));
assertEquals(2, authorComments2.size());
assertEquals(2, authorComments2.get("1").size());
assertEquals(3, authorComments2.get("2").size());
}
}
class Blog {
private String authorName;
private List<String> comments;
public Blog(String authorName, String... comments) {
this.authorName = authorName;
this.comments = List.of(comments);
}
public String getAuthorName() {
return this.authorName;
}
public List<String> getComments() {
return this.comments;
}
}

View File

@@ -1,111 +0,0 @@
package com.baeldung.java9.language.stream;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.lang.Integer.*;
import static org.junit.Assert.assertEquals;
public class StreamFeaturesUnitTest {
public static class TakeAndDropWhileTest {
public Stream<String> getStreamAfterTakeWhileOperation() {
return Stream.iterate("", s -> s + "s").takeWhile(s -> s.length() < 10);
}
public Stream<String> getStreamAfterDropWhileOperation() {
return Stream.iterate("", s -> s + "s").takeWhile(s -> s.length() < 10).dropWhile(s -> !s.contains("sssss"));
}
@Test
public void testTakeWhileOperation() {
List<String> list = getStreamAfterTakeWhileOperation().collect(Collectors.toList());
assertEquals(10, list.size());
assertEquals("", list.get(0));
assertEquals("ss", list.get(2));
assertEquals("sssssssss", list.get(list.size() - 1));
}
@Test
public void testDropWhileOperation() {
List<String> list = getStreamAfterDropWhileOperation().collect(Collectors.toList());
assertEquals(5, list.size());
assertEquals("sssss", list.get(0));
assertEquals("sssssss", list.get(2));
assertEquals("sssssssss", list.get(list.size() - 1));
}
}
public static class IterateTest {
private Stream<Integer> getStream() {
return Stream.iterate(0, i -> i < 10, i -> i + 1);
}
@Test
public void testIterateOperation() {
List<Integer> list = getStream().collect(Collectors.toList());
assertEquals(10, list.size());
assertEquals(valueOf(0), list.get(0));
assertEquals(valueOf(5), list.get(5));
assertEquals(valueOf(9), list.get(list.size() - 1));
}
}
public static class OfNullableTest {
private List<String> collection = Arrays.asList("A", "B", "C");
private Map<String, Integer> map = new HashMap<>() {
{
put("A", 10);
put("C", 30);
}
};
private Stream<Integer> getStreamWithOfNullable() {
return collection.stream().flatMap(s -> Stream.ofNullable(map.get(s)));
}
private Stream<Integer> getStream() {
return collection.stream().flatMap(s -> {
Integer temp = map.get(s);
return temp != null ? Stream.of(temp) : Stream.empty();
});
}
private List<Integer> testOfNullableFrom(Stream<Integer> stream) {
List<Integer> list = stream.collect(Collectors.toList());
assertEquals(2, list.size());
assertEquals(valueOf(10), list.get(0));
assertEquals(valueOf(30), list.get(list.size() - 1));
return list;
}
@Test
public void testOfNullable() {
assertEquals(testOfNullableFrom(getStream()), testOfNullableFrom(getStreamWithOfNullable()));
}
}
}

View File

@@ -1,75 +0,0 @@
package com.baeldung.java9.reactive;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.SubmissionPublisher;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Stopwatch;
public class BaeldungBatchSubscriberImplIntegrationTest {
private static final int ITEM_SIZE = 10;
private SubmissionPublisher<String> publisher;
private BaeldungBatchSubscriberImpl<String> subscriber;
@Before
public void initialize() {
this.publisher = new SubmissionPublisher<String>(ForkJoinPool.commonPool(), 6);
this.subscriber = new BaeldungBatchSubscriberImpl<String>();
publisher.subscribe(subscriber);
}
@Rule
public Stopwatch stopwatch = new Stopwatch() {
};
@Test
public void testReactiveStreamCount() {
IntStream.range(0, ITEM_SIZE)
.forEach(item -> publisher.submit(item + ""));
publisher.close();
do {
// wait for subscribers to complete all processing.
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} while (!subscriber.isCompleted());
int count = subscriber.getCounter();
assertEquals(ITEM_SIZE, count);
}
@Test
public void testReactiveStreamTime() {
IntStream.range(0, ITEM_SIZE)
.forEach(item -> publisher.submit(item + ""));
publisher.close();
do {
// wait for subscribers to complete all processing.
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} while (!subscriber.isCompleted());
// The runtime in seconds should be equal to the number of items in each batch.
assertTrue(stopwatch.runtime(TimeUnit.SECONDS) >= (ITEM_SIZE / subscriber.BUFFER_SIZE));
}
}

View File

@@ -1,100 +0,0 @@
package com.baeldung.java9.reactive;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.SubmissionPublisher;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Stopwatch;
public class BaeldungSubscriberImplIntegrationTest {
private static final int ITEM_SIZE = 10;
private SubmissionPublisher<String> publisher;
private BaeldungSubscriberImpl<String> subscriber;
@Before
public void initialize() {
// create Publisher with max buffer capacity 3.
this.publisher = new SubmissionPublisher<String>(ForkJoinPool.commonPool(), 3);
this.subscriber = new BaeldungSubscriberImpl<String>();
publisher.subscribe(subscriber);
}
@Rule
public Stopwatch stopwatch = new Stopwatch() {
};
@Test
public void testReactiveStreamCount() {
IntStream.range(0, ITEM_SIZE)
.forEach(item -> publisher.submit(item + ""));
publisher.close();
do {
// wait for subscribers to complete all processing.
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} while (!subscriber.isCompleted());
int count = subscriber.getCounter();
assertEquals(ITEM_SIZE, count);
}
@Test
public void testReactiveStreamTime() {
IntStream.range(0, ITEM_SIZE)
.forEach(item -> publisher.submit(item + ""));
publisher.close();
do {
// wait for subscribers to complete all processing.
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} while (!subscriber.isCompleted());
// The runtime in seconds should be equal to the number of items.
assertTrue(stopwatch.runtime(TimeUnit.SECONDS) >= ITEM_SIZE);
}
@Test
public void testReactiveStreamOffer() {
IntStream.range(0, ITEM_SIZE)
.forEach(item -> publisher.offer(item + "", (subscriber, string) -> {
// Returning false means this item will be dropped (no retry), if blocked.
return false;
}));
publisher.close();
do {
// wait for subscribers to complete all processing.
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} while (!subscriber.isCompleted());
int count = subscriber.getCounter();
// Because 10 items were offered and the buffer capacity was 3, few items will not be processed.
assertTrue(ITEM_SIZE > count);
}
}

View File

@@ -1,16 +0,0 @@
package com.baeldung.java9.stackwalker;
import org.junit.Test;
public class StackWalkerDemoUnitTest {
@Test
public void giveStalkWalker_whenWalkingTheStack_thenShowStackFrames() {
new StackWalkerDemo().methodOne();
}
@Test
public void giveStalkWalker_whenInvokingFindCaller_thenFindCallingClass() {
new StackWalkerDemo().findCaller();
}
}

View File

@@ -1,73 +0,0 @@
package com.baeldung.java9.streams.reactive;
import org.junit.Test;
import java.util.List;
import java.util.concurrent.SubmissionPublisher;
import static org.assertj.core.api.Java6Assertions.assertThat;
public class ReactiveStreamsTest {
@Test
public void givenPublisher_whenSubscribeToIt_thenShouldConsumeAllElements() throws InterruptedException {
//given
SubmissionPublisher<String> publisher = new SubmissionPublisher<>();
EndSubscriber<String> subscriber = new EndSubscriber<>(6);
publisher.subscribe(subscriber);
List<String> items = List.of("1", "x", "2", "x", "3", "x");
//when
assertThat(publisher.getNumberOfSubscribers()).isEqualTo(1);
items.forEach(publisher::submit);
publisher.close();
//then
await().atMost(1000, TimeUnit.MILLISECONDS).until(
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(items)
);
}
@Test
public void givenPublisher_whenSubscribeAndTransformElements_thenShouldConsumeAllElements() throws InterruptedException {
//given
SubmissionPublisher<String> publisher = new SubmissionPublisher<>();
TransformProcessor<String, Integer> transformProcessor = new TransformProcessor<>(Integer::parseInt);
EndSubscriber<Integer> subscriber = new EndSubscriber<>(3);
List<String> items = List.of("1", "2", "3");
List<Integer> expectedResult = List.of(1, 2, 3);
//when
publisher.subscribe(transformProcessor);
transformProcessor.subscribe(subscriber);
items.forEach(publisher::submit);
publisher.close();
//then
await().atMost(1000, TimeUnit.MILLISECONDS).until(
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(expectedResult)
);
}
@Test
public void givenPublisher_whenRequestForOnlyOneElement_thenShouldConsumeOnlyThatOne() throws InterruptedException {
//given
SubmissionPublisher<String> publisher = new SubmissionPublisher<>();
EndSubscriber<String> subscriber = new EndSubscriber<>(1);
publisher.subscribe(subscriber);
List<String> items = List.of("1", "x", "2", "x", "3", "x");
List<String> expected = List.of("1");
//when
assertThat(publisher.getNumberOfSubscribers()).isEqualTo(1);
items.forEach(publisher::submit);
publisher.close();
//then
await().atMost(1000, TimeUnit.MILLISECONDS).until(
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(expected)
);
}
}