From 1bcd3a1b36f8d566318287ed0c0757b4a749c2b0 Mon Sep 17 00:00:00 2001 From: YuCheng Hu Date: Fri, 13 May 2022 14:41:19 -0400 Subject: [PATCH] Add two new modules: core-java-11 to project --- core-java-modules/core-java-11/README.md | 16 ++ core-java-modules/core-java-11/pom.xml | 105 ++++++++ .../src/main/java/com/baeldung/App.java | 13 + .../src/main/java/com/baeldung/Outer.java | 24 ++ .../src/main/java/com/baeldung/add | 12 + .../baeldung/benchmark/IntegerListFilter.java | 70 +++++ .../baeldung/benchmark/IntegerListSum.java | 67 +++++ .../baeldung/epsilongc/MemoryPolluter.java | 18 ++ .../java11/httpclient/HttpClientExample.java | 132 ++++++++++ .../com/baeldung/predicate/not/Person.java | 19 ++ .../java/com/baeldung/predicate/not/README.md | 3 + .../src/main/resources/logback.xml | 13 + .../com/baeldung/jlink/HelloWorld.java | 12 + .../src/modules/jlinkModule/module-info.java | 3 + .../test/java/com/baeldung/AppUnitTest.java | 38 +++ .../com/baeldung/NewStringAPIUnitTest.java | 43 ++++ .../test/java/com/baeldung/OuterUnitTest.java | 46 ++++ .../benchmark/IntegerListFilterUnitTest.java | 33 +++ .../benchmark/IntegerListSumUnitTest.java | 33 +++ .../httpclient/test/HttpClientUnitTest.java | 240 ++++++++++++++++++ .../httpclient/test/HttpRequestUnitTest.java | 174 +++++++++++++ .../httpclient/test/HttpResponseUnitTest.java | 54 ++++ .../baeldung/optional/OptionalUnitTest.java | 23 ++ .../patternreuse/PatternJava11UnitTest.java | 29 +++ .../predicate/not/PersonUnitTest.java | 61 +++++ .../src/test/resources/sample.txt | 1 + 26 files changed, 1282 insertions(+) create mode 100644 core-java-modules/core-java-11/README.md create mode 100644 core-java-modules/core-java-11/pom.xml create mode 100644 core-java-modules/core-java-11/src/main/java/com/baeldung/App.java create mode 100644 core-java-modules/core-java-11/src/main/java/com/baeldung/Outer.java create mode 100644 core-java-modules/core-java-11/src/main/java/com/baeldung/add create mode 100644 core-java-modules/core-java-11/src/main/java/com/baeldung/benchmark/IntegerListFilter.java create mode 100644 core-java-modules/core-java-11/src/main/java/com/baeldung/benchmark/IntegerListSum.java create mode 100644 core-java-modules/core-java-11/src/main/java/com/baeldung/epsilongc/MemoryPolluter.java create mode 100644 core-java-modules/core-java-11/src/main/java/com/baeldung/java11/httpclient/HttpClientExample.java create mode 100644 core-java-modules/core-java-11/src/main/java/com/baeldung/predicate/not/Person.java create mode 100644 core-java-modules/core-java-11/src/main/java/com/baeldung/predicate/not/README.md create mode 100644 core-java-modules/core-java-11/src/main/resources/logback.xml create mode 100644 core-java-modules/core-java-11/src/modules/jlinkModule/com/baeldung/jlink/HelloWorld.java create mode 100644 core-java-modules/core-java-11/src/modules/jlinkModule/module-info.java create mode 100644 core-java-modules/core-java-11/src/test/java/com/baeldung/AppUnitTest.java create mode 100644 core-java-modules/core-java-11/src/test/java/com/baeldung/NewStringAPIUnitTest.java create mode 100644 core-java-modules/core-java-11/src/test/java/com/baeldung/OuterUnitTest.java create mode 100644 core-java-modules/core-java-11/src/test/java/com/baeldung/benchmark/IntegerListFilterUnitTest.java create mode 100644 core-java-modules/core-java-11/src/test/java/com/baeldung/benchmark/IntegerListSumUnitTest.java create mode 100644 core-java-modules/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpClientUnitTest.java create mode 100644 core-java-modules/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpRequestUnitTest.java create mode 100644 core-java-modules/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpResponseUnitTest.java create mode 100644 core-java-modules/core-java-11/src/test/java/com/baeldung/optional/OptionalUnitTest.java create mode 100644 core-java-modules/core-java-11/src/test/java/com/baeldung/patternreuse/PatternJava11UnitTest.java create mode 100644 core-java-modules/core-java-11/src/test/java/com/baeldung/predicate/not/PersonUnitTest.java create mode 100644 core-java-modules/core-java-11/src/test/resources/sample.txt diff --git a/core-java-modules/core-java-11/README.md b/core-java-modules/core-java-11/README.md new file mode 100644 index 0000000000..a3601c8339 --- /dev/null +++ b/core-java-modules/core-java-11/README.md @@ -0,0 +1,16 @@ +## Core Java 11 + +This module contains articles about Java 11 core features + +### Relevant articles + +- [Java 11 Single File Source Code](https://www.baeldung.com/java-single-file-source-code) +- [Java 11 Local Variable Syntax for Lambda Parameters](https://www.baeldung.com/java-var-lambda-params) +- [Java 11 String API Additions](https://www.baeldung.com/java-11-string-api) +- [Java 11 Nest Based Access Control](https://www.baeldung.com/java-nest-based-access-control) +- [Exploring the New HTTP Client in Java](https://www.baeldung.com/java-9-http-client) +- [An Introduction to Epsilon GC: A No-Op Experimental Garbage Collector](https://www.baeldung.com/jvm-epsilon-gc-garbage-collector) +- [Guide to jlink](https://www.baeldung.com/jlink) +- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference) +- [Benchmark JDK Collections vs Eclipse Collections](https://www.baeldung.com/jdk-collections-vs-eclipse-collections) +- [Pre-compile Regex Patterns Into Pattern Objects](https://www.baeldung.com/java-regex-pre-compile) diff --git a/core-java-modules/core-java-11/pom.xml b/core-java-modules/core-java-11/pom.xml new file mode 100644 index 0000000000..c7a9259c36 --- /dev/null +++ b/core-java-modules/core-java-11/pom.xml @@ -0,0 +1,105 @@ + + + 4.0.0 + core-java-11 + 0.1.0-SNAPSHOT + core-java-11 + jar + http://maven.apache.org + + + com.ossez.core-java-modules + core-java-modules + 0.0.2-SNAPSHOT + + + + + + com.google.guava + guava + ${guava.version} + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-generator.version} + provided + + + org.eclipse.collections + eclipse-collections + ${eclipse.collections.version} + + + org.eclipse.collections + eclipse-collections-api + ${eclipse.collections.version} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source.version} + ${maven.compiler.target.version} + + + + org.apache.maven.plugins + maven-shade-plugin + ${shade.plugin.version} + + + package + + shade + + + ${uberjar.name} + + + org.openjdk.jmh.Main + + + + + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + + + + + + + + + 11 + 11 + benchmarks + 10.0.0 + 3.2.4 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-11/src/main/java/com/baeldung/App.java b/core-java-modules/core-java-11/src/main/java/com/baeldung/App.java new file mode 100644 index 0000000000..c56197d7fc --- /dev/null +++ b/core-java-modules/core-java-11/src/main/java/com/baeldung/App.java @@ -0,0 +1,13 @@ +package com.baeldung; + +/** + * Hello world! + * + */ +public class App +{ + public static void main( String[] args ) + { + System.out.println( "Hello World!" ); + } +} diff --git a/core-java-modules/core-java-11/src/main/java/com/baeldung/Outer.java b/core-java-modules/core-java-11/src/main/java/com/baeldung/Outer.java new file mode 100644 index 0000000000..1d3cd72b44 --- /dev/null +++ b/core-java-modules/core-java-11/src/main/java/com/baeldung/Outer.java @@ -0,0 +1,24 @@ +package com.baeldung; + +import java.lang.reflect.Method; + +public class Outer { + + public void outerPublic() { + } + + private void outerPrivate() { + } + + class Inner { + + public void innerPublic() { + outerPrivate(); + } + + public void innerPublicReflection(Outer ob) throws Exception { + Method method = ob.getClass().getDeclaredMethod("outerPrivate"); + method.invoke(ob); + } + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-11/src/main/java/com/baeldung/add b/core-java-modules/core-java-11/src/main/java/com/baeldung/add new file mode 100644 index 0000000000..539c1a43d4 --- /dev/null +++ b/core-java-modules/core-java-11/src/main/java/com/baeldung/add @@ -0,0 +1,12 @@ +#!/usr/local/bin/java --source 11 + +import java.util.Arrays; + +public class Addition +{ + public static void main(String[] args) { + System.out.println(Arrays.stream(args) + .mapToInt(Integer::parseInt) + .sum()); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-11/src/main/java/com/baeldung/benchmark/IntegerListFilter.java b/core-java-modules/core-java-11/src/main/java/com/baeldung/benchmark/IntegerListFilter.java new file mode 100644 index 0000000000..5961d2d297 --- /dev/null +++ b/core-java-modules/core-java-11/src/main/java/com/baeldung/benchmark/IntegerListFilter.java @@ -0,0 +1,70 @@ +package com.baeldung.benchmark; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.api.list.primitive.IntList; +import org.eclipse.collections.api.list.primitive.MutableIntList; +import org.eclipse.collections.impl.factory.primitive.IntLists; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.eclipse.collections.impl.list.mutable.primitive.IntArrayList; +import org.openjdk.jmh.annotations.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.PrimitiveIterator; +import java.util.Random; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +@State(Scope.Benchmark) +@BenchmarkMode(Mode.Throughput) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(2) +public class IntegerListFilter { + + private List jdkIntList; + private MutableList ecMutableList; + private IntList ecIntList; + private ExecutorService executor; + + @Setup + public void setup() { + PrimitiveIterator.OfInt iterator = new Random(1L).ints(-10000, 10000).iterator(); + ecMutableList = FastList.newWithNValues(1_000_000, iterator::nextInt); + jdkIntList = new ArrayList<>(1_000_000); + jdkIntList.addAll(ecMutableList); + ecIntList = ecMutableList.collectInt(i -> i, new IntArrayList(1_000_000)); + executor = Executors.newWorkStealingPool(); + } + + @Benchmark + public List jdkList() { + return jdkIntList.stream().filter(i -> i % 5 == 0).collect(Collectors.toList()); + } + + @Benchmark + public MutableList ecMutableList() { + return ecMutableList.select(i -> i % 5 == 0); + } + + @Benchmark + public List jdkListParallel() { + return jdkIntList.parallelStream().filter(i -> i % 5 == 0).collect(Collectors.toList()); + } + + @Benchmark + public MutableList ecMutableListParallel() { + return ecMutableList.asParallel(executor, 100_000).select(i -> i % 5 == 0).toList(); + } + + @Benchmark + public IntList ecPrimitive() { + return this.ecIntList.select(i -> i % 5 == 0); + } + + @Benchmark + public IntList ecPrimitiveParallel() { + return this.ecIntList.primitiveParallelStream().filter(i -> i % 5 == 0).collect(IntLists.mutable::empty, MutableIntList::add, MutableIntList::addAll); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-11/src/main/java/com/baeldung/benchmark/IntegerListSum.java b/core-java-modules/core-java-11/src/main/java/com/baeldung/benchmark/IntegerListSum.java new file mode 100644 index 0000000000..cdb2accc0b --- /dev/null +++ b/core-java-modules/core-java-11/src/main/java/com/baeldung/benchmark/IntegerListSum.java @@ -0,0 +1,67 @@ +package com.baeldung.benchmark; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.api.list.primitive.IntList; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.eclipse.collections.impl.list.mutable.primitive.IntArrayList; +import org.openjdk.jmh.annotations.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.PrimitiveIterator; +import java.util.Random; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +@State(Scope.Benchmark) +@BenchmarkMode(Mode.Throughput) +@OutputTimeUnit(TimeUnit.SECONDS) +@Fork(2) +public class IntegerListSum { + + private List jdkIntList; + private MutableList ecMutableList; + private ExecutorService executor; + private IntList ecIntList; + + @Setup + public void setup() { + PrimitiveIterator.OfInt iterator = new Random(1L).ints(-10000, 10000).iterator(); + ecMutableList = FastList.newWithNValues(1_000_000, iterator::nextInt); + jdkIntList = new ArrayList<>(1_000_000); + jdkIntList.addAll(ecMutableList); + ecIntList = ecMutableList.collectInt(i -> i, new IntArrayList(1_000_000)); + executor = Executors.newWorkStealingPool(); + } + + @Benchmark + public long jdkList() { + return jdkIntList.stream().mapToLong(i -> i).sum(); + } + + @Benchmark + public long ecMutableList() { + return ecMutableList.sumOfInt(i -> i); + } + + @Benchmark + public long jdkListParallel() { + return jdkIntList.parallelStream().mapToLong(i -> i).sum(); + } + + @Benchmark + public long ecMutableListParallel() { + return ecMutableList.asParallel(executor, 100_000).sumOfInt(i -> i); + } + + @Benchmark + public long ecPrimitive() { + return this.ecIntList.sum(); + } + + @Benchmark + public long ecPrimitiveParallel() { + return this.ecIntList.primitiveParallelStream().sum(); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-11/src/main/java/com/baeldung/epsilongc/MemoryPolluter.java b/core-java-modules/core-java-11/src/main/java/com/baeldung/epsilongc/MemoryPolluter.java new file mode 100644 index 0000000000..97e216513b --- /dev/null +++ b/core-java-modules/core-java-11/src/main/java/com/baeldung/epsilongc/MemoryPolluter.java @@ -0,0 +1,18 @@ +package com.baeldung.epsilongc; + +public class MemoryPolluter { + + private static final int MEGABYTE_IN_BYTES = 1024 * 1024; + private static final int ITERATION_COUNT = 1024 * 10; + + public static void main(String[] args) { + System.out.println("Starting pollution"); + + for (int i = 0; i < ITERATION_COUNT; i++) { + byte[] array = new byte[MEGABYTE_IN_BYTES]; + } + + System.out.println("Terminating"); + } + +} diff --git a/core-java-modules/core-java-11/src/main/java/com/baeldung/java11/httpclient/HttpClientExample.java b/core-java-modules/core-java-11/src/main/java/com/baeldung/java11/httpclient/HttpClientExample.java new file mode 100644 index 0000000000..725f969596 --- /dev/null +++ b/core-java-modules/core-java-11/src/main/java/com/baeldung/java11/httpclient/HttpClientExample.java @@ -0,0 +1,132 @@ +/* + * 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.java11.httpclient; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.http.HttpClient; +import java.net.http.HttpClient.Version; +import java.net.http.HttpRequest; +import java.net.http.HttpRequest.BodyPublishers; +import java.net.http.HttpResponse; +import java.net.http.HttpResponse.BodyHandlers; +import java.net.http.HttpResponse.PushPromiseHandler; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.function.Function; +import java.util.stream.Collectors; + +public class HttpClientExample { + + public static void main(String[] args) throws Exception { + httpGetRequest(); + httpPostRequest(); + asynchronousGetRequest(); + asynchronousMultipleRequests(); + pushRequest(); + } + + public static void httpGetRequest() throws URISyntaxException, IOException, InterruptedException { + HttpClient client = HttpClient.newHttpClient(); + HttpRequest request = HttpRequest.newBuilder() + .version(HttpClient.Version.HTTP_2) + .uri(URI.create("http://jsonplaceholder.typicode.com/posts/1")) + .headers("Accept-Enconding", "gzip, deflate") + .build(); + HttpResponse response = client.send(request, BodyHandlers.ofString()); + + String responseBody = response.body(); + int responseStatusCode = response.statusCode(); + + System.out.println("httpGetRequest: " + responseBody); + System.out.println("httpGetRequest status code: " + responseStatusCode); + } + + public static void httpPostRequest() throws URISyntaxException, IOException, InterruptedException { + HttpClient client = HttpClient.newBuilder() + .version(HttpClient.Version.HTTP_2) + .build(); + HttpRequest request = HttpRequest.newBuilder(new URI("http://jsonplaceholder.typicode.com/posts")) + .version(HttpClient.Version.HTTP_2) + .POST(BodyPublishers.ofString("Sample Post Request")) + .build(); + HttpResponse response = client.send(request, BodyHandlers.ofString()); + String responseBody = response.body(); + System.out.println("httpPostRequest : " + responseBody); + } + + public static void asynchronousGetRequest() throws URISyntaxException { + HttpClient client = HttpClient.newHttpClient(); + URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1"); + HttpRequest request = HttpRequest.newBuilder(httpURI) + .version(HttpClient.Version.HTTP_2) + .build(); + CompletableFuture futureResponse = client.sendAsync(request, HttpResponse.BodyHandlers.ofString()) + .thenAccept(resp -> { + System.out.println("Got pushed response " + resp.uri()); + System.out.println("Response statuscode: " + resp.statusCode()); + System.out.println("Response body: " + resp.body()); + }); + System.out.println("futureResponse" + futureResponse); + + } + + public static void asynchronousMultipleRequests() throws URISyntaxException { + HttpClient client = HttpClient.newHttpClient(); + List uris = Arrays.asList(new URI("http://jsonplaceholder.typicode.com/posts/1"), new URI("http://jsonplaceholder.typicode.com/posts/2")); + List requests = uris.stream() + .map(HttpRequest::newBuilder) + .map(reqBuilder -> reqBuilder.build()) + .collect(Collectors.toList()); + System.out.println("Got pushed response1 " + requests); + CompletableFuture.allOf(requests.stream() + .map(request -> client.sendAsync(request, BodyHandlers.ofString())) + .toArray(CompletableFuture[]::new)) + .thenAccept(System.out::println) + .join(); + } + + public static void pushRequest() throws URISyntaxException, InterruptedException { + System.out.println("Running HTTP/2 Server Push example..."); + + HttpClient httpClient = HttpClient.newBuilder() + .version(Version.HTTP_2) + .build(); + + HttpRequest pageRequest = HttpRequest.newBuilder() + .uri(URI.create("https://http2.golang.org/serverpush")) + .build(); + + // Interface HttpResponse.PushPromiseHandler + // void applyPushPromise​(HttpRequest initiatingRequest, HttpRequest pushPromiseRequest, Function,​CompletableFuture>> acceptor) + httpClient.sendAsync(pageRequest, BodyHandlers.ofString(), pushPromiseHandler()) + .thenAccept(pageResponse -> { + System.out.println("Page response status code: " + pageResponse.statusCode()); + System.out.println("Page response headers: " + pageResponse.headers()); + String responseBody = pageResponse.body(); + System.out.println(responseBody); + }).join(); + + Thread.sleep(1000); // waiting for full response + } + + private static PushPromiseHandler pushPromiseHandler() { + return (HttpRequest initiatingRequest, + HttpRequest pushPromiseRequest, + Function, + CompletableFuture>> acceptor) -> { + acceptor.apply(BodyHandlers.ofString()) + .thenAccept(resp -> { + System.out.println(" Pushed response: " + resp.uri() + ", headers: " + resp.headers()); + }); + System.out.println("Promise request: " + pushPromiseRequest.uri()); + System.out.println("Promise request: " + pushPromiseRequest.headers()); + }; + } + +} diff --git a/core-java-modules/core-java-11/src/main/java/com/baeldung/predicate/not/Person.java b/core-java-modules/core-java-11/src/main/java/com/baeldung/predicate/not/Person.java new file mode 100644 index 0000000000..3c93e08194 --- /dev/null +++ b/core-java-modules/core-java-11/src/main/java/com/baeldung/predicate/not/Person.java @@ -0,0 +1,19 @@ +package com.baeldung.predicate.not; + +public class Person { + private static final int ADULT_AGE = 18; + + private int age; + + public Person(int age) { + this.age = age; + } + + public boolean isAdult() { + return age >= ADULT_AGE; + } + + public boolean isNotAdult() { + return !isAdult(); + } +} diff --git a/core-java-modules/core-java-11/src/main/java/com/baeldung/predicate/not/README.md b/core-java-modules/core-java-11/src/main/java/com/baeldung/predicate/not/README.md new file mode 100644 index 0000000000..6f8f95970e --- /dev/null +++ b/core-java-modules/core-java-11/src/main/java/com/baeldung/predicate/not/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference) diff --git a/core-java-modules/core-java-11/src/main/resources/logback.xml b/core-java-modules/core-java-11/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/core-java-modules/core-java-11/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/core-java-modules/core-java-11/src/modules/jlinkModule/com/baeldung/jlink/HelloWorld.java b/core-java-modules/core-java-11/src/modules/jlinkModule/com/baeldung/jlink/HelloWorld.java new file mode 100644 index 0000000000..47fe62ba40 --- /dev/null +++ b/core-java-modules/core-java-11/src/modules/jlinkModule/com/baeldung/jlink/HelloWorld.java @@ -0,0 +1,12 @@ +package com.baeldung.jlink; + +import java.util.logging.Logger; + +public class HelloWorld { + + private static final Logger LOG = Logger.getLogger(HelloWorld.class.getName()); + + public static void main(String[] args) { + LOG.info("Hello World!"); + } +} diff --git a/core-java-modules/core-java-11/src/modules/jlinkModule/module-info.java b/core-java-modules/core-java-11/src/modules/jlinkModule/module-info.java new file mode 100644 index 0000000000..0587c65b53 --- /dev/null +++ b/core-java-modules/core-java-11/src/modules/jlinkModule/module-info.java @@ -0,0 +1,3 @@ +module jlinkModule { + requires java.logging; +} \ No newline at end of file diff --git a/core-java-modules/core-java-11/src/test/java/com/baeldung/AppUnitTest.java b/core-java-modules/core-java-11/src/test/java/com/baeldung/AppUnitTest.java new file mode 100644 index 0000000000..73eb8e661a --- /dev/null +++ b/core-java-modules/core-java-11/src/test/java/com/baeldung/AppUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * Unit test for simple App. + */ +public class AppUnitTest + extends TestCase +{ + /** + * Create the test case + * + * @param testName name of the test case + */ + public AppUnitTest(String testName ) + { + super( testName ); + } + + /** + * @return the suite of tests being tested + */ + public static Test suite() + { + return new TestSuite( AppUnitTest.class ); + } + + /** + * Rigourous Test :-) + */ + public void testApp() + { + assertTrue( true ); + } +} diff --git a/core-java-modules/core-java-11/src/test/java/com/baeldung/NewStringAPIUnitTest.java b/core-java-modules/core-java-11/src/test/java/com/baeldung/NewStringAPIUnitTest.java new file mode 100644 index 0000000000..43e9022a64 --- /dev/null +++ b/core-java-modules/core-java-11/src/test/java/com/baeldung/NewStringAPIUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung; + +import static org.hamcrest.CoreMatchers.is; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class NewStringAPIUnitTest { + + @Test + public void whenRepeatStringTwice_thenGetStringTwice() { + String output = "La ".repeat(2) + "Land"; + + is(output).equals("La La Land"); + } + + @Test + public void whenStripString_thenReturnStringWithoutWhitespaces() { + is("\n\t hello \u2005".strip()).equals("hello"); + } + + @Test + public void whenTrimAdvanceString_thenReturnStringWithWhitespaces() { + is("\n\t hello \u2005".trim()).equals("hello \u2005"); + } + + @Test + public void whenBlankString_thenReturnTrue() { + assertTrue("\n\t\u2005 ".isBlank()); + } + + @Test + public void whenMultilineString_thenReturnNonEmptyLineCount() { + String multilineStr = "This is\n \n a multiline\n string."; + + long lineCount = multilineStr.lines() + .filter(String::isBlank) + .count(); + + is(lineCount).equals(3L); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-11/src/test/java/com/baeldung/OuterUnitTest.java b/core-java-modules/core-java-11/src/test/java/com/baeldung/OuterUnitTest.java new file mode 100644 index 0000000000..9e6bd72680 --- /dev/null +++ b/core-java-modules/core-java-11/src/test/java/com/baeldung/OuterUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung; + +import static org.junit.Assert.assertTrue; +import static org.hamcrest.CoreMatchers.is; + +import java.util.Arrays; +import java.util.Set; +import java.util.stream.Collectors; +import org.junit.Test; + +public class OuterUnitTest { + + private static final String NEST_HOST_NAME = "com.baeldung.Outer"; + + @Test + public void whenGetNestHostFromOuter_thenGetNestHost() { + is(Outer.class.getNestHost().getName()).equals(NEST_HOST_NAME); + } + + @Test + public void whenGetNestHostFromInner_thenGetNestHost() { + is(Outer.Inner.class.getNestHost().getName()).equals(NEST_HOST_NAME); + } + + @Test + public void whenCheckNestmatesForNestedClasses_thenGetTrue() { + is(Outer.Inner.class.isNestmateOf(Outer.class)).equals(true); + } + + @Test + public void whenCheckNestmatesForUnrelatedClasses_thenGetFalse() { + is(Outer.Inner.class.isNestmateOf(Outer.class)).equals(false); + } + + @Test + public void whenGetNestMembersForNestedClasses_thenGetAllNestedClasses() { + Set nestMembers = Arrays.stream(Outer.Inner.class.getNestMembers()) + .map(Class::getName) + .collect(Collectors.toSet()); + + is(nestMembers.size()).equals(2); + + assertTrue(nestMembers.contains("com.baeldung.Outer")); + assertTrue(nestMembers.contains("com.baeldung.Outer$Inner")); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-11/src/test/java/com/baeldung/benchmark/IntegerListFilterUnitTest.java b/core-java-modules/core-java-11/src/test/java/com/baeldung/benchmark/IntegerListFilterUnitTest.java new file mode 100644 index 0000000000..bf68ef70e9 --- /dev/null +++ b/core-java-modules/core-java-11/src/test/java/com/baeldung/benchmark/IntegerListFilterUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.benchmark; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + + +public class IntegerListFilterUnitTest { + + private IntegerListFilter integerListFilter; + + @Before + public void init() { + integerListFilter = new IntegerListFilter(); + integerListFilter.setup(); + } + + @Test + public void whenBenchmarkIsExecute_thenJDKListsMustBeOfSameSize() { + assertEquals(integerListFilter.jdkList().size(), integerListFilter.jdkListParallel().size()); + } + + @Test + public void whenBenchmarkIsExecute_thenMutableListsMustBeOfSameSize() { + assertEquals(integerListFilter.ecMutableList().size(), integerListFilter.ecMutableListParallel().size()); + } + + @Test + public void whenBenchmarkIsExecute_thenPrimitiveListsMustBeOfSameSize() { + assertEquals(integerListFilter.ecPrimitive().size(), integerListFilter.ecPrimitiveParallel().size()); + } +} diff --git a/core-java-modules/core-java-11/src/test/java/com/baeldung/benchmark/IntegerListSumUnitTest.java b/core-java-modules/core-java-11/src/test/java/com/baeldung/benchmark/IntegerListSumUnitTest.java new file mode 100644 index 0000000000..b375993ffa --- /dev/null +++ b/core-java-modules/core-java-11/src/test/java/com/baeldung/benchmark/IntegerListSumUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.benchmark; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + + +public class IntegerListSumUnitTest { + + private IntegerListSum integerListSum; + + @Before + public void init() { + integerListSum = new IntegerListSum(); + integerListSum.setup(); + } + + @Test + public void whenBenchmarkIsExecute_thenJDKListsMustHaveSameValue() { + assertEquals(integerListSum.jdkList(), integerListSum.jdkListParallel()); + } + + @Test + public void whenBenchmarkIsExecute_thenMutableListsMustHaveSameValue() { + assertEquals(integerListSum.ecMutableList(), integerListSum.ecMutableListParallel()); + } + + @Test + public void whenBenchmarkIsExecute_thenPrimitiveListsMustHaveSameValue() { + assertEquals(integerListSum.ecPrimitive(), integerListSum.ecPrimitiveParallel()); + } +} diff --git a/core-java-modules/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpClientUnitTest.java b/core-java-modules/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpClientUnitTest.java new file mode 100644 index 0000000000..2a2540a517 --- /dev/null +++ b/core-java-modules/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpClientUnitTest.java @@ -0,0 +1,240 @@ +package com.baeldung.java11.httpclient.test; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.net.Authenticator; +import java.net.CookieManager; +import java.net.CookiePolicy; +import java.net.HttpURLConnection; +import java.net.PasswordAuthentication; +import java.net.ProxySelector; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.net.http.HttpResponse.BodyHandlers; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import org.junit.jupiter.api.Test; + +public class HttpClientUnitTest { + + @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.BodyPublishers.ofString("Sample body")) + .build(); + + + HttpResponse response = HttpClient.newBuilder() + .proxy(ProxySelector.getDefault()) + .build() + .send(request, HttpResponse.BodyHandlers.ofString()); + + 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 response = HttpClient.newBuilder() + .build() + .send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM)); + assertTrue(response.headers().map().get("location").stream().anyMatch("https://stackoverflow.com/"::equals)); + } + + @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 response = HttpClient.newBuilder() + .followRedirects(HttpClient.Redirect.ALWAYS) + .build() + .send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); + assertThat(response.request() + .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 response = HttpClient.newBuilder() + .authenticator(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication("postman", "password".toCharArray()); + } + }) + .build() + .send(request, HttpResponse.BodyHandlers.ofString()); + + 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.BodyPublishers.ofString("Sample body")) + .build(); + CompletableFuture> response = HttpClient.newBuilder() + .build() + .sendAsync(request, HttpResponse.BodyHandlers.ofString()); + + 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> response1 = HttpClient.newBuilder() + .executor(executorService) + .build() + .sendAsync(request, HttpResponse.BodyHandlers.ofString()); + + CompletableFuture> response2 = HttpClient.newBuilder() + .executor(executorService) + .build() + .sendAsync(request, HttpResponse.BodyHandlers.ofString()); + + CompletableFuture> response3 = HttpClient.newBuilder() + .executor(executorService) + .build() + .sendAsync(request, HttpResponse.BodyHandlers.ofString()); + + 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() + .cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_NONE)) + .build(); + + httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + + assertTrue(httpClient.cookieHandler() + .isPresent()); + } + + @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() + .cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ALL)) + .build(); + + httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + + assertTrue(httpClient.cookieHandler() + .isPresent()); + } + + @Test + public void shouldProcessMultipleRequestViaStream() throws URISyntaxException, ExecutionException, InterruptedException { + List 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> futures = targets.stream() + .map(target -> client.sendAsync(HttpRequest.newBuilder(target) + .GET() + .build(), HttpResponse.BodyHandlers.ofString()) + .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")); + } + + } + + @Test + public void completeExceptionallyExample() { + CompletableFuture cf = CompletableFuture.completedFuture("message").thenApplyAsync(String::toUpperCase, + CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS)); + CompletableFuture exceptionHandler = cf.handle((s, th) -> { return (th != null) ? "message upon cancel" : ""; }); + cf.completeExceptionally(new RuntimeException("completed exceptionally")); + assertTrue("Was not completed exceptionally", cf.isCompletedExceptionally()); + try { + cf.join(); + fail("Should have thrown an exception"); + } catch (CompletionException ex) { // just for testing + assertEquals("completed exceptionally", ex.getCause().getMessage()); + } + + assertEquals("message upon cancel", exceptionHandler.join()); + } + +} diff --git a/core-java-modules/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpRequestUnitTest.java b/core-java-modules/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpRequestUnitTest.java new file mode 100644 index 0000000000..3b9db284c8 --- /dev/null +++ b/core-java-modules/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpRequestUnitTest.java @@ -0,0 +1,174 @@ +package com.baeldung.java11.httpclient.test; + +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; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.file.Paths; +import java.security.NoSuchAlgorithmException; +import java.time.Duration; + +import org.junit.Ignore; +import org.junit.Test; + +public class HttpRequestUnitTest { + + @Test + public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException { + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("https://postman-echo.com/get")) + .GET() + .build(); + + HttpResponse response = HttpClient.newHttpClient() + .send(request, HttpResponse.BodyHandlers.ofString()); + + 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 response = HttpClient.newHttpClient() + .send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); + assertThat(response.version(), equalTo(HttpClient.Version.HTTP_2)); + } + + /* + * This test will fail as soon as the given URL returns a HTTP 2 response. + * Therefore, let's leave it ignored. + * */ + @Test + @Ignore + 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 response = HttpClient.newHttpClient() + .send(request, HttpResponse.BodyHandlers.ofString()); + + 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 response = HttpClient.newHttpClient() + .send(request, HttpResponse.BodyHandlers.ofString()); + + 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 response = HttpClient.newHttpClient() + .send(request, HttpResponse.BodyHandlers.ofString()); + + 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.BodyPublishers.noBody()) + .build(); + + HttpResponse response = HttpClient.newHttpClient() + .send(request, HttpResponse.BodyHandlers.ofString()); + + 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.BodyPublishers.ofString("Sample request body")) + .build(); + + HttpResponse response = HttpClient.newHttpClient() + .send(request, HttpResponse.BodyHandlers.ofString()); + + 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.BodyPublishers.ofInputStream(() -> new ByteArrayInputStream(sampleData))) + .build(); + + HttpResponse response = HttpClient.newHttpClient() + .send(request, HttpResponse.BodyHandlers.ofString()); + + 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.BodyPublishers.ofByteArray(sampleData)) + .build(); + + HttpResponse response = HttpClient.newHttpClient() + .send(request, HttpResponse.BodyHandlers.ofString()); + + 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.BodyPublishers.ofFile(Paths.get("src/test/resources/sample.txt"))) + .build(); + + HttpResponse response = HttpClient.newHttpClient() + .send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); + assertThat(response.body(), containsString("Sample file content")); + } + +} diff --git a/core-java-modules/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpResponseUnitTest.java b/core-java-modules/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpResponseUnitTest.java new file mode 100644 index 0000000000..a5cfc3f6b1 --- /dev/null +++ b/core-java-modules/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpResponseUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.java11.httpclient.test; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; + +import org.junit.Test; + +public class HttpResponseUnitTest { + + @Test + public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException { + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("https://postman-echo.com/get")) + .version(HttpClient.Version.HTTP_2) + .GET() + .build(); + + HttpResponse response = HttpClient.newBuilder() + .followRedirects(HttpClient.Redirect.NORMAL) + .build() + .send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); + assertNotNull(response.body()); + } + + @Test + public void shouldResponseURIDifferentThanRequestUIRWhenRedirect() throws IOException, InterruptedException, URISyntaxException { + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("http://stackoverflow.com")) + .version(HttpClient.Version.HTTP_2) + .GET() + .build(); + HttpResponse response = HttpClient.newBuilder() + .followRedirects(HttpClient.Redirect.NORMAL) + .build() + .send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(request.uri() + .toString(), equalTo("http://stackoverflow.com")); + assertThat(response.uri() + .toString(), equalTo("https://stackoverflow.com/")); + } + +} diff --git a/core-java-modules/core-java-11/src/test/java/com/baeldung/optional/OptionalUnitTest.java b/core-java-modules/core-java-11/src/test/java/com/baeldung/optional/OptionalUnitTest.java new file mode 100644 index 0000000000..281155138d --- /dev/null +++ b/core-java-modules/core-java-11/src/test/java/com/baeldung/optional/OptionalUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.optional; + +import org.junit.Test; + +import java.util.Optional; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * Unit tests for {@link Optional} in Java 11. + */ +public class OptionalUnitTest { + + @Test + public void givenAnEmptyOptional_isEmpty_thenBehavesAsExpected() { + Optional opt = Optional.of("Baeldung"); + assertFalse(opt.isEmpty()); + + opt = Optional.ofNullable(null); + assertTrue(opt.isEmpty()); + } +} diff --git a/core-java-modules/core-java-11/src/test/java/com/baeldung/patternreuse/PatternJava11UnitTest.java b/core-java-modules/core-java-11/src/test/java/com/baeldung/patternreuse/PatternJava11UnitTest.java new file mode 100644 index 0000000000..e334d2c843 --- /dev/null +++ b/core-java-modules/core-java-11/src/test/java/com/baeldung/patternreuse/PatternJava11UnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.patternreuse; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.function.Predicate; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class PatternJava11UnitTest { + + @Test + public void givenPreCompiledPattern_whenCallAsMatchPredicate_thenReturnMatchPredicateToMatchesPattern() { + List namesToValidate = Arrays.asList("Fabio Silva", "Fabio Luis Silva"); + Pattern firstLastNamePreCompiledPattern = Pattern.compile("[a-zA-Z]{3,} [a-zA-Z]{3,}"); + + Predicate patternAsMatchPredicate = firstLastNamePreCompiledPattern.asMatchPredicate(); + List validatedNames = namesToValidate.stream() + .filter(patternAsMatchPredicate) + .collect(Collectors.toList()); + + assertTrue(validatedNames.contains("Fabio Silva")); + assertFalse(validatedNames.contains("Fabio Luis Silva")); + } +} diff --git a/core-java-modules/core-java-11/src/test/java/com/baeldung/predicate/not/PersonUnitTest.java b/core-java-modules/core-java-11/src/test/java/com/baeldung/predicate/not/PersonUnitTest.java new file mode 100644 index 0000000000..a4989287be --- /dev/null +++ b/core-java-modules/core-java-11/src/test/java/com/baeldung/predicate/not/PersonUnitTest.java @@ -0,0 +1,61 @@ +package com.baeldung.predicate.not; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static java.util.function.Predicate.not; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class PersonUnitTest { + private List people; + + @BeforeEach + void preparePeople() { + people = Arrays.asList( + new Person(1), + new Person(18), + new Person(2) + ); + } + + @Test + void givenPeople_whenFilterIsAdult_thenOneResult() { + List adults = people.stream() + .filter(Person::isAdult) + .collect(Collectors.toList()); + + assertThat(adults).size().isEqualTo(1); + } + + @Test + void givenPeople_whenFilterIsAdultNegated_thenTwoResults() { + List nonAdults = people.stream() + .filter(person -> !person.isAdult()) + .collect(Collectors.toList()); + + assertThat(nonAdults).size().isEqualTo(2); + } + + @Test + void givenPeople_whenFilterIsNotAdult_thenTwoResults() { + List nonAdults = people.stream() + .filter(Person::isNotAdult) + .collect(Collectors.toList()); + + assertThat(nonAdults).size().isEqualTo(2); + } + + @Test + void givenPeople_whenFilterNotIsAdult_thenTwoResults() { + List nonAdults = people.stream() + .filter(not(Person::isAdult)) + .collect(Collectors.toList()); + + assertThat(nonAdults).size().isEqualTo(2); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-11/src/test/resources/sample.txt b/core-java-modules/core-java-11/src/test/resources/sample.txt new file mode 100644 index 0000000000..64be299017 --- /dev/null +++ b/core-java-modules/core-java-11/src/test/resources/sample.txt @@ -0,0 +1 @@ +Sample file content \ No newline at end of file