Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
a72686d871
|
@ -1,5 +1,3 @@
|
|||
**UPDATE**: The price of "Learn Spring Security OAuth" will permanently change on the 11th of December, along with the upcoming OAuth2 material: http://bit.ly/github-lss
|
||||
|
||||
The Courses
|
||||
==============================
|
||||
|
||||
|
|
|
@ -5,6 +5,6 @@ This module contains articles about genetic algorithms.
|
|||
### Relevant articles:
|
||||
|
||||
- [Introduction to Jenetics Library](https://www.baeldung.com/jenetics)
|
||||
- [Ant Colony Optimization](https://www.baeldung.com/java-ant-colony-optimization)
|
||||
- [Ant Colony Optimization with a Java Example](https://www.baeldung.com/java-ant-colony-optimization)
|
||||
- [Design a Genetic Algorithm in Java](https://www.baeldung.com/java-genetic-algorithm)
|
||||
- [The Traveling Salesman Problem in Java](https://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
|
||||
|
|
|
@ -6,8 +6,8 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
|||
### Relevant articles:
|
||||
|
||||
- [Validating Input With Finite Automata in Java](https://www.baeldung.com/java-finite-automata)
|
||||
- [Example of Hill Climbing Algorithm](https://www.baeldung.com/java-hill-climbing-algorithm)
|
||||
- [Introduction to Minimax Algorithm](https://www.baeldung.com/java-minimax-algorithm)
|
||||
- [Example of Hill Climbing Algorithm in Java](https://www.baeldung.com/java-hill-climbing-algorithm)
|
||||
- [Introduction to Minimax Algorithm with a Java Implementation](https://www.baeldung.com/java-minimax-algorithm)
|
||||
- [How to Calculate Levenshtein Distance in Java?](https://www.baeldung.com/java-levenshtein-distance)
|
||||
- [How to Find the Kth Largest Element in Java](https://www.baeldung.com/java-kth-largest-element)
|
||||
- More articles: [[next -->]](/algorithms-miscellaneous-2)
|
||||
|
|
|
@ -5,8 +5,8 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
|||
### Relevant articles:
|
||||
|
||||
- [Multi-Swarm Optimization Algorithm in Java](https://www.baeldung.com/java-multi-swarm-algorithm)
|
||||
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
|
||||
- [Find the Middle Element of a Linked List](https://www.baeldung.com/java-linked-list-middle-element)
|
||||
- [Check If a String Contains All The Letters of The Alphabet with Java](https://www.baeldung.com/java-string-contains-all-letters)
|
||||
- [Find the Middle Element of a Linked List in Java](https://www.baeldung.com/java-linked-list-middle-element)
|
||||
- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)
|
||||
- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
|
||||
- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)
|
||||
|
|
|
@ -9,11 +9,11 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
|||
- [Reversing a Binary Tree in Java](https://www.baeldung.com/java-reversing-a-binary-tree)
|
||||
- [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers)
|
||||
- [Knapsack Problem Implementation in Java](https://www.baeldung.com/java-knapsack)
|
||||
- [How to Determine if a Binary Tree is Balanced](https://www.baeldung.com/java-balanced-binary-tree)
|
||||
- [How to Determine if a Binary Tree is Balanced in Java](https://www.baeldung.com/java-balanced-binary-tree)
|
||||
- [Overview of Combinatorial Problems in Java](https://www.baeldung.com/java-combinatorial-algorithms)
|
||||
- [Prim’s Algorithm](https://www.baeldung.com/java-prim-algorithm)
|
||||
- [Maximum Subarray Problem](https://www.baeldung.com/java-maximum-subarray)
|
||||
- [How to Merge Two Sorted Arrays](https://www.baeldung.com/java-merge-sorted-arrays)
|
||||
- [Median of Stream of Integers using Heap](https://www.baeldung.com/java-stream-integers-median-using-heap)
|
||||
- [Prim’s Algorithm with a Java Implementation](https://www.baeldung.com/java-prim-algorithm)
|
||||
- [Maximum Subarray Problem in Java](https://www.baeldung.com/java-maximum-subarray)
|
||||
- [How to Merge Two Sorted Arrays in Java](https://www.baeldung.com/java-merge-sorted-arrays)
|
||||
- [Median of Stream of Integers using Heap in Java](https://www.baeldung.com/java-stream-integers-median-using-heap)
|
||||
- More articles: [[<-- prev]](/algorithms-miscellaneous-4) [[next -->]](/algorithms-miscellaneous-6)
|
||||
|
||||
|
|
|
@ -1,13 +1,13 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Boruvka’s Algorithm for Minimum Spanning Trees](https://www.baeldung.com/java-boruvka-algorithm)
|
||||
- [Boruvka’s Algorithm for Minimum Spanning Trees in Java](https://www.baeldung.com/java-boruvka-algorithm)
|
||||
- [Gradient Descent in Java](https://www.baeldung.com/java-gradient-descent)
|
||||
- [Kruskal’s Algorithm for Spanning Trees](https://www.baeldung.com/java-spanning-trees-kruskal)
|
||||
- [Kruskal’s Algorithm for Spanning Trees with a Java Implementation](https://www.baeldung.com/java-spanning-trees-kruskal)
|
||||
- [Balanced Brackets Algorithm in Java](https://www.baeldung.com/java-balanced-brackets-algorithm)
|
||||
- [Efficiently Merge Sorted Java Sequences](https://www.baeldung.com/java-merge-sorted-sequences)
|
||||
- [Introduction to Greedy Algorithms with Java](https://www.baeldung.com/java-greedy-algorithms)
|
||||
- [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher)
|
||||
- [Implementing a 2048 Solver in Java](https://www.baeldung.com/2048-java-solver)
|
||||
- [Finding Top K Elements in an Array](https://www.baeldung.com/java-array-top-elements)
|
||||
- [Finding Top K Elements in a Java Array](https://www.baeldung.com/java-array-top-elements)
|
||||
- [Reversing a Linked List in Java](https://www.baeldung.com/java-reverse-linked-list)
|
||||
- More articles: [[<-- prev]](/algorithms-miscellaneous-5)
|
||||
|
|
|
@ -8,8 +8,8 @@ This module contains articles about searching algorithms.
|
|||
- [Depth First Search in Java](https://www.baeldung.com/java-depth-first-search)
|
||||
- [Interpolation Search in Java](https://www.baeldung.com/java-interpolation-search)
|
||||
- [Breadth-First Search Algorithm in Java](https://www.baeldung.com/java-breadth-first-search)
|
||||
- [String Search Algorithms for Large Texts](https://www.baeldung.com/java-full-text-search-algorithms)
|
||||
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](https://www.baeldung.com/java-monte-carlo-tree-search)
|
||||
- [String Search Algorithms for Large Texts with Java](https://www.baeldung.com/java-full-text-search-algorithms)
|
||||
- [Monte Carlo Tree Search for Tic-Tac-Toe Game in Java](https://www.baeldung.com/java-monte-carlo-tree-search)
|
||||
- [Range Search Algorithm in Java](https://www.baeldung.com/java-range-search)
|
||||
- [Fast Pattern Matching of Strings Using Suffix Tree](https://www.baeldung.com/java-pattern-matching-suffix-tree)
|
||||
- [Find the Kth Smallest Element in Two Sorted Arrays](https://www.baeldung.com/java-kth-smallest-element-in-sorted-arrays)
|
||||
- [Fast Pattern Matching of Strings Using Suffix Tree in Java](https://www.baeldung.com/java-pattern-matching-suffix-tree)
|
||||
- [Find the Kth Smallest Element in Two Sorted Arrays in Java](https://www.baeldung.com/java-kth-smallest-element-in-sorted-arrays)
|
||||
|
|
|
@ -2,6 +2,6 @@
|
|||
|
||||
- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically)
|
||||
- [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers)
|
||||
- [How an In-Place Sorting Algorithm Works](https://www.baeldung.com/java-in-place-sorting)
|
||||
- [Partitioning and Sorting Arrays with Many Repeated Entries](https://www.baeldung.com/java-sorting-arrays-with-repeated-entries)
|
||||
- [Guide to In-Place Sorting Algorithm Works with a Java Implementation](https://www.baeldung.com/java-in-place-sorting)
|
||||
- [Partitioning and Sorting Arrays with Many Repeated Entries with Java Examples](https://www.baeldung.com/java-sorting-arrays-with-repeated-entries)
|
||||
- More articles: [[<-- prev]](/algorithms-sorting)
|
||||
|
|
|
@ -8,3 +8,4 @@ This module contains articles about Apache Spark
|
|||
- [Building a Data Pipeline with Kafka, Spark Streaming and Cassandra](https://www.baeldung.com/kafka-spark-data-pipeline)
|
||||
- [Machine Learning with Spark MLlib](https://www.baeldung.com/spark-mlib-machine-learning)
|
||||
- [Introduction to Spark Graph Processing with GraphFrames](https://www.baeldung.com/spark-graph-graphframes)
|
||||
- [Apache Spark: Differences between Dataframes, Datasets and RDDs](https://www.baeldung.com/java-spark-dataframe-dataset-rdd)
|
||||
|
|
|
@ -51,7 +51,7 @@
|
|||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-entitymanager</artifactId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
<scope>provided</scope>
|
||||
<exclusions>
|
||||
|
|
|
@ -89,7 +89,6 @@
|
|||
|
||||
<properties>
|
||||
<json-simple.version>1.1.1</json-simple.version>
|
||||
<commons-io.version>2.5</commons-io.version>
|
||||
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
|
||||
<aws-lambda-java-core.version>1.2.0</aws-lambda-java-core.version>
|
||||
<gson.version>2.8.2</gson.version>
|
||||
|
|
|
@ -6,10 +6,12 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
|
|||
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistry;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
@ -22,11 +24,14 @@ import static org.hibernate.cfg.AvailableSettings.PASS;
|
|||
*/
|
||||
public class App implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
|
||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||
private SessionFactory sessionFactory = createSessionFactory();
|
||||
|
||||
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
|
||||
try (SessionFactory sessionFactory = createSessionFactory()) {
|
||||
try {
|
||||
ShippingService service = new ShippingService(sessionFactory, new ShippingDao());
|
||||
return routeRequest(input, service);
|
||||
} finally {
|
||||
flushConnectionPool();
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -105,4 +110,12 @@ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
|||
.buildMetadata()
|
||||
.buildSessionFactory();
|
||||
}
|
||||
|
||||
private void flushConnectionPool() {
|
||||
ConnectionProvider connectionProvider = sessionFactory.getSessionFactoryOptions()
|
||||
.getServiceRegistry()
|
||||
.getService(ConnectionProvider.class);
|
||||
HikariDataSource hikariDataSource = connectionProvider.unwrap(HikariDataSource.class);
|
||||
hikariDataSource.getHikariPoolMXBean().softEvictConnections();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -154,7 +154,6 @@
|
|||
<properties>
|
||||
<blade-mvc.version>2.0.14.RELEASE</blade-mvc.version>
|
||||
<bootstrap.version>4.2.1</bootstrap.version>
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<lombok.version>1.18.4</lombok.version>
|
||||
<httpclient.version>4.5.6</httpclient.version>
|
||||
<httpmime.version>4.5.6</httpmime.version>
|
||||
|
|
|
@ -10,3 +10,4 @@ This module contains articles about Java 10 core features
|
|||
- [Deep Dive Into the New Java JIT Compiler – Graal](https://www.baeldung.com/graal-java-jit-compiler)
|
||||
- [Copying Sets in Java](https://www.baeldung.com/java-copy-sets)
|
||||
- [Converting between a List and a Set in Java](https://www.baeldung.com/convert-list-to-set-and-set-to-list)
|
||||
- [Java IndexOutOfBoundsException “Source Does Not Fit in Dest”](https://www.baeldung.com/java-indexoutofboundsexception)
|
||||
|
|
|
@ -6,3 +6,4 @@ This module contains articles about Java 11 core features
|
|||
- [Guide to Java 8 Optional](https://www.baeldung.com/java-optional)
|
||||
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
|
||||
- [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors)
|
||||
- [New Features in Java 11](https://www.baeldung.com/java-11-new-features)
|
||||
|
|
|
@ -28,6 +28,29 @@
|
|||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mock-server</groupId>
|
||||
<artifactId>mockserver-junit-jupiter</artifactId>
|
||||
<version>${mockserver.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-params</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -48,7 +71,9 @@
|
|||
<maven.compiler.source.version>11</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>11</maven.compiler.target.version>
|
||||
<guava.version>29.0-jre</guava.version>
|
||||
<junit.jupiter.version>5.7.0</junit.jupiter.version>
|
||||
<assertj.version>3.17.2</assertj.version>
|
||||
<mockserver.version>5.11.1</mockserver.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.features;
|
||||
|
||||
public class MainClass {
|
||||
|
||||
private static boolean mainPrivateMethod() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public static class NestedClass {
|
||||
|
||||
boolean nestedPublicMethod() {
|
||||
return mainPrivateMethod();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
package com.baeldung.features;
|
||||
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockserver.integration.ClientAndServer;
|
||||
import org.mockserver.model.HttpStatusCode;
|
||||
import org.mockserver.socket.PortFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
|
||||
|
||||
class HttpClientIntegrationTest {
|
||||
|
||||
private static ClientAndServer mockServer;
|
||||
private static int port;
|
||||
|
||||
@BeforeAll
|
||||
static void startServer() {
|
||||
port = PortFactory.findFreePort();
|
||||
mockServer = startClientAndServer(port);
|
||||
mockServer.when(new org.mockserver.model.HttpRequest().withMethod("GET"))
|
||||
.respond(new org.mockserver.model.HttpResponse()
|
||||
.withStatusCode(HttpStatusCode.OK_200.code())
|
||||
.withBody("Hello from the server!"));
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stopServer() {
|
||||
mockServer.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSampleHttpRequest_whenRequestIsSent_thenServerResponseIsReceived() throws IOException, InterruptedException {
|
||||
HttpClient httpClient = HttpClient.newBuilder()
|
||||
.version(HttpClient.Version.HTTP_2)
|
||||
.connectTimeout(Duration.ofSeconds(20))
|
||||
.build();
|
||||
HttpRequest httpRequest = HttpRequest.newBuilder()
|
||||
.GET()
|
||||
.uri(URI.create("http://localhost:" + port))
|
||||
.build();
|
||||
HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
|
||||
assertThat(httpResponse.body()).isEqualTo("Hello from the server!");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
package com.baeldung.features;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class JavaElevenFeaturesUnitTest {
|
||||
|
||||
@Test
|
||||
void givenMultilineString_whenExtractingNonBlankStrippedLines_thenLinesAreReturned() {
|
||||
String multilineString = "Baeldung helps \n \n developers \n explore Java.";
|
||||
List<String> lines = multilineString.lines()
|
||||
.filter(line -> !line.isBlank())
|
||||
.map(String::strip)
|
||||
.collect(Collectors.toList());
|
||||
assertThat(lines).containsExactly("Baeldung helps", "developers", "explore Java.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenTemporaryFile_whenReadingStringContent_thenContentIsReturned(@TempDir Path tempDir) throws IOException {
|
||||
Path filePath = Files.writeString(Files.createTempFile(tempDir, "demo", ".txt"), "Sample text");
|
||||
String fileContent = Files.readString(filePath);
|
||||
assertThat(fileContent).isEqualTo("Sample text");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSampleList_whenConvertingToArray_thenItemsRemainUnchanged() {
|
||||
List<String> sampleList = Arrays.asList("Java", "Kotlin");
|
||||
String[] sampleArray = sampleList.toArray(String[]::new);
|
||||
assertThat(sampleArray).containsExactly("Java", "Kotlin");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSampleList_whenConvertingToUppercaseString_thenUppercaseIsReturned() {
|
||||
List<String> sampleList = Arrays.asList("Java", "Kotlin");
|
||||
String resultString = sampleList.stream()
|
||||
.map((@Nonnull var x) -> x.toUpperCase())
|
||||
.collect(Collectors.joining(", "));
|
||||
assertThat(resultString).isEqualTo("JAVA, KOTLIN");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSampleList_whenExtractingNonBlankValues_thenOnlyNonBlanksAreReturned() {
|
||||
List<String> sampleList = Arrays.asList("Java", "\n \n", "Kotlin", " ");
|
||||
List<String> withoutBlanks = sampleList.stream()
|
||||
.filter(Predicate.not(String::isBlank))
|
||||
.collect(Collectors.toList());
|
||||
assertThat(withoutBlanks).containsExactly("Java", "Kotlin");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung.features;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class NestedClassesUnitTest {
|
||||
|
||||
@Test
|
||||
public void giveNestedClass_whenCallingMainClassPrivateMethod_thenNoExceptionIsThrown() {
|
||||
MainClass.NestedClass nestedInstance = new MainClass.NestedClass();
|
||||
assertThat(nestedInstance.nestedPublicMethod()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giveNestedClass_whenCheckingNestmate_thenNestedClassIsReturned() {
|
||||
assertThat(MainClass.class.isNestmateOf(MainClass.NestedClass.class)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giveNestedClass_whenCheckingNestHost_thenMainClassIsReturned() {
|
||||
assertThat(MainClass.NestedClass.class.getNestHost()).isEqualTo(MainClass.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giveNestedClass_whenCheckingNestMembers_thenNestMembersAreReturned() {
|
||||
Set<String> nestedMembers = Arrays.stream(MainClass.NestedClass.class.getNestMembers())
|
||||
.map(Class::getName)
|
||||
.collect(Collectors.toSet());
|
||||
assertThat(nestedMembers).contains(MainClass.class.getName(), MainClass.NestedClass.class.getName());
|
||||
}
|
||||
|
||||
}
|
|
@ -64,7 +64,7 @@ public class HttpClientUnitTest {
|
|||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM));
|
||||
assertThat(response.body(), containsString("https://stackoverflow.com/"));
|
||||
assertTrue(response.headers().map().get("location").stream().anyMatch("https://stackoverflow.com/"::equals));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
@ -18,6 +18,7 @@ import java.security.NoSuchAlgorithmException;
|
|||
import java.time.Duration;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
|
||||
public class HttpRequestUnitTest {
|
||||
|
||||
|
@ -48,7 +49,12 @@ public class HttpRequestUnitTest {
|
|||
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 commented out.
|
||||
* */
|
||||
@Test
|
||||
@Disabled
|
||||
public void shouldFallbackToHttp1_1WhenWebsiteDoesNotUseHttp2() throws IOException, InterruptedException, URISyntaxException, NoSuchAlgorithmException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
|
|
|
@ -2,3 +2,4 @@
|
|||
|
||||
|
||||
- [String API Updates in Java 12](https://www.baeldung.com/java12-string-api)
|
||||
- [Java 12 New Features](https://www.baeldung.com/java-12-new-features)
|
||||
|
|
|
@ -0,0 +1,21 @@
|
|||
package java.com.baeldung.newfeatures;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.text.NumberFormat;
|
||||
import java.util.Locale;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class CompactNumbersUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenNumber_thenCompactValues() {
|
||||
NumberFormat likesShort = NumberFormat.getCompactNumberInstance(new Locale("en", "US"), NumberFormat.Style.SHORT);
|
||||
likesShort.setMaximumFractionDigits(2);
|
||||
assertEquals("2.59K", likesShort.format(2592));
|
||||
NumberFormat likesLong = NumberFormat.getCompactNumberInstance(new Locale("en", "US"), NumberFormat.Style.LONG);
|
||||
likesLong.setMaximumFractionDigits(2);
|
||||
assertEquals("2.59 thousand", likesShort.format(2592));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package java.com.baeldung.newfeatures;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class FileMismatchUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenIdenticalFiles_thenShouldNotFindMismatch() throws IOException {
|
||||
Path filePath1 = Files.createTempFile("file1", ".txt");
|
||||
Path filePath2 = Files.createTempFile("file2", ".txt");
|
||||
Files.writeString(filePath1, "Java 12 Article");
|
||||
Files.writeString(filePath2, "Java 12 Article");
|
||||
long mismatch = Files.mismatch(filePath1, filePath2);
|
||||
assertEquals(-1, mismatch);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDifferentFiles_thenShouldFindMismatch() throws IOException {
|
||||
Path filePath3 = Files.createTempFile("file3", ".txt");
|
||||
Path filePath4 = Files.createTempFile("file4", ".txt");
|
||||
Files.writeString(filePath3, "Java 12 Article");
|
||||
Files.writeString(filePath4, "Java 12 Tutorial");
|
||||
long mismatch = Files.mismatch(filePath3, filePath4);
|
||||
assertEquals(8, mismatch);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package java.com.baeldung.newfeatures;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StringUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenString_thenRevertValue() {
|
||||
String text = "Baeldung";
|
||||
String transformed = text.transform(value -> new StringBuilder(value).reverse().toString());
|
||||
assertEquals("gnudleaB", transformed);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package java.com.baeldung.newfeatures;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class TeeingCollectorUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenSetOfNumbers_thenCalculateAverage() {
|
||||
double mean = Stream.of(1, 2, 3, 4, 5)
|
||||
.collect(Collectors.teeing(Collectors.summingDouble(i -> i), Collectors.counting(), (sum, count) -> sum / count));
|
||||
assertEquals(3.0, mean);
|
||||
}
|
||||
}
|
|
@ -10,3 +10,4 @@ This module contains articles about Java 14.
|
|||
- [Helpful NullPointerExceptions in Java 14](https://www.baeldung.com/java-14-nullpointerexception)
|
||||
- [Foreign Memory Access API in Java 14](https://www.baeldung.com/java-foreign-memory-access)
|
||||
- [Java 14 Record Keyword](https://www.baeldung.com/java-record-keyword)
|
||||
- [Java 14 – New Features](https://www.baeldung.com/java-14-new-features)
|
||||
|
|
|
@ -44,6 +44,8 @@
|
|||
<configuration>
|
||||
<release>${maven.compiler.release}</release>
|
||||
<compilerArgs>--enable-preview</compilerArgs>
|
||||
<source>14</source>
|
||||
<target>14</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
|
|
|
@ -0,0 +1,30 @@
|
|||
package com.baeldung.java14.character;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
public class IsLetterOrAlphabetUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenLetter_thenAssertIsLetterTrue() {
|
||||
assertTrue(Character.isLetter(65));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenLetter_thenAssertIsAlphabeticTrue() {
|
||||
assertTrue(Character.isAlphabetic(65));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenAlphabeticAndNotLetter_thenAssertIsLetterFalse() {
|
||||
assertFalse(Character.isLetter(837));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenAlphabeticAndNotLetter_thenAssertIsAlphabeticTrue() {
|
||||
assertTrue(Character.isAlphabetic(837));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.java14.newfeatues;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class MultilineUnitTest {
|
||||
|
||||
@SuppressWarnings("preview")
|
||||
String multiline = """
|
||||
A quick brown fox jumps over a lazy dog; \
|
||||
the lazy dog howls loudly.""";
|
||||
|
||||
@SuppressWarnings("preview")
|
||||
String anotherMultiline = """
|
||||
A quick brown fox jumps over a lazy dog;
|
||||
the lazy dog howls loudly.""";
|
||||
|
||||
@Test
|
||||
public void givenMultilineString_whenSlashUsed_thenNoNewLine() {
|
||||
assertFalse(multiline.contains("\n"));
|
||||
assertTrue(anotherMultiline.contains("\n"));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
package com.baeldung.java14.newfeatues;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RecordUnitTest {
|
||||
|
||||
@SuppressWarnings("preview")
|
||||
public record User(int id, String password) {
|
||||
};
|
||||
|
||||
private User user1 = new User(0, "UserOne");
|
||||
|
||||
@Test
|
||||
public void givenRecord_whenObjInitialized_thenValuesCanBeFetchedWithGetters() {
|
||||
|
||||
assertEquals(0, user1.id());
|
||||
assertEquals("UserOne", user1.password());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRecord_thenEqualsImplemented() {
|
||||
|
||||
User user2 = user1;
|
||||
|
||||
assertEquals(user1, user2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRecord_thenToStringImplemented() {
|
||||
|
||||
assertTrue(user1.toString()
|
||||
.contains("UserOne"));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
package com.baeldung.java14.newfeatues;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class SwitchExprUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenDay_whenSunday_thenWeekend() {
|
||||
assertTrue(isTodayHolidayInJava8("SUNDAY"));
|
||||
|
||||
assertTrue(isTodayHolidayInJava14("SUNDAY"));
|
||||
|
||||
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> isTodayHolidayInJava8("SOMEDAY"));
|
||||
|
||||
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> isTodayHolidayInJava14("SOMEDAY"));
|
||||
}
|
||||
|
||||
private boolean isTodayHolidayInJava8(String day) {
|
||||
|
||||
boolean isTodayHoliday;
|
||||
switch (day) {
|
||||
case "MONDAY":
|
||||
case "TUESDAY":
|
||||
case "WEDNESDAY":
|
||||
case "THURSDAY":
|
||||
case "FRIDAY":
|
||||
isTodayHoliday = false;
|
||||
break;
|
||||
case "SATURDAY":
|
||||
case "SUNDAY":
|
||||
isTodayHoliday = true;
|
||||
break;
|
||||
default:
|
||||
throw new IllegalArgumentException("What's a " + day);
|
||||
}
|
||||
return isTodayHoliday;
|
||||
}
|
||||
|
||||
private boolean isTodayHolidayInJava14(String day) {
|
||||
return switch (day) {
|
||||
case "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY" -> false;
|
||||
case "SATURDAY", "SUNDAY" -> true;
|
||||
default -> throw new IllegalArgumentException("What's a " + day);
|
||||
};
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
--enable-preview
|
|
@ -0,0 +1,7 @@
|
|||
## Core Java 15
|
||||
|
||||
This module contains articles about Java 15.
|
||||
|
||||
### Relevant articles
|
||||
|
||||
- [Sealed Classes and Interfaces in Java 15](https://www.baeldung.com/java-sealed-classes-interfaces)
|
|
@ -0,0 +1,76 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-15</artifactId>
|
||||
<name>core-java-15</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<release>${maven.compiler.release}</release>
|
||||
<compilerArgs>--enable-preview</compilerArgs>
|
||||
<source>14</source>
|
||||
<target>14</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${surefire.plugin.version}</version>
|
||||
<configuration>
|
||||
<argLine>--enable-preview</argLine>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.release>15</maven.compiler.release>
|
||||
<assertj.version>3.17.2</assertj.version>
|
||||
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
|
||||
<surefire.plugin.version>3.0.0-M3</surefire.plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,49 @@
|
|||
package com.baeldung.sealed.alternative;
|
||||
|
||||
public class Vehicles {
|
||||
|
||||
abstract static class Vehicle {
|
||||
|
||||
private final String registrationNumber;
|
||||
|
||||
public Vehicle(String registrationNumber) {
|
||||
this.registrationNumber = registrationNumber;
|
||||
}
|
||||
|
||||
public String getRegistrationNumber() {
|
||||
return registrationNumber;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static final class Car extends Vehicle {
|
||||
|
||||
private final int numberOfSeats;
|
||||
|
||||
public Car(int numberOfSeats, String registrationNumber) {
|
||||
super(registrationNumber);
|
||||
this.numberOfSeats = numberOfSeats;
|
||||
}
|
||||
|
||||
public int getNumberOfSeats() {
|
||||
return numberOfSeats;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static final class Truck extends Vehicle {
|
||||
|
||||
private final int loadCapacity;
|
||||
|
||||
public Truck(int loadCapacity, String registrationNumber) {
|
||||
super(registrationNumber);
|
||||
this.loadCapacity = loadCapacity;
|
||||
}
|
||||
|
||||
public int getLoadCapacity() {
|
||||
return loadCapacity;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.sealed.classes;
|
||||
|
||||
public non-sealed class Car extends Vehicle implements Service {
|
||||
|
||||
private final int numberOfSeats;
|
||||
|
||||
public Car(int numberOfSeats, String registrationNumber) {
|
||||
super(registrationNumber);
|
||||
this.numberOfSeats = numberOfSeats;
|
||||
}
|
||||
|
||||
public int getNumberOfSeats() {
|
||||
return numberOfSeats;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMaxServiceIntervalInMonths() {
|
||||
return 12;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung.sealed.classes;
|
||||
|
||||
public sealed interface Service permits Car, Truck {
|
||||
|
||||
int getMaxServiceIntervalInMonths();
|
||||
|
||||
default int getMaxDistanceBetweenServicesInKilometers() {
|
||||
return 100000;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.sealed.classes;
|
||||
|
||||
public final class Truck extends Vehicle implements Service {
|
||||
|
||||
private final int loadCapacity;
|
||||
|
||||
public Truck(int loadCapacity, String registrationNumber) {
|
||||
super(registrationNumber);
|
||||
this.loadCapacity = loadCapacity;
|
||||
}
|
||||
|
||||
public int getLoadCapacity() {
|
||||
return loadCapacity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMaxServiceIntervalInMonths() {
|
||||
return 18;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.sealed.classes;
|
||||
|
||||
public abstract sealed class Vehicle permits Car, Truck {
|
||||
|
||||
protected final String registrationNumber;
|
||||
|
||||
public Vehicle(String registrationNumber) {
|
||||
this.registrationNumber = registrationNumber;
|
||||
}
|
||||
|
||||
public String getRegistrationNumber() {
|
||||
return registrationNumber;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.sealed.records;
|
||||
|
||||
public record Car(int numberOfSeats, String registrationNumber) implements Vehicle {
|
||||
|
||||
@Override
|
||||
public String getRegistrationNumber() {
|
||||
return registrationNumber;
|
||||
}
|
||||
|
||||
public int getNumberOfSeats() {
|
||||
return numberOfSeats;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.sealed.records;
|
||||
|
||||
public record Truck(int loadCapacity, String registrationNumber) implements Vehicle {
|
||||
|
||||
@Override
|
||||
public String getRegistrationNumber() {
|
||||
return registrationNumber;
|
||||
}
|
||||
|
||||
public int getLoadCapacity() {
|
||||
return loadCapacity;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.sealed.records;
|
||||
|
||||
public sealed interface Vehicle permits Car, Truck {
|
||||
|
||||
String getRegistrationNumber();
|
||||
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.whatsnew.records;
|
||||
|
||||
/**
|
||||
* Java record with a header indicating 2 fields.
|
||||
*/
|
||||
public record Person(String name, int age) {
|
||||
/**
|
||||
* Public constructor that does some basic validation.
|
||||
*/
|
||||
public Person {
|
||||
if (age < 0) {
|
||||
throw new IllegalArgumentException("Age cannot be negative");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.whatsnew.sealedclasses;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public non-sealed class Employee extends Person {
|
||||
public Date getHiredDate() {
|
||||
return new Date();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
package com.baeldung.whatsnew.sealedclasses;
|
||||
|
||||
public final class Manager extends Person {
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.whatsnew.sealedclasses;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public sealed class Person permits Employee, Manager {
|
||||
/**
|
||||
* Demonstration of pattern matching for instanceof
|
||||
*
|
||||
* @param person A Person object
|
||||
* @return
|
||||
*/
|
||||
public static void patternMatchingDemo(Person person) {
|
||||
if(person instanceof Employee employee) {
|
||||
Date hiredDate = employee.getHiredDate();
|
||||
}
|
||||
|
||||
if(person instanceof Employee employee && employee.getHiredDate() != null) {
|
||||
Date hiredDate = employee.getHiredDate();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,76 @@
|
|||
package com.baeldung.sealed.classes;
|
||||
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.constant.ClassDesc;
|
||||
|
||||
public class VehicleUnitTest {
|
||||
|
||||
private static Vehicle car;
|
||||
private static Vehicle truck;
|
||||
|
||||
@BeforeAll
|
||||
public static void createInstances() {
|
||||
car = new Car(5, "VZ500DA");
|
||||
truck = new Truck(19000, "VZ600TA");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCar_whenUsingReflectionAPI_thenSuperClassIsSealed() {
|
||||
Assertions.assertThat(car.getClass().isSealed()).isEqualTo(false);
|
||||
Assertions.assertThat(car.getClass().getSuperclass().isSealed()).isEqualTo(true);
|
||||
Assertions.assertThat(car.getClass().getSuperclass().permittedSubclasses())
|
||||
.contains(ClassDesc.of(car.getClass().getCanonicalName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTruck_whenUsingReflectionAPI_thenSuperClassIsSealed() {
|
||||
Assertions.assertThat(truck.getClass().isSealed()).isEqualTo(false);
|
||||
Assertions.assertThat(truck.getClass().getSuperclass().isSealed()).isEqualTo(true);
|
||||
Assertions.assertThat(truck.getClass().getSuperclass().permittedSubclasses())
|
||||
.contains(ClassDesc.of(truck.getClass().getCanonicalName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCar_whenGettingPropertyTraditionalWay_thenNumberOfSeatsPropertyIsReturned() {
|
||||
Assertions.assertThat(getPropertyTraditionalWay(car)).isEqualTo(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCar_whenGettingPropertyViaPatternMatching_thenNumberOfSeatsPropertyIsReturned() {
|
||||
Assertions.assertThat(getPropertyViaPatternMatching(car)).isEqualTo(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTruck_whenGettingPropertyTraditionalWay_thenLoadCapacityIsReturned() {
|
||||
Assertions.assertThat(getPropertyTraditionalWay(truck)).isEqualTo(19000);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTruck_whenGettingPropertyViaPatternMatching_thenLoadCapacityIsReturned() {
|
||||
Assertions.assertThat(getPropertyViaPatternMatching(truck)).isEqualTo(19000);
|
||||
}
|
||||
|
||||
private int getPropertyTraditionalWay(Vehicle vehicle) {
|
||||
if (vehicle instanceof Car) {
|
||||
return ((Car) vehicle).getNumberOfSeats();
|
||||
} else if (vehicle instanceof Truck) {
|
||||
return ((Truck) vehicle).getLoadCapacity();
|
||||
} else {
|
||||
throw new RuntimeException("Unknown instance of Vehicle");
|
||||
}
|
||||
}
|
||||
|
||||
private int getPropertyViaPatternMatching(Vehicle vehicle) {
|
||||
if (vehicle instanceof Car car) {
|
||||
return car.getNumberOfSeats();
|
||||
} else if (vehicle instanceof Truck truck) {
|
||||
return truck.getLoadCapacity();
|
||||
} else {
|
||||
throw new RuntimeException("Unknown instance of Vehicle");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,76 @@
|
|||
package com.baeldung.sealed.records;
|
||||
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.constant.ClassDesc;
|
||||
|
||||
public class VehicleUnitTest {
|
||||
|
||||
private static Vehicle car;
|
||||
private static Vehicle truck;
|
||||
|
||||
@BeforeAll
|
||||
public static void createInstances() {
|
||||
car = new Car(4, "VZ500DA");
|
||||
truck = new Truck(16000, "VZ600TA");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCar_whenUsingReflectionAPI_thenInterfaceIsSealed() {
|
||||
Assertions.assertThat(car.getClass().isSealed()).isEqualTo(false);
|
||||
Assertions.assertThat(car.getClass().getInterfaces()[0].isSealed()).isEqualTo(true);
|
||||
Assertions.assertThat(car.getClass().getInterfaces()[0].permittedSubclasses())
|
||||
.contains(ClassDesc.of(car.getClass().getCanonicalName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTruck_whenUsingReflectionAPI_thenInterfaceIsSealed() {
|
||||
Assertions.assertThat(truck.getClass().isSealed()).isEqualTo(false);
|
||||
Assertions.assertThat(truck.getClass().getInterfaces()[0].isSealed()).isEqualTo(true);
|
||||
Assertions.assertThat(truck.getClass().getInterfaces()[0].permittedSubclasses())
|
||||
.contains(ClassDesc.of(truck.getClass().getCanonicalName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCar_whenGettingPropertyTraditionalWay_thenNumberOfSeatsPropertyIsReturned() {
|
||||
Assertions.assertThat(getPropertyTraditionalWay(car)).isEqualTo(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCar_whenGettingPropertyViaPatternMatching_thenNumberOfSeatsPropertyIsReturned() {
|
||||
Assertions.assertThat(getPropertyViaPatternMatching(car)).isEqualTo(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTruck_whenGettingPropertyTraditionalWay_thenLoadCapacityIsReturned() {
|
||||
Assertions.assertThat(getPropertyTraditionalWay(truck)).isEqualTo(16000);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTruck_whenGettingPropertyViaPatternMatching_thenLoadCapacityIsReturned() {
|
||||
Assertions.assertThat(getPropertyViaPatternMatching(truck)).isEqualTo(16000);
|
||||
}
|
||||
|
||||
private int getPropertyTraditionalWay(Vehicle vehicle) {
|
||||
if (vehicle instanceof Car) {
|
||||
return ((Car) vehicle).getNumberOfSeats();
|
||||
} else if (vehicle instanceof Truck) {
|
||||
return ((Truck) vehicle).getLoadCapacity();
|
||||
} else {
|
||||
throw new RuntimeException("Unknown instance of Vehicle");
|
||||
}
|
||||
}
|
||||
|
||||
private int getPropertyViaPatternMatching(Vehicle vehicle) {
|
||||
if (vehicle instanceof Car car) {
|
||||
return car.getNumberOfSeats();
|
||||
} else if (vehicle instanceof Truck truck) {
|
||||
return truck.getLoadCapacity();
|
||||
} else {
|
||||
throw new RuntimeException("Unknown instance of Vehicle");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -2,8 +2,7 @@ package com.baeldung.java9.modules;
|
|||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.hamcrest.CoreMatchers.nullValue;
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.hamcrest.collection.IsEmptyCollection.empty;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
|
@ -74,7 +73,6 @@ public class ModuleAPIUnitTest {
|
|||
ModuleLayer javaBaseModuleLayer = javaBaseModule.getLayer();
|
||||
|
||||
assertTrue(javaBaseModuleLayer.configuration().findModule(JAVA_BASE_MODULE_NAME).isPresent());
|
||||
assertThat(javaBaseModuleLayer.configuration().modules().size(), is(78));
|
||||
assertTrue(javaBaseModuleLayer.parents().get(0).configuration().parents().isEmpty());
|
||||
}
|
||||
|
||||
|
@ -108,8 +106,7 @@ public class ModuleAPIUnitTest {
|
|||
.collect(Collectors.toSet());
|
||||
|
||||
assertThat(javaBaseRequires, empty());
|
||||
assertThat(javaSqlRequires.size(), is(3));
|
||||
assertThat(javaSqlRequiresNames, containsInAnyOrder("java.base", "java.xml", "java.logging"));
|
||||
assertThat(javaSqlRequiresNames, hasItems("java.base", "java.xml", "java.logging"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -127,16 +124,13 @@ public class ModuleAPIUnitTest {
|
|||
|
||||
@Test
|
||||
public void givenModules_whenAccessingModuleDescriptorExports_thenExportsAreReturned() {
|
||||
Set<Exports> javaBaseExports = javaBaseModule.getDescriptor().exports();
|
||||
Set<Exports> javaSqlExports = javaSqlModule.getDescriptor().exports();
|
||||
|
||||
Set<String> javaSqlExportsSource = javaSqlExports.stream()
|
||||
.map(Exports::source)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
assertThat(javaBaseExports.size(), is(108));
|
||||
assertThat(javaSqlExports.size(), is(3));
|
||||
assertThat(javaSqlExportsSource, containsInAnyOrder("java.sql", "javax.transaction.xa", "javax.sql"));
|
||||
assertThat(javaSqlExportsSource, hasItems("java.sql", "javax.sql"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -144,7 +138,6 @@ public class ModuleAPIUnitTest {
|
|||
Set<String> javaBaseUses = javaBaseModule.getDescriptor().uses();
|
||||
Set<String> javaSqlUses = javaSqlModule.getDescriptor().uses();
|
||||
|
||||
assertThat(javaBaseUses.size(), is(34));
|
||||
assertThat(javaSqlUses, contains("java.sql.Driver"));
|
||||
}
|
||||
|
||||
|
|
|
@ -47,12 +47,12 @@
|
|||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.11</version>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>2.7</version>
|
||||
<version>${commons-io.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
|
|
@ -7,3 +7,4 @@ This module contains complete guides about arrays in Java
|
|||
- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays)
|
||||
- [What is \[Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array)
|
||||
- [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception)
|
||||
- [Creating a Generic Array in Java](https://www.baeldung.com/java-generic-array)
|
||||
|
|
|
@ -0,0 +1,30 @@
|
|||
package com.baeldung.genericarrays;
|
||||
|
||||
import java.lang.reflect.Array;
|
||||
|
||||
public class MyStack<E> {
|
||||
private E[] elements;
|
||||
private int size = 0;
|
||||
|
||||
public MyStack(Class<E> clazz, int capacity) {
|
||||
elements = (E[]) Array.newInstance(clazz, capacity);
|
||||
}
|
||||
|
||||
public void push(E item) {
|
||||
if (size == elements.length) {
|
||||
throw new RuntimeException();
|
||||
}
|
||||
elements[size++] = item;
|
||||
}
|
||||
|
||||
public E pop() {
|
||||
if (size == 0) {
|
||||
throw new RuntimeException();
|
||||
}
|
||||
return elements[--size];
|
||||
}
|
||||
|
||||
public E[] getAllElements() {
|
||||
return elements;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.genericarrays;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class ListToArrayUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenListOfItems_whenToArray_thenReturnArrayOfItems() {
|
||||
List<String> items = new LinkedList<>();
|
||||
items.add("first item");
|
||||
items.add("second item");
|
||||
|
||||
String[] itemsAsArray = items.toArray(new String[0]);
|
||||
|
||||
assertEquals("first item", itemsAsArray[0]);
|
||||
assertEquals("second item", itemsAsArray[1]);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
package com.baeldung.genericarrays;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class MyStackUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenStackWithTwoItems_whenPop_thenReturnLastAdded() {
|
||||
MyStack<String> myStack = new MyStack<>(String.class, 2);
|
||||
myStack.push("hello");
|
||||
myStack.push("example");
|
||||
|
||||
assertEquals("example", myStack.pop());
|
||||
}
|
||||
|
||||
@Test (expected = RuntimeException.class)
|
||||
public void givenStackWithFixedCapacity_whenExceedCapacity_thenThrowException() {
|
||||
MyStack<Integer> myStack = new MyStack<>(Integer.class, 2);
|
||||
myStack.push(100);
|
||||
myStack.push(200);
|
||||
myStack.push(300);
|
||||
}
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
public void givenStack_whenPopOnEmptyStack_thenThrowException() {
|
||||
MyStack<Integer> myStack = new MyStack<>(Integer.class, 1);
|
||||
myStack.push(100);
|
||||
myStack.pop();
|
||||
myStack.pop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStackWithItems_whenGetAllElements_thenSizeShouldEqualTotal() {
|
||||
MyStack<String> myStack = new MyStack<>(String.class, 2);
|
||||
myStack.push("hello");
|
||||
myStack.push("example");
|
||||
|
||||
String[] items = myStack.getAllElements();
|
||||
|
||||
assertEquals(2, items.length);
|
||||
}
|
||||
}
|
|
@ -29,8 +29,6 @@
|
|||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<commons-lang3.version>3.9</commons-lang3.version>
|
||||
|
||||
<assertj-core.version>3.10.0</assertj-core.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -68,11 +68,7 @@
|
|||
|
||||
<properties>
|
||||
<shade.plugin.version>3.2.0</shade.plugin.version>
|
||||
|
||||
<commons-lang3.version>3.9</commons-lang3.version>
|
||||
|
||||
<jmh.version>1.19</jmh.version>
|
||||
|
||||
<assertj-core.version>3.10.0</assertj-core.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -76,12 +76,8 @@
|
|||
|
||||
<properties>
|
||||
<shade.plugin.version>3.2.0</shade.plugin.version>
|
||||
|
||||
<commons-lang3.version>3.9</commons-lang3.version>
|
||||
<guava.version>28.2-jre</guava.version>
|
||||
|
||||
<jmh.version>1.19</jmh.version>
|
||||
|
||||
<assertj-core.version>3.10.0</assertj-core.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -0,0 +1,6 @@
|
|||
## Core Java Character
|
||||
|
||||
This module contains articles about Java Character Class
|
||||
|
||||
### Relevant Articles:
|
||||
- [Character#isAlphabetic vs Character#isLetter](https://www.baeldung.com/java-character-isletter-isalphabetic)
|
|
@ -0,0 +1,42 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-char</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-char</name>
|
||||
<packaging>jar</packaging>
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${openjdk.jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${openjdk.jmh.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<openjdk.jmh.version>1.19</openjdk.jmh.version>
|
||||
<assertj.version>3.11.1</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,38 @@
|
|||
package com.baeldung.character;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class CharacterGeneralCategoryTypeUnitTest {
|
||||
@Test
|
||||
public void givenACharacter_whenUpperCaseLetter_thenAssertTrue() {
|
||||
assertEquals(Character.UPPERCASE_LETTER, Character.getType('U'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenLowerCaseLetter_thenAssertTrue() {
|
||||
assertEquals(Character.LOWERCASE_LETTER, Character.getType('u'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenTitleCaseLetter_thenAssertTrue() {
|
||||
assertEquals(Character.TITLECASE_LETTER, Character.getType('\u01f2'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenModifierLetter_thenAssertTrue() {
|
||||
assertEquals(Character.MODIFIER_LETTER, Character.getType('\u02b0'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenOtherLetter_thenAssertTrue() {
|
||||
assertEquals(Character.OTHER_LETTER, Character.getType('\u05d0'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenLetterNumber_thenAssertTrue() {
|
||||
assertEquals(Character.LETTER_NUMBER, Character.getType('\u2164'));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
package com.baeldung.character;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
public class IsLetterOrAlphabetUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenUpperCaseLetter_thenAssertIsAlphabeticTrue() {
|
||||
assertTrue(Character.isAlphabetic('A'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenTitleCaseLetter_thenAssertIsAlphabeticTrue() {
|
||||
assertTrue(Character.isAlphabetic('\u01f2'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenLowerCaseLetter_thenAssertIsLetterTrue() {
|
||||
assertTrue(Character.isAlphabetic('a'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenModifierLetter_thenAssertIsLetterTrue() {
|
||||
assertTrue(Character.isAlphabetic('\u02b0'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenLetter_thenAssertIsLetterTrue() {
|
||||
assertTrue(Character.isLetter('a'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenLetter_thenAssertIsAlphabeticTrue() {
|
||||
assertTrue(Character.isAlphabetic('a'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenAlphabeticAndNotLetter_thenAssertIsLetterFalse() {
|
||||
assertFalse(Character.isLetter('\u2164'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenAlphabeticAndNotLetter_thenAssertIsAlphabeticTrue() {
|
||||
assertTrue(Character.isAlphabetic('\u2164'));
|
||||
}
|
||||
}
|
|
@ -14,3 +14,4 @@
|
|||
- [Convert an Array of Primitives to a List](https://www.baeldung.com/java-primitive-array-to-list)
|
||||
- [A Guide to BitSet in Java](https://www.baeldung.com/java-bitset)
|
||||
- [Get the First Key and Value From a HashMap](https://www.baeldung.com/java-hashmap-get-first-entry)
|
||||
- [Performance of removeAll() in a HashSet](https://www.baeldung.com/java-hashset-removeall-performance)
|
||||
|
|
|
@ -35,7 +35,7 @@
|
|||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.10</version>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
|
|
@ -0,0 +1,7 @@
|
|||
=========
|
||||
|
||||
## Core Java Collections Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [ArrayList vs. LinkedList vs. HashMap in Java](https://www.baeldung.com/java-arraylist-vs-linkedlist-vs-hashmap)
|
|
@ -0,0 +1,31 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-collections-4</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-collections-4</name>
|
||||
<packaging>jar</packaging>
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<assertj.version>3.18.0</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,30 @@
|
|||
package com.baeldung.collections.comparation;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class ArrayListUnitTest {
|
||||
|
||||
@Test
|
||||
void givenArrayList_whenItemAddedToSpecificIndex_thenItCanBeRetrieved() {
|
||||
List<String> list = new ArrayList<>();
|
||||
list.add("Daniel");
|
||||
list.add(0, "Marko");
|
||||
assertThat(list).hasSize(2);
|
||||
assertThat(list.get(0)).isEqualTo("Marko");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayList_whenItemRemovedViaIndex_thenListSizeIsReduced() {
|
||||
List<String> list = new ArrayList<>(Arrays.asList("Daniel", "Marko"));
|
||||
list.remove(1);
|
||||
assertThat(list).hasSize(1);
|
||||
assertThat(list).doesNotContain("Marko");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.collections.comparation;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class HashMapUnitTest {
|
||||
|
||||
@Test
|
||||
void givenHashMap_whenItemAddedByKey_thenItCanBeRetrieved() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("123456", "Daniel");
|
||||
map.put("654321", "Marko");
|
||||
assertThat(map.get("654321")).isEqualTo("Marko");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenHashMap_whenItemRemovedByKey_thenMapSizeIsReduced() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("123456", "Daniel");
|
||||
map.put("654321", "Marko");
|
||||
map.remove("654321");
|
||||
assertThat(map).hasSize(1);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.collections.comparation;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class LinkedListUnitTest {
|
||||
|
||||
@Test
|
||||
void givenLinkedList_whenItemIsAppended_thenItCanBeRetrieved() {
|
||||
LinkedList<String> list = new LinkedList<>();
|
||||
list.addLast("Daniel");
|
||||
list.addFirst("Marko");
|
||||
assertThat(list).hasSize(2);
|
||||
assertThat(list.getLast()).isEqualTo("Daniel");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenLinkedList_whenItemIsRemoved_thenListSizeIsReduced() {
|
||||
LinkedList<String> list = new LinkedList<>(Arrays.asList("Daniel", "Marko", "David"));
|
||||
list.removeFirst();
|
||||
list.removeLast();
|
||||
assertThat(list).hasSize(1);
|
||||
assertThat(list).containsExactly("Marko");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenLinkedList_whenItemInserted_thenItCanBeRetrievedAndDeleted() {
|
||||
LinkedList<String> list = new LinkedList<>();
|
||||
list.push("Daniel");
|
||||
list.push("Marko");
|
||||
assertThat(list.poll()).isEqualTo("Marko");
|
||||
assertThat(list).hasSize(1);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.collections.comparation;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
class ListVsMapUnitTest {
|
||||
|
||||
@Test
|
||||
void givenList_whenIteratingTroughValues_thenEachValueIsPresent() {
|
||||
List<String> list = new ArrayList<>();
|
||||
list.add("Daniel");
|
||||
list.add("Marko");
|
||||
for (String name : list) {
|
||||
assertThat(name).isIn(list);
|
||||
}
|
||||
assertThat(list).containsExactly("Daniel", "Marko");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenIteratingTroughValues_thenEachValueIsPresent() {
|
||||
Map<Integer, String> map = new HashMap<>();
|
||||
map.put(1, "Daniel");
|
||||
map.put(2, "Marko");
|
||||
for (String name : map.values()) {
|
||||
assertThat(name).isIn(map.values());
|
||||
}
|
||||
assertThat(map.values()).containsExactlyInAnyOrder("Daniel", "Marko");
|
||||
}
|
||||
|
||||
}
|
|
@ -8,4 +8,4 @@ This module contains articles about the Java ArrayList collection
|
|||
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
|
||||
- [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist)
|
||||
- [Removing an Element From an ArrayList](https://www.baeldung.com/java-arraylist-remove-element)
|
||||
|
||||
- [The Capacity of an ArrayList vs the Size of an Array in Java](https://www.baeldung.com/java-list-capacity-array-size)
|
||||
|
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.listcapacityvsarraysize;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class ArrayCreatorUnitTest {
|
||||
|
||||
@Test
|
||||
void whenSizeOfAnArrayIsNonZero_thenReturnNewArrayOfGivenSize() {
|
||||
Integer[] array = new Integer[10];
|
||||
assertEquals(10, array.length);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenSizeOfAnArrayIsLessThanZero_thenThrowException() {
|
||||
assertThrows(NegativeArraySizeException.class, () -> { Integer[] array = new Integer[-1]; });
|
||||
}
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.listcapacityvsarraysize;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ArrayListCreatorUnitTest {
|
||||
|
||||
@Test
|
||||
void givenValidCapacityOfList_whenCreateListInvoked_thenCreateNewArrayListWithGivenCapacity() {
|
||||
ArrayList<Integer> list = new ArrayList<>(100);
|
||||
|
||||
assertNotNull(list);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInvalidCapacityOfList_whenCreateListInvoked_thenThrowException() {
|
||||
assertThrows(IllegalArgumentException.class, () -> new ArrayList<>(-1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenValidCapacityOfList_whenCreateListInvoked_thenCreateNewArrayListWithSizeZero() {
|
||||
assertEquals(0, new ArrayList<Integer>(100).size());
|
||||
}
|
||||
}
|
|
@ -36,7 +36,6 @@
|
|||
|
||||
<properties>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<assertj.version>3.11.1</assertj.version>
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -6,4 +6,5 @@ This module contains articles about Map data structures in Java.
|
|||
- [Java TreeMap vs HashMap](https://www.baeldung.com/java-treemap-vs-hashmap)
|
||||
- [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps)
|
||||
- [The Map.computeIfAbsent() Method](https://www.baeldung.com/java-map-computeifabsent)
|
||||
- [Collections.synchronizedMap vs. ConcurrentHashMap](https://www.baeldung.com/java-synchronizedmap-vs-concurrenthashmap)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-2)
|
||||
|
|
|
@ -15,7 +15,11 @@
|
|||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
|
|
|
@ -0,0 +1,96 @@
|
|||
package com.baeldung.map.concurrenthashmap;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Fork;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.Setup;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
import org.openjdk.jmh.annotations.Threads;
|
||||
import org.openjdk.jmh.annotations.Warmup;
|
||||
|
||||
@Fork(5)
|
||||
@Threads(10)
|
||||
@Warmup(iterations = 5)
|
||||
@State(Scope.Benchmark)
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public class MapPerformanceComparison {
|
||||
|
||||
private int TEST_NO_ITEMS;
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
org.openjdk.jmh.Main.main(args);
|
||||
}
|
||||
|
||||
@Setup
|
||||
public void setup() {
|
||||
TEST_NO_ITEMS = 1000;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void randomReadAndWriteSynchronizedMap() {
|
||||
Map<String, Integer> map = Collections.synchronizedMap(new HashMap<String, Integer>());
|
||||
performReadAndWriteTest(map);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void randomReadAndWriteConcurrentHashMap() {
|
||||
Map<String, Integer> map = new ConcurrentHashMap<>();
|
||||
performReadAndWriteTest(map);
|
||||
}
|
||||
|
||||
private void performReadAndWriteTest(final Map<String, Integer> map) {
|
||||
for (int i = 0; i < TEST_NO_ITEMS; i++) {
|
||||
Integer randNumber = (int) Math.ceil(Math.random() * TEST_NO_ITEMS);
|
||||
map.get(String.valueOf(randNumber));
|
||||
map.put(String.valueOf(randNumber), randNumber);
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void randomWriteSynchronizedMap() {
|
||||
Map<String, Integer> map = Collections.synchronizedMap(new HashMap<String, Integer>());
|
||||
performWriteTest(map);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void randomWriteConcurrentHashMap() {
|
||||
Map<String, Integer> map = new ConcurrentHashMap<>();
|
||||
performWriteTest(map);
|
||||
}
|
||||
|
||||
private void performWriteTest(final Map<String, Integer> map) {
|
||||
for (int i = 0; i < TEST_NO_ITEMS; i++) {
|
||||
Integer randNumber = (int) Math.ceil(Math.random() * TEST_NO_ITEMS);
|
||||
map.put(String.valueOf(randNumber), randNumber);
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void randomReadSynchronizedMap() {
|
||||
Map<String, Integer> map = Collections.synchronizedMap(new HashMap<String, Integer>());
|
||||
performReadTest(map);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void randomReadConcurrentHashMap() {
|
||||
Map<String, Integer> map = new ConcurrentHashMap<>();
|
||||
performReadTest(map);
|
||||
}
|
||||
|
||||
private void performReadTest(final Map<String, Integer> map) {
|
||||
for (int i = 0; i < TEST_NO_ITEMS; i++) {
|
||||
Integer randNumber = (int) Math.ceil(Math.random() * TEST_NO_ITEMS);
|
||||
map.get(String.valueOf(randNumber));
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,70 @@
|
|||
package com.baeldung.map.concurrenthashmap;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.ConcurrentModificationException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.TreeMap;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ConcurrentModificationErrorUnitTest {
|
||||
|
||||
@Test(expected = ConcurrentModificationException.class)
|
||||
public void whenRemoveAndAddOnHashMap_thenConcurrentModificationError() {
|
||||
Map<Integer, String> map = new HashMap<>();
|
||||
map.put(1, "baeldung");
|
||||
map.put(2, "HashMap");
|
||||
Map<Integer, String> synchronizedMap = Collections.synchronizedMap(map);
|
||||
Iterator<Entry<Integer, String>> iterator = synchronizedMap.entrySet().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
synchronizedMap.put(3, "Modification");
|
||||
iterator.next();
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expected = ConcurrentModificationException.class)
|
||||
public void whenRemoveAndAddOnTreeMap_thenConcurrentModificationError() {
|
||||
Map<Integer, String> map = new TreeMap<>();
|
||||
map.put(1, "baeldung");
|
||||
map.put(2, "HashMap");
|
||||
Map<Integer, String> synchronizedMap = Collections.synchronizedMap(map);
|
||||
Iterator<Entry<Integer, String>> iterator = synchronizedMap.entrySet().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
synchronizedMap.put(3, "Modification");
|
||||
iterator.next();
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expected = ConcurrentModificationException.class)
|
||||
public void whenRemoveAndAddOnLinkedHashMap_thenConcurrentModificationError() {
|
||||
Map<Integer, String> map = new LinkedHashMap<>();
|
||||
map.put(1, "baeldung");
|
||||
map.put(2, "HashMap");
|
||||
Map<Integer, String> synchronizedMap = Collections.synchronizedMap(map);
|
||||
Iterator<Entry<Integer, String>> iterator = synchronizedMap.entrySet().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
synchronizedMap.put(3, "Modification");
|
||||
iterator.next();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveAndAddOnConcurrentHashMap_thenNoError() {
|
||||
Map<Integer, String> map = new ConcurrentHashMap<>();
|
||||
map.put(1, "baeldung");
|
||||
map.put(2, "HashMap");
|
||||
Iterator<Entry<Integer, String>> iterator = map.entrySet().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
map.put(3, "Modification");
|
||||
iterator.next();
|
||||
}
|
||||
|
||||
Assert.assertEquals(3, map.size());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,73 @@
|
|||
package com.baeldung.map.concurrenthashmap;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class NullAllowInMapUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenHashMapBackedSynchronizedMap_whenNullAsKey_thenNoError() {
|
||||
Map<String, Integer> map = Collections
|
||||
.synchronizedMap(new HashMap<String, Integer>());
|
||||
map.put(null, 1);
|
||||
Assert.assertTrue(map.get(null).equals(1));
|
||||
}
|
||||
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void givenTreeMapBackedSynchronizedMap_whenNullAsKey_thenException() {
|
||||
Map<String, Integer> map = Collections.synchronizedMap(new TreeMap<String, Integer>());
|
||||
map.put(null, 1);
|
||||
Assert.assertTrue(map.get(null).equals(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLinkedHashMapBackedSynchronizedMap_whenNullAsKey_thenNoError() {
|
||||
Map<String, Integer> map = Collections
|
||||
.synchronizedMap(new LinkedHashMap<String, Integer>());
|
||||
map.put(null, 1);
|
||||
Assert.assertTrue(map.get(null).equals(1));
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void givenConcurrentHasMap_whenNullAsKey_thenException() {
|
||||
Map<String, Integer> map = new ConcurrentHashMap<>();
|
||||
map.put(null, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHashMapBackedSynchronizedMap_whenNullAsValue_thenNoError() {
|
||||
Map<String, Integer> map = Collections.synchronizedMap(new HashMap<String, Integer>());
|
||||
map.put("1", null);
|
||||
Assert.assertNull(map.get("1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTreeMapBackedSynchronizedMap_whenNullAsValue_thenNoError() {
|
||||
Map<String, Integer> map = Collections.synchronizedMap(new TreeMap<String, Integer>());
|
||||
map.put("1", null);
|
||||
Assert.assertNull(map.get("1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLinkedHashMapBackedSynchronizedMap_whenNullAsValue_thenNoError() {
|
||||
Map<String, Integer> map = Collections
|
||||
.synchronizedMap(new LinkedHashMap<String, Integer>());
|
||||
map.put("1", null);
|
||||
Assert.assertNull(map.get("1"));
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void givenConcurrentHasMap_whenNullAsValue_thenException() {
|
||||
Map<String, Integer> map = new ConcurrentHashMap<>();
|
||||
map.put("1", null);
|
||||
}
|
||||
|
||||
}
|
|
@ -10,11 +10,17 @@ import org.openjdk.jcstress.annotations.Outcome;
|
|||
import org.openjdk.jcstress.annotations.State;
|
||||
import org.openjdk.jcstress.infra.results.I_Result;
|
||||
|
||||
/**
|
||||
* This is defined as a manual test because it tries to simulate the race conditions
|
||||
* in a concurrent program that is poorly designed and hence may fail nondeterministically.
|
||||
* This will help the CI jobs to ignore these tests and a developer to run them manually.
|
||||
*
|
||||
*/
|
||||
@JCStressTest
|
||||
@Outcome(id = "1", expect = ACCEPTABLE_INTERESTING, desc = "One update lost.")
|
||||
@Outcome(id = "2", expect = ACCEPTABLE, desc = "Both updates.")
|
||||
@State
|
||||
public class MyCounterJCStressUnitTest {
|
||||
public class MyCounterJCStressManualTest {
|
||||
|
||||
private MyCounter counter;
|
||||
|
|
@ -1,12 +1,17 @@
|
|||
package com.baeldung.concurrent;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import edu.umd.cs.mtc.MultithreadedTestCase;
|
||||
import edu.umd.cs.mtc.TestFramework;
|
||||
|
||||
public class MyCounterMultithreadedTCUnitTest extends MultithreadedTestCase {
|
||||
/**
|
||||
* This is defined as a manual test because it tries to simulate the race conditions
|
||||
* in a concurrent program that is poorly designed and hence may fail nondeterministically.
|
||||
* This will help the CI jobs to ignore these tests and a developer to run them manually.
|
||||
*
|
||||
*/
|
||||
public class MyCounterMultithreadedTCManualTest extends MultithreadedTestCase {
|
||||
|
||||
private MyCounter counter;
|
||||
|
||||
|
@ -29,9 +34,8 @@ public class MyCounterMultithreadedTCUnitTest extends MultithreadedTestCase {
|
|||
assertEquals(2, counter.getCount());
|
||||
}
|
||||
|
||||
@Ignore
|
||||
@Test
|
||||
public void testCounter() throws Throwable {
|
||||
TestFramework.runManyTimes(new MyCounterMultithreadedTCUnitTest(), 1000);
|
||||
TestFramework.runManyTimes(new MyCounterMultithreadedTCManualTest(), 1000);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
package com.baeldung.concurrent;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* This is defined as a manual test because it tries to simulate the race conditions
|
||||
* in a concurrent program that is poorly designed and hence may fail nondeterministically.
|
||||
* This will help the CI jobs to ignore these tests and a developer to run them manually.
|
||||
*
|
||||
*/
|
||||
public class MyCounterSimpleManualTest {
|
||||
|
||||
@Test
|
||||
public void testCounter() {
|
||||
MyCounter counter = new MyCounter();
|
||||
for (int i = 0; i < 500; i++)
|
||||
counter.increment();
|
||||
assertEquals(500, counter.getCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCounterWithConcurrency() throws InterruptedException {
|
||||
int numberOfThreads = 100;
|
||||
ExecutorService service = Executors.newFixedThreadPool(10);
|
||||
CountDownLatch latch = new CountDownLatch(numberOfThreads);
|
||||
MyCounter counter = new MyCounter();
|
||||
for (int i = 0; i < numberOfThreads; i++) {
|
||||
service.execute(() -> {
|
||||
counter.increment();
|
||||
latch.countDown();
|
||||
});
|
||||
}
|
||||
latch.await();
|
||||
assertEquals(numberOfThreads, counter.getCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSummationWithConcurrencyAndWait() throws InterruptedException {
|
||||
int numberOfThreads = 2;
|
||||
ExecutorService service = Executors.newFixedThreadPool(10);
|
||||
CountDownLatch latch = new CountDownLatch(numberOfThreads);
|
||||
MyCounter counter = new MyCounter();
|
||||
for (int i = 0; i < numberOfThreads; i++) {
|
||||
service.submit(() -> {
|
||||
try {
|
||||
counter.incrementWithWait();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
latch.countDown();
|
||||
});
|
||||
}
|
||||
latch.await();
|
||||
assertEquals(numberOfThreads, counter.getCount());
|
||||
}
|
||||
|
||||
}
|
|
@ -1,60 +0,0 @@
|
|||
package com.baeldung.concurrent;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class MyCounterSimpleUnitTest {
|
||||
|
||||
@Test
|
||||
public void testCounter() {
|
||||
MyCounter counter = new MyCounter();
|
||||
for (int i = 0; i < 500; i++)
|
||||
counter.increment();
|
||||
assertEquals(500, counter.getCount());
|
||||
}
|
||||
|
||||
@Ignore
|
||||
@Test
|
||||
public void testCounterWithConcurrency() throws InterruptedException {
|
||||
int numberOfThreads = 100;
|
||||
ExecutorService service = Executors.newFixedThreadPool(10);
|
||||
CountDownLatch latch = new CountDownLatch(numberOfThreads);
|
||||
MyCounter counter = new MyCounter();
|
||||
for (int i = 0; i < numberOfThreads; i++) {
|
||||
service.execute(() -> {
|
||||
counter.increment();
|
||||
latch.countDown();
|
||||
});
|
||||
}
|
||||
latch.await();
|
||||
assertEquals(numberOfThreads, counter.getCount());
|
||||
}
|
||||
|
||||
@Ignore
|
||||
@Test
|
||||
public void testSummationWithConcurrencyAndWait() throws InterruptedException {
|
||||
int numberOfThreads = 2;
|
||||
ExecutorService service = Executors.newFixedThreadPool(10);
|
||||
CountDownLatch latch = new CountDownLatch(numberOfThreads);
|
||||
MyCounter counter = new MyCounter();
|
||||
for (int i = 0; i < numberOfThreads; i++) {
|
||||
service.submit(() -> {
|
||||
try {
|
||||
counter.incrementWithWait();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
latch.countDown();
|
||||
});
|
||||
}
|
||||
latch.await();
|
||||
assertEquals(numberOfThreads, counter.getCount());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.concurrent;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.code.tempusfugit.concurrency.ConcurrentRule;
|
||||
import com.google.code.tempusfugit.concurrency.RepeatingRule;
|
||||
import com.google.code.tempusfugit.concurrency.annotations.Concurrent;
|
||||
import com.google.code.tempusfugit.concurrency.annotations.Repeating;
|
||||
|
||||
/**
|
||||
* This is defined as a manual test because it tries to simulate the race conditions
|
||||
* in a concurrent program that is poorly designed and hence may fail nondeterministically.
|
||||
* This will help the CI jobs to ignore these tests and a developer to run them manually.
|
||||
*
|
||||
*/
|
||||
public class MyCounterTempusFugitManualTest {
|
||||
|
||||
@Rule
|
||||
public ConcurrentRule concurrently = new ConcurrentRule();
|
||||
@Rule
|
||||
public RepeatingRule rule = new RepeatingRule();
|
||||
|
||||
private static MyCounter counter = new MyCounter();
|
||||
|
||||
@Test
|
||||
@Concurrent(count = 2)
|
||||
@Repeating(repetition = 10)
|
||||
public void runsMultipleTimes() {
|
||||
counter.increment();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void annotatedTestRunsMultipleTimes() throws InterruptedException {
|
||||
assertEquals(counter.getCount(), 20);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,37 +0,0 @@
|
|||
package com.baeldung.concurrent;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.code.tempusfugit.concurrency.ConcurrentRule;
|
||||
import com.google.code.tempusfugit.concurrency.RepeatingRule;
|
||||
import com.google.code.tempusfugit.concurrency.annotations.Concurrent;
|
||||
import com.google.code.tempusfugit.concurrency.annotations.Repeating;
|
||||
|
||||
public class MyCounterTempusFugitUnitTest {
|
||||
|
||||
@Rule
|
||||
public ConcurrentRule concurrently = new ConcurrentRule();
|
||||
@Rule
|
||||
public RepeatingRule rule = new RepeatingRule();
|
||||
|
||||
private static MyCounter counter = new MyCounter();
|
||||
|
||||
@Ignore
|
||||
@Test
|
||||
@Concurrent(count = 2)
|
||||
@Repeating(repetition = 10)
|
||||
public void runsMultipleTimes() {
|
||||
counter.increment();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void annotatedTestRunsMultipleTimes() throws InterruptedException {
|
||||
assertEquals(counter.getCount(), 20);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
package com.baeldung.concurrent;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.testing.threadtester.AnnotatedTestRunner;
|
||||
import com.google.testing.threadtester.ThreadedAfter;
|
||||
import com.google.testing.threadtester.ThreadedBefore;
|
||||
import com.google.testing.threadtester.ThreadedMain;
|
||||
import com.google.testing.threadtester.ThreadedSecondary;
|
||||
|
||||
/**
|
||||
* This is defined as a manual test because it tries to simulate the race conditions
|
||||
* in a concurrent program that is poorly designed and hence may fail nondeterministically.
|
||||
* This will help the CI jobs to ignore these tests and a developer to run them manually.
|
||||
*
|
||||
*/
|
||||
public class MyCounterThreadWeaverManualTest {
|
||||
|
||||
private MyCounter counter;
|
||||
|
||||
@ThreadedBefore
|
||||
public void before() {
|
||||
counter = new MyCounter();
|
||||
}
|
||||
|
||||
@ThreadedMain
|
||||
public void mainThread() {
|
||||
counter.increment();
|
||||
}
|
||||
|
||||
@ThreadedSecondary
|
||||
public void secondThread() {
|
||||
counter.increment();
|
||||
}
|
||||
|
||||
@ThreadedAfter
|
||||
public void after() {
|
||||
assertEquals(2, counter.getCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCounter() {
|
||||
new AnnotatedTestRunner().runTests(this.getClass(), MyCounter.class);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,44 +0,0 @@
|
|||
package com.baeldung.concurrent;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.testing.threadtester.AnnotatedTestRunner;
|
||||
import com.google.testing.threadtester.ThreadedAfter;
|
||||
import com.google.testing.threadtester.ThreadedBefore;
|
||||
import com.google.testing.threadtester.ThreadedMain;
|
||||
import com.google.testing.threadtester.ThreadedSecondary;
|
||||
|
||||
public class MyCounterThreadWeaverUnitTest {
|
||||
|
||||
private MyCounter counter;
|
||||
|
||||
@ThreadedBefore
|
||||
public void before() {
|
||||
counter = new MyCounter();
|
||||
}
|
||||
|
||||
@ThreadedMain
|
||||
public void mainThread() {
|
||||
counter.increment();
|
||||
}
|
||||
|
||||
@ThreadedSecondary
|
||||
public void secondThread() {
|
||||
counter.increment();
|
||||
}
|
||||
|
||||
@ThreadedAfter
|
||||
public void after() {
|
||||
assertEquals(2, counter.getCount());
|
||||
}
|
||||
|
||||
@Ignore
|
||||
@Test
|
||||
public void testCounter() {
|
||||
new AnnotatedTestRunner().runTests(this.getClass(), MyCounter.class);
|
||||
}
|
||||
|
||||
}
|
|
@ -13,7 +13,7 @@ This module contains articles about advanced topics about multithreading with co
|
|||
- [Java Thread Deadlock and Livelock](https://www.baeldung.com/java-deadlock-livelock)
|
||||
- [Guide to AtomicStampedReference in Java](https://www.baeldung.com/java-atomicstampedreference)
|
||||
- [The ABA Problem in Concurrency](https://www.baeldung.com/cs/aba-concurrency)
|
||||
- [Introduction to Lock-Free Data Structures](https://www.baeldung.com/lock-free-programming)
|
||||
- [Introduction to Lock-Free Data Structures with Java Examples](https://www.baeldung.com/lock-free-programming)
|
||||
- [Introduction to Exchanger in Java](https://www.baeldung.com/java-exchanger)
|
||||
- [Why Not To Start A Thread In The Constructor?](https://www.baeldung.com/java-thread-constructor)
|
||||
- [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2)
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Binary Semaphore vs Reentrant Lock](https://www.baeldung.com/java-binary-semaphore-vs-reentrant-lock)
|
|
@ -0,0 +1,47 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-concurrency-advanced-4</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-concurrency-advanced-4</name>
|
||||
<packaging>jar</packaging>
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-concurrency-advanced-4</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,58 @@
|
|||
package com.baeldung.binarysemaphorereentrantlock;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class BinarySemaphoreVsReentrantLockUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenBinarySemaphore_whenAcquireAndRelease_thenCheckAvailablePermits() throws InterruptedException {
|
||||
Semaphore binarySemaphore = new Semaphore(1);
|
||||
try {
|
||||
binarySemaphore.acquire();
|
||||
assertEquals(0, binarySemaphore.availablePermits());
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
binarySemaphore.release();
|
||||
assertEquals(1, binarySemaphore.availablePermits());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenReentrantLock_whenLockAndUnlock_thenCheckHoldCountAndIsLocked() throws InterruptedException {
|
||||
ReentrantLock reentrantLock = new ReentrantLock();
|
||||
try {
|
||||
reentrantLock.lock();
|
||||
assertEquals(1, reentrantLock.getHoldCount());
|
||||
assertEquals(true, reentrantLock.isLocked());
|
||||
} finally {
|
||||
reentrantLock.unlock();
|
||||
assertEquals(0, reentrantLock.getHoldCount());
|
||||
assertEquals(false, reentrantLock.isLocked());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenReentrantLock_whenLockMultipleTimes_thenUnlockMultipleTimesToRelease() throws InterruptedException {
|
||||
ReentrantLock reentrantLock = new ReentrantLock();
|
||||
try {
|
||||
reentrantLock.lock();
|
||||
reentrantLock.lock();
|
||||
assertEquals(2, reentrantLock.getHoldCount());
|
||||
assertEquals(true, reentrantLock.isLocked());
|
||||
} finally {
|
||||
reentrantLock.unlock();
|
||||
assertEquals(1, reentrantLock.getHoldCount());
|
||||
assertEquals(true, reentrantLock.isLocked());
|
||||
|
||||
reentrantLock.unlock();
|
||||
assertEquals(0, reentrantLock.getHoldCount());
|
||||
assertEquals(false, reentrantLock.isLocked());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,263 @@
|
|||
package com.baeldung.concurrent.stopexecution;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Reader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
public class StopExecution {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(StopExecution.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
StopExecution stopExecution = new StopExecution();
|
||||
//stopExecution.testUsingLoop();
|
||||
//stopExecution.testTimer();
|
||||
stopExecution.testScheduledExecutor();
|
||||
LOG.info("done");
|
||||
}
|
||||
|
||||
public void testUsingLoop() {
|
||||
long start = System.currentTimeMillis();
|
||||
long end = start + 5000;
|
||||
List<String> items = new ArrayList<>();
|
||||
int counter = 0;
|
||||
|
||||
// Let this loop run only upto 5 seconds
|
||||
while (System.currentTimeMillis() < end && counter < items.size()) {
|
||||
// Fetch the item from the list.
|
||||
// Some expensive operation on the item.
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
counter++;
|
||||
}
|
||||
}
|
||||
|
||||
public static void testThreads() {
|
||||
Thread thread = new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
LOG.info("inside run");
|
||||
|
||||
try {
|
||||
Thread.sleep(10000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
LOG.info("exit run");
|
||||
}
|
||||
});
|
||||
thread.start();
|
||||
while (thread.getState() != Thread.State.TERMINATED) {
|
||||
LOG.info(thread.getState().name());
|
||||
try {
|
||||
Thread.sleep(500);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void testExecutor() {
|
||||
final ExecutorService service = Executors.newSingleThreadExecutor();
|
||||
Future<String> f = null;
|
||||
try {
|
||||
f = service.submit(() -> {
|
||||
// Do you long running calculation here
|
||||
try {
|
||||
Thread.sleep(2737); // Simulate some delay
|
||||
} catch (InterruptedException e) {
|
||||
LOG.info("Interrupted");
|
||||
return "interrupted";
|
||||
}
|
||||
LOG.info("Sleep finished");
|
||||
return "42";
|
||||
});
|
||||
|
||||
LOG.info(f.get(2, TimeUnit.SECONDS));
|
||||
} catch (TimeoutException e) {
|
||||
f.cancel(true);
|
||||
LOG.error("Calculation took to long");
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
} finally {
|
||||
service.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
public void testExecutor2() {
|
||||
final ExecutorService service = Executors.newSingleThreadExecutor();
|
||||
Future f = null;
|
||||
try {
|
||||
f = service.submit(new LongRunningTask());
|
||||
LOG.info("testExecutor2");
|
||||
f.get(1, TimeUnit.SECONDS);
|
||||
} catch (final TimeoutException e) {
|
||||
f.cancel(true);
|
||||
LOG.error("Calculation took to long");
|
||||
} catch (final Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
} finally {
|
||||
service.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
public void testScheduledExecutor() {
|
||||
LOG.info("testScheduledExecutor");
|
||||
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
|
||||
Future future = executor.submit(new LongRunningTask());
|
||||
executor.schedule(new Runnable() {
|
||||
public void run() {
|
||||
future.cancel(true);
|
||||
}
|
||||
}, 1000, TimeUnit.MILLISECONDS);
|
||||
executor.shutdown();
|
||||
}
|
||||
|
||||
public void testThreadAndInterrupt() {
|
||||
|
||||
Thread t;
|
||||
try {
|
||||
t = new Thread(new LongRunningTask());
|
||||
|
||||
LOG.info("testExecutor3");
|
||||
long end = System.currentTimeMillis() + 2000;
|
||||
t.start();
|
||||
while (t.isAlive() && System.currentTimeMillis() < end) {
|
||||
Thread.sleep(50);
|
||||
}
|
||||
t.interrupt();
|
||||
} catch (final Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public void testTimer() {
|
||||
LOG.info("Timer test");
|
||||
Thread t = new Thread(new LongRunningTask());
|
||||
Timer timeoutTimer = new Timer();
|
||||
timeoutTimer.schedule(new TimeOutTask(t, timeoutTimer), 1000);
|
||||
t.start();
|
||||
}
|
||||
|
||||
class MyRunnableTask implements Runnable {
|
||||
public void run() {
|
||||
try {
|
||||
LOG.info("MyRunnable...");
|
||||
Thread.sleep(10000);
|
||||
} catch (InterruptedException ie) {
|
||||
LOG.info("MyRunnable interrupted...");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class TimeOutTask extends TimerTask {
|
||||
private Thread t;
|
||||
private Timer timer;
|
||||
|
||||
TimeOutTask(Thread t, Timer timer) {
|
||||
this.t = t;
|
||||
this.timer = timer;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
if (t != null && t.isAlive()) {
|
||||
t.interrupt();
|
||||
timer.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class LongRunningTask implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
longRunningSort();
|
||||
}
|
||||
|
||||
private void longRunningOperation() {
|
||||
LOG.info("long Running operation started");
|
||||
|
||||
try {
|
||||
//Thread.sleep(500);
|
||||
longFileRead();
|
||||
LOG.info("long running operation finished");
|
||||
} catch (InterruptedException e) {
|
||||
LOG.info("long Running operation interrupted");
|
||||
}
|
||||
}
|
||||
|
||||
private void longRunningSort() {
|
||||
LOG.info("long Running task started");
|
||||
// Do you long running calculation here
|
||||
int len = 100000;
|
||||
List<Integer> numbers = new ArrayList<>();
|
||||
try {
|
||||
for (int i = len; i > 0; i--) {
|
||||
//Thread.sleep(5)
|
||||
numbers.add(i);
|
||||
}
|
||||
|
||||
int i = 0;
|
||||
for (i = 0; i < len; i++) {
|
||||
int minIndex = i;
|
||||
for (int j = i + 1; j < len; j++) {
|
||||
if (numbers.get(minIndex) > numbers.get(j))
|
||||
minIndex = j;
|
||||
}
|
||||
if (minIndex != i) {
|
||||
int temp = numbers.get(i);
|
||||
numbers.set(i, numbers.get(minIndex));
|
||||
numbers.set(minIndex, temp);
|
||||
}
|
||||
throwExceptionOnThreadInterrupt();
|
||||
}
|
||||
LOG.info("Index position: " + i);
|
||||
LOG.info("Long running task finished");
|
||||
} catch (InterruptedException e) {
|
||||
LOG.info("long Running operation interrupted");
|
||||
}
|
||||
}
|
||||
|
||||
private void longFileRead() throws InterruptedException {
|
||||
String file = "input.txt";
|
||||
ClassLoader classloader = getClass().getClassLoader();
|
||||
|
||||
try (InputStream inputStream = classloader.getResourceAsStream(file)) {
|
||||
Reader inputStreamReader = new InputStreamReader(inputStream);
|
||||
|
||||
int data = inputStreamReader.read();
|
||||
while (data != -1) {
|
||||
char theChar = (char) data;
|
||||
data = inputStreamReader.read();
|
||||
throwExceptionOnThreadInterrupt();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOG.error("Exception: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void throwExceptionOnThreadInterrupt() throws InterruptedException {
|
||||
if (Thread.currentThread().interrupted()) {
|
||||
throw new InterruptedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
|
@ -6,6 +6,7 @@ import java.sql.Timestamp;
|
|||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
@ -21,9 +22,12 @@ public class ConvertInstantToTimestampUnitTest {
|
|||
instant = timestamp.toInstant();
|
||||
assertThat(instant.toEpochMilli()).isEqualTo(timestamp.getTime());
|
||||
|
||||
DateFormat df = DateFormat.getDateTimeInstance();
|
||||
df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'");
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
|
||||
formatter = formatter.withZone(TimeZone.getTimeZone("UTC").toZoneId());
|
||||
|
||||
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
|
||||
df.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
assertThat(instant.toString()).isEqualTo(df.format(timestamp).toString());
|
||||
|
||||
assertThat(formatter.format(instant)).isEqualTo(df.format(timestamp));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -58,7 +58,8 @@ public class StringToDateUnitTest {
|
|||
LocalDateTime localDateTime = LocalDateTime.of(2015, 05, 05, 10, 15, 30);
|
||||
ZonedDateTime expectedZonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("Europe/Paris"));
|
||||
|
||||
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2015-05-05T10:15:30+01:00[Europe/Paris]");
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");
|
||||
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2015-05-05 10:15:30 Europe/Paris", formatter);
|
||||
|
||||
assertThat(zonedDateTime).isEqualTo(expectedZonedDateTime);
|
||||
}
|
||||
|
|
|
@ -38,14 +38,16 @@ public class DateTimeFormatterUnitTest {
|
|||
LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 1, 10, 15, 50, 500);
|
||||
ZoneId losAngelesTimeZone = TimeZone.getTimeZone("America/Los_Angeles").toZoneId();
|
||||
|
||||
DateTimeFormatter localizedFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL);
|
||||
DateTimeFormatter frLocalizedFormatter =
|
||||
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(Locale.FRANCE);
|
||||
DateTimeFormatter localizedFormatter = DateTimeFormatter.ofPattern("EEEE, MMMM dd, yyyy z", Locale.US);
|
||||
DateTimeFormatter frLocalizedFormatter = DateTimeFormatter.ofPattern("EEEE, MMMM dd, yyyy z", Locale.FRANCE);
|
||||
String formattedDateTime = localizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone));
|
||||
String frFormattedDateTime = frLocalizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone));
|
||||
|
||||
Assert.assertEquals("Monday, January 1, 2018 10:15:50 AM PST", formattedDateTime);
|
||||
Assert.assertEquals("lundi 1 janvier 2018 10 h 15 PST", frFormattedDateTime);
|
||||
System.out.println(formattedDateTime);
|
||||
System.out.println(frFormattedDateTime);
|
||||
|
||||
Assert.assertEquals("Monday, January 01, 2018 PST", formattedDateTime);
|
||||
Assert.assertEquals("lundi, janvier 01, 2018 PST", frFormattedDateTime);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -105,14 +107,15 @@ public class DateTimeFormatterUnitTest {
|
|||
Assert.assertEquals("8/23/16", DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).format(anotherSummerDay));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldPrintStyledDateTime() {
|
||||
LocalDateTime anotherSummerDay = LocalDateTime.of(2016, 8, 23, 13, 12, 45);
|
||||
Assert.assertEquals("Tuesday, August 23, 2016 1:12:45 PM EET", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
|
||||
Assert.assertEquals("August 23, 2016 1:12:45 PM EET", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
|
||||
Assert.assertEquals("Aug 23, 2016 1:12:45 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
|
||||
Assert.assertEquals("8/23/16 1:12 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
|
||||
}
|
||||
// Note: The exact output format using the different FormatStyle constants differs by JVM/Java version
|
||||
// @Test
|
||||
// public void shouldPrintStyledDateTime() {
|
||||
// LocalDateTime anotherSummerDay = LocalDateTime.of(2016, 8, 23, 13, 12, 45);
|
||||
// Assert.assertEquals("Tuesday, August 23, 2016 1:12:45 PM EET", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
|
||||
// Assert.assertEquals("August 23, 2016 1:12:45 PM EET", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
|
||||
// Assert.assertEquals("Aug 23, 2016 1:12:45 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
|
||||
// Assert.assertEquals("8/23/16 1:12 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
|
||||
// }
|
||||
|
||||
@Test
|
||||
public void shouldPrintFormattedDateTimeWithPredefined() {
|
||||
|
@ -126,11 +129,12 @@ public class DateTimeFormatterUnitTest {
|
|||
Assert.assertEquals(LocalDate.of(2018, 3, 12), LocalDate.from(DateTimeFormatter.ISO_LOCAL_DATE.parse("2018-03-09")).plusDays(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldParseFormatStyleFull() {
|
||||
ZonedDateTime dateTime = ZonedDateTime.from(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).parse("Tuesday, August 23, 2016 1:12:45 PM EET"));
|
||||
Assert.assertEquals(ZonedDateTime.of(LocalDateTime.of(2016, 8, 23, 22, 12, 45), ZoneId.of("Europe/Bucharest")), dateTime.plusHours(9));
|
||||
}
|
||||
// Note: The exact output format using the different FormatStyle constants differs by JVM/Java version
|
||||
// @Test
|
||||
// public void shouldParseFormatStyleFull() {
|
||||
// ZonedDateTime dateTime = ZonedDateTime.from(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).parse("Tuesday, August 23, 2016 1:12:45 PM EET"));
|
||||
// Assert.assertEquals(ZonedDateTime.of(LocalDateTime.of(2016, 8, 23, 22, 12, 45), ZoneId.of("Europe/Bucharest")), dateTime.plusHours(9));
|
||||
// }
|
||||
|
||||
@Test
|
||||
public void shouldParseDateWithCustomFormatter() {
|
||||
|
|
|
@ -3,3 +3,8 @@
|
|||
- [NoSuchMethodError in Java](https://www.baeldung.com/java-nosuchmethod-error)
|
||||
- [IllegalArgumentException or NullPointerException for a Null Parameter?](https://www.baeldung.com/java-illegalargumentexception-or-nullpointerexception)
|
||||
- [IllegalMonitorStateException in Java](https://www.baeldung.com/java-illegalmonitorstateexception)
|
||||
- [AbstractMethodError in Java](https://www.baeldung.com/java-abstractmethoderror)
|
||||
- [Java IndexOutOfBoundsException “Source Does Not Fit in Dest”](https://www.baeldung.com/java-indexoutofboundsexception)
|
||||
- [Localizing Exception Messages in Java](https://www.baeldung.com/java-localize-exception-messages)
|
||||
- [Explanation of ClassCastException in Java](https://www.baeldung.com/java-classcastexception)
|
||||
- [NoSuchFieldError in Java](https://www.baeldung.com/java-nosuchfielderror)
|
||||
|
|
|
@ -17,6 +17,14 @@
|
|||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>1.4.191</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
|
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.exception.indexoutofbounds;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class CopyListUsingAddAllMethodDemo {
|
||||
static List<Integer> copyList(List<Integer> source) {
|
||||
List<Integer> destination = new ArrayList<>();
|
||||
|
||||
destination.addAll(source);
|
||||
|
||||
return destination;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung.exception.indexoutofbounds;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class CopyListUsingCollectionsCopyMethodDemo {
|
||||
static void copyList(List<Integer> source, List<Integer> destination) {
|
||||
Collections.copy(destination, source);
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue