[BAEL-9555] - Created a core-java-modules folder

This commit is contained in:
amit2103
2019-05-05 17:22:09 +05:30
parent 8b63b0d90a
commit 3bae5e5334
1480 changed files with 25600 additions and 5594 deletions

View File

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

View File

@@ -0,0 +1,25 @@
=========
## Core Java 9 Examples
[Java 9 New Features](http://www.baeldung.com/new-java-9)
### Relevant Articles:
- [Java 9 New Features](https://www.baeldung.com/new-java-9)
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
- [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity)
- [Java 9 Variable Handles Demystified](http://www.baeldung.com/java-variable-handles)
- [Exploring the New HTTP Client in Java 9 and 11](http://www.baeldung.com/java-9-http-client)
- [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)
- [Multi-Release Jar Files](https://www.baeldung.com/java-multi-release-jar)
- [Ahead of Time Compilation (AoT)](https://www.baeldung.com/ahead-of-time-compilation)
- [Java 9 Process API Improvements](https://www.baeldung.com/java-9-process-api)
- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api)

View File

@@ -0,0 +1,5 @@
#!/usr/bin/env bash
cd src/main/java
javac com/baeldung/java9/aot/JaotCompilation.java
jaotc --output jaotCompilation.so com/baeldung/java9/aot/JaotCompilation.class

View File

@@ -0,0 +1,3 @@
javac --module-path mods -d mods/com.baeldung.httpclient^
src/modules/com.baeldung.httpclient/module-info.java^
src/modules/com.baeldung.httpclient/com/baeldung/httpclient/HttpClientExample.java

View File

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

View File

@@ -0,0 +1,2 @@
#!/usr/bin/env bash
javac -d outDir --module-source-path src/simple-modules $(find src/simple-modules -name "*.java")

View File

@@ -0,0 +1,3 @@
javac --module-path mods -d mods/com.baeldung.student.client^
src/modules/com.baeldung.student.client/module-info.java^
src/modules/com.baeldung.student.client/com/baeldung/student/client/StudentClient.java

View File

@@ -0,0 +1,2 @@
javac -d mods/com.baeldung.student.model src/modules/com.baeldung.student.model/module-info.java^
src/modules/com.baeldung.student.model/com/baeldung/student/model/Student.java

View File

@@ -0,0 +1,3 @@
javac --module-path mods -d mods/com.baeldung.student.service.dbimpl^
src/modules/com.baeldung.student.service.dbimpl/module-info.java^
src/modules/com.baeldung.student.service.dbimpl/com/baeldung/student/service/dbimpl/StudentDbService.java

View File

@@ -0,0 +1,3 @@
javac --module-path mods -d mods/com.baeldung.student.service^
src/modules/com.baeldung.student.service/module-info.java^
src/modules/com.baeldung.student.service/com/baeldung/student/service/StudentService.java

View File

@@ -0,0 +1,15 @@
# 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

@@ -0,0 +1,16 @@
<?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

@@ -0,0 +1,73 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-9</artifactId>
<version>0.2-SNAPSHOT</version>
<name>core-java-9</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-9</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>
<pluginRepositories>
<pluginRepository>
<id>apache.snapshots</id>
<url>http://repository.apache.org/snapshots/</url>
</pluginRepository>
</pluginRepositories>
<properties>
<!-- testing -->
<assertj.version>3.10.0</assertj.version>
<junit.platform.version>1.2.0</junit.platform.version>
<awaitility.version>1.7.0</awaitility.version>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
<guava.version>25.1-jre</guava.version>
</properties>
</project>

View File

@@ -0,0 +1,3 @@
#!/usr/bin/env bash
cd src/main/java
java -XX:AOTLibrary=./jaotCompilation.so com/baeldung/java9/aot/JaotCompilation

View File

@@ -0,0 +1 @@
java --module-path mods -m com.baeldung.httpclient/com.baeldung.httpclient.HttpClientExample

View File

@@ -0,0 +1,2 @@
#!/usr/bin/env bash
java --module-path outDir -m main.app/com.baeldung.modules.main.MainApp

View File

@@ -0,0 +1 @@
java --module-path mods -m com.baeldung.student.client/com.baeldung.student.client.StudentClient

View File

@@ -0,0 +1 @@
java --module-path mods -m com.baeldung.student.client/com.baeldung.student.client.StudentClient

View File

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

View File

@@ -0,0 +1,12 @@
package com.baeldung.java9.aot;
public class JaotCompilation {
public static void main(String[] argv) {
System.out.println(message());
}
public static String message() {
return "The JAOT compiler says 'Hello'";
}
}

View File

@@ -0,0 +1,23 @@
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

@@ -0,0 +1,27 @@
package com.baeldung.java9.language.stream;
import static java.util.stream.Collectors.filtering;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
public class StreamsGroupingCollectionFilter {
static public Map<Integer, List<Integer>> findEvenNumbersAfterGroupingByQuantityOfDigits(Collection<Integer> baseCollection) {
Function<Integer, Integer> getQuantityOfDigits = item -> (int) Math.log10(item) + 1;
return baseCollection.stream()
.collect(groupingBy(getQuantityOfDigits, filtering(item -> item % 2 == 0, toList())));
}
static public Map<Integer, List<Integer>> findEvenNumbersBeforeGroupingByQuantityOfDigits(Collection<Integer> baseCollection) {
return baseCollection.stream()
.filter(item -> item % 2 == 0)
.collect(groupingBy(item -> (int) Math.log10(item) + 1, toList()));
}
}

View File

@@ -0,0 +1,33 @@
package com.baeldung.java9.maps.initialize;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
public class MapsInitializer {
@SuppressWarnings("unused")
public void createMapWithMapOf() {
Map<String, String> emptyMap = Map.of();
Map<String, String> singletonMap = Map.of("key1", "value");
Map<String, String> map = Map.of("key1","value1", "key2", "value2");
}
public void createMapWithMapEntries() {
Map<String, String> map = Map.ofEntries(
new AbstractMap.SimpleEntry<String, String>("name", "John"),
new AbstractMap.SimpleEntry<String, String>("city", "budapest"),
new AbstractMap.SimpleEntry<String, String>("zip", "000000"),
new AbstractMap.SimpleEntry<String, String>("home", "1231231231")
);
}
@SuppressWarnings("unused")
public void createMutableMaps() {
Map<String, String> map = new HashMap<String, String> (Map.of("key1","value1", "key2", "value2"));
Map<String, String> map2 = new HashMap<String, String> ( Map.ofEntries(
new AbstractMap.SimpleEntry<String, String>("name", "John"),
new AbstractMap.SimpleEntry<String, String>("city", "budapest")));
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.java9.methodhandles;
public class Book {
String id;
String title;
public Book(String id, String title) {
this.id = id;
this.title = title;
}
@SuppressWarnings("unused")
private String formatBook() {
return id + " > " + title;
}
}

View File

@@ -0,0 +1,24 @@
package com.baeldung.java9.rangedates;
import java.util.Collection;
import java.util.Date;
public class DatesCollectionIteration {
public void iteratingRangeOfDatesJava7(Collection<Date> dates) {
for (Date date : dates) {
processDate(date);
}
}
public void iteratingRangeOfDatesJava8(Collection<Date> dates) {
dates.stream()
.forEach(this::processDate);
}
private void processDate(Date date) {
System.out.println(date);
}
}

View File

@@ -0,0 +1,43 @@
package com.baeldung.java9.rangedates;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
public class RangeDatesIteration {
public void iterateBetweenDatesJava9(LocalDate startDate, LocalDate endDate) {
startDate.datesUntil(endDate)
.forEach(this::processDate);
}
public void iterateBetweenDatesJava8(LocalDate start, LocalDate end) {
for (LocalDate date = start; date.isBefore(end); date = date.plusDays(1)) {
processDate(date);
}
}
public void iterateBetweenDatesJava7(Date start, Date end) {
Date current = start;
while (current.before(end)) {
processDate(current);
Calendar calendar = Calendar.getInstance();
calendar.setTime(current);
calendar.add(Calendar.DATE, 1);
current = calendar.getTime();
}
}
private void processDate(LocalDate date) {
System.out.println(date);
}
private void processDate(Date date) {
System.out.println(date);
}
}

View File

@@ -0,0 +1,82 @@
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

@@ -0,0 +1,55 @@
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

@@ -0,0 +1,44 @@
package com.baeldung.java9.set;
import com.google.common.collect.ImmutableSet;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class UnmodifiableSet {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("Canada");
set.add("USA");
coreJDK(set);
guavaOf();
copyOf(set);
java9Of();
}
private static void java9Of() {
Set<String> immutable = Set.of("Canada", "USA");
System.out.println(immutable);
}
private static void guavaOf() {
Set<String> immutable = ImmutableSet.of("Canada", "USA");
System.out.println(immutable);
}
private static void copyOf(Set<String> set) {
Set<String> immutable = ImmutableSet.copyOf(set);
set.add("Costa Rica");
System.out.println(immutable);
}
private static void coreJDK(Set<String> set) {
Set<String> unmodifiableSet = Collections.unmodifiableSet(set);
set.add("Costa Rica");
System.out.println(unmodifiableSet);
}
}

View File

@@ -0,0 +1,84 @@
package com.baeldung.java9.stackwalker;
import java.lang.StackWalker.StackFrame;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StackWalkerDemo {
public void methodOne() {
this.methodTwo();
}
public void methodTwo() {
this.methodThree();
}
public void methodThree() {
List<StackFrame> stackTrace = StackWalker.getInstance()
.walk(this::walkExample);
printStackTrace(stackTrace);
System.out.println("---------------------------------------------");
stackTrace = StackWalker.getInstance()
.walk(this::walkExample2);
printStackTrace(stackTrace);
System.out.println("---------------------------------------------");
String line = StackWalker.getInstance().walk(this::walkExample3);
System.out.println(line);
System.out.println("---------------------------------------------");
stackTrace = StackWalker.getInstance(StackWalker.Option.SHOW_REFLECT_FRAMES)
.walk(this::walkExample);
printStackTrace(stackTrace);
System.out.println("---------------------------------------------");
Runnable r = () -> {
List<StackFrame> stackTrace2 = StackWalker.getInstance(StackWalker.Option.SHOW_HIDDEN_FRAMES)
.walk(this::walkExample);
printStackTrace(stackTrace2);
};
r.run();
}
public List<StackFrame> walkExample(Stream<StackFrame> stackFrameStream) {
return stackFrameStream.collect(Collectors.toList());
}
public List<StackFrame> walkExample2(Stream<StackFrame> stackFrameStream) {
return stackFrameStream.filter(frame -> frame.getClassName()
.contains("com.baeldung"))
.collect(Collectors.toList());
}
public String walkExample3(Stream<StackFrame> stackFrameStream) {
return stackFrameStream.filter(frame -> frame.getClassName()
.contains("com.baeldung")
&& frame.getClassName()
.endsWith("Test"))
.findFirst()
.map(frame -> frame.getClassName() + "#" + frame.getMethodName() + ", Line " + frame.getLineNumber())
.orElse("Unknown caller");
}
public void findCaller() {
Class<?> caller = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).getCallerClass();
System.out.println(caller.getCanonicalName());
}
public void printStackTrace(List<StackFrame> stackTrace) {
for (StackFrame stackFrame : stackTrace) {
System.out.println(stackFrame.getClassName()
.toString() + "#" + stackFrame.getMethodName() + ", Line " + stackFrame.getLineNumber());
}
}
}

View File

@@ -0,0 +1,43 @@
package com.baeldung.java9.streams.reactive;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Flow.Subscriber;
import java.util.concurrent.Flow.Subscription;
import java.util.concurrent.atomic.AtomicInteger;
public class EndSubscriber<T> implements Subscriber<T> {
private final AtomicInteger howMuchMessagesToConsume;
private Subscription subscription;
public List<T> consumedElements = new LinkedList<>();
public EndSubscriber(Integer howMuchMessagesToConsume) {
this.howMuchMessagesToConsume = new AtomicInteger(howMuchMessagesToConsume);
}
@Override
public void onSubscribe(Subscription subscription) {
this.subscription = subscription;
subscription.request(1);
}
@Override
public void onNext(T item) {
howMuchMessagesToConsume.decrementAndGet();
System.out.println("Got : " + item);
consumedElements.add(item);
if (howMuchMessagesToConsume.get() > 0) {
subscription.request(1);
}
}
@Override
public void onError(Throwable t) {
t.printStackTrace();
}
@Override
public void onComplete() {
System.out.println("Done");
}
}

View File

@@ -0,0 +1,38 @@
package com.baeldung.java9.streams.reactive;
import java.util.concurrent.Flow;
import java.util.concurrent.SubmissionPublisher;
import java.util.function.Function;
public class TransformProcessor<T, R> extends SubmissionPublisher<R> implements Flow.Processor<T, R> {
private Function<T, R> function;
private Flow.Subscription subscription;
public TransformProcessor(Function<T, R> function) {
super();
this.function = function;
}
@Override
public void onSubscribe(Flow.Subscription subscription) {
this.subscription = subscription;
subscription.request(1);
}
@Override
public void onNext(T item) {
submit(function.apply(item));
subscription.request(1);
}
@Override
public void onError(Throwable t) {
t.printStackTrace();
}
@Override
public void onComplete() {
close();
}
}

View File

@@ -0,0 +1,16 @@
package com.baeldung.multireleaseapp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class App {
private static final Logger logger = LoggerFactory.getLogger(App.class);
public static void main(String[] args) throws Exception {
String dateToCheck = args[0];
boolean isLeapYear = DateHelper.checkIfLeapYear(dateToCheck);
logger.info("Date given " + dateToCheck + " is leap year: " + isLeapYear);
}
}

View File

@@ -0,0 +1,22 @@
package com.baeldung.multireleaseapp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DateHelper {
private static final Logger logger = LoggerFactory.getLogger(DateHelper.class);
public static boolean checkIfLeapYear(String dateStr) throws Exception {
logger.info("Checking for leap year using Java 1 calendar API");
Calendar cal = Calendar.getInstance();
cal.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(dateStr));
int year = cal.get(Calendar.YEAR);
return (new GregorianCalendar()).isLeapYear(year);
}
}

View File

@@ -0,0 +1,26 @@
package com.baeldung.optionals;
import java.util.Optional;
public class Optionals {
public static <T> Optional<T> or(Optional<T> optional, Optional<T> fallback) {
return optional.isPresent() ? optional : fallback;
}
public static Optional<String> getName(Optional<String> name) {
return name.or(() -> getCustomMessage());
}
public static com.google.common.base.Optional<String> getOptionalGuavaName(com.google.common.base.Optional<String> name) {
return name.or(getCustomMessageGuava());
}
private static Optional<String> getCustomMessage() {
return Optional.of("Name not provided");
}
private static com.google.common.base.Optional<String> getCustomMessageGuava() {
return com.google.common.base.Optional.of("Name not provided");
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.multireleaseapp;
import java.time.LocalDate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DateHelper {
private static final Logger logger = LoggerFactory.getLogger(DateHelper.class);
public static boolean checkIfLeapYear(String dateStr) throws Exception {
logger.info("Checking for leap year using Java 9 Date Api");
return LocalDate.parse(dateStr)
.isLeapYear();
}
}

View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -0,0 +1,84 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.baeldung.httpclient;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import jdk.incubator.http.HttpClient;
import jdk.incubator.http.HttpRequest;
import jdk.incubator.http.HttpRequest.BodyProcessor;
import jdk.incubator.http.HttpResponse;
import jdk.incubator.http.HttpResponse.BodyHandler;
/**
*
* @author pkaria
*/
public class HttpClientExample {
public static void main(String[] args) throws Exception {
httpGetRequest();
httpPostRequest();
asynchronousRequest();
asynchronousMultipleRequests();
}
public static void httpGetRequest() throws URISyntaxException, IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1");
HttpRequest request = HttpRequest.newBuilder(httpURI).GET()
.headers("Accept-Enconding", "gzip, deflate").build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString());
String responseBody = response.body();
int responseStatusCode = response.statusCode();
System.out.println(responseBody);
}
public static void httpPostRequest() throws URISyntaxException, IOException, InterruptedException {
HttpClient client = HttpClient
.newBuilder()
.build();
HttpRequest request = HttpRequest
.newBuilder(new URI("http://jsonplaceholder.typicode.com/posts"))
.POST(BodyProcessor.fromString("Sample Post Request"))
.build();
HttpResponse<String> response
= client.send(request, HttpResponse.BodyHandler.asString());
String responseBody = response.body();
System.out.println(responseBody);
}
public static void asynchronousRequest() throws URISyntaxException {
HttpClient client = HttpClient.newHttpClient();
URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1");
HttpRequest request = HttpRequest.newBuilder(httpURI).GET().build();
CompletableFuture<HttpResponse<String>> futureResponse = client.sendAsync(request,
HttpResponse.BodyHandler.asString());
}
public static void asynchronousMultipleRequests() throws URISyntaxException {
List<URI> targets = Arrays.asList(new URI("http://jsonplaceholder.typicode.com/posts/1"), new URI("http://jsonplaceholder.typicode.com/posts/2"));
HttpClient client = HttpClient.newHttpClient();
List<CompletableFuture<File>> futures = targets
.stream()
.map(target -> client
.sendAsync(
HttpRequest.newBuilder(target)
.GET()
.build(),
BodyHandler.asFile(Paths.get("base", target.getPath())))
.thenApply(response -> response.body())
.thenApply(path -> path.toFile()))
.collect(Collectors.toList());
}
}

View File

@@ -0,0 +1,3 @@
module com.baeldung.httpclient {
requires jdk.incubator.httpclient;
}

View File

@@ -0,0 +1,13 @@
package com.baeldung.logging.app;
import static java.lang.System.Logger.*;
public class MainApp {
private static System.Logger LOGGER = System.getLogger("MainApp");
public static void main(String[] args) {
LOGGER.log(Level.ERROR, "error test");
LOGGER.log(Level.INFO, "info test");
}
}

View File

@@ -0,0 +1,2 @@
module com.baeldung.logging.app {
}

View File

@@ -0,0 +1,99 @@
package com.baeldung.logging.slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ResourceBundle;
public class Slf4jLogger implements System.Logger {
private final String name;
private final Logger logger;
public Slf4jLogger(String name) {
this.name = name;
logger = LoggerFactory.getLogger(name);
}
@Override
public String getName() {
return name;
}
@Override
public boolean isLoggable(Level level) {
switch (level) {
case OFF:
return false;
case TRACE:
return logger.isTraceEnabled();
case DEBUG:
return logger.isDebugEnabled();
case INFO:
return logger.isInfoEnabled();
case WARNING:
return logger.isWarnEnabled();
case ERROR:
return logger.isErrorEnabled();
case ALL:
default:
return true;
}
}
@Override
public void log(Level level, ResourceBundle bundle, String msg, Throwable thrown) {
if (!isLoggable(level)) {
return;
}
switch (level) {
case TRACE:
logger.trace(msg, thrown);
break;
case DEBUG:
logger.debug(msg, thrown);
break;
case INFO:
logger.info(msg, thrown);
break;
case WARNING:
logger.warn(msg, thrown);
break;
case ERROR:
logger.error(msg, thrown);
break;
case ALL:
default:
logger.info(msg, thrown);
}
}
@Override
public void log(Level level, ResourceBundle bundle, String format, Object... params) {
if (!isLoggable(level)) {
return;
}
switch (level) {
case TRACE:
logger.trace(format, params);
break;
case DEBUG:
logger.debug(format, params);
break;
case INFO:
logger.info(format, params);
break;
case WARNING:
logger.warn(format, params);
break;
case ERROR:
logger.error(format, params);
break;
case ALL:
default:
logger.info(format, params);
}
}
}

View File

@@ -0,0 +1,8 @@
package com.baeldung.logging.slf4j;
public class Slf4jLoggerFinder extends System.LoggerFinder {
@Override
public System.Logger getLogger(String name, Module module) {
return new Slf4jLogger(name);
}
}

View File

@@ -0,0 +1,6 @@
module com.baeldung.logging.slf4j {
requires org.slf4j;
provides java.lang.System.LoggerFinder
with com.baeldung.logging.slf4j.Slf4jLoggerFinder;
exports com.baeldung.logging.slf4j;
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.logging;
import java.text.MessageFormat;
import java.util.ResourceBundle;
public class ConsoleLogger implements System.Logger {
@Override
public String getName() {
return "ConsoleLogger";
}
@Override
public boolean isLoggable(Level level) {
return true;
}
@Override
public void log(Level level, ResourceBundle bundle, String msg, Throwable thrown) {
System.out.printf("ConsoleLogger [%s]: %s - %s%n", level, msg, thrown);
}
@Override
public void log(Level level, ResourceBundle bundle, String format, Object... params) {
System.out.printf("ConsoleLogger [%s]: %s%n", level, MessageFormat.format(format, params));
}
}

View File

@@ -0,0 +1,9 @@
package com.baeldung.logging;
public class CustomLoggerFinder extends System.LoggerFinder {
@Override
public System.Logger getLogger(String name, Module module) {
return new ConsoleLogger();
}
}

View File

@@ -0,0 +1,5 @@
module com.baeldung.logging {
provides java.lang.System.LoggerFinder
with com.baeldung.logging.CustomLoggerFinder;
exports com.baeldung.logging;
}

View File

@@ -0,0 +1,16 @@
package com.baeldung.student.client;
import com.baeldung.student.service.StudentService;
import com.baeldung.student.service.dbimpl.StudentDbService;
import com.baeldung.student.model.Student;
public class StudentClient {
public static void main(String[] args) {
StudentService service = new StudentDbService();
service.create(new Student());
service.read("17SS0001");
service.update(new Student());
service.delete("17SS0001");
}
}

View File

@@ -0,0 +1,3 @@
module com.baeldung.student.client{
requires com.baeldung.student.service.dbimpl;
}

View File

@@ -0,0 +1,15 @@
package com.baeldung.student.model;
import java.util.Date;
public class Student {
private String registrationId;
public String getRegistrationId() {
return registrationId;
}
public void setRegistrationId(String registrationId) {
this.registrationId = registrationId;
}
}

View File

@@ -0,0 +1,3 @@
module com.baeldung.student.model{
exports com.baeldung.student.model;
}

View File

@@ -0,0 +1,30 @@
package com.baeldung.student.service.dbimpl;
import com.baeldung.student.service.StudentService;
import com.baeldung.student.model.Student;
import java.util.logging.*;
public class StudentDbService implements StudentService {
private static Logger logger = Logger.getLogger("StudentDbService");
public String create(Student student) {
logger.log(Level.INFO, "Creating student in DB...");
return student.getRegistrationId();
}
public Student read(String registrationId) {
logger.log(Level.INFO, "Reading student from DB...");
return new Student();
}
public Student update(Student student) {
logger.log(Level.INFO, "Updating sutdent in DB...");
return student;
}
public String delete(String registrationId) {
logger.log(Level.INFO, "Deleteing sutdent in DB...");
return registrationId;
}
}

View File

@@ -0,0 +1,5 @@
module com.baeldung.student.service.dbimpl{
requires transitive com.baeldung.student.service;
exports com.baeldung.student.service.dbimpl;
requires java.logging;
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.student.service;
import com.baeldung.student.model.Student;
public interface StudentService {
public String create(Student student);
public Student read(String registrationId);
public Student update(Student student);
public String delete(String registrationId);
}

View File

@@ -0,0 +1,4 @@
module com.baeldung.student.service{
requires transitive com.baeldung.student.model;
exports com.baeldung.student.service;
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.modules.hello;
public interface HelloInterface {
public void sayHello();
}

View File

@@ -0,0 +1,11 @@
package com.baeldung.modules.hello;
public class HelloModules implements HelloInterface {
public static void doSomething() {
System.out.println("Hello, Modules!");
}
public void sayHello() {
System.out.println("Hello!");
}
}

View File

@@ -0,0 +1,4 @@
module hello.modules {
exports com.baeldung.modules.hello;
provides com.baeldung.modules.hello.HelloInterface with com.baeldung.modules.hello.HelloModules;
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.modules.main;
import com.baeldung.modules.hello.HelloModules;
public class MainApp {
public static void main(String[] args) {
HelloModules.doSomething();
HelloModules module = new HelloModules();
module.sayHello();
}
}

View File

@@ -0,0 +1,4 @@
module main.app {
requires hello.modules;
uses com.baeldung.modules.hello.HelloInterface;
}

View File

@@ -0,0 +1,85 @@
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

@@ -0,0 +1,61 @@
package com.baeldung.java9;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Test;
public class Java9OptionalsStreamUnitTest {
private static List<Optional<String>> listOfOptionals = Arrays.asList(Optional.empty(), Optional.of("foo"), Optional.empty(), Optional.of("bar"));
@Test
public void filterOutPresentOptionalsWithFilter() {
assertEquals(4, listOfOptionals.size());
List<String> filteredList = listOfOptionals.stream().filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
assertEquals(2, filteredList.size());
assertEquals("foo", filteredList.get(0));
assertEquals("bar", filteredList.get(1));
}
@Test
public void filterOutPresentOptionalsWithFlatMap() {
assertEquals(4, listOfOptionals.size());
List<String> filteredList = listOfOptionals.stream().flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()).collect(Collectors.toList());
assertEquals(2, filteredList.size());
assertEquals("foo", filteredList.get(0));
assertEquals("bar", filteredList.get(1));
}
@Test
public void filterOutPresentOptionalsWithFlatMap2() {
assertEquals(4, listOfOptionals.size());
List<String> filteredList = listOfOptionals.stream().flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)).collect(Collectors.toList());
assertEquals(2, filteredList.size());
assertEquals("foo", filteredList.get(0));
assertEquals("bar", filteredList.get(1));
}
@Test
public void filterOutPresentOptionalsWithJava9() {
assertEquals(4, listOfOptionals.size());
List<String> filteredList = listOfOptionals.stream().flatMap(Optional::stream).collect(Collectors.toList());
assertEquals(2, filteredList.size());
assertEquals("foo", filteredList.get(0));
assertEquals("bar", filteredList.get(1));
}
}

View File

@@ -0,0 +1,44 @@
package com.baeldung.java9;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import java.awt.Image;
import java.awt.image.BaseMultiResolutionImage;
import java.awt.image.BufferedImage;
import java.awt.image.MultiResolutionImage;
import java.util.List;
import org.junit.Test;
public class MultiResultionImageUnitTest {
@Test
public void baseMultiResImageTest() {
int baseIndex = 1;
int length = 4;
BufferedImage[] resolutionVariants = new BufferedImage[length];
for (int i = 0; i < length; i++) {
resolutionVariants[i] = createImage(i);
}
MultiResolutionImage bmrImage = new BaseMultiResolutionImage(baseIndex, resolutionVariants);
List<Image> rvImageList = bmrImage.getResolutionVariants();
assertEquals("MultiResoltion Image shoudl contain the same number of resolution variants!", rvImageList.size(), length);
for (int i = 0; i < length; i++) {
int imageSize = getSize(i);
Image testRVImage = bmrImage.getResolutionVariant(imageSize, imageSize);
assertSame("Images should be the same", testRVImage, resolutionVariants[i]);
}
}
private static int getSize(int i) {
return 8 * (i + 1);
}
private static BufferedImage createImage(int i) {
return new BufferedImage(getSize(i), getSize(i), BufferedImage.TYPE_INT_RGB);
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.java9;
import java.util.Optional;
import java.util.stream.Stream;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class OptionalToStreamUnitTest {
@Test
public void testOptionalToStream() {
Optional<String> op = Optional.ofNullable("String value");
Stream<String> strOptionalStream = op.stream();
Stream<String> filteredStream = strOptionalStream.filter((str) -> {
return str != null && str.startsWith("String");
});
assertEquals(1, filteredStream.count());
}
}

View File

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

View File

@@ -0,0 +1,38 @@
package com.baeldung.java9;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class SetExamplesUnitTest {
@Test
public void testUnmutableSet() {
Set<String> strKeySet = Set.of("key1", "key2", "key3");
try {
strKeySet.add("newKey");
} catch (UnsupportedOperationException uoe) {
}
assertEquals(strKeySet.size(), 3);
}
@Test
public void testArrayToSet() {
Integer[] intArray = new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
Set<Integer> intSet = Set.of(intArray);
assertEquals(intSet.size(), intArray.length);
}
@Test(expected = UnsupportedOperationException.class)
public void testUnmodifiableSet() {
Set<String> set = new HashSet<>();
set.add("Canada");
set.add("USA");
Set<String> unmodifiableSet = Collections.unmodifiableSet(set);
unmodifiableSet.add("Costa Rica");
}
}

View File

@@ -0,0 +1,74 @@
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

@@ -0,0 +1,218 @@
package com.baeldung.java9.httpclient;
import jdk.incubator.http.HttpClient;
import jdk.incubator.http.HttpRequest;
import jdk.incubator.http.HttpResponse;
import org.junit.Test;
import java.io.IOException;
import java.net.*;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;
/**
* Created by adam.
*/
public class HttpClientTest {
@Test
public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post"))
.headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyProcessor.fromString("Sample body"))
.build();
HttpResponse<String> response = HttpClient.newBuilder()
.proxy(ProxySelector.getDefault())
.build()
.send(request, HttpResponse.BodyHandler.asString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.body(), containsString("Sample body"));
}
@Test
public void shouldNotFollowRedirectWhenSetToDefaultNever() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("http://stackoverflow.com"))
.version(HttpClient.Version.HTTP_1_1)
.GET()
.build();
HttpResponse<String> response = HttpClient.newBuilder()
.build()
.send(request, HttpResponse.BodyHandler.asString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM));
assertThat(response.body(), containsString("https://stackoverflow.com/"));
}
@Test
public void shouldFollowRedirectWhenSetToAlways() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("http://stackoverflow.com"))
.version(HttpClient.Version.HTTP_1_1)
.GET()
.build();
HttpResponse<String> response = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.ALWAYS)
.build()
.send(request, HttpResponse.BodyHandler.asString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.finalRequest()
.uri()
.toString(), equalTo("https://stackoverflow.com/"));
}
@Test
public void shouldReturnOKStatusForAuthenticatedAccess() throws URISyntaxException, IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/basic-auth"))
.GET()
.build();
HttpResponse<String> response = HttpClient.newBuilder()
.authenticator(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("postman", "password".toCharArray());
}
})
.build()
.send(request, HttpResponse.BodyHandler.asString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
}
@Test
public void shouldSendRequestAsync() throws URISyntaxException, InterruptedException, ExecutionException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post"))
.headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyProcessor.fromString("Sample body"))
.build();
CompletableFuture<HttpResponse<String>> response = HttpClient.newBuilder()
.build()
.sendAsync(request, HttpResponse.BodyHandler.asString());
assertThat(response.get()
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
}
@Test
public void shouldUseJustTwoThreadWhenProcessingSendAsyncRequest() throws URISyntaxException, InterruptedException, ExecutionException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
.GET()
.build();
ExecutorService executorService = Executors.newFixedThreadPool(2);
CompletableFuture<HttpResponse<String>> response1 = HttpClient.newBuilder()
.executor(executorService)
.build()
.sendAsync(request, HttpResponse.BodyHandler.asString());
CompletableFuture<HttpResponse<String>> response2 = HttpClient.newBuilder()
.executor(executorService)
.build()
.sendAsync(request, HttpResponse.BodyHandler.asString());
CompletableFuture<HttpResponse<String>> response3 = HttpClient.newBuilder()
.executor(executorService)
.build()
.sendAsync(request, HttpResponse.BodyHandler.asString());
CompletableFuture.allOf(response1, response2, response3)
.join();
assertThat(response1.get()
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response2.get()
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response3.get()
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
}
@Test
public void shouldNotStoreCookieWhenPolicyAcceptNone() throws URISyntaxException, IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
.GET()
.build();
HttpClient httpClient = HttpClient.newBuilder()
.cookieManager(new CookieManager(null, CookiePolicy.ACCEPT_NONE))
.build();
httpClient.send(request, HttpResponse.BodyHandler.asString());
assertThat(httpClient.cookieManager()
.get()
.getCookieStore()
.getCookies(), empty());
}
@Test
public void shouldStoreCookieWhenPolicyAcceptAll() throws URISyntaxException, IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
.GET()
.build();
HttpClient httpClient = HttpClient.newBuilder()
.cookieManager(new CookieManager(null, CookiePolicy.ACCEPT_ALL))
.build();
httpClient.send(request, HttpResponse.BodyHandler.asString());
assertThat(httpClient.cookieManager()
.get()
.getCookieStore()
.getCookies(), not(empty()));
}
@Test
public void shouldProcessMultipleRequestViaStream() throws URISyntaxException, ExecutionException, InterruptedException {
List<URI> targets = Arrays.asList(new URI("https://postman-echo.com/get?foo1=bar1"), new URI("https://postman-echo.com/get?foo2=bar2"));
HttpClient client = HttpClient.newHttpClient();
List<CompletableFuture<String>> futures = targets.stream()
.map(target -> client.sendAsync(HttpRequest.newBuilder(target)
.GET()
.build(), HttpResponse.BodyHandler.asString())
.thenApply(response -> response.body()))
.collect(Collectors.toList());
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.join();
if (futures.get(0)
.get()
.contains("foo1")) {
assertThat(futures.get(0)
.get(), containsString("bar1"));
assertThat(futures.get(1)
.get(), containsString("bar2"));
} else {
assertThat(futures.get(1)
.get(), containsString("bar2"));
assertThat(futures.get(1)
.get(), containsString("bar1"));
}
}
}

View File

@@ -0,0 +1,171 @@
package com.baeldung.java9.httpclient;
import jdk.incubator.http.HttpClient;
import jdk.incubator.http.HttpRequest;
import jdk.incubator.http.HttpResponse;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import static java.time.temporal.ChronoUnit.SECONDS;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
/**
* Created by adam.
*/
public class HttpRequestTest {
@Test
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
.GET()
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandler.asString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
}
@Test
public void shouldUseHttp2WhenWebsiteUsesHttp2() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://stackoverflow.com"))
.version(HttpClient.Version.HTTP_2)
.GET()
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandler.asString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.version(), equalTo(HttpClient.Version.HTTP_2));
}
@Test
public void shouldFallbackToHttp1_1WhenWebsiteDoesNotUseHttp2() throws IOException, InterruptedException, URISyntaxException, NoSuchAlgorithmException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
.version(HttpClient.Version.HTTP_2)
.GET()
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandler.asString());
assertThat(response.version(), equalTo(HttpClient.Version.HTTP_1_1));
}
@Test
public void shouldReturnStatusOKWhenSendGetRequestWithDummyHeaders() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
.headers("key1", "value1", "key2", "value2")
.GET()
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandler.asString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
}
@Test
public void shouldReturnStatusOKWhenSendGetRequestTimeoutSet() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
.timeout(Duration.of(10, SECONDS))
.GET()
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandler.asString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
}
@Test
public void shouldReturnNoContentWhenPostWithNoBody() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post"))
.POST(HttpRequest.noBody())
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandler.asString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
}
@Test
public void shouldReturnSampleDataContentWhenPostWithBodyText() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post"))
.headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyProcessor.fromString("Sample request body"))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandler.asString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.body(), containsString("Sample request body"));
}
@Test
public void shouldReturnSampleDataContentWhenPostWithInputStream() throws IOException, InterruptedException, URISyntaxException {
byte[] sampleData = "Sample request body".getBytes();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post"))
.headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyProcessor.fromInputStream(() -> new ByteArrayInputStream(sampleData)))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandler.asString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.body(), containsString("Sample request body"));
}
@Test
public void shouldReturnSampleDataContentWhenPostWithByteArrayProcessorStream() throws IOException, InterruptedException, URISyntaxException {
byte[] sampleData = "Sample request body".getBytes();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post"))
.headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyProcessor.fromByteArray(sampleData))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandler.asString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.body(), containsString("Sample request body"));
}
@Test
public void shouldReturnSampleDataContentWhenPostWithFileProcessorStream() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post"))
.headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyProcessor.fromFile(Paths.get("src/test/resources/sample.txt")))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandler.asString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.body(), containsString("Sample file content"));
}
}

View File

@@ -0,0 +1,55 @@
package com.baeldung.java9.httpclient;
import jdk.incubator.http.HttpClient;
import jdk.incubator.http.HttpRequest;
import jdk.incubator.http.HttpResponse;
import org.junit.Test;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.isEmptyString;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;
/**
* Created by adam.
*/
public class HttpResponseTest {
@Test
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
.GET()
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandler.asString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.body(), not(isEmptyString()));
}
@Test
public void shouldResponseURIDifferentThanRequestUIRWhenRedirect() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("http://stackoverflow.com"))
.version(HttpClient.Version.HTTP_1_1)
.GET()
.build();
HttpResponse<String> response = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.ALWAYS)
.build()
.send(request, HttpResponse.BodyHandler.asString());
assertThat(request.uri()
.toString(), equalTo("http://stackoverflow.com"));
assertThat(response.uri()
.toString(), equalTo("https://stackoverflow.com/"));
}
}

View File

@@ -0,0 +1,36 @@
package com.baeldung.java9.language;
import org.junit.Test;
public class DiamondUnitTest {
static class FooClass<X> {
FooClass(X x) {
}
<Z> FooClass(X x, Z z) {
}
}
@Test
public void diamondTest() {
FooClass<Integer> fc = new FooClass<>(1) {
};
FooClass<? extends Integer> fc0 = new FooClass<>(1) {
};
FooClass<?> fc1 = new FooClass<>(1) {
};
FooClass<? super Integer> fc2 = new FooClass<>(1) {
};
FooClass<Integer> fc3 = new FooClass<>(1, "") {
};
FooClass<? extends Integer> fc4 = new FooClass<>(1, "") {
};
FooClass<?> fc5 = new FooClass<>(1, "") {
};
FooClass<? super Integer> fc6 = new FooClass<>(1, "") {
};
}
}

View File

@@ -0,0 +1,86 @@
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

@@ -0,0 +1,15 @@
package com.baeldung.java9.language;
import com.baeldung.java9.language.PrivateInterface;
import org.junit.Test;
public class PrivateInterfaceUnitTest {
@Test
public void test() {
PrivateInterface piClass = new PrivateInterface() {
};
piClass.check();
}
}

View File

@@ -0,0 +1,67 @@
package com.baeldung.java9.language;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class TryWithResourcesUnitTest {
static int closeCount = 0;
static class MyAutoCloseable implements AutoCloseable {
final FinalWrapper finalWrapper = new FinalWrapper();
public void close() {
closeCount++;
}
static class FinalWrapper {
public final AutoCloseable finalCloseable = new AutoCloseable() {
@Override
public void close() throws Exception {
closeCount++;
}
};
}
}
@Test
public void tryWithResourcesTest() {
MyAutoCloseable mac = new MyAutoCloseable();
try (mac) {
assertEquals("Expected and Actual does not match", 0, closeCount);
}
try (mac.finalWrapper.finalCloseable) {
assertEquals("Expected and Actual does not match", 1, closeCount);
} catch (Exception ex) {
}
try (new MyAutoCloseable() { }.finalWrapper.finalCloseable) {
assertEquals("Expected and Actual does not match", 2, closeCount);
} catch (Exception ex) {
}
try ((closeCount > 0 ? mac : new MyAutoCloseable()).finalWrapper.finalCloseable) {
assertEquals("Expected and Actual does not match", 3, closeCount);
} catch (Exception ex) {
}
try {
throw new CloseableException();
} catch (CloseableException ex) {
try (ex) {
assertEquals("Expected and Actual does not match", 4, closeCount);
}
}
assertEquals("Expected and Actual does not match", 5, closeCount);
}
static class CloseableException extends Exception implements AutoCloseable {
@Override
public void close() {
closeCount++;
}
}
}

View File

@@ -0,0 +1,61 @@
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

@@ -0,0 +1,62 @@
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

@@ -0,0 +1,60 @@
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

@@ -0,0 +1,51 @@
package com.baeldung.java9.language.stream;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
@RunWith(JUnitPlatform.class)
public class CollectionFilterUnitTest {
private static final Collection<Integer> BASE_INTEGER_COLLECTION = Arrays.asList(9, 12, 55, 56, 101, 115, 8002, 223, 2668, 19, 8);
private static final Map<Integer, List<Integer>> EXPECTED_EVEN_FILTERED_AFTER_GROUPING_MAP = createExpectedFilterAfterGroupingMap();
private static Map<Integer, List<Integer>> createExpectedFilterAfterGroupingMap() {
Map<Integer, List<Integer>> map = new HashMap<>();
map.put(1, Arrays.asList(8));
map.put(2, Arrays.asList(12, 56));
map.put(3, Collections.emptyList());
map.put(4, Arrays.asList(8002, 2668));
return map;
}
private static final Map<Integer, List<Integer>> EXPECTED_EVEN_FILTERED_BEFORE_GROUPING_MAP = createExpectedFilterBeforeGroupingMap();
private static Map<Integer, List<Integer>> createExpectedFilterBeforeGroupingMap() {
Map<Integer, List<Integer>> map = new HashMap<>();
map.put(1, Arrays.asList(8));
map.put(2, Arrays.asList(12, 56));
map.put(4, Arrays.asList(8002, 2668));
return map;
}
@Test
public void givenAStringCollection_whenFilteringFourLetterWords_thenObtainTheFilteredCollection() {
Map<Integer, List<Integer>> filteredAfterGroupingMap = StreamsGroupingCollectionFilter.findEvenNumbersAfterGroupingByQuantityOfDigits(BASE_INTEGER_COLLECTION);
Map<Integer, List<Integer>> filteredBeforeGroupingMap = StreamsGroupingCollectionFilter.findEvenNumbersBeforeGroupingByQuantityOfDigits(BASE_INTEGER_COLLECTION);
assertThat(filteredAfterGroupingMap).containsAllEntriesOf(EXPECTED_EVEN_FILTERED_AFTER_GROUPING_MAP);
assertThat(filteredBeforeGroupingMap).doesNotContainKey(3)
.containsAllEntriesOf(EXPECTED_EVEN_FILTERED_BEFORE_GROUPING_MAP);
}
}

View File

@@ -0,0 +1,61 @@
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

@@ -0,0 +1,111 @@
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

@@ -0,0 +1,152 @@
package com.baeldung.java9.methodhandles;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.WrongMethodTypeException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
/**
* Test case for the {@link MethodHandles} API
*/
public class MethodHandlesTest {
@Test
public void givenConcatMethodHandle_whenInvoked_thenCorrectlyConcatenated() throws Throwable {
MethodHandles.Lookup publicLookup = MethodHandles.publicLookup();
MethodType mt = MethodType.methodType(String.class, String.class);
MethodHandle concatMH = publicLookup.findVirtual(String.class, "concat", mt);
String output = (String) concatMH.invoke("Effective ", "Java");
assertEquals("Effective Java", output);
}
@Test
public void givenAsListMethodHandle_whenInvokingWithArguments_thenCorrectlyInvoked() throws Throwable {
MethodHandles.Lookup publicLookup = MethodHandles.publicLookup();
MethodType mt = MethodType.methodType(List.class, Object[].class);
MethodHandle asListMH = publicLookup.findStatic(Arrays.class, "asList", mt);
List<Integer> list = (List<Integer>) asListMH.invokeWithArguments(1, 2);
assertThat(Arrays.asList(1, 2), is(list));
}
@Test
public void givenConstructorMethodHandle_whenInvoked_thenObjectCreatedCorrectly() throws Throwable {
MethodHandles.Lookup publicLookup = MethodHandles.publicLookup();
MethodType mt = MethodType.methodType(void.class, String.class);
MethodHandle newIntegerMH = publicLookup.findConstructor(Integer.class, mt);
Integer integer = (Integer) newIntegerMH.invoke("1");
assertEquals(1, integer.intValue());
}
@Test
public void givenAFieldWithoutGetter_whenCreatingAGetter_thenCorrectlyInvoked() throws Throwable {
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodHandle getTitleMH = lookup.findGetter(Book.class, "title", String.class);
Book book = new Book("ISBN-1234", "Effective Java");
assertEquals("Effective Java", getTitleMH.invoke(book));
}
@Test
public void givenPrivateMethod_whenCreatingItsMethodHandle_thenCorrectlyInvoked() throws Throwable {
MethodHandles.Lookup lookup = MethodHandles.lookup();
Method formatBookMethod = Book.class.getDeclaredMethod("formatBook");
formatBookMethod.setAccessible(true);
MethodHandle formatBookMH = lookup.unreflect(formatBookMethod);
Book book = new Book("ISBN-123", "Java in Action");
assertEquals("ISBN-123 > Java in Action", formatBookMH.invoke(book));
}
@Test
public void givenReplaceMethod_whenUsingReflectionAndInvoked_thenCorrectlyReplaced() throws Throwable {
Method replaceMethod = String.class.getMethod("replace", char.class, char.class);
String string = (String) replaceMethod.invoke("jovo", 'o', 'a');
assertEquals("java", string);
}
@Test
public void givenReplaceMethodHandle_whenInvoked_thenCorrectlyReplaced() throws Throwable {
MethodHandles.Lookup publicLookup = MethodHandles.publicLookup();
MethodType mt = MethodType.methodType(String.class, char.class, char.class);
MethodHandle replaceMH = publicLookup.findVirtual(String.class, "replace", mt);
String replacedString = (String) replaceMH.invoke("jovo", Character.valueOf('o'), 'a');
assertEquals("java", replacedString);
}
@Test
public void givenReplaceMethodHandle_whenInvokingExact_thenCorrectlyReplaced() throws Throwable {
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodType mt = MethodType.methodType(String.class, char.class, char.class);
MethodHandle replaceMH = lookup.findVirtual(String.class, "replace", mt);
String s = (String) replaceMH.invokeExact("jovo", 'o', 'a');
assertEquals("java", s);
}
@Test
public void givenSumMethodHandle_whenInvokingExact_thenSumIsCorrect() throws Throwable {
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodType mt = MethodType.methodType(int.class, int.class, int.class);
MethodHandle sumMH = lookup.findStatic(Integer.class, "sum", mt);
int sum = (int) sumMH.invokeExact(1, 11);
assertEquals(12, sum);
}
@Test(expected = WrongMethodTypeException.class)
public void givenSumMethodHandleAndIncompatibleArguments_whenInvokingExact_thenException() throws Throwable {
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodType mt = MethodType.methodType(int.class, int.class, int.class);
MethodHandle sumMH = lookup.findStatic(Integer.class, "sum", mt);
sumMH.invokeExact(Integer.valueOf(1), 11);
}
@Test
public void givenSpreadedEqualsMethodHandle_whenInvokedOnArray_thenCorrectlyEvaluated() throws Throwable {
MethodHandles.Lookup publicLookup = MethodHandles.publicLookup();
MethodType mt = MethodType.methodType(boolean.class, Object.class);
MethodHandle equalsMH = publicLookup.findVirtual(String.class, "equals", mt);
MethodHandle methodHandle = equalsMH.asSpreader(Object[].class, 2);
assertTrue((boolean) methodHandle.invoke(new Object[] { "java", "java" }));
assertFalse((boolean) methodHandle.invoke(new Object[] { "java", "jova" }));
}
@Test
public void givenConcatMethodHandle_whenBindToAString_thenCorrectlyConcatenated() throws Throwable {
MethodHandles.Lookup publicLookup = MethodHandles.publicLookup();
MethodType mt = MethodType.methodType(String.class, String.class);
MethodHandle concatMH = publicLookup.findVirtual(String.class, "concat", mt);
MethodHandle bindedConcatMH = concatMH.bindTo("Hello ");
assertEquals("Hello World!", bindedConcatMH.invoke("World!"));
}
}

View File

@@ -0,0 +1,199 @@
package com.baeldung.java9.modules;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.junit.Assert.*;
import java.lang.module.ModuleDescriptor;
import java.lang.module.ModuleDescriptor.*;
import java.sql.Date;
import java.sql.Driver;
import java.util.HashMap;
import java.util.Set;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
public class ModuleAPIUnitTest {
public static final String JAVA_BASE_MODULE_NAME = "java.base";
private Module javaBaseModule;
private Module javaSqlModule;
private Module module;
@Before
public void setUp() {
Class<HashMap> hashMapClass = HashMap.class;
javaBaseModule = hashMapClass.getModule();
Class<Date> dateClass = Date.class;
javaSqlModule = dateClass.getModule();
Class<Person> personClass = Person.class;
module = personClass.getModule();
}
@Test
public void whenCheckingIfNamed_thenModuleIsNamed() {
assertThat(javaBaseModule.isNamed(), is(true));
assertThat(javaBaseModule.getName(), is(JAVA_BASE_MODULE_NAME));
}
@Test
public void whenCheckingIfNamed_thenModuleIsUnnamed() {
assertThat(module.isNamed(), is(false));
assertThat(module.getName(), is(nullValue()));
}
@Test
public void whenExtractingPackagesContainedInAModule_thenModuleContainsOnlyFewOfThem() {
assertTrue(javaBaseModule.getPackages().contains("java.lang.annotation"));
assertFalse(javaBaseModule.getPackages().contains("java.sql"));
}
@Test
public void whenRetrievingClassLoader_thenClassLoaderIsReturned() {
assertThat(
module.getClassLoader().getClass().getName(),
is("jdk.internal.loader.ClassLoaders$AppClassLoader")
);
}
@Test
public void whenGettingAnnotationsPresentOnAModule_thenNoAnnotationsArePresent() {
assertThat(javaBaseModule.getAnnotations().length, is(0));
}
@Test
public void whenGettingLayerOfAModule_thenModuleLayerInformationAreAvailable() {
ModuleLayer javaBaseModuleLayer = javaBaseModule.getLayer();
assertTrue(javaBaseModuleLayer.configuration().findModule(JAVA_BASE_MODULE_NAME).isPresent());
assertThat(javaBaseModuleLayer.configuration().modules().size(), is(78));
assertTrue(javaBaseModuleLayer.parents().get(0).configuration().parents().isEmpty());
}
@Test
public void whenRetrievingModuleDescriptor_thenTypeOfModuleIsInferred() {
ModuleDescriptor javaBaseModuleDescriptor = javaBaseModule.getDescriptor();
ModuleDescriptor javaSqlModuleDescriptor = javaSqlModule.getDescriptor();
assertFalse(javaBaseModuleDescriptor.isAutomatic());
assertFalse(javaBaseModuleDescriptor.isOpen());
assertFalse(javaSqlModuleDescriptor.isAutomatic());
assertFalse(javaSqlModuleDescriptor.isOpen());
}
@Test
public void givenModuleName_whenBuildingModuleDescriptor_thenBuilt() {
Builder moduleBuilder = ModuleDescriptor.newModule("baeldung.base");
ModuleDescriptor moduleDescriptor = moduleBuilder.build();
assertThat(moduleDescriptor.name(), is("baeldung.base"));
}
@Test
public void givenModules_whenAccessingModuleDescriptorRequires_thenRequiresAreReturned() {
Set<Requires> javaBaseRequires = javaBaseModule.getDescriptor().requires();
Set<Requires> javaSqlRequires = javaSqlModule.getDescriptor().requires();
Set<String> javaSqlRequiresNames = javaSqlRequires.stream()
.map(Requires::name)
.collect(Collectors.toSet());
assertThat(javaBaseRequires, empty());
assertThat(javaSqlRequires.size(), is(3));
assertThat(javaSqlRequiresNames, containsInAnyOrder("java.base", "java.xml", "java.logging"));
}
@Test
public void givenModules_whenAccessingModuleDescriptorProvides_thenProvidesAreReturned() {
Set<Provides> javaBaseProvides = javaBaseModule.getDescriptor().provides();
Set<Provides> javaSqlProvides = javaSqlModule.getDescriptor().provides();
Set<String> javaBaseProvidesService = javaBaseProvides.stream()
.map(Provides::service)
.collect(Collectors.toSet());
assertThat(javaBaseProvidesService, contains("java.nio.file.spi.FileSystemProvider"));
assertThat(javaSqlProvides, empty());
}
@Test
public void givenModules_whenAccessingModuleDescriptorExports_thenExportsAreReturned() {
Set<Exports> javaBaseExports = javaBaseModule.getDescriptor().exports();
Set<Exports> javaSqlExports = javaSqlModule.getDescriptor().exports();
Set<String> javaSqlExportsSource = javaSqlExports.stream()
.map(Exports::source)
.collect(Collectors.toSet());
assertThat(javaBaseExports.size(), is(108));
assertThat(javaSqlExports.size(), is(3));
assertThat(javaSqlExportsSource, containsInAnyOrder("java.sql", "javax.transaction.xa", "javax.sql"));
}
@Test
public void givenModules_whenAccessingModuleDescriptorUses_thenUsesAreReturned() {
Set<String> javaBaseUses = javaBaseModule.getDescriptor().uses();
Set<String> javaSqlUses = javaSqlModule.getDescriptor().uses();
assertThat(javaBaseUses.size(), is(34));
assertThat(javaSqlUses, contains("java.sql.Driver"));
}
@Test
public void givenModules_whenAccessingModuleDescriptorOpen_thenOpenAreReturned() {
Set<Opens> javaBaseUses = javaBaseModule.getDescriptor().opens();
Set<Opens> javaSqlUses = javaSqlModule.getDescriptor().opens();
assertThat(javaBaseUses, empty());
assertThat(javaSqlUses, empty());
}
@Test
public void whenAddingReadsToAModule_thenModuleCanReadNewModule() {
Module updatedModule = module.addReads(javaSqlModule);
assertTrue(updatedModule.canRead(javaSqlModule));
}
@Test
public void whenExportingPackage_thenPackageIsExported() {
Module updatedModule = module.addExports("com.baeldung.java9.modules", javaSqlModule);
assertTrue(updatedModule.isExported("com.baeldung.java9.modules"));
}
@Test
public void whenOpeningAModulePackage_thenPackagedIsOpened() {
Module updatedModule = module.addOpens("com.baeldung.java9.modules", javaSqlModule);
assertTrue(updatedModule.isOpen("com.baeldung.java9.modules", javaSqlModule));
}
@Test
public void whenAddingUsesToModule_thenUsesIsAdded() {
Module updatedModule = module.addUses(Driver.class);
assertTrue(updatedModule.canUse(Driver.class));
}
private class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}

View File

@@ -0,0 +1,61 @@
package com.baeldung.java9.rangedates;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Test;
public class DatesCollectionIterationUnitTest {
private Collection<LocalDate> localDates = LocalDate.now()
.datesUntil(LocalDate.now()
.plus(10L, ChronoUnit.DAYS))
.collect(Collectors.toList());
private Collection<Date> dates = localDates.stream()
.map(localDate -> Date.from(localDate.atStartOfDay(ZoneId.systemDefault())
.toInstant()))
.collect(Collectors.toList());
@Test
public void givenIteratingListOfDatesJava7_WhenStartTodayAndEnding10DaysAhead() {
DatesCollectionIteration iterateInColleciton = new DatesCollectionIteration();
Calendar today = Calendar.getInstance();
Calendar next10Ahead = (Calendar) today.clone();
next10Ahead.add(Calendar.DATE, 10);
iterateInColleciton.iteratingRangeOfDatesJava7(createRangeDates(today.getTime(), next10Ahead.getTime()));
}
@Test
public void givenIteratingListOfDatesJava8_WhenStartTodayAndEnd10DaysAhead() {
DatesCollectionIteration iterateInColleciton = new DatesCollectionIteration();
iterateInColleciton.iteratingRangeOfDatesJava8(dates);
}
private List<Date> createRangeDates(Date start, Date end) {
List<Date> dates = new ArrayList<>();
Date current = start;
while (current.before(end)) {
dates.add(current);
Calendar calendar = Calendar.getInstance();
calendar.setTime(current);
calendar.add(Calendar.DATE, 1);
current = calendar.getTime();
}
return dates;
}
}

View File

@@ -0,0 +1,48 @@
package com.baeldung.java9.rangedates;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
import org.junit.Test;
public class RangeDatesIterationUnitTest {
@Test
public void givenIterateBetweenDatesJava9_WhenStartDateAsTodayAndEndDateAs10DaysAhead() {
LocalDate start = LocalDate.now();
LocalDate end = start.plus(10L, ChronoUnit.DAYS);
RangeDatesIteration iteration = new RangeDatesIteration();
iteration.iterateBetweenDatesJava9(start, end);
}
@Test
public void givenIterateBetweenDatesJava8_WhenStartDateAsTodayAndEndDateAs10DaysAhead() {
LocalDate start = LocalDate.now();
LocalDate end = start.plus(10L, ChronoUnit.DAYS);
RangeDatesIteration iteration = new RangeDatesIteration();
iteration.iterateBetweenDatesJava8(start, end);
}
@Test
public void givenIterateBetweenDatesJava7_WhenStartDateAsTodayAndEndDateAs10DaysAhead() {
Calendar today = Calendar.getInstance();
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE));
Date start = calendar.getTime();
calendar.add(Calendar.DATE, 10);
Date end = calendar.getTime();
RangeDatesIteration iteration = new RangeDatesIteration();
iteration.iterateBetweenDatesJava7(start, end);
}
}

View File

@@ -0,0 +1,75 @@
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

@@ -0,0 +1,100 @@
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

@@ -0,0 +1,16 @@
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

@@ -0,0 +1,73 @@
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)
);
}
}

View File

@@ -0,0 +1,106 @@
package com.baeldung.java9.varhandles;
import org.junit.Test;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import static org.assertj.core.api.Assertions.assertThat;
public class VariableHandlesTest {
public int publicTestVariable = 1;
private int privateTestVariable = 1;
public int variableToSet = 1;
public int variableToCompareAndSet = 1;
public int variableToGetAndAdd = 0;
public byte variableToBitwiseOr = 0;
@Test
public void whenVariableHandleForPublicVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
VarHandle publicIntHandle = MethodHandles
.lookup()
.in(VariableHandlesTest.class)
.findVarHandle(VariableHandlesTest.class, "publicTestVariable", int.class);
assertThat(publicIntHandle.coordinateTypes().size() == 1);
assertThat(publicIntHandle.coordinateTypes().get(0) == VariableHandles.class);
}
@Test
public void whenVariableHandleForPrivateVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
VarHandle privateIntHandle = MethodHandles
.privateLookupIn(VariableHandlesTest.class, MethodHandles.lookup())
.findVarHandle(VariableHandlesTest.class, "privateTestVariable", int.class);
assertThat(privateIntHandle.coordinateTypes().size() == 1);
assertThat(privateIntHandle.coordinateTypes().get(0) == VariableHandlesTest.class);
}
@Test
public void whenVariableHandleForArrayVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
VarHandle arrayVarHandle = MethodHandles
.arrayElementVarHandle(int[].class);
assertThat(arrayVarHandle.coordinateTypes().size() == 2);
assertThat(arrayVarHandle.coordinateTypes().get(0) == int[].class);
}
@Test
public void givenVarHandle_whenGetIsInvoked_ThenValueOfVariableIsReturned() throws NoSuchFieldException, IllegalAccessException {
VarHandle publicIntHandle = MethodHandles
.lookup()
.in(VariableHandlesTest.class)
.findVarHandle(VariableHandlesTest.class, "publicTestVariable", int.class);
assertThat((int) publicIntHandle.get(this) == 1);
}
@Test
public void givenVarHandle_whenSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
VarHandle publicIntHandle = MethodHandles
.lookup()
.in(VariableHandlesTest.class)
.findVarHandle(VariableHandlesTest.class, "variableToSet", int.class);
publicIntHandle.set(this, 15);
assertThat((int) publicIntHandle.get(this) == 15);
}
@Test
public void givenVarHandle_whenCompareAndSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
VarHandle publicIntHandle = MethodHandles
.lookup()
.in(VariableHandlesTest.class)
.findVarHandle(VariableHandlesTest.class, "variableToCompareAndSet", int.class);
publicIntHandle.compareAndSet(this, 1, 100);
assertThat((int) publicIntHandle.get(this) == 100);
}
@Test
public void givenVarHandle_whenGetAndAddIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
VarHandle publicIntHandle = MethodHandles
.lookup()
.in(VariableHandlesTest.class)
.findVarHandle(VariableHandlesTest.class, "variableToGetAndAdd", int.class);
int before = (int) publicIntHandle.getAndAdd(this, 200);
assertThat(before == 0);
assertThat((int) publicIntHandle.get(this) == 200);
}
@Test
public void givenVarHandle_whenGetAndBitwiseOrIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
VarHandle publicIntHandle = MethodHandles
.lookup()
.in(VariableHandlesTest.class)
.findVarHandle(VariableHandlesTest.class, "variableToBitwiseOr", byte.class);
byte before = (byte) publicIntHandle.getAndBitwiseOr(this, (byte) 127);
assertThat(before == 0);
assertThat(variableToBitwiseOr == 127);
}
}

View File

@@ -0,0 +1,51 @@
package com.baeldung.optionals;
import static org.junit.Assert.assertEquals;
import java.util.Optional;
import org.junit.Test;
public class OptionalsTest {
@Test
public void givenOptional_whenEmptyValue_thenCustomMessage() {
assertEquals(Optional.of("Name not provided"), Optionals.getName(Optional.ofNullable(null)));
}
@Test
public void givenOptional_whenValue_thenOptional() {
String name = "Filan Fisteku";
Optional<String> optionalString = Optional.ofNullable(name);
assertEquals(optionalString, Optionals.getName(optionalString));
}
@Test
public void givenOptional_whenValue_thenOptionalGeneralMethod() {
String name = "Filan Fisteku";
String missingOptional = "Name not provided";
Optional<String> optionalString = Optional.ofNullable(name);
Optional<String> fallbackOptionalString = Optional.ofNullable(missingOptional);
assertEquals(optionalString, Optionals.or(optionalString, fallbackOptionalString));
}
@Test
public void givenEmptyOptional_whenValue_thenOptionalGeneralMethod() {
String missingOptional = "Name not provided";
Optional<String> optionalString = Optional.empty();
Optional<String> fallbackOptionalString = Optional.ofNullable(missingOptional);
assertEquals(fallbackOptionalString, Optionals.or(optionalString, fallbackOptionalString));
}
@Test
public void givenGuavaOptional_whenInvoke_thenOptional() {
String name = "Filan Fisteku";
com.google.common.base.Optional<String> stringOptional = com.google.common.base.Optional.of(name);
assertEquals(stringOptional, Optionals.getOptionalGuavaName(stringOptional));
}
@Test
public void givenGuavaOptional_whenNull_thenDefaultText() {
assertEquals(com.google.common.base.Optional.of("Name not provided"), Optionals.getOptionalGuavaName(com.google.common.base.Optional.fromNullable(null)));
}
}

View File

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