Merge branch 'master' into thombergs-patch-27
This commit is contained in:
commit
0550bb1c77
|
@ -1,13 +1,9 @@
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<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/maven-v4_0_0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
<groupId>com.mabsisa</groupId>
|
|
||||||
<artifactId>Twitter4J</artifactId>
|
<artifactId>Twitter4J</artifactId>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
<version>1.0-SNAPSHOT</version>
|
|
||||||
<name>Twitter4J</name>
|
<name>Twitter4J</name>
|
||||||
<url>http://maven.apache.org</url>
|
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
|
@ -23,27 +19,6 @@
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
|
||||||
<finalName>${project.artifactId}</finalName>
|
|
||||||
<resources>
|
|
||||||
<resource>
|
|
||||||
<directory>src/main/resources</directory>
|
|
||||||
</resource>
|
|
||||||
</resources>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
|
||||||
<version>${maven-surefire-plugin.version}</version>
|
|
||||||
<configuration>
|
|
||||||
<excludes>
|
|
||||||
<exclude>**/ApplicationTest.java</exclude>
|
|
||||||
</excludes>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<twitter4j-stream.version>4.0.6</twitter4j-stream.version>
|
<twitter4j-stream.version>4.0.6</twitter4j-stream.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
|
@ -1,7 +1,6 @@
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<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">
|
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>
|
|
||||||
<artifactId>activejdbc</artifactId>
|
<artifactId>activejdbc</artifactId>
|
||||||
<version>1.0-SNAPSHOT</version>
|
<version>1.0-SNAPSHOT</version>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
@ -79,55 +78,11 @@
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
|
||||||
<version>${maven-surefire-plugin.version}</version>
|
|
||||||
<configuration>
|
|
||||||
<reportFormat>brief</reportFormat>
|
|
||||||
<trimStackTrace>true</trimStackTrace>
|
|
||||||
<useFile>false</useFile>
|
|
||||||
<includes>
|
|
||||||
<include>**/*Spec*.java</include>
|
|
||||||
<include>**/*Test*.java</include>
|
|
||||||
</includes>
|
|
||||||
<excludes>
|
|
||||||
<exclude>**/helpers/*</exclude>
|
|
||||||
<exclude>**/*$*</exclude>
|
|
||||||
</excludes>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<repositories>
|
|
||||||
<repository>
|
|
||||||
<id>snapshots1</id>
|
|
||||||
<name>JavaLite Snapshots1</name>
|
|
||||||
<url>http://repo.javalite.io/</url>
|
|
||||||
<snapshots>
|
|
||||||
<enabled>true</enabled>
|
|
||||||
<updatePolicy>always</updatePolicy>
|
|
||||||
<checksumPolicy>warn</checksumPolicy>
|
|
||||||
</snapshots>
|
|
||||||
</repository>
|
|
||||||
</repositories>
|
|
||||||
|
|
||||||
<pluginRepositories>
|
|
||||||
<pluginRepository>
|
|
||||||
<id>snapshots2</id>
|
|
||||||
<name>JavaLite Snapshots2</name>
|
|
||||||
<url>http://repo.javalite.io/</url>
|
|
||||||
<snapshots>
|
|
||||||
<enabled>true</enabled>
|
|
||||||
<updatePolicy>always</updatePolicy>
|
|
||||||
<checksumPolicy>warn</checksumPolicy>
|
|
||||||
</snapshots>
|
|
||||||
</pluginRepository>
|
|
||||||
</pluginRepositories>
|
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<activejdbc.version>1.4.13</activejdbc.version>
|
<activejdbc.version>2.0</activejdbc.version>
|
||||||
<environments>development.test,development</environments>
|
<environments>development.test,development</environments>
|
||||||
<mysql.connector.version>5.1.34</mysql.connector.version>
|
<mysql.connector.version>5.1.34</mysql.connector.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
|
@ -16,4 +16,8 @@ public class Employee extends Model {
|
||||||
set("created_by",createdBy);
|
set("created_by",createdBy);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getLastName() {
|
||||||
|
return getString("last_name");
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -15,4 +15,8 @@ public class Role extends Model {
|
||||||
set("role_name",role);
|
set("role_name",role);
|
||||||
set("created_by",createdBy);
|
set("created_by",createdBy);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getRoleName() {
|
||||||
|
return getString("role_name");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,7 +7,7 @@ import org.junit.Test;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public class ActiveJDBCAppTest extends DBSpec
|
public class ActiveJDBCAppManualTest extends DBSpec
|
||||||
{
|
{
|
||||||
@Test
|
@Test
|
||||||
public void ifEmployeeCreated_thenIsValid() {
|
public void ifEmployeeCreated_thenIsValid() {
|
|
@ -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)
|
||||||
|
|
|
@ -0,0 +1 @@
|
||||||
|
/bin/
|
|
@ -0,0 +1,20 @@
|
||||||
|
package com.java.src;
|
||||||
|
|
||||||
|
import java.util.Scanner;
|
||||||
|
|
||||||
|
public class RoundUpToHundred {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
Scanner scanner = new Scanner(System.in);
|
||||||
|
double input = scanner.nextDouble();
|
||||||
|
scanner.close();
|
||||||
|
|
||||||
|
RoundUpToHundred.round(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
static long round(double input) {
|
||||||
|
long i = (long) Math.ceil(input);
|
||||||
|
return ((i + 99) / 100) * 100;
|
||||||
|
};
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,14 @@
|
||||||
|
package com.java.src;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class RoundUpToHundredTest {
|
||||||
|
@Test
|
||||||
|
public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
|
||||||
|
assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
|
||||||
|
assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2));
|
||||||
|
assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400));
|
||||||
|
}
|
||||||
|
}
|
|
@ -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());
|
||||||
|
}
|
||||||
|
}
|
|
@ -3,7 +3,6 @@
|
||||||
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>
|
|
||||||
<artifactId>apache-shiro</artifactId>
|
<artifactId>apache-shiro</artifactId>
|
||||||
<version>1.0-SNAPSHOT</version>
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
|
||||||
|
@ -36,13 +35,11 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>jcl-over-slf4j</artifactId>
|
<artifactId>jcl-over-slf4j</artifactId>
|
||||||
<version>${slf4j-version}</version>
|
|
||||||
<scope>runtime</scope>
|
<scope>runtime</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>slf4j-log4j12</artifactId>
|
<artifactId>slf4j-log4j12</artifactId>
|
||||||
<version>${slf4j-version}</version>
|
|
||||||
<scope>runtime</scope>
|
<scope>runtime</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
|
@ -53,26 +50,9 @@
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
|
||||||
<version>${maven-compiler-plugin.version}</version>
|
|
||||||
<configuration>
|
|
||||||
<source>${java.version}</source>
|
|
||||||
<target>${java.version}</target>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<apache-shiro-core-version>1.4.0</apache-shiro-core-version>
|
<apache-shiro-core-version>1.4.0</apache-shiro-core-version>
|
||||||
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
|
||||||
<java.version>1.8</java.version>
|
|
||||||
<log4j-version>1.2.17</log4j-version>
|
<log4j-version>1.2.17</log4j-version>
|
||||||
<slf4j-version>1.7.25</slf4j-version>
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -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() {
|
|
@ -42,14 +42,6 @@
|
||||||
</archive>
|
</archive>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
|
||||||
<version>${maven-surefire-plugin.version}</version>
|
|
||||||
<configuration>
|
|
||||||
<argLine>-javaagent:"C:\asm-1.0.jar"</argLine>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
|
|
@ -2,12 +2,10 @@
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<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">
|
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>
|
|
||||||
<artifactId>cas-secured-app</artifactId>
|
<artifactId>cas-secured-app</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
<name>cas-secured-app</name>
|
<name>cas-secured-app</name>
|
||||||
<description>Demo project for Spring Boot</description>
|
<description>Demo project for CAS</description>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<artifactId>parent-boot-1</artifactId>
|
<artifactId>parent-boot-1</artifactId>
|
||||||
|
@ -60,10 +58,4 @@
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
|
||||||
<java.version>1.8</java.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -2,11 +2,17 @@
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<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 ">
|
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>
|
|
||||||
<artifactId>cas-server</artifactId>
|
<artifactId>cas-server</artifactId>
|
||||||
<packaging>war</packaging>
|
<packaging>war</packaging>
|
||||||
<version>1.0</version>
|
<version>1.0</version>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<artifactId>parent-boot-1</artifactId>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../../parent-boot-1</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apereo.cas</groupId>
|
<groupId>org.apereo.cas</groupId>
|
||||||
|
@ -39,7 +45,6 @@
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
<version>${springboot.version}</version>
|
|
||||||
<configuration>
|
<configuration>
|
||||||
<mainClass>${mainClassName}</mainClass>
|
<mainClass>${mainClassName}</mainClass>
|
||||||
<addResources>true</addResources>
|
<addResources>true</addResources>
|
||||||
|
@ -74,42 +79,10 @@
|
||||||
</overlays>
|
</overlays>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
|
||||||
<version>${maven-compiler-plugin.version}</version>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
</plugins>
|
||||||
<finalName>cas</finalName>
|
<finalName>cas</finalName>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<repositories>
|
|
||||||
<repository>
|
|
||||||
<id>sonatype-releases</id>
|
|
||||||
<url>http://oss.sonatype.org/content/repositories/releases/</url>
|
|
||||||
<snapshots>
|
|
||||||
<enabled>false</enabled>
|
|
||||||
</snapshots>
|
|
||||||
<releases>
|
|
||||||
<enabled>true</enabled>
|
|
||||||
</releases>
|
|
||||||
</repository>
|
|
||||||
<repository>
|
|
||||||
<id>sonatype-snapshots</id>
|
|
||||||
<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
|
|
||||||
<snapshots>
|
|
||||||
<enabled>true</enabled>
|
|
||||||
</snapshots>
|
|
||||||
<releases>
|
|
||||||
<enabled>false</enabled>
|
|
||||||
</releases>
|
|
||||||
</repository>
|
|
||||||
<repository>
|
|
||||||
<id>shibboleth-releases</id>
|
|
||||||
<url>https://build.shibboleth.net/nexus/content/repositories/releases</url>
|
|
||||||
</repository>
|
|
||||||
</repositories>
|
|
||||||
|
|
||||||
<profiles>
|
<profiles>
|
||||||
<profile>
|
<profile>
|
||||||
<activation>
|
<activation>
|
||||||
|
@ -214,8 +187,7 @@
|
||||||
</profiles>
|
</profiles>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<cas.version>5.3.0-SNAPSHOT</cas.version>
|
<cas.version>5.3.3</cas.version>
|
||||||
<springboot.version>1.5.13.RELEASE</springboot.version>
|
|
||||||
<!-- app.server could be -jetty, -undertow, -tomcat, or blank if you plan to provide appserver -->
|
<!-- app.server could be -jetty, -undertow, -tomcat, or blank if you plan to provide appserver -->
|
||||||
<app.server>-tomcat</app.server>
|
<app.server>-tomcat</app.server>
|
||||||
|
|
||||||
|
@ -223,12 +195,10 @@
|
||||||
<isExecutable>false</isExecutable>
|
<isExecutable>false</isExecutable>
|
||||||
<manifestFileToUse>${project.build.directory}/war/work/org.apereo.cas/cas-server-webapp${app.server}/META-INF/MANIFEST.MF</manifestFileToUse>
|
<manifestFileToUse>${project.build.directory}/war/work/org.apereo.cas/cas-server-webapp${app.server}/META-INF/MANIFEST.MF</manifestFileToUse>
|
||||||
|
|
||||||
<maven.compiler.source>1.8</maven.compiler.source>
|
|
||||||
<maven.compiler.target>1.8</maven.compiler.target>
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
<wrapper-maven-plugin.version>0.0.4</wrapper-maven-plugin.version>
|
<wrapper-maven-plugin.version>0.0.4</wrapper-maven-plugin.version>
|
||||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||||
<maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>
|
||||||
|
|
||||||
<echo-maven-plugin.version>0.3.0</echo-maven-plugin.version>
|
<echo-maven-plugin.version>0.3.0</echo-maven-plugin.version>
|
||||||
<pgpverify-maven-plugin.version>1.1.0</pgpverify-maven-plugin.version>
|
<pgpverify-maven-plugin.version>1.1.0</pgpverify-maven-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
|
@ -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>
|
|
@ -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,12 @@
|
||||||
<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>
|
||||||
|
|
||||||
</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,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,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)
|
||||||
|
|
|
@ -1,7 +1,6 @@
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<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">
|
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>
|
|
||||||
<artifactId>core-java-io</artifactId>
|
<artifactId>core-java-io</artifactId>
|
||||||
<version>0.1.0-SNAPSHOT</version>
|
<version>0.1.0-SNAPSHOT</version>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
@ -166,36 +165,6 @@
|
||||||
</resource>
|
</resource>
|
||||||
</resources>
|
</resources>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
|
||||||
<configuration>
|
|
||||||
<excludes>
|
|
||||||
<exclude>**/*LiveTest.java</exclude>
|
|
||||||
<exclude>**/*IntegrationTest.java</exclude>
|
|
||||||
<exclude>**/*IntTest.java</exclude>
|
|
||||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
|
||||||
<exclude>**/*ManualTest.java</exclude>
|
|
||||||
</excludes>
|
|
||||||
<testFailureIgnore>true</testFailureIgnore>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
|
||||||
<version>${spring-boot-maven-plugin.version}</version>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<goals>
|
|
||||||
<goal>repackage</goal>
|
|
||||||
</goals>
|
|
||||||
<configuration>
|
|
||||||
<classifier>spring-boot</classifier>
|
|
||||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
|
||||||
</configuration>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.codehaus.mojo</groupId>
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
<artifactId>exec-maven-plugin</artifactId>
|
<artifactId>exec-maven-plugin</artifactId>
|
||||||
|
@ -229,32 +198,6 @@
|
||||||
<id>integration</id>
|
<id>integration</id>
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<phase>integration-test</phase>
|
|
||||||
<goals>
|
|
||||||
<goal>test</goal>
|
|
||||||
</goals>
|
|
||||||
<configuration>
|
|
||||||
<excludes>
|
|
||||||
<exclude>**/*ManualTest.java</exclude>
|
|
||||||
</excludes>
|
|
||||||
<includes>
|
|
||||||
<include>**/*IntegrationTest.java</include>
|
|
||||||
<include>**/*IntTest.java</include>
|
|
||||||
</includes>
|
|
||||||
</configuration>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
<configuration>
|
|
||||||
<systemPropertyVariables>
|
|
||||||
<test.mime>json</test.mime>
|
|
||||||
</systemPropertyVariables>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.codehaus.mojo</groupId>
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
<artifactId>exec-maven-plugin</artifactId>
|
<artifactId>exec-maven-plugin</artifactId>
|
||||||
|
@ -310,14 +253,11 @@
|
||||||
<avaitility.version>1.7.0</avaitility.version>
|
<avaitility.version>1.7.0</avaitility.version>
|
||||||
|
|
||||||
<!-- maven plugins -->
|
<!-- maven plugins -->
|
||||||
<maven.compiler.source>1.8</maven.compiler.source>
|
|
||||||
<maven.compiler.target>1.8</maven.compiler.target>
|
|
||||||
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
|
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
|
||||||
<hsqldb.version>2.4.0</hsqldb.version>
|
<hsqldb.version>2.4.0</hsqldb.version>
|
||||||
<esapi.version>2.1.0.1</esapi.version>
|
<esapi.version>2.1.0.1</esapi.version>
|
||||||
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
|
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
|
||||||
<async-http-client.version>2.4.5</async-http-client.version>
|
<async-http-client.version>2.4.5</async-http-client.version>
|
||||||
<spring-boot-maven-plugin.version>2.0.4.RELEASE</spring-boot-maven-plugin.version>
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -24,6 +24,13 @@ public class ZipDirectory {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (fileToZip.isDirectory()) {
|
if (fileToZip.isDirectory()) {
|
||||||
|
if (fileName.endsWith("/")) {
|
||||||
|
zipOut.putNextEntry(new ZipEntry(fileName));
|
||||||
|
zipOut.closeEntry();
|
||||||
|
} else {
|
||||||
|
zipOut.putNextEntry(new ZipEntry(fileName + "/"));
|
||||||
|
zipOut.closeEntry();
|
||||||
|
}
|
||||||
final File[] children = fileToZip.listFiles();
|
final File[] children = fileToZip.listFiles();
|
||||||
for (final File childFile : children) {
|
for (final File childFile : children) {
|
||||||
zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
|
zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
package com.baeldung.file;
|
package com.baeldung.file;
|
||||||
|
|
||||||
import org.apache.commons.io.FileUtils;
|
import org.apache.commons.io.FileUtils;
|
||||||
|
import org.apache.commons.io.IOUtils;
|
||||||
import org.hamcrest.CoreMatchers;
|
import org.hamcrest.CoreMatchers;
|
||||||
import org.hamcrest.Matchers;
|
import org.hamcrest.Matchers;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
@ -17,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;
|
||||||
|
@ -49,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");
|
||||||
|
@ -78,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());
|
||||||
}
|
}
|
||||||
|
@ -101,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 {
|
||||||
|
@ -120,4 +121,14 @@ public class FileOperationsManualTest {
|
||||||
|
|
||||||
return resultStringBuilder.toString();
|
return resultStringBuilder.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFileName_whenUsingIOUtils_thenFileData() throws IOException {
|
||||||
|
String expectedData = "This is a content of the file";
|
||||||
|
|
||||||
|
FileInputStream fis = new FileInputStream("src/test/resources/fileToRead.txt");
|
||||||
|
String data = IOUtils.toString(fis, "UTF-8");
|
||||||
|
|
||||||
|
assertEquals(expectedData, data.trim());
|
||||||
|
}
|
||||||
}
|
}
|
|
@ -9,7 +9,7 @@ import java.nio.file.Paths;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class SymLinkExampleUnitTest {
|
public class SymLinkExampleManualTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingFiles_thenCreateSymbolicLink() throws IOException {
|
public void whenUsingFiles_thenCreateSymbolicLink() throws IOException {
|
|
@ -0,0 +1 @@
|
||||||
|
Hello World from fileTest.txt!!!
|
|
@ -151,3 +151,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,40 @@
|
||||||
|
package com.baeldung.doubles;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
|
public class SplitFloatingPointNumbers {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
double doubleNumber = 24.04;
|
||||||
|
splitUsingFloatingTypes(doubleNumber);
|
||||||
|
splitUsingString(doubleNumber);
|
||||||
|
splitUsingBigDecimal(doubleNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void splitUsingFloatingTypes(double doubleNumber) {
|
||||||
|
System.out.println("Using Floating Point Arithmetics:");
|
||||||
|
int intPart = (int) doubleNumber;
|
||||||
|
System.out.println("Double Number: "+doubleNumber);
|
||||||
|
System.out.println("Integer Part: "+ intPart);
|
||||||
|
System.out.println("Decimal Part: "+ (doubleNumber - intPart));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void splitUsingString(double doubleNumber) {
|
||||||
|
System.out.println("Using String Operations:");
|
||||||
|
String doubleAsString = String.valueOf(doubleNumber);
|
||||||
|
int indexOfDecimal = doubleAsString.indexOf(".");
|
||||||
|
System.out.println("Double Number: "+doubleNumber);
|
||||||
|
System.out.println("Integer Part: "+ doubleAsString.substring(0, indexOfDecimal));
|
||||||
|
System.out.println("Decimal Part: "+ doubleAsString.substring(indexOfDecimal));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void splitUsingBigDecimal(double doubleNumber) {
|
||||||
|
System.out.println("Using BigDecimal Operations:");
|
||||||
|
BigDecimal bigDecimal = new BigDecimal(String.valueOf(doubleNumber));
|
||||||
|
int intValue = bigDecimal.intValue();
|
||||||
|
System.out.println("Double Number: "+bigDecimal.toPlainString());
|
||||||
|
System.out.println("Integer Part: "+intValue);
|
||||||
|
System.out.println("Decimal Part: "+bigDecimal.subtract(new BigDecimal(intValue)).toPlainString());
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,25 @@
|
||||||
|
package com.baeldung.heapdump;
|
||||||
|
|
||||||
|
import com.sun.management.HotSpotDiagnosticMXBean;
|
||||||
|
|
||||||
|
import javax.management.MBeanServer;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.lang.management.ManagementFactory;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
|
||||||
|
public class HeapDump {
|
||||||
|
|
||||||
|
public static void dumpHeap(String filePath, boolean live) throws IOException {
|
||||||
|
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
|
||||||
|
HotSpotDiagnosticMXBean mxBean = ManagementFactory.newPlatformMXBeanProxy(
|
||||||
|
server, "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class);
|
||||||
|
mxBean.dumpHeap(filePath, live);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws IOException {
|
||||||
|
String file = Paths.get("dump.hprof").toFile().getPath();
|
||||||
|
|
||||||
|
dumpHeap(file, true);
|
||||||
|
}
|
||||||
|
}
|
|
@ -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,149 @@
|
||||||
|
package com.baeldung.passwordhashing;
|
||||||
|
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
import java.security.spec.InvalidKeySpecException;
|
||||||
|
import java.security.spec.KeySpec;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import javax.crypto.SecretKeyFactory;
|
||||||
|
import javax.crypto.spec.PBEKeySpec;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hash passwords for storage, and test passwords against password tokens.
|
||||||
|
*
|
||||||
|
* Instances of this class can be used concurrently by multiple threads.
|
||||||
|
*
|
||||||
|
* @author erickson
|
||||||
|
* @see <a href="http://stackoverflow.com/a/2861125/3474">StackOverflow</a>
|
||||||
|
*/
|
||||||
|
public final class PBKDF2Hasher
|
||||||
|
{
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Each token produced by this class uses this identifier as a prefix.
|
||||||
|
*/
|
||||||
|
public static final String ID = "$31$";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The minimum recommended cost, used by default
|
||||||
|
*/
|
||||||
|
public static final int DEFAULT_COST = 16;
|
||||||
|
|
||||||
|
private static final String ALGORITHM = "PBKDF2WithHmacSHA1";
|
||||||
|
|
||||||
|
private static final int SIZE = 128;
|
||||||
|
|
||||||
|
private static final Pattern layout = Pattern.compile("\\$31\\$(\\d\\d?)\\$(.{43})");
|
||||||
|
|
||||||
|
private final SecureRandom random;
|
||||||
|
|
||||||
|
private final int cost;
|
||||||
|
|
||||||
|
public PBKDF2Hasher()
|
||||||
|
{
|
||||||
|
this(DEFAULT_COST);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a password manager with a specified cost
|
||||||
|
*
|
||||||
|
* @param cost the exponential computational cost of hashing a password, 0 to 30
|
||||||
|
*/
|
||||||
|
public PBKDF2Hasher(int cost)
|
||||||
|
{
|
||||||
|
iterations(cost); /* Validate cost */
|
||||||
|
this.cost = cost;
|
||||||
|
this.random = new SecureRandom();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int iterations(int cost)
|
||||||
|
{
|
||||||
|
if ((cost < 0) || (cost > 30))
|
||||||
|
throw new IllegalArgumentException("cost: " + cost);
|
||||||
|
return 1 << cost;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hash a password for storage.
|
||||||
|
*
|
||||||
|
* @return a secure authentication token to be stored for later authentication
|
||||||
|
*/
|
||||||
|
public String hash(char[] password)
|
||||||
|
{
|
||||||
|
byte[] salt = new byte[SIZE / 8];
|
||||||
|
random.nextBytes(salt);
|
||||||
|
byte[] dk = pbkdf2(password, salt, 1 << cost);
|
||||||
|
byte[] hash = new byte[salt.length + dk.length];
|
||||||
|
System.arraycopy(salt, 0, hash, 0, salt.length);
|
||||||
|
System.arraycopy(dk, 0, hash, salt.length, dk.length);
|
||||||
|
Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding();
|
||||||
|
return ID + cost + '$' + enc.encodeToString(hash);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authenticate with a password and a stored password token.
|
||||||
|
*
|
||||||
|
* @return true if the password and token match
|
||||||
|
*/
|
||||||
|
public boolean checkPassword(char[] password, String token)
|
||||||
|
{
|
||||||
|
Matcher m = layout.matcher(token);
|
||||||
|
if (!m.matches())
|
||||||
|
throw new IllegalArgumentException("Invalid token format");
|
||||||
|
int iterations = iterations(Integer.parseInt(m.group(1)));
|
||||||
|
byte[] hash = Base64.getUrlDecoder().decode(m.group(2));
|
||||||
|
byte[] salt = Arrays.copyOfRange(hash, 0, SIZE / 8);
|
||||||
|
byte[] check = pbkdf2(password, salt, iterations);
|
||||||
|
int zero = 0;
|
||||||
|
for (int idx = 0; idx < check.length; ++idx)
|
||||||
|
zero |= hash[salt.length + idx] ^ check[idx];
|
||||||
|
return zero == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] pbkdf2(char[] password, byte[] salt, int iterations)
|
||||||
|
{
|
||||||
|
KeySpec spec = new PBEKeySpec(password, salt, iterations, SIZE);
|
||||||
|
try {
|
||||||
|
SecretKeyFactory f = SecretKeyFactory.getInstance(ALGORITHM);
|
||||||
|
return f.generateSecret(spec).getEncoded();
|
||||||
|
}
|
||||||
|
catch (NoSuchAlgorithmException ex) {
|
||||||
|
throw new IllegalStateException("Missing algorithm: " + ALGORITHM, ex);
|
||||||
|
}
|
||||||
|
catch (InvalidKeySpecException ex) {
|
||||||
|
throw new IllegalStateException("Invalid SecretKeyFactory", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hash a password in an immutable {@code String}.
|
||||||
|
*
|
||||||
|
* <p>Passwords should be stored in a {@code char[]} so that it can be filled
|
||||||
|
* with zeros after use instead of lingering on the heap and elsewhere.
|
||||||
|
*
|
||||||
|
* @deprecated Use {@link #hash(char[])} instead
|
||||||
|
*/
|
||||||
|
@Deprecated
|
||||||
|
public String hash(String password)
|
||||||
|
{
|
||||||
|
return hash(password.toCharArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authenticate with a password in an immutable {@code String} and a stored
|
||||||
|
* password token.
|
||||||
|
*
|
||||||
|
* @deprecated Use {@link #checkPassword(char[],String)} instead.
|
||||||
|
* @see #hash(String)
|
||||||
|
*/
|
||||||
|
@Deprecated
|
||||||
|
public boolean checkPassword(String password, String token)
|
||||||
|
{
|
||||||
|
return checkPassword(password.toCharArray(), token);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,35 @@
|
||||||
|
package com.baeldung.passwordhashing;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
|
||||||
|
|
||||||
|
/** A really simple SHA_512 Encryption example.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public class SHA512Hasher {
|
||||||
|
|
||||||
|
public String hash(String passwordToHash, byte[] salt){
|
||||||
|
String generatedPassword = null;
|
||||||
|
try {
|
||||||
|
MessageDigest md = MessageDigest.getInstance("SHA-512");
|
||||||
|
md.update(salt);
|
||||||
|
byte[] bytes = md.digest(passwordToHash.getBytes(StandardCharsets.UTF_8));
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
for(int i=0; i< bytes.length ;i++){
|
||||||
|
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
|
||||||
|
}
|
||||||
|
generatedPassword = sb.toString();
|
||||||
|
}
|
||||||
|
catch (NoSuchAlgorithmException e){
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return generatedPassword;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean checkPassword(String hash, String attempt, byte[] salt){
|
||||||
|
String generatedHash = hash(attempt, salt);
|
||||||
|
return hash.equals(generatedHash);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,18 @@
|
||||||
|
package com.baeldung.passwordhashing;
|
||||||
|
|
||||||
|
import javax.crypto.SecretKeyFactory;
|
||||||
|
import javax.crypto.spec.PBEKeySpec;
|
||||||
|
import java.security.spec.KeySpec;
|
||||||
|
|
||||||
|
/** A really simple SimplePBKDF2 Encryption example.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public class SimplePBKDF2Hasher {
|
||||||
|
|
||||||
|
public static String hashSimple(String password, byte[] salt) throws Exception{
|
||||||
|
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128);
|
||||||
|
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
|
||||||
|
byte[] hash = f.generateSecret(spec).getEncoded();
|
||||||
|
return String.valueOf(hash);
|
||||||
|
}
|
||||||
|
}
|
|
@ -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,13 @@
|
||||||
|
package com.baeldung.zoneddatetime;
|
||||||
|
|
||||||
|
import java.time.OffsetDateTime;
|
||||||
|
import java.time.ZoneOffset;
|
||||||
|
|
||||||
|
public class OffsetDateTimeExample {
|
||||||
|
|
||||||
|
public OffsetDateTime getCurrentTimeByZoneOffset(String offset) {
|
||||||
|
ZoneOffset zoneOffSet= ZoneOffset.of(offset);
|
||||||
|
OffsetDateTime date = OffsetDateTime.now(zoneOffSet);
|
||||||
|
return date;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,13 @@
|
||||||
|
package com.baeldung.zoneddatetime;
|
||||||
|
|
||||||
|
import java.time.OffsetTime;
|
||||||
|
import java.time.ZoneOffset;
|
||||||
|
|
||||||
|
public class OffsetTimeExample {
|
||||||
|
|
||||||
|
public OffsetTime getCurrentTimeByZoneOffset(String offset) {
|
||||||
|
ZoneOffset zoneOffSet = ZoneOffset.of(offset);
|
||||||
|
OffsetTime time = OffsetTime.now(zoneOffSet);
|
||||||
|
return time;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
package com.baeldung.zoneddatetime;
|
||||||
|
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.time.ZonedDateTime;
|
||||||
|
|
||||||
|
public class ZoneDateTimeExample {
|
||||||
|
|
||||||
|
public ZonedDateTime getCurrentTimeByZoneId(String region) {
|
||||||
|
ZoneId zone = ZoneId.of(region);
|
||||||
|
ZonedDateTime date = ZonedDateTime.now(zone);
|
||||||
|
return date;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ZonedDateTime convertZonedDateTime(ZonedDateTime sourceDate, String destZone) {
|
||||||
|
|
||||||
|
ZoneId destZoneId = ZoneId.of(destZone);
|
||||||
|
ZonedDateTime destDate = sourceDate.withZoneSameInstant(destZoneId);
|
||||||
|
|
||||||
|
return destDate;
|
||||||
|
}
|
||||||
|
}
|
|
@ -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,41 @@
|
||||||
|
package com.baeldung.passwordhashing;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
|
||||||
|
public class PBKDF2HasherUnitTest {
|
||||||
|
|
||||||
|
private PBKDF2Hasher mPBKDF2Hasher;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() throws Exception {
|
||||||
|
mPBKDF2Hasher = new PBKDF2Hasher();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCorrectMessageAndHash_whenAuthenticated_checkAuthenticationSucceeds() throws Exception {
|
||||||
|
String message1 = "password123";
|
||||||
|
|
||||||
|
String hash1 = mPBKDF2Hasher.hash(message1.toCharArray());
|
||||||
|
|
||||||
|
assertTrue(mPBKDF2Hasher.checkPassword(message1.toCharArray(), hash1));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenWrongMessage_whenAuthenticated_checkAuthenticationFails() throws Exception {
|
||||||
|
String message1 = "password123";
|
||||||
|
|
||||||
|
String hash1 = mPBKDF2Hasher.hash(message1.toCharArray());
|
||||||
|
|
||||||
|
String wrongPasswordAttempt = "IamWrong";
|
||||||
|
|
||||||
|
assertFalse(mPBKDF2Hasher.checkPassword(wrongPasswordAttempt.toCharArray(), hash1));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,70 @@
|
||||||
|
package com.baeldung.passwordhashing;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Created by PhysicsSam on 06-Sep-18.
|
||||||
|
*/
|
||||||
|
public class SHA512HasherUnitTest {
|
||||||
|
|
||||||
|
private SHA512Hasher hasher;
|
||||||
|
private SecureRandom secureRandom;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() throws Exception {
|
||||||
|
hasher = new SHA512Hasher();
|
||||||
|
secureRandom = new SecureRandom();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSamePasswordAndSalt_whenHashed_checkResultingHashesAreEqual() throws Exception {
|
||||||
|
|
||||||
|
byte[] salt = new byte[16];
|
||||||
|
secureRandom.nextBytes(salt);
|
||||||
|
|
||||||
|
String hash1 = hasher.hash("password", salt);
|
||||||
|
String hash2 = hasher.hash("password", salt);
|
||||||
|
|
||||||
|
assertEquals(hash1, hash2);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSamePasswordAndDifferentSalt_whenHashed_checkResultingHashesNotEqual() throws Exception {
|
||||||
|
|
||||||
|
byte[] salt = new byte[16];
|
||||||
|
secureRandom.nextBytes(salt);
|
||||||
|
String hash1 = hasher.hash("password", salt);
|
||||||
|
//generate a second salt
|
||||||
|
byte[] secondSalt = new byte[16];
|
||||||
|
String hash2 = hasher.hash("password", secondSalt);
|
||||||
|
|
||||||
|
assertNotEquals(hash1, hash2);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPredefinedHash_whenCorrectAttemptGiven_checkAuthenticationSucceeds() throws Exception {
|
||||||
|
byte[] salt = new byte[16];
|
||||||
|
secureRandom.nextBytes(salt);
|
||||||
|
|
||||||
|
String originalHash = hasher.hash("password123", salt);
|
||||||
|
|
||||||
|
assertTrue(hasher.checkPassword(originalHash, "password123", salt));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPredefinedHash_whenIncorrectAttemptGiven_checkAuthenticationFails() throws Exception {
|
||||||
|
byte[] salt = new byte[16];
|
||||||
|
secureRandom.nextBytes(salt);
|
||||||
|
|
||||||
|
String originalHash = hasher.hash("password123", salt);
|
||||||
|
|
||||||
|
assertFalse(hasher.checkPassword(originalHash, "password124", salt));
|
||||||
|
}
|
||||||
|
}
|
|
@ -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");
|
||||||
|
}
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue