#BAEL-16633 split Core Java 9 module - new Java 9 features
This commit is contained in:
@@ -4,25 +4,17 @@ This module contains articles about Java 9 core features
|
||||
|
||||
### 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)
|
||||
- [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)
|
||||
- [Java 9 java.util.Objects Additions](https://www.baeldung.com/java-9-objects-new)
|
||||
- [Java 9 Reactive Streams](https://www.baeldung.com/java-9-reactive-streams)
|
||||
- [Java 9 Optional API Additions](https://www.baeldung.com/java-9-optional)
|
||||
- [Java 9 CompletableFuture API Improvements](https://www.baeldung.com/java-9-completablefuture)
|
||||
- [Introduction to Java 9 StackWalking API](https://www.baeldung.com/java-9-stackwalking-api)
|
||||
- [Java 9 Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods)
|
||||
- [Java 9 Stream API Improvements](https://www.baeldung.com/java-9-stream-api)
|
||||
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
|
||||
- [Filtering a Stream of Optionals in Java](https://www.baeldung.com/java-filter-stream-of-optional)
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
#!/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
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
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
|
||||
@@ -1,3 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
cd src/main/java
|
||||
java -XX:AOTLibrary=./jaotCompilation.so com/baeldung/java9/aot/JaotCompilation
|
||||
@@ -1 +0,0 @@
|
||||
java --module-path mods -m com.baeldung.httpclient/com.baeldung.httpclient.HttpClientExample
|
||||
@@ -1,13 +0,0 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
@@ -1,12 +0,0 @@
|
||||
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'";
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
/*
|
||||
* 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());
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
module com.baeldung.httpclient {
|
||||
requires jdk.incubator.httpclient;
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
module com.baeldung.logging.app {
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
package com.baeldung.logging.slf4j;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.ResourceBundle;
|
||||
import java.text.MessageFormat;
|
||||
|
||||
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;
|
||||
}
|
||||
String message = MessageFormat.format(format, params);
|
||||
|
||||
switch (level) {
|
||||
case TRACE:
|
||||
logger.trace(message);
|
||||
break;
|
||||
case DEBUG:
|
||||
logger.debug(message);
|
||||
break;
|
||||
case INFO:
|
||||
logger.info(message);
|
||||
break;
|
||||
case WARNING:
|
||||
logger.warn(message);
|
||||
break;
|
||||
case ERROR:
|
||||
logger.error(message);
|
||||
break;
|
||||
case ALL:
|
||||
default:
|
||||
logger.info(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.baeldung.logging.slf4j;
|
||||
|
||||
public class Slf4jLoggerFinder extends System.LoggerFinder {
|
||||
@Override
|
||||
public System.Logger getLogger(String name, Module module) {
|
||||
return new Slf4jLogger(name);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
module com.baeldung.logging.slf4j {
|
||||
requires org.slf4j;
|
||||
provides java.lang.System.LoggerFinder
|
||||
with com.baeldung.logging.slf4j.Slf4jLoggerFinder;
|
||||
exports com.baeldung.logging.slf4j;
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.baeldung.logging;
|
||||
|
||||
public class CustomLoggerFinder extends System.LoggerFinder {
|
||||
|
||||
@Override
|
||||
public System.Logger getLogger(String name, Module module) {
|
||||
return new ConsoleLogger();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
module com.baeldung.logging {
|
||||
provides java.lang.System.LoggerFinder
|
||||
with com.baeldung.logging.CustomLoggerFinder;
|
||||
exports com.baeldung.logging;
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
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());
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,218 +0,0 @@
|
||||
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"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,171 +0,0 @@
|
||||
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"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
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/"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
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, "") {
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
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++;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user