Merge branch 'master' into javabeanconstraints
This commit is contained in:
commit
9060d6c3ba
33
README.md
33
README.md
|
@ -2,41 +2,22 @@
|
||||||
The "REST with Spring" Classes
|
The "REST with Spring" Classes
|
||||||
==============================
|
==============================
|
||||||
|
|
||||||
Here's the Master Class of REST With Spring (price changes permanently next Friday): <br/>
|
Here's the Master Class of REST With Spring (along with the newly announced Boot 2 material): <br/>
|
||||||
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
**[>> THE REST WITH SPRING - MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
||||||
|
|
||||||
And here's the Master Class of Learn Spring Security: <br/>
|
And here's the Master Class of Learn Spring Security: <br/>
|
||||||
**[>> LEARN SPRING SECURITY MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
|
**[>> LEARN SPRING SECURITY - MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Spring Tutorials
|
Java and Spring Tutorials
|
||||||
================
|
================
|
||||||
|
|
||||||
This project is **a collection of small and focused tutorials** each covering a single and well defined area of development.
|
This project is **a collection of small and focused tutorials** - each covering a single and well defined area of development in the Java ecosystem.
|
||||||
Most of the tutorial projects are focused on the `Spring Framework` (and `Spring Security`).
|
A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Securiyt.
|
||||||
In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`.
|
In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`.
|
||||||
|
|
||||||
|
|
||||||
Building the project
|
Building the project
|
||||||
====================
|
====================
|
||||||
To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false`
|
To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false`
|
||||||
|
|
||||||
|
|
||||||
Working with the code in Eclipse
|
|
||||||
================================
|
|
||||||
Any IDE can be used to work with the projects, but if you're using Eclipse, consider the following.
|
|
||||||
|
|
||||||
- import the included **formatter** in Eclipse:
|
|
||||||
`https://github.com/eugenp/tutorials/tree/master/eclipse`
|
|
||||||
|
|
||||||
|
|
||||||
CI - Jenkins
|
|
||||||
================================
|
|
||||||
This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/tutorials-unit/)**
|
|
||||||
|
|
||||||
### Relevant Articles:
|
|
||||||
================================
|
|
||||||
|
|
||||||
- [Apache Maven Standard Directory Layout](http://www.baeldung.com/maven-directory-structure)
|
|
||||||
- [Apache Maven Tutorial](http://www.baeldung.com/maven)
|
|
||||||
- [Designing a User Friendly Java Library](http://www.baeldung.com/design-a-user-friendly-java-library)
|
|
||||||
|
|
|
@ -24,3 +24,7 @@
|
||||||
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
|
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
|
||||||
- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)
|
- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)
|
||||||
- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation)
|
- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation)
|
||||||
|
- [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)
|
||||||
|
- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines)
|
||||||
|
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
|
||||||
|
|
|
@ -98,7 +98,7 @@ public class FindKthLargest {
|
||||||
|
|
||||||
private int randomPartition(Integer arr[], int left, int right) {
|
private int randomPartition(Integer arr[], int left, int right) {
|
||||||
int n = right - left + 1;
|
int n = right - left + 1;
|
||||||
int pivot = (int) (Math.random()) % n;
|
int pivot = (int) (Math.random() * n);
|
||||||
swap(arr, left + pivot, right);
|
swap(arr, left + pivot, right);
|
||||||
return partition(arr, left, right);
|
return partition(arr, left, right);
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,50 @@
|
||||||
|
package com.baeldung.algorithms.mergesort;
|
||||||
|
|
||||||
|
public class MergeSort {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
int[] a = { 5, 1, 6, 2, 3, 4 };
|
||||||
|
mergeSort(a, a.length);
|
||||||
|
for (int i = 0; i < a.length; i++)
|
||||||
|
System.out.println(a[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void mergeSort(int[] a, int n) {
|
||||||
|
if (n < 2)
|
||||||
|
return;
|
||||||
|
int mid = n / 2;
|
||||||
|
int[] l = new int[mid];
|
||||||
|
int[] r = new int[n - mid];
|
||||||
|
|
||||||
|
for (int i = 0; i < mid; i++) {
|
||||||
|
l[i] = a[i];
|
||||||
|
}
|
||||||
|
for (int i = mid; i < n; i++) {
|
||||||
|
r[i - mid] = a[i];
|
||||||
|
}
|
||||||
|
mergeSort(l, mid);
|
||||||
|
mergeSort(r, n - mid);
|
||||||
|
|
||||||
|
merge(a, l, r, mid, n - mid);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void merge(int[] a, int[] l, int[] r, int left, int right) {
|
||||||
|
|
||||||
|
int i = 0, j = 0, k = 0;
|
||||||
|
|
||||||
|
while (i < left && j < right) {
|
||||||
|
|
||||||
|
if (l[i] < r[j])
|
||||||
|
a[k++] = l[i++];
|
||||||
|
else
|
||||||
|
a[k++] = r[j++];
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
while (i < left)
|
||||||
|
a[k++] = l[i++];
|
||||||
|
|
||||||
|
while (j < right)
|
||||||
|
a[k++] = r[j++];
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,39 @@
|
||||||
|
package com.baeldung.algorithms.quicksort;
|
||||||
|
|
||||||
|
public class QuickSort {
|
||||||
|
|
||||||
|
public static void quickSort(int arr[], int begin, int end)
|
||||||
|
{
|
||||||
|
if (begin < end) {
|
||||||
|
int partitionIndex = partition(arr, begin, end);
|
||||||
|
|
||||||
|
// Recursively sort elements of the 2 sub-arrays
|
||||||
|
quickSort(arr, begin, partitionIndex-1);
|
||||||
|
quickSort(arr, partitionIndex+1, end);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int partition(int arr[], int begin, int end)
|
||||||
|
{
|
||||||
|
int pivot = arr[end];
|
||||||
|
int i = (begin-1);
|
||||||
|
|
||||||
|
for (int j=begin; j<end; j++)
|
||||||
|
{
|
||||||
|
if (arr[j] <= pivot) {
|
||||||
|
i++;
|
||||||
|
|
||||||
|
int swapTemp = arr[i];
|
||||||
|
arr[i] = arr[j];
|
||||||
|
arr[j] = swapTemp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int swapTemp = arr[i+1];
|
||||||
|
arr[i+1] = arr[end];
|
||||||
|
arr[end] = swapTemp;
|
||||||
|
|
||||||
|
return i+1;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,38 @@
|
||||||
|
package com.baeldung.algorithms.quicksort;
|
||||||
|
|
||||||
|
public class ThreeWayQuickSort {
|
||||||
|
|
||||||
|
public static void threeWayQuickSort(int[] a, int begin, int end)
|
||||||
|
{
|
||||||
|
if (end <= begin) return;
|
||||||
|
|
||||||
|
// partition
|
||||||
|
int i = begin;
|
||||||
|
int less = begin;
|
||||||
|
int greater = end;
|
||||||
|
|
||||||
|
while (i <= greater){
|
||||||
|
if (a[i] < a[less]) {
|
||||||
|
int tmp = a[i];
|
||||||
|
a[i] = a[less];
|
||||||
|
a[less] = tmp;
|
||||||
|
|
||||||
|
i++;
|
||||||
|
less++;
|
||||||
|
}
|
||||||
|
else if (a[less] < a[i]) {
|
||||||
|
int tmp = a[i];
|
||||||
|
a[i] = a[greater];
|
||||||
|
a[greater] = tmp;
|
||||||
|
|
||||||
|
greater--;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
threeWayQuickSort(a, begin, less - 1);
|
||||||
|
threeWayQuickSort(a, greater + 1, end);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,17 @@
|
||||||
|
package com.baeldung.algorithms.mergesort;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class MergeSortUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void positiveTest() {
|
||||||
|
int[] actual = { 5, 1, 6, 2, 3, 4 };
|
||||||
|
int[] expected = { 1, 2, 3, 4, 5, 6 };
|
||||||
|
MergeSort.mergeSort(actual, actual.length);
|
||||||
|
Assert.assertArrayEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,17 @@
|
||||||
|
package com.baeldung.algorithms.quicksort;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.quicksort.QuickSort;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class QuickSortUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIntegerArray_whenSortedWithQuickSort_thenGetSortedArray() {
|
||||||
|
int[] actual = { 9, 5, 1, 0, 6, 2, 3, 4, 7, 8 };
|
||||||
|
int[] expected = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
|
||||||
|
QuickSort.quickSort(actual, 0, actual.length-1);
|
||||||
|
Assert.assertArrayEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,15 @@
|
||||||
|
package com.baeldung.algorithms.quicksort;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class ThreeWayQuickSortUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIntegerArray_whenSortedWithThreeWayQuickSort_thenGetSortedArray() {
|
||||||
|
int[] actual = { 3, 5, 5, 5, 3, 7, 7, 3, 5, 5, 7, 3, 3 };
|
||||||
|
int[] expected = { 3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 7, 7, 7 };
|
||||||
|
ThreeWayQuickSort.threeWayQuickSort(actual, 0, actual.length-1);
|
||||||
|
Assert.assertArrayEquals(expected, actual);
|
||||||
|
}
|
||||||
|
}
|
|
@ -7,7 +7,7 @@ import junit.framework.TestSuite;
|
||||||
/**
|
/**
|
||||||
* Unit test for simple App.
|
* Unit test for simple App.
|
||||||
*/
|
*/
|
||||||
public class AppTest
|
public class AppUnitTest
|
||||||
extends TestCase
|
extends TestCase
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
|
@ -15,7 +15,7 @@ public class AppTest
|
||||||
*
|
*
|
||||||
* @param testName name of the test case
|
* @param testName name of the test case
|
||||||
*/
|
*/
|
||||||
public AppTest( String testName )
|
public AppUnitTest( String testName )
|
||||||
{
|
{
|
||||||
super( testName );
|
super( testName );
|
||||||
}
|
}
|
||||||
|
@ -25,7 +25,7 @@ public class AppTest
|
||||||
*/
|
*/
|
||||||
public static Test suite()
|
public static Test suite()
|
||||||
{
|
{
|
||||||
return new TestSuite( AppTest.class );
|
return new TestSuite( AppUnitTest.class );
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
|
@ -6,7 +6,7 @@
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>apache-avro</artifactId>
|
<artifactId>apache-avro</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<name>Apache Avro</version>
|
<name>Apache Avro</name>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
|
|
@ -13,7 +13,7 @@ import java.util.Objects;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
public class AvroSerealizerDeSerealizerTest {
|
public class AvroSerealizerDeSerealizerUnitTest {
|
||||||
|
|
||||||
AvroSerealizer serealizer;
|
AvroSerealizer serealizer;
|
||||||
AvroDeSerealizer deSerealizer;
|
AvroDeSerealizer deSerealizer;
|
|
@ -0,0 +1,46 @@
|
||||||
|
<?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>
|
||||||
|
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>apache-geode</artifactId>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<geode.core>1.6.0</geode.core>
|
||||||
|
</properties>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.geode</groupId>
|
||||||
|
<artifactId>geode-core</artifactId>
|
||||||
|
<version>${geode.core}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>RELEASE</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
</project>
|
|
@ -0,0 +1,78 @@
|
||||||
|
package com.baeldung.geode;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public class Customer implements Serializable {
|
||||||
|
|
||||||
|
private static final long serialVersionUID = -7482516011038799900L;
|
||||||
|
|
||||||
|
private CustomerKey key;
|
||||||
|
private String firstName;
|
||||||
|
private String lastName;
|
||||||
|
private Integer age;
|
||||||
|
|
||||||
|
public Customer() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Customer(String firstName, String lastName, int age) {
|
||||||
|
this.firstName = firstName;
|
||||||
|
this.lastName = lastName;
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Customer(CustomerKey key, String firstName, String lastName, int age) {
|
||||||
|
this(firstName, lastName, age);
|
||||||
|
this.key = key;
|
||||||
|
}
|
||||||
|
|
||||||
|
// setters and getters
|
||||||
|
|
||||||
|
public static long getSerialVersionUID() {
|
||||||
|
return serialVersionUID;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFirstName() {
|
||||||
|
return firstName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setFirstName(String firstName) {
|
||||||
|
this.firstName = firstName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLastName() {
|
||||||
|
return lastName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLastName(String lastName) {
|
||||||
|
this.lastName = lastName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getAge() {
|
||||||
|
return age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAge(Integer age) {
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Customer{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", age=" + age + '}';
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o)
|
||||||
|
return true;
|
||||||
|
if (o == null || getClass() != o.getClass())
|
||||||
|
return false;
|
||||||
|
Customer customer = (Customer) o;
|
||||||
|
return Objects.equals(firstName, customer.firstName) && Objects.equals(lastName, customer.lastName) && Objects.equals(age, customer.age);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Objects.hash(firstName, lastName, age);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,57 @@
|
||||||
|
package com.baeldung.geode;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
public class CustomerKey implements Serializable {
|
||||||
|
|
||||||
|
private static final long serialVersionUID = -3529253035303792458L;
|
||||||
|
private long id;
|
||||||
|
private String country;
|
||||||
|
|
||||||
|
public CustomerKey(long id) {
|
||||||
|
this.id = id;
|
||||||
|
this.country = "USA";
|
||||||
|
}
|
||||||
|
|
||||||
|
public CustomerKey(long id, String country) {
|
||||||
|
this.id = id;
|
||||||
|
this.country = country;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCountry() {
|
||||||
|
return country;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCountry(String country) {
|
||||||
|
this.country = country;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o)
|
||||||
|
return true;
|
||||||
|
if (o == null || getClass() != o.getClass())
|
||||||
|
return false;
|
||||||
|
|
||||||
|
CustomerKey that = (CustomerKey) o;
|
||||||
|
|
||||||
|
if (id != that.id)
|
||||||
|
return false;
|
||||||
|
return country != null ? country.equals(that.country) : that.country == null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
int result = (int) (id ^ (id >>> 32));
|
||||||
|
result = 31 * result + (country != null ? country.hashCode() : 0);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,34 @@
|
||||||
|
package com.baeldung.geode.functions;
|
||||||
|
|
||||||
|
import com.baeldung.geode.Customer;
|
||||||
|
import com.baeldung.geode.CustomerKey;
|
||||||
|
import org.apache.geode.cache.Region;
|
||||||
|
import org.apache.geode.cache.execute.Function;
|
||||||
|
import org.apache.geode.cache.execute.FunctionContext;
|
||||||
|
import org.apache.geode.cache.execute.RegionFunctionContext;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class UpperCaseNames implements Function<Boolean> {
|
||||||
|
private static final long serialVersionUID = -8946294032165677602L;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void execute(FunctionContext<Boolean> context) {
|
||||||
|
RegionFunctionContext regionContext = (RegionFunctionContext) context;
|
||||||
|
Region<CustomerKey, Customer> region = regionContext.getDataSet();
|
||||||
|
|
||||||
|
for (Map.Entry<CustomerKey, Customer> entry : region.entrySet()) {
|
||||||
|
Customer customer = entry.getValue();
|
||||||
|
customer.setFirstName(customer.getFirstName()
|
||||||
|
.toUpperCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
context.getResultSender()
|
||||||
|
.lastResult(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getId() {
|
||||||
|
return getClass().getName();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,110 @@
|
||||||
|
package com.baeldung.geode;
|
||||||
|
|
||||||
|
import com.baeldung.geode.functions.UpperCaseNames;
|
||||||
|
import org.apache.geode.cache.Region;
|
||||||
|
import org.apache.geode.cache.client.ClientCache;
|
||||||
|
import org.apache.geode.cache.client.ClientCacheFactory;
|
||||||
|
import org.apache.geode.cache.client.ClientRegionShortcut;
|
||||||
|
import org.apache.geode.cache.execute.Execution;
|
||||||
|
import org.apache.geode.cache.execute.FunctionService;
|
||||||
|
import org.apache.geode.cache.query.*;
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.function.Function;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class GeodeSamplesIntegrationTest {
|
||||||
|
|
||||||
|
ClientCache cache = null;
|
||||||
|
Region<String, String> region = null;
|
||||||
|
Region<Integer, Customer> queryRegion = null;
|
||||||
|
Region<CustomerKey, Customer> customerRegion = null;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void connect() {
|
||||||
|
this.cache = new ClientCacheFactory().addPoolLocator("localhost", 10334)
|
||||||
|
.create();
|
||||||
|
this.region = this.cache.<String, String> createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY)
|
||||||
|
.create("baeldung");
|
||||||
|
this.customerRegion = this.cache.<CustomerKey, Customer> createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY)
|
||||||
|
.create("baeldung-customers");
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void cleanup() {
|
||||||
|
this.cache.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenSendMessageToRegion_thenMessageSavedSuccessfully() {
|
||||||
|
|
||||||
|
this.region.put("1", "Hello");
|
||||||
|
this.region.put("2", "Baeldung");
|
||||||
|
|
||||||
|
assertEquals("Hello", region.get("1"));
|
||||||
|
assertEquals("Baeldung", region.get("2"));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPutMultipleValuesAtOnce_thenValuesSavedSuccessfully() {
|
||||||
|
|
||||||
|
Supplier<Stream<String>> keys = () -> Stream.of("A", "B", "C", "D", "E");
|
||||||
|
Map<String, String> values = keys.get()
|
||||||
|
.collect(Collectors.toMap(Function.identity(), String::toLowerCase));
|
||||||
|
|
||||||
|
this.region.putAll(values);
|
||||||
|
|
||||||
|
keys.get()
|
||||||
|
.forEach(k -> assertEquals(k.toLowerCase(), this.region.get(k)));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPutCustomKey_thenValuesSavedSuccessfully() {
|
||||||
|
CustomerKey key = new CustomerKey(123);
|
||||||
|
Customer customer = new Customer(key, "William", "Russell", 35);
|
||||||
|
|
||||||
|
Map<CustomerKey, Customer> customerInfo = new HashMap<>();
|
||||||
|
customerInfo.put(key, customer);
|
||||||
|
|
||||||
|
this.customerRegion.putAll(customerInfo);
|
||||||
|
|
||||||
|
Customer storedCustomer = this.customerRegion.get(key);
|
||||||
|
assertEquals("William", storedCustomer.getFirstName());
|
||||||
|
assertEquals("Russell", storedCustomer.getLastName());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFindACustomerUsingOQL_thenCorrectCustomerObject() throws NameResolutionException, TypeMismatchException, QueryInvocationTargetException, FunctionDomainException {
|
||||||
|
|
||||||
|
Map<CustomerKey, Customer> data = new HashMap<>();
|
||||||
|
data.put(new CustomerKey(1), new Customer("Gheorge", "Manuc", 36));
|
||||||
|
data.put(new CustomerKey(2), new Customer("Allan", "McDowell", 43));
|
||||||
|
this.customerRegion.putAll(data);
|
||||||
|
|
||||||
|
QueryService queryService = this.cache.getQueryService();
|
||||||
|
String query = "select * from /baeldung-customers c where c.firstName = 'Allan'";
|
||||||
|
SelectResults<Customer> queryResults = (SelectResults<Customer>) queryService.newQuery(query)
|
||||||
|
.execute();
|
||||||
|
assertEquals(1, queryResults.size());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenExecuteUppercaseNames_thenCustomerNamesAreUppercased() {
|
||||||
|
Execution execution = FunctionService.onRegion(this.customerRegion);
|
||||||
|
execution.execute(UpperCaseNames.class.getName());
|
||||||
|
Customer customer = this.customerRegion.get(new CustomerKey(1));
|
||||||
|
assertEquals("GHEORGE", customer.getFirstName());
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,5 +1,4 @@
|
||||||
### Relevant articles
|
### Relevant articles
|
||||||
|
|
||||||
- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor)
|
|
||||||
- [Generating a Book with Asciidoctor](http://www.baeldung.com/asciidoctor-book)
|
- [Generating a Book with Asciidoctor](http://www.baeldung.com/asciidoctor-book)
|
||||||
- [Introduction to Asciidoctor in Java](http://www.baeldung.com/asciidoctor)
|
- [Introduction to Asciidoctor in Java](http://www.baeldung.com/asciidoctor)
|
||||||
|
|
|
@ -61,9 +61,10 @@
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<asciidoctor-maven-plugin.version>1.5.5</asciidoctor-maven-plugin.version>
|
<asciidoctor-maven-plugin.version>1.5.6</asciidoctor-maven-plugin.version>
|
||||||
<asciidoctorj.version>1.5.4</asciidoctorj.version>
|
<asciidoctorj.version>1.5.6</asciidoctorj.version>
|
||||||
<asciidoctorj-pdf.src.version>1.5.0-alpha.11</asciidoctorj-pdf.src.version>
|
|
||||||
|
<asciidoctorj-pdf.version>1.5.0-alpha.15</asciidoctorj-pdf.version>
|
||||||
<asciidoctorj-pdf.plugin.version>1.5.0-alpha.15</asciidoctorj-pdf.plugin.version>
|
<asciidoctorj-pdf.plugin.version>1.5.0-alpha.15</asciidoctorj-pdf.plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
|
|
@ -3,7 +3,7 @@ package com.baeldung.asciidoctor;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class AsciidoctorDemoTest {
|
public class AsciidoctorDemoIntegrationTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenString_whenConverting_thenResultingHTMLCode() {
|
public void givenString_whenConverting_thenResultingHTMLCode() {
|
|
@ -0,0 +1,38 @@
|
||||||
|
<?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>flyway-cdi</artifactId>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>cdi-portable-extension</artifactId>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.enterprise</groupId>
|
||||||
|
<artifactId>cdi-api</artifactId>
|
||||||
|
<version>2.0.SP1</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.flywaydb</groupId>
|
||||||
|
<artifactId>flyway-core</artifactId>
|
||||||
|
<version>5.1.4</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.tomcat</groupId>
|
||||||
|
<artifactId>tomcat-jdbc</artifactId>
|
||||||
|
<version>8.5.33</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.annotation</groupId>
|
||||||
|
<artifactId>javax.annotation-api</artifactId>
|
||||||
|
<version>1.3.2</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
</project>
|
|
@ -0,0 +1,74 @@
|
||||||
|
package com.baeldung.cdi.extension;
|
||||||
|
|
||||||
|
import org.apache.tomcat.jdbc.pool.DataSource;
|
||||||
|
import org.flywaydb.core.Flyway;
|
||||||
|
|
||||||
|
import javax.annotation.sql.DataSourceDefinition;
|
||||||
|
import javax.enterprise.context.ApplicationScoped;
|
||||||
|
import javax.enterprise.event.Observes;
|
||||||
|
import javax.enterprise.inject.Any;
|
||||||
|
import javax.enterprise.inject.Default;
|
||||||
|
import javax.enterprise.inject.literal.InjectLiteral;
|
||||||
|
import javax.enterprise.inject.spi.*;
|
||||||
|
import javax.enterprise.util.AnnotationLiteral;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flyway is now under CDI container like:
|
||||||
|
*
|
||||||
|
* @ApplicationScoped
|
||||||
|
* @FlywayType public class Flyway{
|
||||||
|
* @Inject setDataSource(DataSource dataSource){
|
||||||
|
* //...
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
|
||||||
|
public class FlywayExtension implements Extension {
|
||||||
|
|
||||||
|
DataSourceDefinition dataSourceDefinition = null;
|
||||||
|
|
||||||
|
public void registerFlywayType(@Observes BeforeBeanDiscovery bbdEvent) {
|
||||||
|
bbdEvent.addAnnotatedType(Flyway.class, Flyway.class.getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void detectDataSourceDefinition(@Observes @WithAnnotations(DataSourceDefinition.class) ProcessAnnotatedType<?> patEvent) {
|
||||||
|
AnnotatedType at = patEvent.getAnnotatedType();
|
||||||
|
dataSourceDefinition = at.getAnnotation(DataSourceDefinition.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void processAnnotatedType(@Observes ProcessAnnotatedType<Flyway> patEvent) {
|
||||||
|
patEvent.configureAnnotatedType()
|
||||||
|
//Add Scope
|
||||||
|
.add(ApplicationScoped.Literal.INSTANCE)
|
||||||
|
//Add Qualifier
|
||||||
|
.add(new AnnotationLiteral<FlywayType>() {
|
||||||
|
})
|
||||||
|
//Decorate setDataSource(DataSource dataSource){} with @Inject
|
||||||
|
.filterMethods(annotatedMethod -> {
|
||||||
|
return annotatedMethod.getParameters().size() == 1 &&
|
||||||
|
annotatedMethod.getParameters().get(0).getBaseType().equals(javax.sql.DataSource.class);
|
||||||
|
})
|
||||||
|
.findFirst().get().add(InjectLiteral.INSTANCE);
|
||||||
|
}
|
||||||
|
|
||||||
|
void afterBeanDiscovery(@Observes AfterBeanDiscovery abdEvent, BeanManager bm) {
|
||||||
|
abdEvent.addBean()
|
||||||
|
.types(javax.sql.DataSource.class, DataSource.class)
|
||||||
|
.qualifiers(new AnnotationLiteral<Default>() {}, new AnnotationLiteral<Any>() {})
|
||||||
|
.scope(ApplicationScoped.class)
|
||||||
|
.name(DataSource.class.getName())
|
||||||
|
.beanClass(DataSource.class)
|
||||||
|
.createWith(creationalContext -> {
|
||||||
|
DataSource instance = new DataSource();
|
||||||
|
instance.setUrl(dataSourceDefinition.url());
|
||||||
|
instance.setDriverClassName(dataSourceDefinition.className());
|
||||||
|
return instance;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void runFlywayMigration(@Observes AfterDeploymentValidation adv, BeanManager manager) {
|
||||||
|
Flyway flyway = manager.createInstance().select(Flyway.class, new AnnotationLiteral<FlywayType>() {}).get();
|
||||||
|
flyway.migrate();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,14 @@
|
||||||
|
package com.baeldung.cdi.extension;
|
||||||
|
|
||||||
|
import javax.inject.Qualifier;
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.RetentionPolicy;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
|
import static java.lang.annotation.ElementType.*;
|
||||||
|
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
@Target({FIELD, METHOD, PARAMETER, TYPE})
|
||||||
|
@Qualifier
|
||||||
|
public @interface FlywayType {
|
||||||
|
}
|
|
@ -0,0 +1,6 @@
|
||||||
|
<beans version="2.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
|
||||||
|
http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
|
||||||
|
bean-discovery-mode="annotated">
|
||||||
|
</beans>
|
|
@ -0,0 +1,2 @@
|
||||||
|
com.baeldung.cdi.extension.FlywayExtension
|
||||||
|
|
|
@ -0,0 +1,52 @@
|
||||||
|
<?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>main-app</artifactId>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>cdi-portable-extension</artifactId>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.enterprise</groupId>
|
||||||
|
<artifactId>cdi-api</artifactId>
|
||||||
|
<version>2.0.SP1</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jboss.weld.se</groupId>
|
||||||
|
<artifactId>weld-se-core</artifactId>
|
||||||
|
<version>3.0.5.Final</version>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>flyway-cdi</artifactId>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.h2database</groupId>
|
||||||
|
<artifactId>h2</artifactId>
|
||||||
|
<version>1.4.197</version>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.annotation</groupId>
|
||||||
|
<artifactId>javax.annotation-api</artifactId>
|
||||||
|
<version>1.3.2</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
</project>
|
|
@ -0,0 +1,16 @@
|
||||||
|
package com.baeldung.cdi.extension;
|
||||||
|
|
||||||
|
import javax.annotation.sql.DataSourceDefinition;
|
||||||
|
import javax.enterprise.context.ApplicationScoped;
|
||||||
|
import javax.enterprise.inject.se.SeContainer;
|
||||||
|
import javax.enterprise.inject.se.SeContainerInitializer;
|
||||||
|
|
||||||
|
@ApplicationScoped
|
||||||
|
@DataSourceDefinition(name = "ds", className = "org.h2.Driver", url = "jdbc:h2:mem:testdb")
|
||||||
|
public class MainApp {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SeContainerInitializer initializer = SeContainerInitializer.newInstance();
|
||||||
|
try (SeContainer container = initializer.initialize()) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,6 @@
|
||||||
|
<beans version="2.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
|
||||||
|
http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
|
||||||
|
bean-discovery-mode="annotated">
|
||||||
|
</beans>
|
|
@ -0,0 +1,4 @@
|
||||||
|
create table PERSON (
|
||||||
|
ID int not null,
|
||||||
|
NAME varchar(100) not null
|
||||||
|
);
|
|
@ -0,0 +1,3 @@
|
||||||
|
insert into PERSON (ID, NAME) values (1, 'Axel');
|
||||||
|
insert into PERSON (ID, NAME) values (2, 'Mr. Foo');
|
||||||
|
insert into PERSON (ID, NAME) values (3, 'Ms. Bar');
|
|
@ -0,0 +1,30 @@
|
||||||
|
<?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>
|
||||||
|
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>cdi-portable-extension</artifactId>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<maven.compiler.source>1.8</maven.compiler.source>
|
||||||
|
<maven.compiler.target>1.8</maven.compiler.target>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<modules>
|
||||||
|
<module>main-app</module>
|
||||||
|
<module>flyway-cdi</module>
|
||||||
|
</modules>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.enterprise</groupId>
|
||||||
|
<artifactId>cdi-api</artifactId>
|
||||||
|
<version>2.0.SP1</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
</project>
|
|
@ -1,16 +1,18 @@
|
||||||
package com.baeldung.java8;
|
package com.baeldung.java8;
|
||||||
|
|
||||||
import com.baeldung.java8.entity.Human;
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
import com.google.common.collect.Lists;
|
|
||||||
import com.google.common.primitives.Ints;
|
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.java8.entity.Human;
|
||||||
|
import com.google.common.collect.Lists;
|
||||||
|
import com.google.common.primitives.Ints;
|
||||||
|
|
||||||
public class Java8SortUnitTest {
|
public class Java8SortUnitTest {
|
||||||
|
|
||||||
|
@ -111,5 +113,22 @@ public class Java8SortUnitTest {
|
||||||
humans.sort(Comparator.comparing(Human::getName));
|
humans.sort(Comparator.comparing(Human::getName));
|
||||||
Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
|
Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public final void givenStreamNaturalOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
|
||||||
|
final List<String> letters = Lists.newArrayList("B", "A", "C");
|
||||||
|
|
||||||
|
final List<String> sortedLetters = letters.stream().sorted().collect(Collectors.toList());
|
||||||
|
Assert.assertThat(sortedLetters.get(0), equalTo("A"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public final void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
|
||||||
|
|
||||||
|
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
|
||||||
|
final Comparator<Human> nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
|
||||||
|
|
||||||
|
final List<Human> sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList());
|
||||||
|
Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12)));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,41 @@
|
||||||
|
package com.baeldung.stream.conditional;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class StreamForEachIfElseUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public final void givenIntegerStream_whenCheckingIntegerParityWithIfElse_thenEnsureCorrectParity() {
|
||||||
|
List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
|
||||||
|
|
||||||
|
ints.stream()
|
||||||
|
.forEach(i -> {
|
||||||
|
if (i.intValue() % 2 == 0) {
|
||||||
|
Assert.assertTrue(i.intValue() + " is not even", i.intValue() % 2 == 0);
|
||||||
|
} else {
|
||||||
|
Assert.assertTrue(i.intValue() + " is not odd", i.intValue() % 2 != 0);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public final void givenIntegerStream_whenCheckingIntegerParityWithStreamFilter_thenEnsureCorrectParity() {
|
||||||
|
List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
|
||||||
|
|
||||||
|
Stream<Integer> evenIntegers = ints.stream()
|
||||||
|
.filter(i -> i.intValue() % 2 == 0);
|
||||||
|
Stream<Integer> oddIntegers = ints.stream()
|
||||||
|
.filter(i -> i.intValue() % 2 != 0);
|
||||||
|
|
||||||
|
evenIntegers.forEach(i -> Assert.assertTrue(i.intValue() + " is not even", i.intValue() % 2 == 0));
|
||||||
|
oddIntegers.forEach(i -> Assert.assertTrue(i.intValue() + " is not odd", i.intValue() % 2 != 0));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -48,4 +48,6 @@
|
||||||
- [Thread Safe LIFO Data Structure Implementations](https://www.baeldung.com/java-lifo-thread-safe)
|
- [Thread Safe LIFO Data Structure Implementations](https://www.baeldung.com/java-lifo-thread-safe)
|
||||||
- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list)
|
- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list)
|
||||||
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
|
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
|
||||||
- [](https://www.baeldung.com/java-hashset-arraylist-contains-performance)
|
- [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance)
|
||||||
|
- [Get the Key for a Value from a Java Map](https://www.baeldung.com/java-map-key-from-value)
|
||||||
|
- [Time Complexity of Java Collections](https://www.baeldung.com/java-collections-complexity)
|
||||||
|
|
|
@ -63,6 +63,17 @@
|
||||||
<artifactId>jmh-generator-annprocess</artifactId>
|
<artifactId>jmh-generator-annprocess</artifactId>
|
||||||
<version>${openjdk.jmh.version}</version>
|
<version>${openjdk.jmh.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-exec</artifactId>
|
||||||
|
<version>1.3</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>one.util</groupId>
|
||||||
|
<artifactId>streamex</artifactId>
|
||||||
|
<version>0.6.5</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,39 @@
|
||||||
|
package com.baeldung.combiningcollections;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.ArrayUtils;
|
||||||
|
|
||||||
|
import com.google.common.collect.ObjectArrays;
|
||||||
|
|
||||||
|
public class CombiningArrays {
|
||||||
|
|
||||||
|
public static Object[] usingNativeJava(Object[] first, Object[] second) {
|
||||||
|
Object[] combined = new Object[first.length + second.length];
|
||||||
|
System.arraycopy(first, 0, combined, 0, first.length);
|
||||||
|
System.arraycopy(second, 0, combined, first.length, second.length);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Object[] usingJava8ObjectStream(Object[] first, Object[] second) {
|
||||||
|
Object[] combined = Stream.concat(Arrays.stream(first), Arrays.stream(second)).toArray();
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Object[] usingJava8FlatMaps(Object[] first, Object[] second) {
|
||||||
|
Object[] combined = Stream.of(first, second).flatMap(Stream::of).toArray(String[]::new);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Object[] usingApacheCommons(Object[] first, Object[] second) {
|
||||||
|
Object[] combined = ArrayUtils.addAll(first, second);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Object[] usingGuava(Object[] first, Object[] second) {
|
||||||
|
Object [] combined = ObjectArrays.concat(first, second, Object.class);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,46 @@
|
||||||
|
package com.baeldung.combiningcollections;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import org.apache.commons.collections4.ListUtils;
|
||||||
|
|
||||||
|
import com.google.common.collect.Iterables;
|
||||||
|
import com.google.common.collect.Lists;
|
||||||
|
|
||||||
|
public class CombiningLists {
|
||||||
|
|
||||||
|
public static List<Object> usingNativeJava(List<Object> first, List<Object> second) {
|
||||||
|
List<Object> combined = new ArrayList<>();
|
||||||
|
combined.addAll(first);
|
||||||
|
combined.addAll(second);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<Object> usingJava8ObjectStream(List<Object> first, List<Object> second) {
|
||||||
|
List<Object> combined = Stream.concat(first.stream(), second.stream()).collect(Collectors.toList());
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<Object> usingJava8FlatMaps(List<Object> first, List<Object> second) {
|
||||||
|
List<Object> combined = Stream.of(first, second).flatMap(Collection::stream).collect(Collectors.toList());
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<Object> usingApacheCommons(List<Object> first, List<Object> second) {
|
||||||
|
List<Object> combined = ListUtils.union(first, second);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<Object> usingGuava(List<Object> first, List<Object> second) {
|
||||||
|
Iterable<Object> combinedIterables = Iterables.unmodifiableIterable(
|
||||||
|
Iterables.concat(first, second));
|
||||||
|
|
||||||
|
List<Object> combined = Lists.newArrayList(combinedIterables);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,47 @@
|
||||||
|
package com.baeldung.combiningcollections;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import org.apache.commons.exec.util.MapUtils;
|
||||||
|
|
||||||
|
import com.google.common.collect.ImmutableMap;
|
||||||
|
|
||||||
|
public class CombiningMaps {
|
||||||
|
|
||||||
|
public static Map<String, String> usingPlainJava(Map<String, String> first, Map<String, String> second) {
|
||||||
|
Map<String, String> combined = new HashMap<>();
|
||||||
|
combined.putAll(first);
|
||||||
|
combined.putAll(second);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Map<String, String> usingJava8ForEach(Map<String, String> first, Map<String, String> second) {
|
||||||
|
second.forEach((key, value) -> first.merge(key, value, String::concat));
|
||||||
|
return first;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Map<String, String> usingJava8FlatMaps(Map<String, String> first, Map<String, String> second) {
|
||||||
|
Map<String, String> combined = Stream.of(first, second).map(Map::entrySet).flatMap(Collection::stream)
|
||||||
|
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, String::concat));
|
||||||
|
return combined;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Map<String, String> usingApacheCommons(Map<String, String> first, Map<String, String> second) {
|
||||||
|
Map<String, String> combined = MapUtils.merge(first, second);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Map<String, String> usingGuava(Map<String, String> first, Map<String, String> second) {
|
||||||
|
Map<String, String> combined = ImmutableMap.<String, String>builder()
|
||||||
|
.putAll(first)
|
||||||
|
.putAll(second)
|
||||||
|
.build();
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,42 @@
|
||||||
|
package com.baeldung.combiningcollections;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import org.apache.commons.collections4.SetUtils;
|
||||||
|
|
||||||
|
import com.google.common.collect.Sets;
|
||||||
|
|
||||||
|
public class CombiningSets {
|
||||||
|
|
||||||
|
public static Set<Object> usingNativeJava(Set<Object> first, Set<Object> second) {
|
||||||
|
Set<Object> combined = new HashSet<>();
|
||||||
|
combined.addAll(first);
|
||||||
|
combined.addAll(second);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Set<Object> usingJava8ObjectStream(Set<Object> first, Set<Object> second) {
|
||||||
|
Set<Object> combined = Stream.concat(first.stream(), second.stream()).collect(Collectors.toSet());
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Set<Object> usingJava8FlatMaps(Set<Object> first, Set<Object> second) {
|
||||||
|
Set<Object> combined = Stream.of(first, second).flatMap(Collection::stream).collect(Collectors.toSet());
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Set<Object> usingApacheCommons(Set<Object> first, Set<Object> second) {
|
||||||
|
Set<Object> combined = SetUtils.union(first, second);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Set<Object> usingGuava(Set<Object> first, Set<Object> second) {
|
||||||
|
Set<Object> combined = Sets.union(first, second);
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,105 @@
|
||||||
|
package com.baeldung.map.java_8;
|
||||||
|
|
||||||
|
import com.baeldung.sort.Employee;
|
||||||
|
import one.util.streamex.EntryStream;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
public class MergeMaps {
|
||||||
|
|
||||||
|
private static Map<String, Employee> map1 = new HashMap<>();
|
||||||
|
private static Map<String, Employee> map2 = new HashMap<>();
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
initialize();
|
||||||
|
|
||||||
|
mergeFunction();
|
||||||
|
|
||||||
|
streamConcat();
|
||||||
|
|
||||||
|
streamOf();
|
||||||
|
|
||||||
|
streamEx();
|
||||||
|
|
||||||
|
streamMerge();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void streamMerge() {
|
||||||
|
|
||||||
|
Map<String, Employee> map3 = map2.entrySet()
|
||||||
|
.stream()
|
||||||
|
.collect(
|
||||||
|
Collectors.toMap(
|
||||||
|
Map.Entry::getKey,
|
||||||
|
Map.Entry::getValue,
|
||||||
|
(v1, v2) -> new Employee(v1.getId(), v2.getName()),
|
||||||
|
() -> new HashMap<>(map1)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
System.out.println(map3);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void streamEx() {
|
||||||
|
Map<String, Employee> map3 = EntryStream.of(map1)
|
||||||
|
.append(EntryStream.of(map2))
|
||||||
|
.toMap((e1, e2) -> e1);
|
||||||
|
|
||||||
|
System.out.println(map3);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void streamOf() {
|
||||||
|
Map<String, Employee> map3 = Stream.of(map1, map2)
|
||||||
|
.flatMap(map -> map.entrySet().stream())
|
||||||
|
.collect(
|
||||||
|
Collectors.toMap(
|
||||||
|
Map.Entry::getKey,
|
||||||
|
Map.Entry::getValue,
|
||||||
|
(v1, v2) -> new Employee(v1.getId(), v2.getName())
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
map3.entrySet().forEach(System.out::println);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void streamConcat() {
|
||||||
|
Map<String, Employee> result = Stream.concat(map1.entrySet().stream(), map2.entrySet().stream()).collect(Collectors.toMap(
|
||||||
|
Map.Entry::getKey,
|
||||||
|
Map.Entry::getValue,
|
||||||
|
(value1, value2) -> new Employee(value2.getId(), value1.getName())
|
||||||
|
));
|
||||||
|
|
||||||
|
result.entrySet().forEach(System.out::println);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void mergeFunction() {
|
||||||
|
Map<String, Employee> map3 = new HashMap<>(map1);
|
||||||
|
|
||||||
|
map2.forEach(
|
||||||
|
(key, value) -> map3.merge(key, value, (v1, v2) ->
|
||||||
|
new Employee(v1.getId(), v2.getName()))
|
||||||
|
);
|
||||||
|
|
||||||
|
map3.entrySet().forEach(System.out::println);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private static void initialize() {
|
||||||
|
Employee employee1 = new Employee(1L, "Henry");
|
||||||
|
map1.put(employee1.getName(), employee1);
|
||||||
|
Employee employee2 = new Employee(22L, "Annie");
|
||||||
|
map1.put(employee2.getName(), employee2);
|
||||||
|
Employee employee3 = new Employee(8L, "John");
|
||||||
|
map1.put(employee3.getName(), employee3);
|
||||||
|
|
||||||
|
Employee employee4 = new Employee(2L, "George");
|
||||||
|
map2.put(employee4.getName(), employee4);
|
||||||
|
Employee employee5 = new Employee(3L, "Henry");
|
||||||
|
map2.put(employee5.getName(), employee5);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,96 @@
|
||||||
|
package com.baeldung.map.util;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Map.Entry;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public class MapMax {
|
||||||
|
|
||||||
|
public <K, V extends Comparable<V>> V maxUsingIteration(Map<K, V> map) {
|
||||||
|
|
||||||
|
Map.Entry<K, V> maxEntry = null;
|
||||||
|
|
||||||
|
for (Map.Entry<K, V> entry : map.entrySet()) {
|
||||||
|
|
||||||
|
if (maxEntry == null || entry.getValue()
|
||||||
|
.compareTo(maxEntry.getValue()) > 0) {
|
||||||
|
maxEntry = entry;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return maxEntry.getValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
public <K, V extends Comparable<V>> V maxUsingCollectionsMax(Map<K, V> map) {
|
||||||
|
|
||||||
|
Entry<K, V> maxEntry = Collections.max(map.entrySet(), new Comparator<Entry<K, V>>() {
|
||||||
|
public int compare(Entry<K, V> e1, Entry<K, V> e2) {
|
||||||
|
return e1.getValue()
|
||||||
|
.compareTo(e2.getValue());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return maxEntry.getValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
public <K, V extends Comparable<V>> V maxUsingCollectionsMaxAndLambda(Map<K, V> map) {
|
||||||
|
|
||||||
|
Entry<K, V> maxEntry = Collections.max(map.entrySet(), (Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue()
|
||||||
|
.compareTo(e2.getValue()));
|
||||||
|
|
||||||
|
return maxEntry.getValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
public <K, V extends Comparable<V>> V maxUsingCollectionsMaxAndMethodReference(Map<K, V> map) {
|
||||||
|
|
||||||
|
Entry<K, V> maxEntry = Collections.max(map.entrySet(), Comparator.comparing(Map.Entry::getValue));
|
||||||
|
|
||||||
|
return maxEntry.getValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
public <K, V extends Comparable<V>> V maxUsingStreamAndLambda(Map<K, V> map) {
|
||||||
|
|
||||||
|
Optional<Entry<K, V>> maxEntry = map.entrySet()
|
||||||
|
.stream()
|
||||||
|
.max((Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue()
|
||||||
|
.compareTo(e2.getValue()));
|
||||||
|
|
||||||
|
return maxEntry.get()
|
||||||
|
.getValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
public <K, V extends Comparable<V>> V maxUsingStreamAndMethodReference(Map<K, V> map) {
|
||||||
|
|
||||||
|
Optional<Entry<K, V>> maxEntry = map.entrySet()
|
||||||
|
.stream()
|
||||||
|
.max(Comparator.comparing(Map.Entry::getValue));
|
||||||
|
|
||||||
|
return maxEntry.get()
|
||||||
|
.getValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
|
||||||
|
|
||||||
|
map.put(1, 3);
|
||||||
|
map.put(2, 4);
|
||||||
|
map.put(3, 5);
|
||||||
|
map.put(4, 6);
|
||||||
|
map.put(5, 7);
|
||||||
|
|
||||||
|
MapMax mapMax = new MapMax();
|
||||||
|
|
||||||
|
System.out.println(mapMax.maxUsingIteration(map));
|
||||||
|
System.out.println(mapMax.maxUsingCollectionsMax(map));
|
||||||
|
System.out.println(mapMax.maxUsingCollectionsMaxAndLambda(map));
|
||||||
|
System.out.println(mapMax.maxUsingCollectionsMaxAndMethodReference(map));
|
||||||
|
System.out.println(mapMax.maxUsingStreamAndLambda(map));
|
||||||
|
System.out.println(mapMax.maxUsingStreamAndMethodReference(map));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -44,4 +44,12 @@ public class Employee {
|
||||||
result = 31 * result + name.hashCode();
|
result = 31 * result + name.hashCode();
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Employee{" +
|
||||||
|
"id=" + id +
|
||||||
|
", name='" + name + '\'' +
|
||||||
|
'}';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,60 @@
|
||||||
|
package com.baeldung.sort;
|
||||||
|
|
||||||
|
public class Employee implements Comparable<Employee> {
|
||||||
|
|
||||||
|
private Long id;
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
public Employee(Long id, String name) {
|
||||||
|
this.name = name;
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(Long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) return true;
|
||||||
|
if (o == null || getClass() != o.getClass()) return false;
|
||||||
|
|
||||||
|
Employee employee = (Employee) o;
|
||||||
|
|
||||||
|
if (!id.equals(employee.id)) return false;
|
||||||
|
return name.equals(employee.name);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
int result = id.hashCode();
|
||||||
|
result = 31 * result + name.hashCode();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Employee{" +
|
||||||
|
"id=" + id +
|
||||||
|
", name='" + name + '\'' +
|
||||||
|
'}';
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int compareTo(Employee employee) {
|
||||||
|
return (int)(this.id - employee.getId());
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,104 @@
|
||||||
|
package com.baeldung.sort;
|
||||||
|
|
||||||
|
import com.google.common.base.Functions;
|
||||||
|
import com.google.common.collect.ImmutableSortedMap;
|
||||||
|
import com.google.common.collect.Lists;
|
||||||
|
import com.google.common.collect.Ordering;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
public class SortHashMap {
|
||||||
|
|
||||||
|
private static Map<String, Employee> map = new HashMap<>();
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
initialize();
|
||||||
|
|
||||||
|
treeMapSortByKey();
|
||||||
|
|
||||||
|
arrayListSortByValue();
|
||||||
|
arrayListSortByKey();
|
||||||
|
|
||||||
|
sortStream();
|
||||||
|
|
||||||
|
sortGuava();
|
||||||
|
|
||||||
|
addDuplicates();
|
||||||
|
|
||||||
|
treeSetByKey();
|
||||||
|
treeSetByValue();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void sortGuava() {
|
||||||
|
final Ordering naturalOrdering =
|
||||||
|
Ordering.natural().onResultOf(Functions.forMap(map, null));
|
||||||
|
|
||||||
|
System.out.println(ImmutableSortedMap.copyOf(map, naturalOrdering));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void sortStream() {
|
||||||
|
map.entrySet().stream()
|
||||||
|
.sorted(Map.Entry.<String, Employee>comparingByKey().reversed())
|
||||||
|
.forEach(System.out::println);
|
||||||
|
|
||||||
|
Map<String, Employee> result = map.entrySet().stream()
|
||||||
|
.sorted(Map.Entry.comparingByValue())
|
||||||
|
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
|
||||||
|
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
|
||||||
|
|
||||||
|
result.entrySet().forEach(System.out::println);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void treeSetByValue() {
|
||||||
|
SortedSet<Employee> values = new TreeSet<>(map.values());
|
||||||
|
System.out.println(values);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void treeSetByKey() {
|
||||||
|
SortedSet<String> keysSet = new TreeSet<>(map.keySet());
|
||||||
|
System.out.println(keysSet);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void treeMapSortByKey() {
|
||||||
|
TreeMap<String, Employee> sorted = new TreeMap<>(map);
|
||||||
|
sorted.putAll(map);
|
||||||
|
|
||||||
|
sorted.entrySet().forEach(System.out::println);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void arrayListSortByValue() {
|
||||||
|
List<Employee> employeeById = new ArrayList<>(map.values());
|
||||||
|
|
||||||
|
Collections.sort(employeeById);
|
||||||
|
|
||||||
|
System.out.println(employeeById);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void arrayListSortByKey() {
|
||||||
|
List<String> employeeByKey = new ArrayList<>(map.keySet());
|
||||||
|
Collections.sort(employeeByKey);
|
||||||
|
System.out.println(employeeByKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void initialize() {
|
||||||
|
Employee employee1 = new Employee(1L, "Mher");
|
||||||
|
map.put(employee1.getName(), employee1);
|
||||||
|
Employee employee2 = new Employee(22L, "Annie");
|
||||||
|
map.put(employee2.getName(), employee2);
|
||||||
|
Employee employee3 = new Employee(8L, "John");
|
||||||
|
map.put(employee3.getName(), employee3);
|
||||||
|
Employee employee4 = new Employee(2L, "George");
|
||||||
|
map.put(employee4.getName(), employee4);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void addDuplicates() {
|
||||||
|
Employee employee5 = new Employee(1L, "Mher");
|
||||||
|
map.put(employee5.getName(), employee5);
|
||||||
|
Employee employee6 = new Employee(22L, "Annie");
|
||||||
|
map.put(employee6.getName(), employee6);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,52 @@
|
||||||
|
package com.baeldung.combiningcollections;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class CombiningArraysUnitTest {
|
||||||
|
private static final String first[] = {
|
||||||
|
"One",
|
||||||
|
"Two",
|
||||||
|
"Three"
|
||||||
|
};
|
||||||
|
|
||||||
|
private static final String second[] = {
|
||||||
|
"Four",
|
||||||
|
"Five",
|
||||||
|
"Six"
|
||||||
|
};
|
||||||
|
|
||||||
|
private static final String expected[] = {
|
||||||
|
"One",
|
||||||
|
"Two",
|
||||||
|
"Three",
|
||||||
|
"Four",
|
||||||
|
"Five",
|
||||||
|
"Six"
|
||||||
|
};
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoArrays_whenUsingNativeJava_thenArraysCombined() {
|
||||||
|
assertArrayEquals(expected, CombiningArrays.usingNativeJava(first, second));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoArrays_whenUsingObjectStreams_thenArraysCombined() {
|
||||||
|
assertArrayEquals(expected, CombiningArrays.usingJava8ObjectStream(first, second));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoArrays_whenUsingFlatMaps_thenArraysCombined() {
|
||||||
|
assertArrayEquals(expected, CombiningArrays.usingJava8FlatMaps(first, second));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoArrays_whenUsingApacheCommons_thenArraysCombined() {
|
||||||
|
assertArrayEquals(expected, CombiningArrays.usingApacheCommons(first, second));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoArrays_whenUsingGuava_thenArraysCombined() {
|
||||||
|
assertArrayEquals(expected, CombiningArrays.usingGuava(first, second));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,57 @@
|
||||||
|
package com.baeldung.combiningcollections;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.is;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class CombiningListsUnitTest {
|
||||||
|
private static final List<Object> first = Arrays.asList(new Object[]{
|
||||||
|
"One",
|
||||||
|
"Two",
|
||||||
|
"Three"
|
||||||
|
});
|
||||||
|
|
||||||
|
private static final List<Object> second = Arrays.asList(new Object[]{
|
||||||
|
"Four",
|
||||||
|
"Five",
|
||||||
|
"Six"
|
||||||
|
});
|
||||||
|
|
||||||
|
private static final List<Object> expected = Arrays.asList(new Object[]{
|
||||||
|
"One",
|
||||||
|
"Two",
|
||||||
|
"Three",
|
||||||
|
"Four",
|
||||||
|
"Five",
|
||||||
|
"Six"
|
||||||
|
});
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoLists_whenUsingNativeJava_thenArraysCombined() {
|
||||||
|
assertThat(CombiningLists.usingNativeJava(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoLists_whenUsingObjectStreams_thenArraysCombined() {
|
||||||
|
assertThat(CombiningLists.usingJava8ObjectStream(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoLists_whenUsingFlatMaps_thenArraysCombined() {
|
||||||
|
assertThat(CombiningLists.usingJava8FlatMaps(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoLists_whenUsingApacheCommons_thenArraysCombined() {
|
||||||
|
assertThat(CombiningLists.usingApacheCommons(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoLists_whenUsingGuava_thenArraysCombined() {
|
||||||
|
assertThat(CombiningLists.usingGuava(first, second), is(expected));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,54 @@
|
||||||
|
package com.baeldung.combiningcollections;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.is;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class CombiningMapsUnitTest {
|
||||||
|
private static final Map<String, String> first = new HashMap<>();
|
||||||
|
private static final Map<String, String> second = new HashMap<>();
|
||||||
|
private static Map<String, String> expected = new HashMap<>();
|
||||||
|
|
||||||
|
static {
|
||||||
|
first.put("one", "first String");
|
||||||
|
first.put("two", "second String");
|
||||||
|
|
||||||
|
second.put("three", "third String");
|
||||||
|
second.put("four", "fourth String");
|
||||||
|
|
||||||
|
expected.put("one", "first String");
|
||||||
|
expected.put("two", "second String");
|
||||||
|
expected.put("three", "third String");
|
||||||
|
expected.put("four", "fourth String");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoMaps_whenUsingNativeJava_thenMapsCombined() {
|
||||||
|
assertThat(CombiningMaps.usingPlainJava(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoMaps_whenUsingForEach_thenMapsCombined() {
|
||||||
|
assertThat(CombiningMaps.usingJava8ForEach(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoMaps_whenUsingFlatMaps_thenMapsCombined() {
|
||||||
|
assertThat(CombiningMaps.usingJava8FlatMaps(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoMaps_whenUsingApacheCommons_thenMapsCombined() {
|
||||||
|
assertThat(CombiningMaps.usingApacheCommons(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoMaps_whenUsingGuava_thenMapsCombined() {
|
||||||
|
assertThat(CombiningMaps.usingGuava(first, second), is(expected));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,45 @@
|
||||||
|
|
||||||
|
package com.baeldung.combiningcollections;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.is;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class CombiningSetsUnitTest {
|
||||||
|
private static final Set<Object> first = new HashSet<Object>(Arrays.asList(new Object[] { "One", "Two", "Three" }));
|
||||||
|
|
||||||
|
private static final Set<Object> second = new HashSet<Object>(Arrays.asList(new Object[] { "Four", "Five", "Six" }));
|
||||||
|
|
||||||
|
private static final Set<Object> expected = new HashSet<Object>(Arrays
|
||||||
|
.asList(new Object[] { "One", "Two", "Three", "Four", "Five", "Six" }));
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoSets_whenUsingNativeJava_thenArraysCombined() {
|
||||||
|
assertThat(CombiningSets.usingNativeJava(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoSets_whenUsingObjectStreams_thenArraysCombined() {
|
||||||
|
assertThat(CombiningSets.usingJava8ObjectStream(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoSets_whenUsingFlatMaps_thenArraysCombined() {
|
||||||
|
assertThat(CombiningSets.usingJava8FlatMaps(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoSets_whenUsingApacheCommons_thenArraysCombined() {
|
||||||
|
assertThat(CombiningSets.usingApacheCommons(first, second), is(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoSets_whenUsingGuava_thenArraysCombined() {
|
||||||
|
assertThat(CombiningSets.usingGuava(first, second), is(expected));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,44 @@
|
||||||
|
package com.baeldung.java.map;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.apache.commons.collections4.MultiMap;
|
||||||
|
import org.apache.commons.collections4.MultiMapUtils;
|
||||||
|
import org.apache.commons.collections4.MultiValuedMap;
|
||||||
|
import org.apache.commons.collections4.map.MultiValueMap;
|
||||||
|
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
|
||||||
|
import org.apache.commons.collections4.multimap.HashSetValuedHashMap;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import com.google.common.collect.ArrayListMultimap;
|
||||||
|
import com.google.common.collect.LinkedHashMultimap;
|
||||||
|
import com.google.common.collect.Multimap;
|
||||||
|
import com.google.common.collect.TreeMultimap;
|
||||||
|
|
||||||
|
|
||||||
|
public class KeyCheckTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenKeyIsPresent_thenContainsKeyReturnsTrue() {
|
||||||
|
Map<String, String> map = Collections.singletonMap("key", "value");
|
||||||
|
|
||||||
|
assertTrue(map.containsKey("key"));
|
||||||
|
assertFalse(map.containsKey("missing"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenKeyHasNullValue_thenGetStillWorks() {
|
||||||
|
Map<String, String> map = Collections.singletonMap("nothing", null);
|
||||||
|
|
||||||
|
assertTrue(map.containsKey("nothing"));
|
||||||
|
assertNull(map.get("nothing"));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,59 @@
|
||||||
|
package com.baeldung.map.util;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class MapMaxUnitTest {
|
||||||
|
|
||||||
|
Map<Integer, Integer> map = null;
|
||||||
|
MapMax mapMax = null;
|
||||||
|
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setupTestData() {
|
||||||
|
map = new HashMap<Integer, Integer>();
|
||||||
|
map.put(23, 12);
|
||||||
|
map.put(46, 24);
|
||||||
|
map.put(27, 38);
|
||||||
|
mapMax = new MapMax();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMap_whenIterated_thenReturnMaxValue() {
|
||||||
|
assertEquals(new Integer(38), mapMax.maxUsingIteration(map));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMap_whenUsingCollectionsMax_thenReturnMaxValue() {
|
||||||
|
assertEquals(new Integer(38), mapMax.maxUsingCollectionsMax(map));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMap_whenUsingCollectionsMaxAndLambda_thenReturnMaxValue() {
|
||||||
|
assertEquals(new Integer(38), mapMax.maxUsingCollectionsMaxAndLambda(map));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMap_whenUsingCollectionsMaxAndMethodReference_thenReturnMaxValue() {
|
||||||
|
assertEquals(new Integer(38), mapMax.maxUsingCollectionsMaxAndMethodReference(map));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMap_whenUsingStreamAndLambda_thenReturnMaxValue() {
|
||||||
|
assertEquals(new Integer(38), mapMax.maxUsingStreamAndLambda(map));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMap_whenUsingStreamAndMethodReference_thenReturnMaxValue() {
|
||||||
|
assertEquals(new Integer(38), mapMax.maxUsingStreamAndMethodReference (map));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
|
@ -31,3 +31,4 @@
|
||||||
- [Create a Symbolic Link with Java](http://www.baeldung.com/java-symlink)
|
- [Create a Symbolic Link with Java](http://www.baeldung.com/java-symlink)
|
||||||
- [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter)
|
- [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter)
|
||||||
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
|
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
|
||||||
|
- [ Read a File into an ArrayList](https://www.baeldung.com/java-file-to-arraylist)
|
||||||
|
|
|
@ -18,6 +18,7 @@ import java.net.URLConnection;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
@ -50,7 +51,7 @@ public class FileOperationsManualTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenFileName_whenUsingJarFile_thenFileData() throws IOException {
|
public void givenFileName_whenUsingJarFile_thenFileData() throws IOException {
|
||||||
String expectedData = "BSD License";
|
String expectedData = "MIT License";
|
||||||
|
|
||||||
Class clazz = Matchers.class;
|
Class clazz = Matchers.class;
|
||||||
InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt");
|
InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt");
|
||||||
|
@ -79,7 +80,7 @@ public class FileOperationsManualTest {
|
||||||
|
|
||||||
ClassLoader classLoader = getClass().getClassLoader();
|
ClassLoader classLoader = getClass().getClassLoader();
|
||||||
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
||||||
String data = FileUtils.readFileToString(file);
|
String data = FileUtils.readFileToString(file, "UTF-8");
|
||||||
|
|
||||||
assertEquals(expectedData, data.trim());
|
assertEquals(expectedData, data.trim());
|
||||||
}
|
}
|
||||||
|
@ -102,12 +103,11 @@ public class FileOperationsManualTest {
|
||||||
|
|
||||||
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
|
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
|
||||||
|
|
||||||
StringBuilder data = new StringBuilder();
|
|
||||||
Stream<String> lines = Files.lines(path);
|
Stream<String> lines = Files.lines(path);
|
||||||
lines.forEach(line -> data.append(line).append("\n"));
|
String data = lines.collect(Collectors.joining("\n"));
|
||||||
lines.close();
|
lines.close();
|
||||||
|
|
||||||
assertEquals(expectedData, data.toString().trim());
|
assertEquals(expectedData, data.trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
private String readFromInputStream(InputStream inputStream) throws IOException {
|
private String readFromInputStream(InputStream inputStream) throws IOException {
|
||||||
|
|
|
@ -0,0 +1 @@
|
||||||
|
Hello World from fileTest.txt!!!
|
|
@ -25,7 +25,6 @@
|
||||||
- [The Traveling Salesman Problem in Java](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
|
- [The Traveling Salesman Problem in Java](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
|
||||||
- [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)
|
||||||
- [How to Design a Genetic Algorithm in Java](http://www.baeldung.com/java-genetic-algorithm)
|
- [How to Design a Genetic Algorithm in Java](http://www.baeldung.com/java-genetic-algorithm)
|
||||||
- [Spring Security – Cache Control Headers](http://www.baeldung.com/spring-security-cache-control-headers)
|
|
||||||
- [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions)
|
- [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions)
|
||||||
- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda)
|
- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda)
|
||||||
- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn)
|
- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn)
|
||||||
|
@ -37,7 +36,6 @@
|
||||||
- [Guide to sun.misc.Unsafe](http://www.baeldung.com/java-unsafe)
|
- [Guide to sun.misc.Unsafe](http://www.baeldung.com/java-unsafe)
|
||||||
- [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
|
- [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
|
||||||
- [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection)
|
- [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection)
|
||||||
- [Guide to UUID in JAVA](http://www.baeldung.com/guide-to-uuid-in-java)
|
|
||||||
- [How to Add a Single Element to a Stream](http://www.baeldung.com/java-stream-append-prepend)
|
- [How to Add a Single Element to a Stream](http://www.baeldung.com/java-stream-append-prepend)
|
||||||
- [Iterating Over Enum Values in Java](http://www.baeldung.com/java-enum-iteration)
|
- [Iterating Over Enum Values in Java](http://www.baeldung.com/java-enum-iteration)
|
||||||
- [Kotlin Java Interoperability](http://www.baeldung.com/kotlin-java-interoperability)
|
- [Kotlin Java Interoperability](http://www.baeldung.com/kotlin-java-interoperability)
|
||||||
|
@ -151,3 +149,4 @@
|
||||||
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
|
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
|
||||||
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
|
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
|
||||||
- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string)
|
- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string)
|
||||||
|
- [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic)
|
||||||
|
|
|
@ -0,0 +1,9 @@
|
||||||
|
package com.baeldung.memoryleaks.equalshashcode;
|
||||||
|
|
||||||
|
public class Person {
|
||||||
|
public String name;
|
||||||
|
|
||||||
|
public Person(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,25 @@
|
||||||
|
package com.baeldung.memoryleaks.equalshashcode;
|
||||||
|
|
||||||
|
public class PersonOptimized {
|
||||||
|
public String name;
|
||||||
|
|
||||||
|
public PersonOptimized(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (o == this) return true;
|
||||||
|
if (!(o instanceof PersonOptimized)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
PersonOptimized person = (PersonOptimized) o;
|
||||||
|
return person.name.equals(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
int result = 17;
|
||||||
|
result = 31 * result + name.hashCode();
|
||||||
|
return result;
|
||||||
|
}}
|
|
@ -0,0 +1,32 @@
|
||||||
|
package com.baeldung.memoryleaks.finalize;
|
||||||
|
|
||||||
|
import java.nio.charset.Charset;
|
||||||
|
import java.util.Random;
|
||||||
|
|
||||||
|
public class BulkyObject {
|
||||||
|
private String data[];
|
||||||
|
|
||||||
|
public BulkyObject() {
|
||||||
|
data = new String[1000000];
|
||||||
|
|
||||||
|
for(int i=0; i<1000000; i++) {
|
||||||
|
data[i] = getRandomString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getRandomString() {
|
||||||
|
byte[] array = new byte[1000];
|
||||||
|
new Random().nextBytes(array);
|
||||||
|
return new String(array, Charset.forName("UTF-8"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void finalize() {
|
||||||
|
try {
|
||||||
|
Thread.sleep(100);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
System.out.println("Finalizer called");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,22 @@
|
||||||
|
package com.baeldung.memoryleaks.finalize;
|
||||||
|
|
||||||
|
import java.nio.charset.Charset;
|
||||||
|
import java.util.Random;
|
||||||
|
|
||||||
|
public class BulkyObjectOptimized {
|
||||||
|
private String data[];
|
||||||
|
|
||||||
|
public BulkyObjectOptimized() {
|
||||||
|
data = new String[1000000];
|
||||||
|
|
||||||
|
for(int i=0; i<1000000; i++) {
|
||||||
|
data[i] = getRandomString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getRandomString() {
|
||||||
|
byte[] array = new byte[1000];
|
||||||
|
new Random().nextBytes(array);
|
||||||
|
return new String(array, Charset.forName("UTF-8"));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,22 @@
|
||||||
|
package com.baeldung.memoryleaks.innerclass;
|
||||||
|
|
||||||
|
import java.nio.charset.Charset;
|
||||||
|
import java.util.Random;
|
||||||
|
|
||||||
|
public class BulkyObject {
|
||||||
|
private String data[];
|
||||||
|
|
||||||
|
public BulkyObject() {
|
||||||
|
data = new String[1000000];
|
||||||
|
|
||||||
|
for(int i=0; i<1000000; i++) {
|
||||||
|
data[i] = getRandomString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getRandomString() {
|
||||||
|
byte[] array = new byte[1000];
|
||||||
|
new Random().nextBytes(array);
|
||||||
|
return new String(array, Charset.forName("UTF-8"));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,17 @@
|
||||||
|
package com.baeldung.memoryleaks.innerclass;
|
||||||
|
|
||||||
|
public class InnerClassDriver {
|
||||||
|
public static InnerClassWrapper.SimpleInnerClass getSimpleInnerClassObj() {
|
||||||
|
return new InnerClassWrapper().new SimpleInnerClass();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main2(String[] args) {
|
||||||
|
InnerClassWrapper.SimpleInnerClass simpleInnerClassObj = getSimpleInnerClassObj();
|
||||||
|
System.out.println("Debug point");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
StaticNestedClassWrapper.StaticNestedClass simpleInnerClassObj = new StaticNestedClassWrapper.StaticNestedClass();
|
||||||
|
System.out.println("Debug point");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,10 @@
|
||||||
|
package com.baeldung.memoryleaks.innerclass;
|
||||||
|
|
||||||
|
|
||||||
|
public class InnerClassWrapper {
|
||||||
|
private BulkyObject bulkyObject = new BulkyObject();
|
||||||
|
|
||||||
|
public class SimpleInnerClass {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,10 @@
|
||||||
|
package com.baeldung.memoryleaks.innerclass;
|
||||||
|
|
||||||
|
|
||||||
|
public class StaticNestedClassWrapper {
|
||||||
|
private BulkyObject bulkyObject = new BulkyObject();
|
||||||
|
|
||||||
|
public static class StaticNestedClass {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,17 @@
|
||||||
|
package com.baeldung.memoryleaks.internedstrings;
|
||||||
|
|
||||||
|
public class InternedString {
|
||||||
|
private static final String FILEPATH = "C:\\bigstring.txt";
|
||||||
|
|
||||||
|
public void readString() {
|
||||||
|
String s1 = ReadStringFromFileUtil.read(FILEPATH).intern();
|
||||||
|
String s2 = ReadStringFromFileUtil.read(FILEPATH).intern();
|
||||||
|
|
||||||
|
if (s1 == s2) {
|
||||||
|
System.out.println("Both the strings objects are same");
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
System.out.println("Both the strings objects are different");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,34 @@
|
||||||
|
package com.baeldung.memoryleaks.internedstrings;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.FileReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public class ReadStringFromFileUtil {
|
||||||
|
|
||||||
|
public static String read(String fileName) {
|
||||||
|
BufferedReader br = null;
|
||||||
|
try {
|
||||||
|
br = new BufferedReader(new FileReader(fileName));
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
String line = br.readLine();
|
||||||
|
|
||||||
|
while (line != null) {
|
||||||
|
sb.append(line);
|
||||||
|
sb.append("\n");
|
||||||
|
line = br.readLine();
|
||||||
|
}
|
||||||
|
return sb.toString();
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
br.close();
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,17 @@
|
||||||
|
package com.baeldung.memoryleaks.internedstrings;
|
||||||
|
|
||||||
|
public class StringObject {
|
||||||
|
private static final String FILEPATH = "C:\\bigstring.txt";
|
||||||
|
|
||||||
|
public void readString() {
|
||||||
|
String s1 = ReadStringFromFileUtil.read(FILEPATH);
|
||||||
|
String s2 = ReadStringFromFileUtil.read(FILEPATH);
|
||||||
|
|
||||||
|
if (s1 == s2) {
|
||||||
|
System.out.println("Both the strings objects are same");
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
System.out.println("Both the strings objects are different");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
package com.baeldung.memoryleaks.staticfields;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class NonStaticFieldsDemo {
|
||||||
|
public List<Double> list = new ArrayList<>();
|
||||||
|
|
||||||
|
public void populateList() {
|
||||||
|
for (int i = 0; i < 10000000; i++) {
|
||||||
|
list.add(Math.random());
|
||||||
|
}
|
||||||
|
System.out.println("Debug Point 2");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
System.out.println("Debug Point 1");
|
||||||
|
new NonStaticFieldsDemo().populateList();
|
||||||
|
System.out.println("Debug Point 3");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
package com.baeldung.memoryleaks.staticfields;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class StaticFieldsDemo {
|
||||||
|
public static List<Double> list = new ArrayList<>();
|
||||||
|
|
||||||
|
public void populateList() {
|
||||||
|
for (int i = 0; i < 10000000; i++) {
|
||||||
|
list.add(Math.random());
|
||||||
|
}
|
||||||
|
System.out.println("Debug Point 2");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
System.out.println("Debug Point 1");
|
||||||
|
new StaticFieldsDemo().populateList();
|
||||||
|
System.out.println("Debug Point 3");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,8 @@
|
||||||
|
package com.baeldung.nth.root.calculator;
|
||||||
|
|
||||||
|
public class NthRootCalculator
|
||||||
|
{
|
||||||
|
public Double calculate(Double base, Double n) {
|
||||||
|
return Math.pow(Math.E, Math.log(base)/n);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,13 @@
|
||||||
|
package com.baeldung.nth.root.main;
|
||||||
|
|
||||||
|
import com.baeldung.nth.root.calculator.NthRootCalculator;
|
||||||
|
|
||||||
|
public class Main {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
NthRootCalculator calculator = new NthRootCalculator();
|
||||||
|
Double base = Double.parseDouble(args[0]);
|
||||||
|
Double n = Double.parseDouble(args[1]);
|
||||||
|
Double result = calculator.calculate(base, n);
|
||||||
|
System.out.println("The " + n + " root of " + base + " equals to " + result + ".");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,70 @@
|
||||||
|
package com.baeldung.switchstatement;
|
||||||
|
|
||||||
|
public class SwitchStatement {
|
||||||
|
|
||||||
|
public String exampleOfIF(String animal) {
|
||||||
|
|
||||||
|
String result;
|
||||||
|
|
||||||
|
if (animal.equals("DOG") || animal.equals("CAT")) {
|
||||||
|
result = "domestic animal";
|
||||||
|
} else if (animal.equals("TIGER")) {
|
||||||
|
result = "wild animal";
|
||||||
|
} else {
|
||||||
|
result = "unknown animal";
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String exampleOfSwitch(String animal) {
|
||||||
|
|
||||||
|
String result;
|
||||||
|
|
||||||
|
switch (animal) {
|
||||||
|
case "DOG":
|
||||||
|
case "CAT":
|
||||||
|
result = "domestic animal";
|
||||||
|
break;
|
||||||
|
case "TIGER":
|
||||||
|
result = "wild animal";
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
result = "unknown animal";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String forgetBreakInSwitch(String animal) {
|
||||||
|
|
||||||
|
String result;
|
||||||
|
|
||||||
|
switch (animal) {
|
||||||
|
|
||||||
|
case "DOG":
|
||||||
|
System.out.println("domestic animal");
|
||||||
|
result = "domestic animal";
|
||||||
|
|
||||||
|
default:
|
||||||
|
System.out.println("unknown animal");
|
||||||
|
result = "unknown animal";
|
||||||
|
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String constantCaseValue(String animal) {
|
||||||
|
|
||||||
|
String result = "";
|
||||||
|
|
||||||
|
final String dog = "DOG";
|
||||||
|
|
||||||
|
switch (animal) {
|
||||||
|
|
||||||
|
case dog:
|
||||||
|
result = "domestic animal";
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,33 @@
|
||||||
|
package com.baeldung.memoryleaks.equalshashcode;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.junit.Ignore;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class PersonMemoryLeakUnitTest {
|
||||||
|
@Test
|
||||||
|
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||||
|
public void givenMap_whenEqualsAndHashCodeNotOverridden_thenMemoryLeak() {
|
||||||
|
Map<Person, Integer> map = new HashMap<Person, Integer>();
|
||||||
|
for(int i=0; i<10000000; i++) {
|
||||||
|
map.put(new Person("jon"), 1);
|
||||||
|
}
|
||||||
|
assertTrue(map.size() > 1);
|
||||||
|
System.out.print("Debug Point - VisuaLVM");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||||
|
public void givenMap_whenEqualsAndHashCodeOverridden_thenNoMemoryLeak() {
|
||||||
|
Map<PersonOptimized, Integer> map = new HashMap<PersonOptimized, Integer>();
|
||||||
|
for(int i=0; i<10000; i++) {
|
||||||
|
map.put(new PersonOptimized("jon"), 1);
|
||||||
|
}
|
||||||
|
assertTrue(map.size() == 1);
|
||||||
|
System.out.print("Debug Point - VisuaLVM");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
package com.baeldung.memoryleaks.finalize;
|
||||||
|
|
||||||
|
import org.junit.Ignore;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class FinalizeMemoryLeakUnitTest {
|
||||||
|
@Test
|
||||||
|
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||||
|
public void givenObjectWithFinalizer_whenCreatingAndDestroyingThisObject_thenMemoryLeak() {
|
||||||
|
BulkyObject[] stock = new BulkyObject[100000];
|
||||||
|
|
||||||
|
for(int i=0; i<100000; i++) {
|
||||||
|
stock[i] = new BulkyObject();
|
||||||
|
}
|
||||||
|
System.out.print("Debug Point - VisuaLVM");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||||
|
public void givenObjectWithoutFinalizer_whenCreatingAndDestroyingThisObject_thenNoMemoryLeak() {
|
||||||
|
BulkyObjectOptimized[] stock = new BulkyObjectOptimized[100000];
|
||||||
|
|
||||||
|
for(int i=0; i<100000; i++) {
|
||||||
|
stock[i] = new BulkyObjectOptimized();
|
||||||
|
}
|
||||||
|
System.out.print("Debug Point - VisuaLVM");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,20 @@
|
||||||
|
package com.baeldung.memoryleaks.innerclass;
|
||||||
|
|
||||||
|
import org.junit.Ignore;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class StaticInnerClassMemoryLeakUnitTest {
|
||||||
|
@Test
|
||||||
|
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||||
|
public void givenUsingInnerClass_whenInitializingInnerClass_thenInnerClassHoldsReferenceOfOuterObject() {
|
||||||
|
InnerClassWrapper.SimpleInnerClass simpleInnerClassObj = new InnerClassWrapper().new SimpleInnerClass();
|
||||||
|
System.out.print("Debug Point - VisuaLVM");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||||
|
public void givenUsingStaticNestedClass_whenInitializingInnerClass_thenStaticNestedClassDoesntReferenceOuterObject() {
|
||||||
|
StaticNestedClassWrapper.StaticNestedClass staticNestedClassObj = new StaticNestedClassWrapper.StaticNestedClass();
|
||||||
|
System.out.print("Debug Point - VisuaLVM");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,20 @@
|
||||||
|
package com.baeldung.memoryleaks.internedstrings;
|
||||||
|
|
||||||
|
import org.junit.Ignore;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class StringInternMemoryLeakUnitTest {
|
||||||
|
@Test
|
||||||
|
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||||
|
public void givenJava6OrBelow_whenInterningLargeStrings_thenPermgenIncreases() {
|
||||||
|
new InternedString().readString();
|
||||||
|
System.out.print("Debug Point - VisuaLVM");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||||
|
public void givenJava6OrBelow_whenNotInterningLargeStrings_thenPermgenDoesntIncrease() {
|
||||||
|
new StringObject().readString();
|
||||||
|
System.out.print("Debug Point - VisuaLVM");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,26 @@
|
||||||
|
package com.baeldung.memoryleaks.staticfields;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.Ignore;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class NonStaticFieldsMemoryLeakUnitTest {
|
||||||
|
public List<Double> list = new ArrayList<>();
|
||||||
|
|
||||||
|
public void populateList() {
|
||||||
|
for (int i = 0; i < 10000000; i++) {
|
||||||
|
list.add(Math.random());
|
||||||
|
}
|
||||||
|
System.out.println("Debug Point 2");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||||
|
public void givenNonStaticLargeList_whenPopulatingList_thenListGarbageCollected() {
|
||||||
|
System.out.println("Debug Point 1");
|
||||||
|
new NonStaticFieldsMemoryLeakUnitTest().populateList();
|
||||||
|
System.out.println("Debug Point 3");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,26 @@
|
||||||
|
package com.baeldung.memoryleaks.staticfields;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.Ignore;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class StaticFieldsMemoryLeakUnitTest {
|
||||||
|
public static List<Double> list = new ArrayList<>();
|
||||||
|
|
||||||
|
public void populateList() {
|
||||||
|
for (int i = 0; i < 10000000; i++) {
|
||||||
|
list.add(Math.random());
|
||||||
|
}
|
||||||
|
System.out.println("Debug Point 2");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||||
|
public void givenStaticLargeList_whenPopulatingList_thenListIsNotGarbageCollected() {
|
||||||
|
System.out.println("Debug Point 1");
|
||||||
|
new StaticFieldsDemo().populateList();
|
||||||
|
System.out.println("Debug Point 3");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
package com.baeldung.nth.root.calculator;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.runners.MockitoJUnitRunner;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
@RunWith(MockitoJUnitRunner.class)
|
||||||
|
public class NthRootCalculatorUnitTest {
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private NthRootCalculator nthRootCalculator;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void giventThatTheBaseIs125_andTheExpIs3_whenCalculateIsCalled_thenTheResultIsTheCorrectOne() {
|
||||||
|
Double result = nthRootCalculator.calculate(125.0, 3.0);
|
||||||
|
assertEquals(result, (Double) 5.0d);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,34 @@
|
||||||
|
package com.baeldung.nth.root.main;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.PrintStream;
|
||||||
|
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class MainUnitTest {
|
||||||
|
@InjectMocks
|
||||||
|
private Main main;
|
||||||
|
|
||||||
|
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
|
||||||
|
private final PrintStream originalOut = System.out;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUpStreams() {
|
||||||
|
System.setOut(new PrintStream(outContent));
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void restoreStreams() {
|
||||||
|
System.setOut(originalOut);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenThatTheBaseIs125_andTheExpIs3_whenMainIsCalled_thenTheCorrectResultIsPrinted() {
|
||||||
|
main.main(new String[]{"125.0", "3.0"});
|
||||||
|
assertEquals("The 3.0 root of 125.0 equals to 5.0.\n", outContent.toString().replaceAll("\r", ""));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,38 @@
|
||||||
|
package com.baeldung.switchstatement;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
|
||||||
|
public class SwitchStatementUnitTest {
|
||||||
|
private SwitchStatement s = new SwitchStatement();
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenDog_thenDomesticAnimal() {
|
||||||
|
|
||||||
|
String animal = "DOG";
|
||||||
|
Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenNoBreaks_thenGoThroughBlocks() {
|
||||||
|
String animal = "DOG";
|
||||||
|
Assert.assertEquals("unknown animal", s.forgetBreakInSwitch(animal));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected=NullPointerException.class)
|
||||||
|
public void whenSwitchAgumentIsNull_thenNullPointerException() {
|
||||||
|
String animal = null;
|
||||||
|
Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCompareStrings_thenByEqual() {
|
||||||
|
String animal = new String("DOG");
|
||||||
|
Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,43 @@
|
||||||
|
package com.baeldung.ternaryoperator;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class TernaryOperatorUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenACondition_whenUsingTernaryOperator_thenItEvaluatesConditionAndReturnsAValue() {
|
||||||
|
int number = 10;
|
||||||
|
String msg = number > 10 ? "Number is greater than 10" : "Number is less than or equal to 10";
|
||||||
|
|
||||||
|
assertThat(msg).isEqualTo("Number is less than or equal to 10");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenATrueCondition_whenUsingTernaryOperator_thenOnlyExpression1IsEvaluated() {
|
||||||
|
int exp1 = 0, exp2 = 0;
|
||||||
|
int result = 12 > 10 ? ++exp1 : ++exp2;
|
||||||
|
|
||||||
|
assertThat(exp1).isEqualTo(1);
|
||||||
|
assertThat(exp2).isEqualTo(0);
|
||||||
|
assertThat(result).isEqualTo(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAFalseCondition_whenUsingTernaryOperator_thenOnlyExpression2IsEvaluated() {
|
||||||
|
int exp1 = 0, exp2 = 0;
|
||||||
|
int result = 8 > 10 ? ++exp1 : ++exp2;
|
||||||
|
|
||||||
|
assertThat(exp1).isEqualTo(0);
|
||||||
|
assertThat(exp2).isEqualTo(1);
|
||||||
|
assertThat(result).isEqualTo(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenANestedCondition_whenUsingTernaryOperator_thenCorrectValueIsReturned() {
|
||||||
|
int number = 6;
|
||||||
|
String msg = number > 10 ? "Number is greater than 10" : number > 5 ? "Number is greater than 5" : "Number is less than or equal to 5";
|
||||||
|
|
||||||
|
assertThat(msg).isEqualTo("Number is greater than 5");
|
||||||
|
}
|
||||||
|
}
|
|
@ -33,4 +33,7 @@
|
||||||
- [Idiomatic Logging in Kotlin](http://www.baeldung.com/kotlin-logging)
|
- [Idiomatic Logging in Kotlin](http://www.baeldung.com/kotlin-logging)
|
||||||
- [Kotlin Constructors](https://www.baeldung.com/kotlin-constructors)
|
- [Kotlin Constructors](https://www.baeldung.com/kotlin-constructors)
|
||||||
- [Creational Design Patterns in Kotlin: Builder](https://www.baeldung.com/kotlin-builder-pattern)
|
- [Creational Design Patterns in Kotlin: Builder](https://www.baeldung.com/kotlin-builder-pattern)
|
||||||
- [Kotlin Nested and Inner Classes](https://www.baeldung.com/kotlin-inner-classes)
|
- [Kotlin Nested and Inner Classes](https://www.baeldung.com/kotlin-inner-classes)
|
||||||
|
- [Kotlin with Ktor](https://www.baeldung.com/kotlin-ktor)
|
||||||
|
- [Fuel HTTP Library with Kotlin](https://www.baeldung.com/kotlin-fuel)
|
||||||
|
- [Introduction to Kovenant Library for Kotlin](https://www.baeldung.com/kotlin-kovenant)
|
||||||
|
|
|
@ -0,0 +1,121 @@
|
||||||
|
package com.baeldung.kotlin
|
||||||
|
|
||||||
|
import org.junit.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
import kotlin.test.assertFalse
|
||||||
|
|
||||||
|
class StructuralJumpUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun givenLoop_whenBreak_thenComplete() {
|
||||||
|
var value = ""
|
||||||
|
for (i in "hello_world") {
|
||||||
|
if (i == '_')
|
||||||
|
break
|
||||||
|
value += i.toString()
|
||||||
|
}
|
||||||
|
assertEquals("hello", value)
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
fun givenLoop_whenBreakWithLabel_thenComplete() {
|
||||||
|
var value = ""
|
||||||
|
outer_loop@ for (i in 'a'..'d') {
|
||||||
|
for (j in 1..3) {
|
||||||
|
value += "" + i + j
|
||||||
|
if (i == 'b' && j == 1)
|
||||||
|
break@outer_loop
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals("a1a2a3b1", value)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun givenLoop_whenContinue_thenComplete() {
|
||||||
|
var result = ""
|
||||||
|
for (i in "hello_world") {
|
||||||
|
if (i == '_')
|
||||||
|
continue
|
||||||
|
result += i
|
||||||
|
}
|
||||||
|
assertEquals("helloworld", result)
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
fun givenLoop_whenContinueWithLabel_thenComplete() {
|
||||||
|
var result = ""
|
||||||
|
outer_loop@ for (i in 'a'..'c') {
|
||||||
|
for (j in 1..3) {
|
||||||
|
if (i == 'b')
|
||||||
|
continue@outer_loop
|
||||||
|
result += "" + i + j
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals("a1a2a3c1c2c3", result)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun givenLambda_whenReturn_thenComplete() {
|
||||||
|
var result = returnInLambda();
|
||||||
|
assertEquals("hello", result)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun returnInLambda(): String {
|
||||||
|
var result = ""
|
||||||
|
"hello_world".forEach {
|
||||||
|
// non-local return directly to the caller
|
||||||
|
if (it == '_') return result
|
||||||
|
result += it.toString()
|
||||||
|
}
|
||||||
|
//this line won't be reached
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun givenLambda_whenReturnWithExplicitLabel_thenComplete() {
|
||||||
|
var result = ""
|
||||||
|
"hello_world".forEach lit@{
|
||||||
|
if (it == '_') {
|
||||||
|
// local return to the caller of the lambda, i.e. the forEach loop
|
||||||
|
return@lit
|
||||||
|
}
|
||||||
|
result += it.toString()
|
||||||
|
}
|
||||||
|
assertEquals("helloworld", result)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun givenLambda_whenReturnWithImplicitLabel_thenComplete() {
|
||||||
|
var result = ""
|
||||||
|
"hello_world".forEach {
|
||||||
|
if (it == '_') {
|
||||||
|
// local return to the caller of the lambda, i.e. the forEach loop
|
||||||
|
return@forEach
|
||||||
|
}
|
||||||
|
result += it.toString()
|
||||||
|
}
|
||||||
|
assertEquals("helloworld", result)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun givenAnonymousFunction_return_thenComplete() {
|
||||||
|
var result = ""
|
||||||
|
"hello_world".forEach(fun(element) {
|
||||||
|
// local return to the caller of the anonymous fun, i.e. the forEach loop
|
||||||
|
if (element == '_') return
|
||||||
|
result += element.toString()
|
||||||
|
})
|
||||||
|
assertEquals("helloworld", result)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun givenAnonymousFunction_returnToLabel_thenComplete() {
|
||||||
|
var result = ""
|
||||||
|
run loop@{
|
||||||
|
"hello_world".forEach {
|
||||||
|
// non-local return from the lambda passed to run
|
||||||
|
if (it == '_') return@loop
|
||||||
|
result += it.toString()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals("hello", result)
|
||||||
|
}
|
||||||
|
}
|
|
@ -15,7 +15,6 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>javax</groupId>
|
<groupId>javax</groupId>
|
||||||
<artifactId>javaee-api</artifactId>
|
<artifactId>javaee-api</artifactId>
|
||||||
<version>${javaee-api.version}</version>
|
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
|
@ -24,7 +24,6 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>javax</groupId>
|
<groupId>javax</groupId>
|
||||||
<artifactId>javaee-api</artifactId>
|
<artifactId>javaee-api</artifactId>
|
||||||
<version>${javaee-api.version}</version>
|
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
|
|
|
@ -0,0 +1,51 @@
|
||||||
|
<?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>
|
||||||
|
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>flyway-cdi-extension</artifactId>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<maven.compiler.source>1.8</maven.compiler.source>
|
||||||
|
<maven.compiler.target>1.8</maven.compiler.target>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.enterprise</groupId>
|
||||||
|
<artifactId>cdi-api</artifactId>
|
||||||
|
<version>2.0.SP1</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jboss.weld.se</groupId>
|
||||||
|
<artifactId>weld-se-core</artifactId>
|
||||||
|
<version>3.0.5.Final</version>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.flywaydb</groupId>
|
||||||
|
<artifactId>flyway-core</artifactId>
|
||||||
|
<version>5.1.4</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.tomcat</groupId>
|
||||||
|
<artifactId>tomcat-jdbc</artifactId>
|
||||||
|
<version>8.5.33</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.annotation</groupId>
|
||||||
|
<artifactId>javax.annotation-api</artifactId>
|
||||||
|
<version>1.3.2</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.h2database</groupId>
|
||||||
|
<artifactId>h2</artifactId>
|
||||||
|
<version>1.4.197</version>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
</project>
|
|
@ -0,0 +1,74 @@
|
||||||
|
package com.baeldung.cdi.extension;
|
||||||
|
|
||||||
|
import org.apache.tomcat.jdbc.pool.DataSource;
|
||||||
|
import org.flywaydb.core.Flyway;
|
||||||
|
|
||||||
|
import javax.annotation.sql.DataSourceDefinition;
|
||||||
|
import javax.enterprise.context.ApplicationScoped;
|
||||||
|
import javax.enterprise.event.Observes;
|
||||||
|
import javax.enterprise.inject.Any;
|
||||||
|
import javax.enterprise.inject.Default;
|
||||||
|
import javax.enterprise.inject.literal.InjectLiteral;
|
||||||
|
import javax.enterprise.inject.spi.*;
|
||||||
|
import javax.enterprise.util.AnnotationLiteral;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flyway is now under CDI container like:
|
||||||
|
*
|
||||||
|
* @ApplicationScoped
|
||||||
|
* @FlywayType public class Flyway{
|
||||||
|
* @Inject setDataSource(DataSource dataSource){
|
||||||
|
* //...
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
|
||||||
|
public class FlywayExtension implements Extension {
|
||||||
|
|
||||||
|
DataSourceDefinition dataSourceDefinition = null;
|
||||||
|
|
||||||
|
public void registerFlywayType(@Observes BeforeBeanDiscovery bbdEvent) {
|
||||||
|
bbdEvent.addAnnotatedType(Flyway.class, Flyway.class.getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void detectDataSourceDefinition(@Observes @WithAnnotations(DataSourceDefinition.class) ProcessAnnotatedType<?> patEvent) {
|
||||||
|
AnnotatedType at = patEvent.getAnnotatedType();
|
||||||
|
dataSourceDefinition = at.getAnnotation(DataSourceDefinition.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void processAnnotatedType(@Observes ProcessAnnotatedType<Flyway> patEvent) {
|
||||||
|
patEvent.configureAnnotatedType()
|
||||||
|
//Add Scope
|
||||||
|
.add(ApplicationScoped.Literal.INSTANCE)
|
||||||
|
//Add Qualifier
|
||||||
|
.add(new AnnotationLiteral<FlywayType>() {
|
||||||
|
})
|
||||||
|
//Decorate setDataSource(DataSource dataSource){} with @Inject
|
||||||
|
.filterMethods(annotatedMethod -> {
|
||||||
|
return annotatedMethod.getParameters().size() == 1 &&
|
||||||
|
annotatedMethod.getParameters().get(0).getBaseType().equals(javax.sql.DataSource.class);
|
||||||
|
})
|
||||||
|
.findFirst().get().add(InjectLiteral.INSTANCE);
|
||||||
|
}
|
||||||
|
|
||||||
|
void afterBeanDiscovery(@Observes AfterBeanDiscovery abdEvent, BeanManager bm) {
|
||||||
|
abdEvent.addBean()
|
||||||
|
.types(javax.sql.DataSource.class, DataSource.class)
|
||||||
|
.qualifiers(new AnnotationLiteral<Default>() {}, new AnnotationLiteral<Any>() {})
|
||||||
|
.scope(ApplicationScoped.class)
|
||||||
|
.name(DataSource.class.getName())
|
||||||
|
.beanClass(DataSource.class)
|
||||||
|
.createWith(creationalContext -> {
|
||||||
|
DataSource instance = new DataSource();
|
||||||
|
instance.setUrl(dataSourceDefinition.url());
|
||||||
|
instance.setDriverClassName(dataSourceDefinition.className());
|
||||||
|
return instance;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void runFlywayMigration(@Observes AfterDeploymentValidation adv, BeanManager manager) {
|
||||||
|
Flyway flyway = manager.createInstance().select(Flyway.class, new AnnotationLiteral<FlywayType>() {}).get();
|
||||||
|
flyway.migrate();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,14 @@
|
||||||
|
package com.baeldung.cdi.extension;
|
||||||
|
|
||||||
|
import javax.inject.Qualifier;
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.RetentionPolicy;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
|
import static java.lang.annotation.ElementType.*;
|
||||||
|
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
@Target({FIELD, METHOD, PARAMETER, TYPE})
|
||||||
|
@Qualifier
|
||||||
|
public @interface FlywayType {
|
||||||
|
}
|
|
@ -0,0 +1,16 @@
|
||||||
|
package com.baeldung.cdi.extension;
|
||||||
|
|
||||||
|
import javax.annotation.sql.DataSourceDefinition;
|
||||||
|
import javax.enterprise.context.ApplicationScoped;
|
||||||
|
import javax.enterprise.inject.se.SeContainer;
|
||||||
|
import javax.enterprise.inject.se.SeContainerInitializer;
|
||||||
|
|
||||||
|
@ApplicationScoped
|
||||||
|
@DataSourceDefinition(name = "ds", className = "org.h2.Driver", url = "jdbc:h2:mem:testdb")
|
||||||
|
public class MainApp {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SeContainerInitializer initializer = SeContainerInitializer.newInstance();
|
||||||
|
try (SeContainer container = initializer.initialize()) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,6 @@
|
||||||
|
<beans version="2.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
|
||||||
|
http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
|
||||||
|
bean-discovery-mode="annotated">
|
||||||
|
</beans>
|
|
@ -0,0 +1,2 @@
|
||||||
|
com.baeldung.cdi.extension.FlywayExtension
|
||||||
|
|
|
@ -0,0 +1,4 @@
|
||||||
|
create table PERSON (
|
||||||
|
ID int not null,
|
||||||
|
NAME varchar(100) not null
|
||||||
|
);
|
|
@ -0,0 +1,3 @@
|
||||||
|
insert into PERSON (ID, NAME) values (1, 'Axel');
|
||||||
|
insert into PERSON (ID, NAME) values (2, 'Mr. Foo');
|
||||||
|
insert into PERSON (ID, NAME) values (3, 'Ms. Bar');
|
|
@ -65,6 +65,7 @@
|
||||||
<properties>
|
<properties>
|
||||||
<flyway-core.version>5.0.2</flyway-core.version>
|
<flyway-core.version>5.0.2</flyway-core.version>
|
||||||
<flyway-maven-plugin.version>5.0.2</flyway-maven-plugin.version>
|
<flyway-maven-plugin.version>5.0.2</flyway-maven-plugin.version>
|
||||||
|
<h2.version>1.4.195</h2.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -16,7 +16,7 @@ import org.springframework.test.context.junit4.SpringRunner;
|
||||||
@RunWith(SpringRunner.class)
|
@RunWith(SpringRunner.class)
|
||||||
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
|
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
|
||||||
@ContextConfiguration(classes = FlywayCallbackTestConfig.class)
|
@ContextConfiguration(classes = FlywayCallbackTestConfig.class)
|
||||||
public class FlywayApplicationTest {
|
public class FlywayApplicationUnitTest {
|
||||||
|
|
||||||
private Log log = LogFactory.getLog(getClass());
|
private Log log = LogFactory.getLog(getClass());
|
||||||
|
|
130
gson/pom.xml
130
gson/pom.xml
|
@ -1,73 +1,73 @@
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
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">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>gson</artifactId>
|
<artifactId>gson</artifactId>
|
||||||
<version>0.1-SNAPSHOT</version>
|
<version>0.1-SNAPSHOT</version>
|
||||||
<name>gson</name>
|
<name>gson</name>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-java</artifactId>
|
<artifactId>parent-java</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<relativePath>../parent-java</relativePath>
|
<relativePath>../parent-java</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<!-- utils -->
|
<!-- utils -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.projectlombok</groupId>
|
<groupId>org.projectlombok</groupId>
|
||||||
<artifactId>lombok</artifactId>
|
<artifactId>lombok</artifactId>
|
||||||
<version>${lombok.version}</version>
|
<version>${lombok.version}</version>
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>joda-time</groupId>
|
<groupId>joda-time</groupId>
|
||||||
<artifactId>joda-time</artifactId>
|
<artifactId>joda-time</artifactId>
|
||||||
<version>${joda-time.version}</version>
|
<version>${joda-time.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>commons-io</groupId>
|
<groupId>commons-io</groupId>
|
||||||
<artifactId>commons-io</artifactId>
|
<artifactId>commons-io</artifactId>
|
||||||
<version>${commons-io.version}</version>
|
<version>${commons-io.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.commons</groupId>
|
<groupId>org.apache.commons</groupId>
|
||||||
<artifactId>commons-collections4</artifactId>
|
<artifactId>commons-collections4</artifactId>
|
||||||
<version>${commons-collections4.version}</version>
|
<version>${commons-collections4.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.commons</groupId>
|
<groupId>org.apache.commons</groupId>
|
||||||
<artifactId>commons-lang3</artifactId>
|
<artifactId>commons-lang3</artifactId>
|
||||||
<version>${commons-lang3.version}</version>
|
<version>${commons-lang3.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<!-- marshalling -->
|
<!-- marshalling -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.code.gson</groupId>
|
<groupId>com.google.code.gson</groupId>
|
||||||
<artifactId>gson</artifactId>
|
<artifactId>gson</artifactId>
|
||||||
<version>${gson.version}</version>
|
<version>${gson.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<finalName>gson</finalName>
|
<finalName>gson</finalName>
|
||||||
<resources>
|
<resources>
|
||||||
<resource>
|
<resource>
|
||||||
<directory>src/main/resources</directory>
|
<directory>src/main/resources</directory>
|
||||||
<filtering>true</filtering>
|
<filtering>true</filtering>
|
||||||
</resource>
|
</resource>
|
||||||
</resources>
|
</resources>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<!-- marshalling -->
|
<!-- marshalling -->
|
||||||
<gson.version>2.8.0</gson.version>
|
<gson.version>2.8.0</gson.version>
|
||||||
<!-- util -->
|
<!-- util -->
|
||||||
<commons-lang3.version>3.5</commons-lang3.version>
|
<commons-lang3.version>3.5</commons-lang3.version>
|
||||||
<commons-collections4.version>4.1</commons-collections4.version>
|
<commons-collections4.version>4.1</commons-collections4.version>
|
||||||
<joda-time.version>2.9.6</joda-time.version>
|
<joda-time.version>2.9.6</joda-time.version>
|
||||||
<lombok.version>1.16.10</lombok.version>
|
<lombok.version>1.16.10</lombok.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -0,0 +1,36 @@
|
||||||
|
package org.baeldung.gson.entities;
|
||||||
|
|
||||||
|
public class Employee {
|
||||||
|
private int id;
|
||||||
|
private String name;
|
||||||
|
private String address;
|
||||||
|
|
||||||
|
public Employee(int id, String name) {
|
||||||
|
this.id = id;
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(int id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAddress() {
|
||||||
|
return address;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAddress(String address) {
|
||||||
|
this.address = address;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,66 @@
|
||||||
|
package org.baeldung.gson.serialization;
|
||||||
|
|
||||||
|
import java.lang.reflect.Type;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.baeldung.gson.entities.Employee;
|
||||||
|
|
||||||
|
import com.google.gson.*;
|
||||||
|
|
||||||
|
public class HashMapDeserializer implements JsonDeserializer<HashMap<String, Object>> {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public HashMap<String, Object> deserialize(JsonElement elem, Type type, JsonDeserializationContext context) throws JsonParseException {
|
||||||
|
HashMap<String, Object> map = new HashMap<>();
|
||||||
|
for (Map.Entry<String, JsonElement> entry : elem.getAsJsonObject().entrySet()) {
|
||||||
|
JsonElement jsonValue = entry.getValue();
|
||||||
|
Object value = null;
|
||||||
|
if (jsonValue.isJsonPrimitive()) {
|
||||||
|
value = toPrimitive(jsonValue.getAsJsonPrimitive(), context);
|
||||||
|
} else {
|
||||||
|
value = context.deserialize(jsonValue, Employee.class);
|
||||||
|
}
|
||||||
|
map.put(entry.getKey(), value);
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private Object toPrimitive(JsonPrimitive jsonValue, JsonDeserializationContext context) {
|
||||||
|
if (jsonValue.isBoolean())
|
||||||
|
return jsonValue.getAsBoolean();
|
||||||
|
else if (jsonValue.isString())
|
||||||
|
return jsonValue.getAsString();
|
||||||
|
else {
|
||||||
|
BigDecimal bigDec = jsonValue.getAsBigDecimal();
|
||||||
|
Long l;
|
||||||
|
Integer i;
|
||||||
|
if ((i = toInteger(bigDec)) != null) {
|
||||||
|
return i;
|
||||||
|
} else if ((l = toLong(bigDec)) != null) {
|
||||||
|
return l;
|
||||||
|
} else {
|
||||||
|
return bigDec.doubleValue();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Long toLong(BigDecimal val) {
|
||||||
|
try {
|
||||||
|
return val.toBigIntegerExact().longValue();
|
||||||
|
} catch (ArithmeticException e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Integer toInteger(BigDecimal val) {
|
||||||
|
try {
|
||||||
|
return val.intValueExact();
|
||||||
|
} catch (ArithmeticException e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -7,13 +7,13 @@
|
||||||
</encoder>
|
</encoder>
|
||||||
</appender>
|
</appender>
|
||||||
|
|
||||||
<logger name="org.springframework" level="WARN" />
|
<logger name="org.springframework" level="WARN"/>
|
||||||
<logger name="org.springframework.transaction" level="WARN" />
|
<logger name="org.springframework.transaction" level="WARN"/>
|
||||||
|
|
||||||
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
||||||
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
|
<logger name="org.springframework.web.servlet.mvc" level="WARN"/>
|
||||||
|
|
||||||
<root level="INFO">
|
<root level="INFO">
|
||||||
<appender-ref ref="STDOUT" />
|
<appender-ref ref="STDOUT"/>
|
||||||
</root>
|
</root>
|
||||||
</configuration>
|
</configuration>
|
|
@ -0,0 +1,86 @@
|
||||||
|
package org.baeldung.gson.deserialization;
|
||||||
|
|
||||||
|
import java.lang.reflect.Type;
|
||||||
|
import java.util.HashMap;
|
||||||
|
|
||||||
|
import org.baeldung.gson.entities.Employee;
|
||||||
|
import org.baeldung.gson.serialization.HashMapDeserializer;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import com.google.gson.Gson;
|
||||||
|
import com.google.gson.GsonBuilder;
|
||||||
|
import com.google.gson.JsonSyntaxException;
|
||||||
|
import com.google.gson.internal.LinkedTreeMap;
|
||||||
|
import com.google.gson.reflect.TypeToken;
|
||||||
|
|
||||||
|
public class HashMapDeserializationUnitTest {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(HashMapDeserializationUnitTest.class);
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingHashMapClass_thenShouldReturnMapWithDefaultClasses() {
|
||||||
|
|
||||||
|
String jsonString = "{'employee.name':'Bob','employee.salary':10000, 'employee.active':true, "
|
||||||
|
+ "'employee':{'id':10, 'name': 'Bob Willis', 'address':'London'}}";
|
||||||
|
|
||||||
|
Gson gson = new Gson();
|
||||||
|
HashMap map = gson.fromJson(jsonString, HashMap.class);
|
||||||
|
|
||||||
|
logger.info("The converted map: {}", map);
|
||||||
|
Assert.assertEquals(4, map.size());
|
||||||
|
Assert.assertEquals(Double.class, map.get("employee.salary").getClass());
|
||||||
|
Assert.assertEquals(LinkedTreeMap.class, map.get("employee").getClass());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = JsonSyntaxException.class)
|
||||||
|
public void whenUsingJsonStringWithDuplicateKey_thenShouldThrowJsonSyntaxException() {
|
||||||
|
|
||||||
|
String jsonString = "{'employee.name':'Bob', 'employee.name':'Jenny','employee.salary':10000, "
|
||||||
|
+ "'employee.active':true, " + "'employee':{'id':10, 'name': 'Bob Willis', 'address':'London'}}";
|
||||||
|
|
||||||
|
Gson gson = new Gson();
|
||||||
|
HashMap map = gson.fromJson(jsonString, HashMap.class);
|
||||||
|
|
||||||
|
logger.info("The converted map: {}", map);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingTypeToken_thenShouldReturnMapWithProperClass() {
|
||||||
|
|
||||||
|
String jsonString = "{'Bob':{'id':10, 'name': 'Bob Willis', 'address':'UK'},"
|
||||||
|
+ "'Jenny':{'id':10, 'name': 'Jenny McCarthy', 'address':'USA'}, "
|
||||||
|
+ "'Steve':{'id':10, 'name': 'Steven Waugh', 'address':'Australia'}}";
|
||||||
|
|
||||||
|
Gson gson = new Gson();
|
||||||
|
Type empMapType = new TypeToken<HashMap<String, Employee>>(){}.getType();
|
||||||
|
HashMap<String, Employee> nameEmployeeMap = gson.fromJson(jsonString, empMapType);
|
||||||
|
|
||||||
|
logger.info("The converted map: {}", nameEmployeeMap);
|
||||||
|
Assert.assertEquals(3, nameEmployeeMap.size());
|
||||||
|
Assert.assertEquals(Employee.class, nameEmployeeMap.get("Bob").getClass());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingCustomDeserializer_thenShouldReturnMapWithProperClass() {
|
||||||
|
|
||||||
|
String jsonString = "{'employee.name':'Bob','employee.salary':10000, 'employee.active':true, "
|
||||||
|
+ "'employee':{'id':10, 'name': 'Bob Willis', 'address':'London'}}";
|
||||||
|
|
||||||
|
Type type = new TypeToken<HashMap<String, Object>>(){}.getType();
|
||||||
|
Gson gson = new GsonBuilder()
|
||||||
|
.registerTypeAdapter(type, new HashMapDeserializer())
|
||||||
|
.create();
|
||||||
|
HashMap<String, Object> blendedMap = gson.fromJson(jsonString, type);
|
||||||
|
|
||||||
|
logger.info("The converted map: {}", blendedMap);
|
||||||
|
Assert.assertEquals(4, blendedMap.size());
|
||||||
|
Assert.assertEquals(Integer.class, blendedMap.get("employee.salary").getClass());
|
||||||
|
Assert.assertEquals(Employee.class, blendedMap.get("employee").getClass());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,19 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||||
|
</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<logger name="org.springframework" level="WARN"/>
|
||||||
|
<logger name="org.springframework.transaction" level="WARN"/>
|
||||||
|
|
||||||
|
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
||||||
|
<logger name="org.springframework.web.servlet.mvc" level="WARN"/>
|
||||||
|
|
||||||
|
<root level="INFO">
|
||||||
|
<appender-ref ref="STDOUT"/>
|
||||||
|
</root>
|
||||||
|
</configuration>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue