This commit is contained in:
Jonathan Cook 2020-11-04 11:03:04 +01:00
commit f72fce6549
145 changed files with 2921 additions and 165 deletions

View File

@ -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 The Courses
============================== ==============================

View File

@ -5,6 +5,6 @@ This module contains articles about genetic algorithms.
### Relevant articles: ### Relevant articles:
- [Introduction to Jenetics Library](https://www.baeldung.com/jenetics) - [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) - [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) - [The Traveling Salesman Problem in Java](https://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)

View File

@ -6,8 +6,8 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
### Relevant articles: ### Relevant articles:
- [Validating Input With Finite Automata in Java](https://www.baeldung.com/java-finite-automata) - [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) - [Example of Hill Climbing Algorithm in Java](https://www.baeldung.com/java-hill-climbing-algorithm)
- [Introduction to Minimax Algorithm](https://www.baeldung.com/java-minimax-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 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) - [How to Find the Kth Largest Element in Java](https://www.baeldung.com/java-kth-largest-element)
- More articles: [[next -->]](/algorithms-miscellaneous-2) - More articles: [[next -->]](/algorithms-miscellaneous-2)

View File

@ -5,8 +5,8 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
### Relevant articles: ### Relevant articles:
- [Multi-Swarm Optimization Algorithm in Java](https://www.baeldung.com/java-multi-swarm-algorithm) - [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) - [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](https://www.baeldung.com/java-linked-list-middle-element) - [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 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) - [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) - [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)

View File

@ -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) - [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) - [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) - [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) - [Overview of Combinatorial Problems in Java](https://www.baeldung.com/java-combinatorial-algorithms)
- [Prims Algorithm](https://www.baeldung.com/java-prim-algorithm) - [Prims Algorithm with a Java Implementation](https://www.baeldung.com/java-prim-algorithm)
- [Maximum Subarray Problem](https://www.baeldung.com/java-maximum-subarray) - [Maximum Subarray Problem in Java](https://www.baeldung.com/java-maximum-subarray)
- [How to Merge Two Sorted Arrays](https://www.baeldung.com/java-merge-sorted-arrays) - [How to Merge Two Sorted Arrays in Java](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) - [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) - More articles: [[<-- prev]](/algorithms-miscellaneous-4) [[next -->]](/algorithms-miscellaneous-6)

View File

@ -1,13 +1,13 @@
### Relevant Articles: ### Relevant Articles:
- [Boruvkas Algorithm for Minimum Spanning Trees](https://www.baeldung.com/java-boruvka-algorithm) - [Boruvkas 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) - [Gradient Descent in Java](https://www.baeldung.com/java-gradient-descent)
- [Kruskals Algorithm for Spanning Trees](https://www.baeldung.com/java-spanning-trees-kruskal) - [Kruskals 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) - [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) - [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) - [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) - [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) - [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) - [Reversing a Linked List in Java](https://www.baeldung.com/java-reverse-linked-list)
- More articles: [[<-- prev]](/algorithms-miscellaneous-5) - More articles: [[<-- prev]](/algorithms-miscellaneous-5)

View File

@ -8,8 +8,8 @@ This module contains articles about searching algorithms.
- [Depth First Search in Java](https://www.baeldung.com/java-depth-first-search) - [Depth First Search in Java](https://www.baeldung.com/java-depth-first-search)
- [Interpolation Search in Java](https://www.baeldung.com/java-interpolation-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) - [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) - [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](https://www.baeldung.com/java-monte-carlo-tree-search) - [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) - [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) - [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](https://www.baeldung.com/java-kth-smallest-element-in-sorted-arrays) - [Find the Kth Smallest Element in Two Sorted Arrays in Java](https://www.baeldung.com/java-kth-smallest-element-in-sorted-arrays)

View File

@ -2,6 +2,6 @@
- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically) - [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) - [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) - [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](https://www.baeldung.com/java-sorting-arrays-with-repeated-entries) - [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) - More articles: [[<-- prev]](/algorithms-sorting)

View File

@ -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) - [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) - [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) - [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)

View File

@ -0,0 +1 @@
--enable-preview

View File

@ -0,0 +1,7 @@
## Core Java 15
This module contains articles about Java 15.
### Relevant articles
- TODO: add article links here

View File

@ -0,0 +1,77 @@
<?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>${apache-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>15</source>
<target>15</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>
<apache-commons-lang3.version>3.11</apache-commons-lang3.version>
<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>

View File

@ -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;
}
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.sealed.classes;
public sealed interface Service permits Car, Truck {
int getMaxServiceIntervalInMonths();
default int getMaxDistanceBetweenServicesInKilometers() {
return 100000;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.sealed.records;
public sealed interface Vehicle permits Car, Truck {
String getRegistrationNumber();
}

View File

@ -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");
}
}
}

View File

@ -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");
}
}
}

View File

@ -14,3 +14,4 @@
- [Convert an Array of Primitives to a List](https://www.baeldung.com/java-primitive-array-to-list) - [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) - [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) - [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)

View File

@ -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) - [Java Thread Deadlock and Livelock](https://www.baeldung.com/java-deadlock-livelock)
- [Guide to AtomicStampedReference in Java](https://www.baeldung.com/java-atomicstampedreference) - [Guide to AtomicStampedReference in Java](https://www.baeldung.com/java-atomicstampedreference)
- [The ABA Problem in Concurrency](https://www.baeldung.com/cs/aba-concurrency) - [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) - [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) - [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) - [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2)

View File

@ -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();
}
}
}
}

View File

@ -17,6 +17,14 @@
</parent> </parent>
<dependencies> <dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.191</version>
<scope>test</scope>
</dependency>
<!-- test scoped --> <!-- test scoped -->
<dependency> <dependency>
<groupId>org.assertj</groupId> <groupId>org.assertj</groupId>

View File

@ -0,0 +1,23 @@
package com.baeldung.exceptions.abstractmethoderror;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import static org.junit.jupiter.api.Assertions.assertNotNull;
class AbstractMethodErrorUnitTest {
private static final String url = "jdbc:h2:mem:A-DATABASE;INIT=CREATE SCHEMA IF NOT EXISTS myschema";
private static final String username = "sa";
@Test
void givenOldH2Database_whenCallgetSchemaMethod_thenThrowAbstractMethodError() throws SQLException {
Connection conn = DriverManager.getConnection(url, username, "");
assertNotNull(conn);
Assertions.assertThrows(AbstractMethodError.class, () -> conn.getSchema());
}
}

View File

@ -0,0 +1 @@
## Relevant articles:

View File

@ -0,0 +1,18 @@
<?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-functional</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-functional</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>
</project>

View File

@ -0,0 +1,26 @@
package com.baeldung.functional;
import java.util.function.Function;
public class Currying {
private static Function<Double, Function<Double, Double>> weight = mass -> gravity -> mass * gravity;
private static Function<Double, Double> weightOnEarth = weight.apply(9.81);
private static Function<Double, Double> weightOnMars = weight.apply(3.75);
public static Double weightOnEarth(Double mass) {
return weightOnEarth.apply(mass);
}
public static Double weightOnMars(Double mass) {
return weightOnMars.apply(mass);
}
public static Function<Double, Double> weightOnEarth() {
final double gravity = 9.81;
return mass -> mass * gravity;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.functional;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class FirstClassFunctions {
public static List<Integer> sortWithoutLambda(List<Integer> numbers) {
Collections.sort(numbers, new Comparator<Integer>() {
@Override
public int compare(Integer n1, Integer n2) {
return n1.compareTo(n2);
}
});
return numbers;
}
public static List<Integer> sortWithLambda(List<Integer> numbers) {
Collections.sort(numbers, (n1, n2) -> n1.compareTo(n2));
return numbers;
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.functional;
import java.util.function.Function;
public class FunctionComposition {
private static Function<Double, Double> log = (value) -> Math.log(value);
private static Function<Double, Double> sqrt = (value) -> Math.sqrt(value);
public static Double logThenSqrt(Double number) {
Function<Double, Double> logThenSqrt = sqrt.compose(log);
return (logThenSqrt.apply(3.14));
}
public static Double sqrtThenLog(Double number) {
Function<Double, Double> sqrtThenLog = sqrt.andThen(log);
return (sqrtThenLog.apply(3.14));
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.functional;
public class ImmutableData {
private final String someData;
private final AnotherImmutableData anotherImmutableData;
public ImmutableData(final String someData, final AnotherImmutableData anotherImmutableData) {
this.someData = someData;
this.anotherImmutableData = anotherImmutableData;
}
public String getSomeData() {
return someData;
}
public AnotherImmutableData getAnotherImmutableData() {
return anotherImmutableData;
}
public class AnotherImmutableData {
private final Integer someOtherData;
public AnotherImmutableData(final Integer someData) {
this.someOtherData = someData;
}
public Integer getSomeOtherData() {
return someOtherData;
}
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.functional;
import java.util.Optional;
public class Monads {
public static Optional<Integer> add(Optional<Integer> val1, Optional<Integer> val2) {
return val1.flatMap(first -> val2.flatMap(second -> Optional.of(first + second)));
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.functional;
import java.util.List;
import java.util.stream.Collectors;
public class PureFunctions {
public static Integer sum(List<Integer> numbers) {
return numbers.stream()
.collect(Collectors.summingInt(Integer::intValue));
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.functional;
public class Recursion {
public static Integer headRecursion(Integer number) {
return (number == 1) ? 1 : number * headRecursion(number - 1);
}
public static Integer tailRecursion(Integer number, Integer result) {
return (number == 1) ? result : tailRecursion(number - 1, result * number);
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.functional;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ReferentialTransparency {
private static Logger logger = Logger.getGlobal();
public void main() {
String data = new SimpleData().setData("Baeldung")
.getData();
logger.log(Level.INFO, new SimpleData().setData("Baeldung")
.getData());
logger.log(Level.INFO, data);
logger.log(Level.INFO, "Baeldung");
}
public class SimpleData {
private Logger logger = Logger.getGlobal();
private String data;
public String getData() {
logger.log(Level.INFO, "Get data called for SimpleData");
return data;
}
public SimpleData setData(String data) {
logger.log(Level.INFO, "Set data called for SimpleData");
this.data = data;
return this;
}
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.functional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
public class CurryingUnitTest {
@Test
public void testWeightOnEarth() {
assertEquals(588.6, Currying.weightOnEarth(60.0), 0.1);
}
@Test
public void testWeightOnMars() {
assertEquals(225.0, Currying.weightOnMars(60.0), 0.1);
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.functional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import org.junit.Test;
public class FirstClassFunctionsUnitTest {
@Test
public void testSortingWithoutLambda() {
assertEquals(new Integer(8), FirstClassFunctions.sortWithoutLambda(Arrays.asList(new Integer(10), new Integer(8)))
.get(0));
}
@Test
public void testSortingWithLambda() {
assertEquals(new Integer(8), FirstClassFunctions.sortWithLambda(Arrays.asList(new Integer(10), new Integer(8)))
.get(0));
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.functional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
public class FunctionCompositionUnitTest {
@Test
public void testLogThenSqrt() {
assertEquals(1.07, FunctionComposition.logThenSqrt(3.14), 0.01);
}
@Test
public void testSqrtThenLog() {
assertEquals(0.57, FunctionComposition.sqrtThenLog(3.14), 0.01);
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.functional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Optional;
import org.junit.Test;
public class MonadsUnitTest {
@Test
public void testOptionalAdd() {
assertEquals(5, Monads.add(Optional.of(new Integer(2)), Optional.of(new Integer(3)))
.get());
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.functional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import org.junit.Test;
public class PureFunctionsUnitTets {
@Test
public void testSortingWithoutLambda() {
assertEquals(new Integer(18), PureFunctions.sum(Arrays.asList(new Integer(10), new Integer(8))));
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.functional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
public class RecursionUnitTest {
@Test
public void testHeadRecursion() {
assertEquals(120, Recursion.headRecursion(5));
}
@Test
public void testTailRecursion() {
assertEquals(120, Recursion.tailRecursion(5, 1));
}
}

View File

@ -0,0 +1 @@
!src/test/resources/example-jar/stripe-0.0.1-SNAPSHOT.jar

View File

@ -7,3 +7,4 @@ This module contains articles about JAR files
- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven) - [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven)
- [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class) - [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class)
- [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar) - [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar)
- [Get Names of Classes Inside a JAR File](https://www.baeldung.com/jar-file-get-class-names)

View File

@ -0,0 +1,43 @@
package com.baeldung.jar;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class GetClassNamesFromJar {
public static Set<String> getClassNamesFromJarFile(File givenFile) throws IOException {
Set<String> classNames = new HashSet<>();
try (JarFile jarFile = new JarFile(givenFile)) {
Enumeration<JarEntry> e = jarFile.entries();
while (e.hasMoreElements()) {
JarEntry jarEntry = e.nextElement();
if (jarEntry.getName().endsWith(".class")) {
String className = jarEntry.getName()
.replace("/", ".")
.replace(".class", "");
classNames.add(className);
}
}
return classNames;
}
}
public static Set<Class> getClassesFromJarFile(File jarFile) throws IOException, ClassNotFoundException {
Set<String> classNames = getClassNamesFromJarFile(jarFile);
Set<Class> classes = new HashSet<>(classNames.size());
try (URLClassLoader cl = URLClassLoader.newInstance(new URL[] { new URL("jar:file:" + jarFile + "!/") })) {
for (String name : classNames) {
Class clazz = cl.loadClass(name); // Loading the class by its name
classes.add(clazz);
}
}
return classes;
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.jar;
import com.google.common.collect.Sets;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
public class GetClassNamesFromJarUnitTest {
private static final String JAR_PATH = "example-jar/stripe-0.0.1-SNAPSHOT.jar";
private static final Set<String> EXPECTED_CLASS_NAMES = Sets.newHashSet(
"com.baeldung.stripe.StripeApplication",
"com.baeldung.stripe.ChargeRequest",
"com.baeldung.stripe.StripeService",
"com.baeldung.stripe.ChargeRequest$Currency",
"com.baeldung.stripe.ChargeController",
"com.baeldung.stripe.CheckoutController");
@Test
public void givenJarFilePath_whenLoadClassNames_thenGetClassNames() throws IOException, URISyntaxException {
File jarFile = new File(Objects.requireNonNull(getClass().getClassLoader().getResource(JAR_PATH)).toURI());
Set<String> classNames = GetClassNamesFromJar.getClassNamesFromJarFile(jarFile);
Assert.assertEquals(EXPECTED_CLASS_NAMES, classNames);
}
@Test
public void givenJarFilePath_whenLoadClass_thenGetClassObjects() throws IOException, ClassNotFoundException, URISyntaxException {
File jarFile = new File(Objects.requireNonNull(getClass().getClassLoader().getResource(JAR_PATH)).toURI());
Set<Class> classes = GetClassNamesFromJar.getClassesFromJarFile(jarFile);
Set<String> names = classes.stream().map(Class::getName).collect(Collectors.toSet());
Assert.assertEquals(EXPECTED_CLASS_NAMES, names);
}
}

View File

@ -7,4 +7,5 @@ This module contains articles about core features in the Java language
- [When are Static Variables Initialized in Java?](https://www.baeldung.com/java-static-variables-initialization) - [When are Static Variables Initialized in Java?](https://www.baeldung.com/java-static-variables-initialization)
- [Checking if a Class Exists in Java](https://www.baeldung.com/java-check-class-exists) - [Checking if a Class Exists in Java](https://www.baeldung.com/java-check-class-exists)
- [The Difference Between a.getClass() and A.class in Java](https://www.baeldung.com/java-getclass-vs-class) - [The Difference Between a.getClass() and A.class in Java](https://www.baeldung.com/java-getclass-vs-class)
- [Constants in Java: Patterns and Anti-Patterns](https://www.baeldung.com/java-constants-good-practices)
- [[<-- Prev]](/core-java-modules/core-java-lang-2) - [[<-- Prev]](/core-java-modules/core-java-lang-2)

View File

@ -9,9 +9,9 @@
- [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap) - [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap)
- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points) - [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points)
- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines) - [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines)
- [Round Up to the Nearest Hundred](https://www.baeldung.com/java-round-up-nearest-hundred) - [Round Up to the Nearest Hundred in Java](https://www.baeldung.com/java-round-up-nearest-hundred)
- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude) - [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude)
- [Debugging with Eclipse](https://www.baeldung.com/eclipse-debugging) - [Debugging with Eclipse](https://www.baeldung.com/eclipse-debugging)
- [Matrix Multiplication in Java](https://www.baeldung.com/java-matrix-multiplication) - [Matrix Multiplication in Java](https://www.baeldung.com/java-matrix-multiplication)
- [Largest Power of 2 That Is Less Than the Given Number](https://www.baeldung.com/java-largest-power-of-2-less-than-number) - [Largest Power of 2 That Is Less Than the Given Number with Java](https://www.baeldung.com/java-largest-power-of-2-less-than-number)
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math) - More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math)

View File

@ -0,0 +1,28 @@
package com.baeldung.finalize;
import java.lang.ref.ReferenceQueue;
import java.lang.reflect.Field;
public class CrashedFinalizable {
public static void main(String[] args) throws ReflectiveOperationException {
for (int i = 0; ; i++) {
new CrashedFinalizable();
if ((i % 1_000_000) == 0) {
Class<?> finalizerClass = Class.forName("java.lang.ref.Finalizer");
Field queueStaticField = finalizerClass.getDeclaredField("queue");
queueStaticField.setAccessible(true);
ReferenceQueue<Object> referenceQueue = (ReferenceQueue) queueStaticField.get(null);
Field queueLengthField = ReferenceQueue.class.getDeclaredField("queueLength");
queueLengthField.setAccessible(true);
long queueLength = (long) queueLengthField.get(referenceQueue);
System.out.format("There are %d references in the queue%n", queueLength);
}
}
}
@Override
protected void finalize() {
System.out.print("");
}
}

View File

@ -14,4 +14,5 @@ This module contains articles about networking in Java
- [Handling java.net.ConnectException](https://www.baeldung.com/java-net-connectexception) - [Handling java.net.ConnectException](https://www.baeldung.com/java-net-connectexception)
- [Getting MAC addresses in Java](https://www.baeldung.com/java-mac-address) - [Getting MAC addresses in Java](https://www.baeldung.com/java-mac-address)
- [Sending Emails with Attachments in Java](https://www.baeldung.com/java-send-emails-attachments) - [Sending Emails with Attachments in Java](https://www.baeldung.com/java-send-emails-attachments)
- [Finding a Free Port in Java](https://www.baeldung.com/java-free-port)
- [[<-- Prev]](/core-java-modules/core-java-networking) - [[<-- Prev]](/core-java-modules/core-java-networking)

View File

@ -9,7 +9,7 @@
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char) - [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
- [Pre-compile Regex Patterns Into Pattern Objects](https://www.baeldung.com/java-regex-pre-compile) - [Pre-compile Regex Patterns Into Pattern Objects](https://www.baeldung.com/java-regex-pre-compile)
- [Difference Between Java Matcher find() and matches()](https://www.baeldung.com/java-matcher-find-vs-matches) - [Difference Between Java Matcher find() and matches()](https://www.baeldung.com/java-matcher-find-vs-matches)
- [How to Use Regular Expressions to Replace Tokens in Strings](https://www.baeldung.com/java-regex-token-replacement) - [How to Use Regular Expressions to Replace Tokens in Strings in Java](https://www.baeldung.com/java-regex-token-replacement)
- [Regular Expressions \s and \s+ in Java](https://www.baeldung.com/java-regex-s-splus) - [Regular Expressions \s and \s+ in Java](https://www.baeldung.com/java-regex-s-splus)
- [Validate Phone Numbers With Java Regex](https://www.baeldung.com/java-regex-validate-phone-numbers) - [Validate Phone Numbers With Java Regex](https://www.baeldung.com/java-regex-validate-phone-numbers)
- [How to Count the Number of Matches for a Regex?](https://www.baeldung.com/java-count-regex-matches) - [How to Count the Number of Matches for a Regex?](https://www.baeldung.com/java-count-regex-matches)

View File

@ -11,6 +11,6 @@ This module contains articles about string-related algorithms.
- [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array) - [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array)
- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string) - [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string)
- [Remove Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters) - [Remove Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters)
- [Counting Words in a String](https://www.baeldung.com/java-word-counting) - [Counting Words in a String with Java](https://www.baeldung.com/java-word-counting)
- [Finding the Difference Between Two Strings in Java](https://www.baeldung.com/java-difference-between-two-strings) - [Finding the Difference Between Two Strings in Java](https://www.baeldung.com/java-difference-between-two-strings)
- More articles: [[<-- prev]](../core-java-string-algorithms) - More articles: [[<-- prev]](../core-java-string-algorithms)

View File

@ -3,14 +3,14 @@
This module contains articles about string-related algorithms. This module contains articles about string-related algorithms.
### Relevant Articles: ### Relevant Articles:
- [Check If a String Is a Palindrome](https://www.baeldung.com/java-palindrome) - [Check if a String is a Palindrome in Java](https://www.baeldung.com/java-palindrome)
- [Count Occurrences of a Char in a String](https://www.baeldung.com/java-count-chars) - [Count Occurrences of a Char in a String](https://www.baeldung.com/java-count-chars)
- [Using indexOf to Find All Occurrences of a Word in a String](https://www.baeldung.com/java-indexOf-find-string-occurrences) - [Using indexOf to Find All Occurrences of a Word in a String](https://www.baeldung.com/java-indexOf-find-string-occurrences)
- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords) - [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords)
- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char) - [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char)
- [How to Reverse a String in Java](https://www.baeldung.com/java-reverse-string) - [How to Reverse a String in Java](https://www.baeldung.com/java-reverse-string)
- [Check If a String Is a Pangram in Java](https://www.baeldung.com/java-string-pangram) - [Check If a String Is a Pangram in Java](https://www.baeldung.com/java-string-pangram)
- [Check If a String Contains Multiple Keywords](https://www.baeldung.com/string-contains-multiple-words) - [Check If a String Contains Multiple Keywords in Java](https://www.baeldung.com/string-contains-multiple-words)
- [Checking If a String Is a Repeated Substring](https://www.baeldung.com/java-repeated-substring) - [Checking If a String Is a Repeated Substring](https://www.baeldung.com/java-repeated-substring)
- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis) - [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis)
- More articles: [[next -->]](../core-java-string-algorithms-2) - More articles: [[next -->]](../core-java-string-algorithms-2)

View File

@ -60,6 +60,7 @@
<module>core-java-exceptions-2</module> <module>core-java-exceptions-2</module>
<module>core-java-exceptions-3</module> <module>core-java-exceptions-3</module>
<module>core-java-function</module> <module>core-java-function</module>
<module>core-java-functional</module>
<module>core-java-io</module> <module>core-java-io</module>
<module>core-java-io-2</module> <module>core-java-io-2</module>

View File

@ -0,0 +1,29 @@
package com.baeldung.channles
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val basket = Channel<String>(1)
launch { // coroutine1
val fruits = listOf("Apple", "Orange", "Banana")
for (fruit in fruits) {
println("coroutine1: Sending $fruit")
basket.send(fruit)
}
}
launch { // coroutine2
repeat(3) {
delay(100)
println("coroutine2: Received ${basket.receive()}")
}
}
delay(2000)
coroutineContext.cancelChildren()
}

View File

@ -0,0 +1,27 @@
package com.baeldung.channles
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.Channel.Factory.CONFLATED
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val basket = Channel<String>(CONFLATED)
launch { // coroutine1
val fruits = listOf("Apple", "Orange", "Banana")
for (fruit in fruits) {
println("coroutine1: Sending $fruit")
basket.send(fruit)
}
}
launch { // coroutine2
println("coroutine2: Received ${basket.receive()}")
}
delay(2000)
coroutineContext.cancelChildren()
}

View File

@ -0,0 +1,52 @@
package com.baeldung.channles
import com.baeldung.channles.OrderStatus.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
enum class OrderStatus { ORDERED, BAKED, TOPPED, SERVED }
data class PizzaOrder(val orderNumber: Int, val orderStatus: OrderStatus = ORDERED)
@ExperimentalCoroutinesApi
fun CoroutineScope.baking(orders: ReceiveChannel<PizzaOrder>) = produce {
for (order in orders) {
delay(200)
println("Baking ${order.orderNumber}")
send(order.copy(orderStatus = BAKED))
}
}
@ExperimentalCoroutinesApi
fun CoroutineScope.topping(orders: ReceiveChannel<PizzaOrder>) = produce {
for (order in orders) {
delay(50)
println("Topping ${order.orderNumber}")
send(order.copy(orderStatus = TOPPED))
}
}
@ExperimentalCoroutinesApi
fun CoroutineScope.produceOrders(count: Int) = produce {
repeat(count) {
delay(50)
send(PizzaOrder(orderNumber = it + 1))
}
}
@ObsoleteCoroutinesApi
@ExperimentalCoroutinesApi
fun main() = runBlocking {
val orders = produceOrders(3)
val readyOrders = topping(baking(orders))
for (order in readyOrders) {
println("Serving ${order.orderNumber}")
}
delay(3000)
println("End!")
coroutineContext.cancelChildren()
}

View File

@ -0,0 +1,22 @@
package com.baeldung.channles
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.runBlocking
@ExperimentalCoroutinesApi
fun CoroutineScope.produceFruits(): ReceiveChannel<String> = produce {
val fruits = listOf("Apple", "Orange", "Apple")
for (fruit in fruits) send(fruit)
}
@ExperimentalCoroutinesApi
fun main() = runBlocking {
val fruitChannel = produceFruits()
for (fruit in fruitChannel) {
println(fruit)
}
println("End!")
}

View File

@ -0,0 +1,26 @@
package com.baeldung.channles
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
fun main() = runBlocking {
val basket = Channel<String>()
launch { // coroutine1
val fruits = listOf("Apple", "Orange", "Banana")
for (fruit in fruits) {
println("coroutine1: Sending $fruit")
basket.send(fruit)
}
}
launch { // coroutine2
repeat(3) {
delay(100)
println("coroutine2: Received ${basket.receive()}")
}
}
delay(2000)
coroutineContext.cancelChildren()
}

View File

@ -0,0 +1,36 @@
package com.baeldung.channles
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
suspend fun fetchYoutubeVideos(channel: SendChannel<String>) {
val videos = listOf("cat video", "food video")
for (video in videos) {
delay(100)
channel.send(video)
}
}
suspend fun fetchTweets(channel: SendChannel<String>) {
val tweets = listOf("tweet: Earth is round", "tweet: Coroutines and channels are cool")
for (tweet in tweets) {
delay(100)
channel.send(tweet)
}
}
fun main() = runBlocking {
val aggregate = Channel<String>()
launch { fetchYoutubeVideos(aggregate) }
launch { fetchTweets(aggregate) }
repeat(4) {
println(aggregate.receive())
}
coroutineContext.cancelChildren()
}

View File

@ -0,0 +1,31 @@
package com.baeldung.channles
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
@ExperimentalCoroutinesApi
fun CoroutineScope.producePizzaOrders(): ReceiveChannel<String> = produce {
var x = 1
while (true) {
send("Pizza Order No. ${x++}")
delay(100)
}
}
fun CoroutineScope.pizzaOrderProcessor(id: Int, orders: ReceiveChannel<String>) = launch {
for (order in orders) {
println("Processor #$id is processing $order")
}
}
@ExperimentalCoroutinesApi
fun main() = runBlocking {
val pizzaOrders = producePizzaOrders()
repeat(3) {
pizzaOrderProcessor(it + 1, pizzaOrders)
}
delay(1000)
pizzaOrders.cancel()
}

View File

@ -0,0 +1,24 @@
package com.baeldung.channles
import kotlinx.coroutines.channels.ticker
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import java.time.Duration
import kotlin.random.Random
fun stockPrice(stock: String): Double {
log("Fetching stock price of $stock")
return Random.nextDouble(2.0, 3.0)
}
fun main() = runBlocking {
val tickerChannel = ticker(Duration.ofSeconds(5).toMillis())
repeat(3) {
tickerChannel.receive()
log(stockPrice("TESLA"))
}
delay(Duration.ofSeconds(11).toMillis())
tickerChannel.cancel()
}

View File

@ -0,0 +1,28 @@
package com.baeldung.channles
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.Channel.Factory.UNLIMITED
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val channel = Channel<Int>(UNLIMITED)
launch { // coroutine1
repeat(100) {
println("coroutine1: Sending $it")
channel.send(it)
}
}
launch { // coroutine2
repeat(100) {
println("coroutine2: Received ${channel.receive()}")
}
}
delay(2000)
coroutineContext.cancelChildren()
}

View File

@ -0,0 +1,8 @@
package com.baeldung.channles
import java.text.SimpleDateFormat
import java.util.*
fun log(value: Any) {
println(SimpleDateFormat("HH:MM:ss").format(Date()) + " - $value")
}

View File

@ -0,0 +1,29 @@
package com.baeldung.channels
import kotlinx.coroutines.async
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class ChannelsTest {
@Test
fun should_pass_data_from_one_coroutine_to_another() {
runBlocking {
// given
val channel = Channel<String>()
// when
launch { // coroutine1
channel.send("Hello World!")
}
val result = async { // coroutine 2
channel.receive()
}
// then
assertThat(result.await()).isEqualTo("Hello World!")
}
}
}

View File

@ -0,0 +1,32 @@
plugins {
id 'java'
id 'org.springframework.boot' version '2.3.4.RELEASE'
}
group = 'com.gradle'
version = '1.0.0'
sourceCompatibility = '14'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter:2.3.4.RELEASE'
testImplementation 'org.springframework.boot:spring-boot-starter-test:2.3.4.RELEASE'
compileOnly 'org.projectlombok:lombok:1.18.14'
testCompileOnly 'org.projectlombok:lombok:1.18.14'
runtimeOnly files('libs/sampleOne.jar', 'libs/sampleTwo.jar')
runtimeOnly fileTree('libs') { include '*.jar' }
// implementation gradleApi()
}
test {
useJUnitPlatform()
}

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@ -0,0 +1 @@
rootProject.name = 'dependencymanagement'

View File

@ -0,0 +1,13 @@
package com.gradle.dependencymanagement;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DependencyManagementApplication {
public static void main(String[] args) {
SpringApplication.run(DependencyManagementApplication.class, args);
}
}

View File

@ -0,0 +1,13 @@
package com.gradle.dependencymanagement;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DependencyManagementApplicationTests {
@Test
void contextLoads() {
}
}

View File

@ -4,12 +4,13 @@ import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.Cookie; import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.impl.cookie.BasicClientCookie;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -47,6 +48,7 @@ public class HttpClientGettingCookieValueUnitTest {
BasicCookieStore cookieStore = new BasicCookieStore(); BasicCookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("custom_cookie", "test_value"); BasicClientCookie cookie = new BasicClientCookie("custom_cookie", "test_value");
cookie.setDomain("baeldung.com"); cookie.setDomain("baeldung.com");
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");
cookie.setPath("/"); cookie.setPath("/");
cookieStore.addCookie(cookie); cookieStore.addCookie(cookie);
return cookieStore; return cookieStore;

View File

@ -302,7 +302,7 @@
<!-- testing --> <!-- testing -->
<wiremock.version>2.5.1</wiremock.version> <wiremock.version>2.5.1</wiremock.version>
<httpcore.version>4.4.11</httpcore.version> <httpcore.version>4.4.11</httpcore.version>
<httpclient.version>4.5.8</httpclient.version> <!-- 4.3.6 --> <!-- 4.4-beta1 --> <httpclient.version>4.5.8</httpclient.version>
<!-- maven plugins --> <!-- maven plugins -->
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version> <cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
</properties> </properties>

View File

@ -1,19 +1,23 @@
package com.baeldung.httpclient.sec; package com.baeldung.httpclient.sec;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
import com.baeldung.httpclient.ResponseUtil; import com.baeldung.httpclient.ResponseUtil;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
@ -26,6 +30,8 @@ public class HttpClientCookieLiveTest {
private CloseableHttpResponse response; private CloseableHttpResponse response;
private static Logger log = LoggerFactory.getLogger(HttpClientCookieLiveTest.class);
@Before @Before
public final void before() { public final void before() {
instance = HttpClientBuilder.create().build(); instance = HttpClientBuilder.create().build();
@ -54,11 +60,15 @@ public class HttpClientCookieLiveTest {
final BasicCookieStore cookieStore = new BasicCookieStore(); final BasicCookieStore cookieStore = new BasicCookieStore();
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
cookie.setDomain(".github.com"); cookie.setDomain(".github.com");
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");
cookie.setPath("/"); cookie.setPath("/");
cookieStore.addCookie(cookie); cookieStore.addCookie(cookie);
final HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
final HttpGet request = new HttpGet("http://www.github.com"); DefaultHttpClient client = new DefaultHttpClient();
client.setCookieStore(cookieStore);
final HttpGet request = new HttpGet("https://www.github.com");
response = (CloseableHttpResponse) client.execute(request); response = (CloseableHttpResponse) client.execute(request);
@ -70,6 +80,7 @@ public class HttpClientCookieLiveTest {
final BasicCookieStore cookieStore = new BasicCookieStore(); final BasicCookieStore cookieStore = new BasicCookieStore();
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
cookie.setDomain(".github.com"); cookie.setDomain(".github.com");
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");
cookie.setPath("/"); cookie.setPath("/");
cookieStore.addCookie(cookie); cookieStore.addCookie(cookie);
instance = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build(); instance = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();

View File

@ -0,0 +1,20 @@
package com.baeldung.number_0xff;
public class Number0xff {
public static int getRedColor(int rgba) {
return rgba >> 24 & 0xff;
}
public static int getGreenColor(int rgba) {
return rgba >> 16 & 0xff;
}
public static int getBlueColor(int rgba) {
return rgba >> 8 & 0xff;
}
public static int getAlfa(int rgba) {
return rgba & 0xff;
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.number_0xff;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class Number0xffUnitTest {
@Test
public void test0xFFAssignedToInteger() {
int x = 0xff;
int expectedValue = 255;
assertEquals(expectedValue, x);
}
@Test
public void test0xFFAssignedToByte() {
byte y = (byte) 0xff;
int expectedValue = -1;
assertEquals(expectedValue, y);
}
@Test
public void givenColor_whenGetRedColor_thenExtractRedColor() {
int rgba = 272214023;
int expectedValue = 16;
assertEquals(expectedValue, Number0xff.getRedColor(rgba));
}
@Test
public void givenColor_whenGetGreenColor_thenExtractGreenColor() {
int rgba = 272214023;
int expectedValue = 57;
assertEquals(expectedValue, Number0xff.getGreenColor(rgba));
}
@Test
public void givenColor_whenGetBlueColor_thenExtractBlueColor() {
int rgba = 272214023;
int expectedValue = 168;
assertEquals(expectedValue, Number0xff.getBlueColor(rgba));
}
@Test
public void givenColor_whenGetAlfa_thenExtractAlfa() {
int rgba = 272214023;
int expectedValue = 7;
assertEquals(expectedValue, Number0xff.getAlfa(rgba));
}
}

View File

@ -3,12 +3,12 @@
This module contains articles about numbers in Java. This module contains articles about numbers in Java.
### Relevant Articles: ### Relevant Articles:
- [Number of Digits in an Integer in Java](http://www.baeldung.com/java-number-of-digits-in-int) - [Number of Digits in an Integer in Java](https://www.baeldung.com/java-number-of-digits-in-int)
- [How to Round a Number to N Decimal Places in Java](http://www.baeldung.com/java-round-decimal-number) - [How to Round a Number to N Decimal Places in Java](https://www.baeldung.com/java-round-decimal-number)
- [BigDecimal and BigInteger in Java](http://www.baeldung.com/java-bigdecimal-biginteger) - [BigDecimal and BigInteger in Java](https://www.baeldung.com/java-bigdecimal-biginteger)
- [Find All Pairs of Numbers in an Array That Add Up to a Given Sum](http://www.baeldung.com/java-algorithm-number-pairs-sum) - [Find All Pairs of Numbers in an Array That Add Up to a Given Sum in Java](https://www.baeldung.com/java-algorithm-number-pairs-sum)
- [Java Random Long, Float, Integer and Double](http://www.baeldung.com/java-generate-random-long-float-integer-double) - [Java Random Long, Float, Integer and Double](https://www.baeldung.com/java-generate-random-long-float-integer-double)
- [A Practical Guide to DecimalFormat](http://www.baeldung.com/java-decimalformat) - [A Practical Guide to DecimalFormat](https://www.baeldung.com/java-decimalformat)
- [Calculating the nth Root in Java](https://www.baeldung.com/java-nth-root) - [Calculating the nth Root in Java](https://www.baeldung.com/java-nth-root)
- [Convert Double to String, Removing Decimal Places](https://www.baeldung.com/java-double-to-string) - [Convert Double to String, Removing Decimal Places](https://www.baeldung.com/java-double-to-string)
- [Changing the Order in a Sum Operation Can Produce Different Results?](https://www.baeldung.com/java-floating-point-sum-order) - [Changing the Order in a Sum Operation Can Produce Different Results?](https://www.baeldung.com/java-floating-point-sum-order)

View File

@ -10,6 +10,7 @@ import javafx.scene.Node;
import javafx.scene.control.*; import javafx.scene.control.*;
import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCode;
import javafx.scene.layout.VBox; import javafx.scene.layout.VBox;
import javafx.scene.control.cell.PropertyValueFactory;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -22,11 +23,14 @@ public class SearchController {
@FXML @FXML
private Button searchButton; private Button searchButton;
@FXML @FXML
private Pagination pagination;
@FXML
private Label searchLabel; private Label searchLabel;
@FXML
private TableView tableView;
@FXML
private VBox dataContainer;
private ObservableList<Person> masterData = FXCollections.observableArrayList(); private ObservableList<Person> masterData = FXCollections.observableArrayList();
private ObservableList<Person> results = FXCollections.observableList(masterData);
public SearchController() { public SearchController() {
masterData.add(new Person(5, "John", true)); masterData.add(new Person(5, "John", true));
@ -40,7 +44,7 @@ public class SearchController {
// search panel // search panel
searchButton.setText("Search"); searchButton.setText("Search");
searchButton.setOnAction(event -> loadData()); searchButton.setOnAction(event -> loadData());
searchButton.setStyle("-fx-background-color: #457ecd; -fx-text-fill: #ffffff;"); searchButton.setStyle("-fx-background-color: slateblue; -fx-text-fill: white;");
searchField.setOnKeyPressed(event -> { searchField.setOnKeyPressed(event -> {
if (event.getCode().equals(KeyCode.ENTER)) { if (event.getCode().equals(KeyCode.ENTER)) {
@ -52,22 +56,23 @@ public class SearchController {
searchLabel.setText(newValue); searchLabel.setText(newValue);
}); });
pagination.setPageFactory(SearchController.this::createPage); initTable();
} }
private Node createPage(Integer pageIndex) { private void initTable() {
tableView = new TableView<>(FXCollections.observableList(masterData));
tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
VBox dataContainer = new VBox();
TableView<Person> tableView = new TableView<>(masterData);
TableColumn id = new TableColumn("ID"); TableColumn id = new TableColumn("ID");
id.setCellValueFactory(new PropertyValueFactory("id"));
TableColumn name = new TableColumn("NAME"); TableColumn name = new TableColumn("NAME");
name.setCellValueFactory(new PropertyValueFactory("name"));
TableColumn employed = new TableColumn("EMPLOYED"); TableColumn employed = new TableColumn("EMPLOYED");
employed.setCellValueFactory(new PropertyValueFactory("isEmployed"));
tableView.getColumns().addAll(id, name, employed); tableView.getColumns().addAll(id, name, employed);
dataContainer.getChildren().add(tableView);
return dataContainer; dataContainer.getChildren().add(tableView);
} }
private void loadData() { private void loadData() {
@ -86,9 +91,8 @@ public class SearchController {
}; };
task.setOnSucceeded(event -> { task.setOnSucceeded(event -> {
masterData = task.getValue(); results = task.getValue();
pagination.setVisible(true); tableView.setItems(FXCollections.observableList(results));
pagination.setPageCount(masterData.size() / PAGE_ITEMS_COUNT);
}); });
Thread th = new Thread(task); Thread th = new Thread(task);

View File

@ -21,13 +21,12 @@
</children> </children>
</HBox> </HBox>
<Pagination fx:id="pagination" <VBox fx:id="dataContainer"
AnchorPane.leftAnchor="10.0" AnchorPane.leftAnchor="10.0"
AnchorPane.rightAnchor="10.0" AnchorPane.rightAnchor="10.0"
AnchorPane.topAnchor="50.0" AnchorPane.topAnchor="50.0">
visible="false">
</Pagination> </VBox>
</children> </children>
</AnchorPane> </AnchorPane>

View File

@ -1,6 +1,5 @@
package com.baeldung.servlets; package com.baeldung.servlets;
import java.io.IOException; import java.io.IOException;
import javax.servlet.RequestDispatcher; import javax.servlet.RequestDispatcher;
@ -18,10 +17,14 @@ public class UpdateServlet extends HttpServlet {
HttpSession session = request.getSession(false); HttpSession session = request.getSession(false);
if (session != null) {
session.setAttribute("userName", request.getParameter("userName")); session.setAttribute("userName", request.getParameter("userName"));
session.setAttribute("age", request.getParameter("age")); session.setAttribute("age", request.getParameter("age"));
request.setAttribute("sessionData", session); request.setAttribute("sessionData", session);
}
RequestDispatcher requestDispather = request.getRequestDispatcher("update.jsp"); RequestDispatcher requestDispather = request.getRequestDispatcher("update.jsp");
requestDispather.forward(request, response); requestDispather.forward(request, response);

2
kotlin-js/build.gradle Executable file → Normal file
View File

@ -1,5 +1,5 @@
buildscript { buildscript {
ext.kotlin_version = '1.2.41' ext.kotlin_version = '1.4.10'
repositories { repositories {
mavenCentral() mavenCentral()
} }

Binary file not shown.

View File

@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-bin.zip

51
kotlin-js/gradlew vendored
View File

@ -1,5 +1,21 @@
#!/usr/bin/env sh #!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
############################################################################## ##############################################################################
## ##
## Gradle start up script for UN*X ## Gradle start up script for UN*X
@ -28,7 +44,7 @@ APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"` APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS="" DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum" MAX_FD="maximum"
@ -109,8 +125,8 @@ if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi fi
# For Cygwin, switch paths to Windows format before running java # For Cygwin or MSYS, switch paths to Windows format before running java
if $cygwin ; then if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"` APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"` JAVACMD=`cygpath --unix "$JAVACMD"`
@ -138,19 +154,19 @@ if $cygwin ; then
else else
eval `echo args$i`="\"$arg\"" eval `echo args$i`="\"$arg\""
fi fi
i=$((i+1)) i=`expr $i + 1`
done done
case $i in case $i in
(0) set -- ;; 0) set -- ;;
(1) set -- "$args0" ;; 1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;; 2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;; 3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;; 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac esac
fi fi
@ -159,14 +175,9 @@ save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " " echo " "
} }
APP_ARGS=$(save "$@") APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules # Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@" exec "$JAVACMD" "$@"

21
kotlin-js/gradlew.bat vendored Executable file → Normal file
View File

@ -1,3 +1,19 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off @if "%DEBUG%" == "" @echo off
@rem ########################################################################## @rem ##########################################################################
@rem @rem
@ -13,8 +29,11 @@ if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0 set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME% set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS= set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe @rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome if defined JAVA_HOME goto findJavaFromJavaHome

16
kotlin-js/package.json Executable file → Normal file
View File

@ -1,17 +1,15 @@
{ {
"name": "kotlin-node.js", "name": "kotlin-node",
"version": "1.0.0", "version": "1.0.0",
"description": "Example of using NodeJS in Kotlin", "description": "Example of using NodeJS in Kotlin",
"main": "crypto.js", "main": "crypto.js",
"dependencies": {
"express": "^4.15.2",
"fs": "0.0.1-security",
"kotlin": "^1.1.0",
"node.js": "0.0.0",
"request": "^2.85.0"
},
"devDependencies": {},
"scripts": { "scripts": {
"start": "node node/crypto.js" "start": "node node/crypto.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"kotlin": "^1.4.10"
} }
} }

View File

@ -1 +1 @@
rootProject.name = 'KotlinNode' rootProject.name = 'kotlin-node'

View File

@ -13,7 +13,7 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m
- [Implementing a FTP-Client in Java](https://www.baeldung.com/java-ftp-client) - [Implementing a FTP-Client in Java](https://www.baeldung.com/java-ftp-client)
- [Introduction to Functional Java](https://www.baeldung.com/java-functional-library) - [Introduction to Functional Java](https://www.baeldung.com/java-functional-library)
- [A Guide to the Reflections Library](https://www.baeldung.com/reflections-library) - [A Guide to the Reflections Library](https://www.baeldung.com/reflections-library)
- [Exactly Once Processing in Kafka](https://www.baeldung.com/kafka-exactly-once) - [Exactly Once Processing in Kafka with Java](https://www.baeldung.com/kafka-exactly-once)
- [Introduction to Protonpack](https://www.baeldung.com/java-protonpack) - [Introduction to Protonpack](https://www.baeldung.com/java-protonpack)
- [Java-R Integration](https://www.baeldung.com/java-r-integration) - [Java-R Integration](https://www.baeldung.com/java-r-integration)
- [Using libphonenumber to Validate Phone Numbers](https://www.baeldung.com/java-libphonenumber) - [Using libphonenumber to Validate Phone Numbers](https://www.baeldung.com/java-libphonenumber)

View File

@ -0,0 +1,182 @@
package com.baeldung.apache.commons;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.bidimap.DualHashBidiMap;
import org.apache.commons.collections4.bidimap.DualTreeBidiMap;
import org.apache.commons.collections4.bidimap.TreeBidiMap;
import org.apache.commons.collections4.map.MultiKeyMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
import org.junit.Test;
public class CollectionsUnitTest {
private final static BidiMap<Integer, String> daysOfWeek = new TreeBidiMap<Integer, String>();
private final static MultiValuedMap<String, String> groceryCart = new ArrayListValuedHashMap<>();
private final static MultiKeyMap<String, String> days = new MultiKeyMap<String, String>();
private final static MultiKeyMap<String, String> cityCoordinates = new MultiKeyMap<String, String>();
private long start;
static {
daysOfWeek.put(1, "Monday");
daysOfWeek.put(2, "Tuesday");
daysOfWeek.put(3, "Wednesday");
daysOfWeek.put(4, "Thursday");
daysOfWeek.put(5, "Friday");
daysOfWeek.put(6, "Saturday");
daysOfWeek.put(7, "Sunday");
groceryCart.put("Fruits", "Apple");
groceryCart.put("Fruits", "Grapes");
groceryCart.put("Fruits", "Strawberries");
groceryCart.put("Vegetables", "Spinach");
groceryCart.put("Vegetables", "Cabbage");
days.put("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Weekday");
days.put("Saturday", "Sunday", "Weekend");
cityCoordinates.put("40.7128° N", "74.0060° W", "New York");
cityCoordinates.put("48.8566° N", "2.3522° E", "Paris");
cityCoordinates.put("19.0760° N", "72.8777° E", "Mumbai");
}
@Test
public void givenBidiMap_whenValue_thenKeyReturned() {
assertEquals(Integer.valueOf(7), daysOfWeek.inverseBidiMap()
.get("Sunday"));
}
@Test
public void givenBidiMap_whenKey_thenValueReturned() {
assertEquals("Tuesday", daysOfWeek.get(2));
}
@Test
public void givenMultiValuedMap_whenFruitsFetched_thenFruitsReturned() {
List<String> fruits = Arrays.asList("Apple", "Grapes", "Strawberries");
assertEquals(fruits, groceryCart.get("Fruits"));
}
@Test
public void givenMultiValuedMap_whenVeggiesFetched_thenVeggiesReturned() {
List<String> veggies = Arrays.asList("Spinach", "Cabbage");
assertEquals(veggies, groceryCart.get("Vegetables"));
}
@Test
public void givenMultiValuedMap_whenFuitsRemoved_thenVeggiesPreserved() {
assertEquals(5, groceryCart.size());
groceryCart.remove("Fruits");
assertEquals(2, groceryCart.size());
}
@Test
public void givenDaysMultiKeyMap_whenFetched_thenOK() {
assertFalse(days.get("Saturday", "Sunday")
.equals("Weekday"));
}
@Test
public void givenCoordinatesMultiKeyMap_whenQueried_thenOK() {
List<String> expectedLongitudes = Arrays.asList("72.8777° E", "2.3522° E", "74.0060° W");
List<String> longitudes = new ArrayList<>();
cityCoordinates.forEach((key, value) -> {
longitudes.add(key.getKey(1));
});
assertArrayEquals(expectedLongitudes.toArray(), longitudes.toArray());
List<String> expectedCities = Arrays.asList("Mumbai", "Paris", "New York");
List<String> cities = new ArrayList<>();
cityCoordinates.forEach((key, value) -> {
cities.add(value);
});
assertArrayEquals(expectedCities.toArray(), cities.toArray());
}
@Test
public void givenTreeBidiMap_whenHundredThousandKeys_thenPerformanceNoted() {
System.out.println("**TreeBidiMap**");
BidiMap<Integer, Integer> map = new TreeBidiMap<>();
start = System.nanoTime();
for (int i = 0; i < 100000; i++) {
Integer key = new Integer(i);
Integer value = new Integer(i + 1);
map.put(key, value);
}
System.out.println("Insertion time:" + TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
start = System.nanoTime();
Integer value = (Integer) map.get(new Integer(500));
System.out.println("Value:" + value);
System.out.println("Fetch time key:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
start = System.nanoTime();
Integer key = (Integer) map.getKey(new Integer(501));
System.out.println("Key:" + key);
System.out.println("Fetch time value:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
}
@Test
public void givenDualTreeBidiMap_whenHundredThousandKeys_thenPerformanceNoted() {
System.out.println("**DualTreeBidiMap**");
BidiMap<Integer, Integer> map = new DualTreeBidiMap<>();
start = System.nanoTime();
for (int i = 0; i < 100000; i++) {
Integer key = new Integer(i);
Integer value = new Integer(i + 1);
map.put(key, value);
}
System.out.println("Insertion time:" + TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
start = System.nanoTime();
Integer value = (Integer) map.get(new Integer(500));
System.out.println("Value:" + value);
System.out.println("Fetch time key:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
start = System.nanoTime();
Integer key = (Integer) map.getKey(new Integer(501));
System.out.println("Key:" + key);
System.out.println("Fetch time value:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
}
@Test
public void givenDualHashBidiMap_whenHundredThousandKeys_thenPerformanceNoted() {
System.out.println("**DualHashBidiMap**");
BidiMap<Integer, Integer> map = new DualHashBidiMap<>();
start = System.nanoTime();
for (int i = 0; i < 100000; i++) {
Integer key = new Integer(i);
Integer value = new Integer(i + 1);
map.put(key, value);
}
System.out.println("Insertion time:" + TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
start = System.nanoTime();
Integer value = (Integer) map.get(new Integer(500));
System.out.println("Value:" + value);
System.out.println("Fetch time key:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
start = System.nanoTime();
Integer key = (Integer) map.getKey(new Integer(501));
System.out.println("Key:" + key);
System.out.println("Fetch time value:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
}
}

View File

@ -0,0 +1,143 @@
package com.baeldung.guava;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Table;
public class GuavaUnitTest {
private final static BiMap<Integer, String> daysOfWeek = HashBiMap.create();
private final static Multimap<String, String> groceryCart = ArrayListMultimap.create();
private final static Table<String, String, String> cityCoordinates = HashBasedTable.create();
private final static Table<String, String, String> movies = HashBasedTable.create();
private long start;
static {
daysOfWeek.put(1, "Monday");
daysOfWeek.put(2, "Tuesday");
daysOfWeek.put(3, "Wednesday");
daysOfWeek.put(4, "Thursday");
daysOfWeek.put(5, "Friday");
daysOfWeek.put(6, "Saturday");
daysOfWeek.put(7, "Sunday");
groceryCart.put("Fruits", "Apple");
groceryCart.put("Fruits", "Grapes");
groceryCart.put("Fruits", "Strawberries");
groceryCart.put("Vegetables", "Spinach");
groceryCart.put("Vegetables", "Cabbage");
cityCoordinates.put("40.7128° N", "74.0060° W", "New York");
cityCoordinates.put("48.8566° N", "2.3522° E", "Paris");
cityCoordinates.put("19.0760° N", "72.8777° E", "Mumbai");
movies.put("Tom Hanks", "Meg Ryan", "You've Got Mail");
movies.put("Tom Hanks", "Catherine Zeta-Jones", "The Terminal");
movies.put("Bradley Cooper", "Lady Gaga", "A Star is Born");
movies.put("Keenu Reaves", "Sandra Bullock", "Speed");
movies.put("Tom Hanks", "Sandra Bullock", "Extremely Loud & Incredibly Close");
}
@Test
public void givenBiMap_whenValue_thenKeyReturned() {
assertEquals(Integer.valueOf(7), daysOfWeek.inverse()
.get("Sunday"));
}
@Test
public void givenBiMap_whenKey_thenValueReturned() {
assertEquals("Tuesday", daysOfWeek.get(2));
}
@Test
public void givenMultiValuedMap_whenFruitsFetched_thenFruitsReturned() {
List<String> fruits = Arrays.asList("Apple", "Grapes", "Strawberries");
assertEquals(fruits, groceryCart.get("Fruits"));
}
@Test
public void givenMultiValuedMap_whenVeggiesFetched_thenVeggiesReturned() {
List<String> veggies = Arrays.asList("Spinach", "Cabbage");
assertEquals(veggies, groceryCart.get("Vegetables"));
}
@Test
public void givenMultiValuedMap_whenFuitsRemoved_thenVeggiesPreserved() {
assertEquals(5, groceryCart.size());
groceryCart.remove("Fruits", "Apple");
assertEquals(4, groceryCart.size());
groceryCart.removeAll("Fruits");
assertEquals(2, groceryCart.size());
}
@Test
public void givenCoordinatesTable_whenFetched_thenOK() {
List<String> expectedLongitudes = Arrays.asList("74.0060° W", "2.3522° E", "72.8777° E");
assertArrayEquals(expectedLongitudes.toArray(), cityCoordinates.columnKeySet()
.toArray());
List<String> expectedCities = Arrays.asList("New York", "Paris", "Mumbai");
assertArrayEquals(expectedCities.toArray(), cityCoordinates.values()
.toArray());
assertTrue(cityCoordinates.rowKeySet()
.contains("48.8566° N"));
}
@Test
public void givenMoviesTable_whenFetched_thenOK() {
assertEquals(3, movies.row("Tom Hanks")
.size());
assertEquals(2, movies.column("Sandra Bullock")
.size());
assertEquals("A Star is Born", movies.get("Bradley Cooper", "Lady Gaga"));
assertTrue(movies.containsValue("Speed"));
}
@Test
public void givenHashBiMap_whenHundredThousandKeys_thenPerformanceNoted() {
BiMap<Integer, Integer> map = HashBiMap.create();
start = System.nanoTime();
for (int i = 0; i < 100000; i++) {
Integer key = new Integer(i);
Integer value = new Integer(i + 1);
map.put(key, value);
}
System.out.println("Insertion time:" + TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
start = System.nanoTime();
Integer value = map.get(new Integer(500));
System.out.println("Value:" + value);
System.out.println("Fetch time key:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
start = System.nanoTime();
Integer key = map.inverse()
.get(new Integer(501));
System.out.println("Key:" + key);
System.out.println("Fetch time value:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
}
}

View File

@ -4,7 +4,7 @@ This module contains articles about libraries for data processing in Java.
### Relevant articles ### Relevant articles
- [Introduction to Apache Flink with Java](https://www.baeldung.com/apache-flink) - [Introduction to Apache Flink with Java](https://www.baeldung.com/apache-flink)
- [Guide to the HyperLogLog Algorithm](https://www.baeldung.com/java-hyperloglog) - [Guide to the HyperLogLog Algorithm in Java](https://www.baeldung.com/java-hyperloglog)
- [Introduction to Conflict-Free Replicated Data Types](https://www.baeldung.com/java-conflict-free-replicated-data-types) - [Introduction to Conflict-Free Replicated Data Types](https://www.baeldung.com/java-conflict-free-replicated-data-types)
- [Introduction to javax.measure](https://www.baeldung.com/javax-measure) - [Introduction to javax.measure](https://www.baeldung.com/javax-measure)
- [A Guide to Infinispan in Java](https://www.baeldung.com/infinispan) - [A Guide to Infinispan in Java](https://www.baeldung.com/infinispan)

View File

@ -66,6 +66,18 @@
<artifactId>reactive-streams</artifactId> <artifactId>reactive-streams</artifactId>
<version>${reactive.stream.version}</version> <version>${reactive.stream.version}</version>
</dependency> </dependency>
<!-- Retrofit -->
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>${retrofit.version}</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-gson</artifactId>
<version>${retrofit.version}</version>
</dependency>
</dependencies> </dependencies>
<properties> <properties>
@ -76,6 +88,7 @@
<jetty.httpclient.version>1.0.3</jetty.httpclient.version> <jetty.httpclient.version>1.0.3</jetty.httpclient.version>
<jetty.server.version>9.4.19.v20190610</jetty.server.version> <jetty.server.version>9.4.19.v20190610</jetty.server.version>
<rxjava2.version>2.2.11</rxjava2.version> <rxjava2.version>2.2.11</rxjava2.version>
<retrofit.version>2.3.0</retrofit.version>
<spring.webflux.version>5.1.9.RELEASE</spring.webflux.version> <spring.webflux.version>5.1.9.RELEASE</spring.webflux.version>
<reactive.stream.version>1.0.3</reactive.stream.version> <reactive.stream.version>1.0.3</reactive.stream.version>
<reactor.version>3.2.12.RELEASE</reactor.version> <reactor.version>3.2.12.RELEASE</reactor.version>

View File

@ -0,0 +1,19 @@
package com.baeldung.retrofit.dynamic;
import com.baeldung.retrofit.models.Contributor;
import com.baeldung.retrofit.models.Repository;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Url;
import java.util.List;
public interface GitHubDynamicApi {
@GET
Call<List<Repository>> reposList(@Url String url);
@GET("{fullUrl}")
Call<List<Contributor>> contributorsList(@Path(value = "fullUrl", encoded = true) String fullUrl);
}

View File

@ -0,0 +1,13 @@
package com.baeldung.retrofit.dynamic;
import java.io.IOException;
import java.util.List;
public class GitHubDynamicApiApp {
public static void main(String[] args) throws IOException {
String url = "https://api.github.com/users/eugenp/repos";
List<String> topContributors = new GitHubDynamicApiService().getTopContributors(url);
topContributors.forEach(System.out::println);
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.retrofit.dynamic;
import com.baeldung.retrofit.models.Contributor;
import com.baeldung.retrofit.models.Repository;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class GitHubDynamicApiService {
private GitHubDynamicApi gitHubDynamicApi;
GitHubDynamicApiService() {
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).build();
gitHubDynamicApi = retrofit.create(GitHubDynamicApi.class);
}
List<String> getTopContributors(String url) throws IOException {
List<Repository> repos = gitHubDynamicApi.reposList(url).execute().body();
repos = repos != null ? repos : Collections.emptyList();
return repos.stream().flatMap(repo -> getContributors("repos/eugenp/"+repo+"/contributors")).sorted((a, b) -> b.getContributions() - a.getContributions()).map(com.baeldung.retrofit.models.Contributor::getName).distinct().sorted().collect(Collectors.toList());
}
private Stream<Contributor> getContributors(String fullUrl) {
List<Contributor> contributors = null;
try {
contributors = gitHubDynamicApi.contributorsList(fullUrl).execute().body();
} catch (IOException e) {
e.printStackTrace();
}
contributors = contributors != null ? contributors : Collections.emptyList();
return contributors.stream().filter(c -> c.getContributions() > 100);
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.retrofit.models;
import com.google.gson.annotations.SerializedName;
public class Contributor {
@SerializedName("login")
private String name;
private Integer contributions;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getContributions() {
return contributions;
}
public void setContributions(Integer contributions) {
this.contributions = contributions;
}
@Override
public String toString() {
return "Contributer [name=" + name + ", contributions=" + contributions + "]";
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.retrofit.models;
public class Repository {
private String name;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "Repository [name=" + name + ", description=" + description + "]";
}
}

View File

@ -2,3 +2,6 @@
This module contains articles about Netflix. This module contains articles about Netflix.
### Relevant Articles:
- [Introduction to Netflix Mantis](https://www.baeldung.com/java-netflix-mantis)

Some files were not shown because too many files have changed in this diff Show More