commit
46c7340991
|
@ -3,10 +3,11 @@
|
|||
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>JGitSnippets</artifactId>
|
||||
<artifactId>JGit</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
<name>JGit</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
|
33
README.md
33
README.md
|
@ -2,41 +2,22 @@
|
|||
The "REST with Spring" Classes
|
||||
==============================
|
||||
|
||||
Here's the Master Class of REST With Spring (price changes permanently next Friday): <br/>
|
||||
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
||||
Here's the Master Class of REST With Spring (along with the newly announced Boot 2 material): <br/>
|
||||
**[>> THE REST WITH SPRING - MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
||||
|
||||
And here's the Master Class of Learn Spring Security: <br/>
|
||||
**[>> LEARN SPRING SECURITY MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
|
||||
**[>> LEARN SPRING SECURITY - MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
|
||||
|
||||
|
||||
|
||||
Spring Tutorials
|
||||
Java and Spring Tutorials
|
||||
================
|
||||
|
||||
This project is **a collection of small and focused tutorials** each covering a single and well defined area of development.
|
||||
Most of the tutorial projects are focused on the `Spring Framework` (and `Spring Security`).
|
||||
This project is **a collection of small and focused tutorials** - each covering a single and well defined area of development in the Java ecosystem.
|
||||
A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Securiyt.
|
||||
In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`.
|
||||
|
||||
|
||||
Building the project
|
||||
====================
|
||||
To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false`
|
||||
|
||||
|
||||
Working with the code in Eclipse
|
||||
================================
|
||||
Any IDE can be used to work with the projects, but if you're using Eclipse, consider the following.
|
||||
|
||||
- import the included **formatter** in Eclipse:
|
||||
`https://github.com/eugenp/tutorials/tree/master/eclipse`
|
||||
|
||||
|
||||
CI - Jenkins
|
||||
================================
|
||||
This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/tutorials-unit/)**
|
||||
|
||||
### Relevant Articles:
|
||||
================================
|
||||
|
||||
- [Apache Maven Standard Directory Layout](http://www.baeldung.com/maven-directory-structure)
|
||||
- [Apache Maven Tutorial](http://www.baeldung.com/maven)
|
||||
- [Designing a User Friendly Java Library](http://www.baeldung.com/design-a-user-friendly-java-library)
|
||||
|
|
|
@ -1,13 +1,9 @@
|
|||
<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">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.mabsisa</groupId>
|
||||
<artifactId>Twitter4J</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>Twitter4J</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
@ -23,27 +19,6 @@
|
|||
</dependency>
|
||||
</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>
|
||||
<twitter4j-stream.version>4.0.6</twitter4j-stream.version>
|
||||
</properties>
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
<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>activejdbc</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
@ -79,55 +78,11 @@
|
|||
</dependency>
|
||||
</dependencies>
|
||||
</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>
|
||||
</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>
|
||||
<activejdbc.version>1.4.13</activejdbc.version>
|
||||
<activejdbc.version>2.0</activejdbc.version>
|
||||
<environments>development.test,development</environments>
|
||||
<mysql.connector.version>5.1.34</mysql.connector.version>
|
||||
</properties>
|
||||
|
|
|
@ -16,4 +16,8 @@ public class Employee extends Model {
|
|||
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("created_by",createdBy);
|
||||
}
|
||||
|
||||
public String getRoleName() {
|
||||
return getString("role_name");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,7 +7,7 @@ import org.junit.Test;
|
|||
|
||||
import java.util.List;
|
||||
|
||||
public class ActiveJDBCAppTest extends DBSpec
|
||||
public class ActiveJDBCAppManualTest extends DBSpec
|
||||
{
|
||||
@Test
|
||||
public void ifEmployeeCreated_thenIsValid() {
|
|
@ -24,3 +24,7 @@
|
|||
- [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)
|
||||
- [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,38 @@
|
|||
package com.baeldung.algorithms.distancebetweenpoints;
|
||||
|
||||
import java.awt.geom.Point2D;
|
||||
|
||||
public class DistanceBetweenPointsService {
|
||||
|
||||
public double calculateDistanceBetweenPoints(
|
||||
double x1,
|
||||
double y1,
|
||||
double x2,
|
||||
double y2) {
|
||||
|
||||
return Math.sqrt((y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1));
|
||||
}
|
||||
|
||||
public double calculateDistanceBetweenPointsWithHypot(
|
||||
double x1,
|
||||
double y1,
|
||||
double x2,
|
||||
double y2) {
|
||||
|
||||
double ac = Math.abs(y2 - y1);
|
||||
double cb = Math.abs(x2 - x1);
|
||||
|
||||
return Math.hypot(ac, cb);
|
||||
}
|
||||
|
||||
public double calculateDistanceBetweenPointsWithPoint2D(
|
||||
double x1,
|
||||
double y1,
|
||||
double x2,
|
||||
double y2) {
|
||||
|
||||
return Point2D.distance(x1, y1, x2, y2);
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -98,7 +98,7 @@ public class FindKthLargest {
|
|||
|
||||
private int randomPartition(Integer arr[], int left, int right) {
|
||||
int n = right - left + 1;
|
||||
int pivot = (int) (Math.random()) % n;
|
||||
int pivot = (int) (Math.random() * n);
|
||||
swap(arr, left + pivot, right);
|
||||
return partition(arr, left, right);
|
||||
}
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.linesintersection;
|
||||
package com.baeldung.algorithms.linesintersection;
|
||||
|
||||
import java.awt.Point;
|
||||
import java.util.Optional;
|
|
@ -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,29 @@
|
|||
package com.baeldung.algorithms.rectanglesoverlap;
|
||||
|
||||
public class Point {
|
||||
|
||||
private int x;
|
||||
private int y;
|
||||
|
||||
public Point(int x, int y) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
public int getX() {
|
||||
return x;
|
||||
}
|
||||
|
||||
public void setX(int x) {
|
||||
this.x = x;
|
||||
}
|
||||
|
||||
public int getY() {
|
||||
return y;
|
||||
}
|
||||
|
||||
public void setY(int y) {
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
package com.baeldung.algorithms.rectanglesoverlap;
|
||||
|
||||
public class Rectangle {
|
||||
|
||||
private Point bottomLeft;
|
||||
private Point topRight;
|
||||
|
||||
public Rectangle(Point bottomLeft, Point topRight) {
|
||||
this.bottomLeft = bottomLeft;
|
||||
this.topRight = topRight;
|
||||
}
|
||||
|
||||
public Point getBottomLeft() {
|
||||
return bottomLeft;
|
||||
}
|
||||
|
||||
public void setBottomLeft(Point bottomLeft) {
|
||||
this.bottomLeft = bottomLeft;
|
||||
}
|
||||
|
||||
public Point getTopRight() {
|
||||
return topRight;
|
||||
}
|
||||
|
||||
public void setTopRight(Point topRight) {
|
||||
this.topRight = topRight;
|
||||
}
|
||||
|
||||
public boolean isOverlapping(Rectangle other) {
|
||||
// one rectangle is to the top of the other
|
||||
if (this.topRight.getY() < other.bottomLeft.getY() || this.bottomLeft.getY() > other.topRight.getY()) {
|
||||
return false;
|
||||
}
|
||||
// one rectangle is to the left of the other
|
||||
if (this.topRight.getX() < other.bottomLeft.getX() || this.bottomLeft.getX() > other.topRight.getX()) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
package com.baeldung.algorithms.distancebetweenpoints;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.algorithms.distancebetweenpoints.DistanceBetweenPointsService;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class DistanceBetweenPointsServiceUnitTest {
|
||||
|
||||
private DistanceBetweenPointsService service = new DistanceBetweenPointsService();
|
||||
|
||||
@Test
|
||||
public void givenTwoPoints_whenCalculateDistanceByFormula_thenCorrect() {
|
||||
|
||||
double x1 = 3;
|
||||
double y1 = 4;
|
||||
double x2 = 7;
|
||||
double y2 = 1;
|
||||
|
||||
double distance = service.calculateDistanceBetweenPoints(x1, y1, x2, y2);
|
||||
|
||||
assertEquals(distance, 5, 0.001);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoPoints_whenCalculateDistanceWithHypot_thenCorrect() {
|
||||
|
||||
double x1 = 3;
|
||||
double y1 = 4;
|
||||
double x2 = 7;
|
||||
double y2 = 1;
|
||||
|
||||
double distance = service.calculateDistanceBetweenPointsWithHypot(x1, y1, x2, y2);
|
||||
|
||||
assertEquals(distance, 5, 0.001);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoPoints_whenCalculateDistanceWithPoint2D_thenCorrect() {
|
||||
|
||||
double x1 = 3;
|
||||
double y1 = 4;
|
||||
double x2 = 7;
|
||||
double y2 = 1;
|
||||
|
||||
double distance = service.calculateDistanceBetweenPointsWithPoint2D(x1, y1, x2, y2);
|
||||
|
||||
assertEquals(distance, 5, 0.001);
|
||||
|
||||
}
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.linesintersection;
|
||||
package com.baeldung.algorithms.linesintersection;
|
||||
|
||||
import java.awt.Point;
|
||||
import java.util.Optional;
|
||||
|
@ -23,7 +23,7 @@ public class LinesIntersectionServiceUnitTest {
|
|||
|
||||
assertTrue(point.isPresent());
|
||||
assertEquals(point.get().getX(), 1, 0.001);
|
||||
assertEquals(point.get().getX(), 1, 0.001);
|
||||
assertEquals(point.get().getY(), 0, 0.001);
|
||||
}
|
||||
|
||||
@Test
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.algorithms.rectanglesoverlap;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.algorithms.rectanglesoverlap.Point;
|
||||
import com.baeldung.algorithms.rectanglesoverlap.Rectangle;
|
||||
|
||||
public class RectangleUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTwoOverlappingRectangles_whenisOverlappingCalled_shouldReturnTrue() {
|
||||
Rectangle rectangle1 = new Rectangle(new Point(2, 1), new Point(4, 3));
|
||||
Rectangle rectangle2 = new Rectangle(new Point(1, 1), new Point(6, 4));
|
||||
assertTrue(rectangle1.isOverlapping(rectangle2));
|
||||
|
||||
rectangle1 = new Rectangle(new Point(-5, -2), new Point(2, 3));
|
||||
rectangle2 = new Rectangle(new Point(-2, -1), new Point(5, 2));
|
||||
assertTrue(rectangle1.isOverlapping(rectangle2));
|
||||
|
||||
rectangle1 = new Rectangle(new Point(-5, 1), new Point(2, 4));
|
||||
rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, 5));
|
||||
assertTrue(rectangle1.isOverlapping(rectangle2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoNonOverlappingRectangles_whenisOverlappingCalled_shouldReturnFalse() {
|
||||
Rectangle rectangle1 = new Rectangle(new Point(-5, 1), new Point(-3, 4));
|
||||
Rectangle rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, 5));
|
||||
assertFalse(rectangle1.isOverlapping(rectangle2));
|
||||
|
||||
rectangle1 = new Rectangle(new Point(-5, 1), new Point(3, 4));
|
||||
rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, -1));
|
||||
assertFalse(rectangle1.isOverlapping(rectangle2));
|
||||
|
||||
rectangle1 = new Rectangle(new Point(-2, 1), new Point(0, 3));
|
||||
rectangle2 = new Rectangle(new Point(3, 1), new Point(5, 4));
|
||||
assertFalse(rectangle1.isOverlapping(rectangle2));
|
||||
}
|
||||
|
||||
}
|
|
@ -7,7 +7,7 @@ import junit.framework.TestSuite;
|
|||
/**
|
||||
* Unit test for simple App.
|
||||
*/
|
||||
public class AppTest
|
||||
public class AppUnitTest
|
||||
extends TestCase
|
||||
{
|
||||
/**
|
||||
|
@ -15,7 +15,7 @@ public class AppTest
|
|||
*
|
||||
* @param testName name of the test case
|
||||
*/
|
||||
public AppTest( String testName )
|
||||
public AppUnitTest( String testName )
|
||||
{
|
||||
super( testName );
|
||||
}
|
||||
|
@ -25,7 +25,7 @@ public class AppTest
|
|||
*/
|
||||
public static Test suite()
|
||||
{
|
||||
return new TestSuite( AppTest.class );
|
||||
return new TestSuite( AppUnitTest.class );
|
||||
}
|
||||
|
||||
/**
|
|
@ -4,8 +4,9 @@
|
|||
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-avro-tutorial</artifactId>
|
||||
<artifactId>apache-avro</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>Apache Avro</name>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
|
|
|
@ -13,7 +13,7 @@ import java.util.Objects;
|
|||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class AvroSerealizerDeSerealizerTest {
|
||||
public class AvroSerealizerDeSerealizerUnitTest {
|
||||
|
||||
AvroSerealizer serealizer;
|
||||
AvroDeSerealizer deSerealizer;
|
|
@ -3,3 +3,4 @@
|
|||
- [Apache CXF Support for RESTful Web Services](http://www.baeldung.com/apache-cxf-rest-api)
|
||||
- [A Guide to Apache CXF with Spring](http://www.baeldung.com/apache-cxf-with-spring)
|
||||
- [Introduction to Apache CXF](http://www.baeldung.com/introduction-to-apache-cxf)
|
||||
- [Server-Sent Events (SSE) In JAX-RS](https://www.baeldung.com/java-ee-jax-rs-sse)
|
||||
|
|
|
@ -20,7 +20,7 @@
|
|||
</properties>
|
||||
|
||||
<build>
|
||||
<finalName>${artifactId}</finalName>
|
||||
<finalName>${project.artifactId}</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>net.wasdev.wlp.maven.plugins</groupId>
|
||||
|
|
|
@ -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"
|
||||
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-shiro</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
|
@ -36,13 +35,11 @@
|
|||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${slf4j-version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-log4j12</artifactId>
|
||||
<version>${slf4j-version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
@ -53,26 +50,9 @@
|
|||
</dependency>
|
||||
</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>
|
||||
<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>
|
||||
<slf4j-version>1.7.25</slf4j-version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -1,5 +1,4 @@
|
|||
### Relevant articles
|
||||
|
||||
- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor)
|
||||
- [Generating a Book with Asciidoctor](http://www.baeldung.com/asciidoctor-book)
|
||||
- [Introduction to Asciidoctor in Java](http://www.baeldung.com/asciidoctor)
|
||||
|
|
|
@ -61,9 +61,10 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<asciidoctor-maven-plugin.version>1.5.5</asciidoctor-maven-plugin.version>
|
||||
<asciidoctorj.version>1.5.4</asciidoctorj.version>
|
||||
<asciidoctorj-pdf.src.version>1.5.0-alpha.11</asciidoctorj-pdf.src.version>
|
||||
<asciidoctor-maven-plugin.version>1.5.6</asciidoctor-maven-plugin.version>
|
||||
<asciidoctorj.version>1.5.6</asciidoctorj.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>
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -3,7 +3,7 @@ package com.baeldung.asciidoctor;
|
|||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class AsciidoctorDemoTest {
|
||||
public class AsciidoctorDemoIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenString_whenConverting_thenResultingHTMLCode() {
|
|
@ -42,14 +42,6 @@
|
|||
</archive>
|
||||
</configuration>
|
||||
</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>
|
||||
</build>
|
||||
|
||||
|
|
|
@ -95,7 +95,6 @@
|
|||
<gson.version>2.8.2</gson.version>
|
||||
<aws-java-sdk.version>1.11.241</aws-java-sdk.version>
|
||||
<maven-shade-plugin.version>3.0.0</maven-shade-plugin.version>
|
||||
<maven-dependency-plugin.version>2.10</maven-dependency-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -1 +1,2 @@
|
|||
/target/
|
||||
.idea/
|
21
aws/pom.xml
21
aws/pom.xml
|
@ -100,26 +100,6 @@
|
|||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<version>${maven-dependency-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-dependencies</id>
|
||||
<phase>test-compile</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<includeScope>test</includeScope>
|
||||
<includeTypes>so,dll,dylib</includeTypes>
|
||||
<outputDirectory>${project.basedir}/native-libs</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
@ -144,7 +124,6 @@
|
|||
<commons-codec-version>1.10.L001</commons-codec-version>
|
||||
<jets3t-version>0.9.4.0006L</jets3t-version>
|
||||
<maven-shade-plugin.version>3.0.0</maven-shade-plugin.version>
|
||||
<maven-dependency-plugin.version>2.10</maven-dependency-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,184 @@
|
|||
package com.baeldung.rds;
|
||||
|
||||
import com.amazonaws.auth.AWSCredentialsProvider;
|
||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
||||
import com.amazonaws.auth.BasicAWSCredentials;
|
||||
import com.amazonaws.regions.Regions;
|
||||
import com.amazonaws.services.rds.AmazonRDS;
|
||||
import com.amazonaws.services.rds.AmazonRDSClientBuilder;
|
||||
import com.amazonaws.services.rds.model.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.sql.*;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import java.util.UUID;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class AWSRDSService {
|
||||
|
||||
|
||||
final static Logger logger = Logger.getLogger(AWSRDSService.class.getName());
|
||||
private AWSCredentialsProvider credentials;
|
||||
private AmazonRDS amazonRDS;
|
||||
private String db_username;
|
||||
private String db_password;
|
||||
private String db_database;
|
||||
private String db_hostname;
|
||||
|
||||
/*
|
||||
* User access key and secret key must be set before execute any operation.
|
||||
* Follow the link on how to get the user access and secret key
|
||||
* https://aws.amazon.com/blogs/security/wheres-my-secret-access-key/
|
||||
* **/
|
||||
public AWSRDSService() throws IOException {
|
||||
//Init RDS client with credentials and region.
|
||||
credentials = new
|
||||
AWSStaticCredentialsProvider(new
|
||||
BasicAWSCredentials("<ACCESS_KEY>",
|
||||
"<SECRET_KEY>"));
|
||||
amazonRDS = AmazonRDSClientBuilder.standard().withCredentials(credentials)
|
||||
.withRegion(Regions.AP_SOUTHEAST_2).build();
|
||||
Properties prop = new Properties();
|
||||
InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties");
|
||||
prop.load(input);
|
||||
db_username = prop.getProperty("db_username");
|
||||
db_password = prop.getProperty("db_password");
|
||||
db_database = prop.getProperty("db_database");
|
||||
}
|
||||
|
||||
public AWSRDSService(AmazonRDS amazonRDS){
|
||||
this.amazonRDS = amazonRDS;
|
||||
}
|
||||
|
||||
/**
|
||||
* create the RDS instance.
|
||||
* After instance creation, update the db_hostname with endpoint in db.properties.
|
||||
* */
|
||||
|
||||
public String launchInstance() {
|
||||
|
||||
String identifier = "";
|
||||
CreateDBInstanceRequest request = new CreateDBInstanceRequest();
|
||||
// RDS instance name
|
||||
request.setDBInstanceIdentifier("Sydney");
|
||||
request.setEngine("postgres");
|
||||
request.setMultiAZ(false);
|
||||
request.setMasterUsername(db_username);
|
||||
request.setMasterUserPassword(db_password);
|
||||
request.setDBName(db_database);
|
||||
request.setStorageType("gp2");
|
||||
request.setAllocatedStorage(10);
|
||||
|
||||
DBInstance instance = amazonRDS.createDBInstance(request);
|
||||
|
||||
// Information about the new RDS instance
|
||||
identifier = instance.getDBInstanceIdentifier();
|
||||
String status = instance.getDBInstanceStatus();
|
||||
Endpoint endpoint = instance.getEndpoint();
|
||||
String endpoint_url = "Endpoint URL not available yet.";
|
||||
if (endpoint != null) {
|
||||
endpoint_url = endpoint.toString();
|
||||
}
|
||||
logger.info(identifier + "\t" + status);
|
||||
logger.info(endpoint_url);
|
||||
|
||||
return identifier;
|
||||
|
||||
}
|
||||
|
||||
// Describe DB instances
|
||||
public void listInstances() {
|
||||
DescribeDBInstancesResult result = amazonRDS.describeDBInstances();
|
||||
List<DBInstance> instances = result.getDBInstances();
|
||||
for (DBInstance instance : instances) {
|
||||
// Information about each RDS instance
|
||||
String identifier = instance.getDBInstanceIdentifier();
|
||||
String engine = instance.getEngine();
|
||||
String status = instance.getDBInstanceStatus();
|
||||
Endpoint endpoint = instance.getEndpoint();
|
||||
String endpoint_url = "Endpoint URL not available yet.";
|
||||
if (endpoint != null) {
|
||||
endpoint_url = endpoint.toString();
|
||||
}
|
||||
logger.info(identifier + "\t" + engine + "\t" + status);
|
||||
logger.info("\t" + endpoint_url);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//Delete RDS instance
|
||||
public void terminateInstance(String identifier) {
|
||||
|
||||
DeleteDBInstanceRequest request = new DeleteDBInstanceRequest();
|
||||
request.setDBInstanceIdentifier(identifier);
|
||||
request.setSkipFinalSnapshot(true);
|
||||
|
||||
// Delete the RDS instance
|
||||
DBInstance instance = amazonRDS.deleteDBInstance(request);
|
||||
|
||||
// Information about the RDS instance being deleted
|
||||
String status = instance.getDBInstanceStatus();
|
||||
Endpoint endpoint = instance.getEndpoint();
|
||||
String endpoint_url = "Endpoint URL not available yet.";
|
||||
if (endpoint != null) {
|
||||
endpoint_url = endpoint.toString();
|
||||
}
|
||||
|
||||
logger.info(identifier + "\t" + status);
|
||||
logger.info(endpoint_url);
|
||||
|
||||
}
|
||||
|
||||
|
||||
public void runJdbcTests() throws SQLException, IOException {
|
||||
|
||||
// Getting database properties from db.properties
|
||||
Properties prop = new Properties();
|
||||
InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties");
|
||||
prop.load(input);
|
||||
db_hostname = prop.getProperty("db_hostname");
|
||||
String jdbc_url = "jdbc:postgresql://" + db_hostname + ":5432/" + db_database;
|
||||
|
||||
// Create a connection using the JDBC driver
|
||||
try (Connection conn = DriverManager.getConnection(jdbc_url, db_username, db_password)) {
|
||||
|
||||
// Create the test table if not exists
|
||||
Statement statement = conn.createStatement();
|
||||
String sql = "CREATE TABLE IF NOT EXISTS jdbc_test (id SERIAL PRIMARY KEY, content VARCHAR(80))";
|
||||
statement.executeUpdate(sql);
|
||||
|
||||
// Do some INSERT
|
||||
PreparedStatement preparedStatement = conn.prepareStatement("INSERT INTO jdbc_test (content) VALUES (?)");
|
||||
String content = "" + UUID.randomUUID();
|
||||
preparedStatement.setString(1, content);
|
||||
preparedStatement.executeUpdate();
|
||||
logger.info("INSERT: " + content);
|
||||
|
||||
// Do some SELECT
|
||||
sql = "SELECT * FROM jdbc_test";
|
||||
ResultSet resultSet = statement.executeQuery(sql);
|
||||
while (resultSet.next()) {
|
||||
String count = resultSet.getString("content");
|
||||
logger.info("Total Records: " + count);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException, SQLException {
|
||||
AWSRDSService awsrdsService = new AWSRDSService();
|
||||
|
||||
String instanceName = awsrdsService.launchInstance();
|
||||
|
||||
//Add some wait for instance creation.
|
||||
|
||||
awsrdsService.listInstances();
|
||||
|
||||
awsrdsService.runJdbcTests();
|
||||
|
||||
awsrdsService.terminateInstance(instanceName);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
db_hostname=<RDS EndPoint>
|
||||
db_username=username
|
||||
db_password=password
|
||||
db_database=mydb
|
|
@ -2,12 +2,10 @@
|
|||
<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>cas-secured-app</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>cas-secured-app</name>
|
||||
<description>Demo project for Spring Boot</description>
|
||||
<description>Demo project for CAS</description>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-boot-1</artifactId>
|
||||
|
@ -60,10 +58,4 @@
|
|||
</plugins>
|
||||
</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>
|
||||
|
|
|
@ -2,11 +2,17 @@
|
|||
<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>cas-server</artifactId>
|
||||
<packaging>war</packaging>
|
||||
<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>
|
||||
<dependency>
|
||||
<groupId>org.apereo.cas</groupId>
|
||||
|
@ -39,7 +45,6 @@
|
|||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${springboot.version}</version>
|
||||
<configuration>
|
||||
<mainClass>${mainClassName}</mainClass>
|
||||
<addResources>true</addResources>
|
||||
|
@ -74,42 +79,10 @@
|
|||
</overlays>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
<finalName>cas</finalName>
|
||||
</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>
|
||||
<profile>
|
||||
<activation>
|
||||
|
@ -214,8 +187,7 @@
|
|||
</profiles>
|
||||
|
||||
<properties>
|
||||
<cas.version>5.3.0-SNAPSHOT</cas.version>
|
||||
<springboot.version>1.5.13.RELEASE</springboot.version>
|
||||
<cas.version>5.3.3</cas.version>
|
||||
<!-- app.server could be -jetty, -undertow, -tomcat, or blank if you plan to provide appserver -->
|
||||
<app.server>-tomcat</app.server>
|
||||
|
||||
|
@ -223,12 +195,10 @@
|
|||
<isExecutable>false</isExecutable>
|
||||
<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>
|
||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||
<maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>
|
||||
|
||||
<echo-maven-plugin.version>0.3.0</echo-maven-plugin.version>
|
||||
<pgpverify-maven-plugin.version>1.1.0</pgpverify-maven-plugin.version>
|
||||
</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>
|
|
@ -41,27 +41,6 @@
|
|||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<!-- This plugin will set properties values using dependency information -->
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<!--
|
||||
Goal that sets a property pointing to the artifact file for each project dependency.
|
||||
For each dependency (direct and transitive) a project property will be set which
|
||||
follows the:
|
||||
|
||||
groupId:artifactId:type:[classifier]
|
||||
|
||||
form and contains the path to the resolved artifact. -->
|
||||
<goal>properties</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
|
|
|
@ -15,24 +15,20 @@
|
|||
- [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing)
|
||||
- [Guide To Java 8 Optional](http://www.baeldung.com/java-optional)
|
||||
- [Guide to the Java 8 forEach](http://www.baeldung.com/foreach-java)
|
||||
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
|
||||
- [Java Base64 Encoding and Decoding](http://www.baeldung.com/java-base64-encode-and-decode)
|
||||
- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap)
|
||||
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)
|
||||
- [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods)
|
||||
- [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency)
|
||||
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
|
||||
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
|
||||
- [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator)
|
||||
- [Java 8 Math New Methods](http://www.baeldung.com/java-8-math)
|
||||
- [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations)
|
||||
- [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max)
|
||||
- [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization)
|
||||
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
|
||||
- [Java Optional – orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get)
|
||||
- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table)
|
||||
- [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection)
|
||||
- [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic)
|
||||
- [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference)
|
||||
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
|
||||
- [Overriding System Time for Testing in Java](http://www.baeldung.com/java-override-system-time)
|
||||
- [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone)
|
||||
- [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance)
|
||||
- [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects)
|
||||
|
|
|
@ -116,23 +116,6 @@
|
|||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-dependencies</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>${project.build.directory}/libs</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
|
|
|
@ -1,16 +1,18 @@
|
|||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.java8.entity.Human;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.primitives.Ints;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.java8.entity.Human;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.primitives.Ints;
|
||||
|
||||
public class Java8SortUnitTest {
|
||||
|
||||
|
@ -112,4 +114,21 @@ public class Java8SortUnitTest {
|
|||
Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenStreamNaturalOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
|
||||
final List<String> letters = Lists.newArrayList("B", "A", "C");
|
||||
|
||||
final List<String> sortedLetters = letters.stream().sorted().collect(Collectors.toList());
|
||||
Assert.assertThat(sortedLetters.get(0), equalTo("A"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
|
||||
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
|
||||
final Comparator<Human> nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
|
||||
|
||||
final List<Human> sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList());
|
||||
Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12)));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.stream.conditional;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StreamForEachIfElseUnitTest {
|
||||
|
||||
@Test
|
||||
public final void givenIntegerStream_whenCheckingIntegerParityWithIfElse_thenEnsureCorrectParity() {
|
||||
List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
|
||||
|
||||
ints.stream()
|
||||
.forEach(i -> {
|
||||
if (i.intValue() % 2 == 0) {
|
||||
Assert.assertTrue(i.intValue() + " is not even", i.intValue() % 2 == 0);
|
||||
} else {
|
||||
Assert.assertTrue(i.intValue() + " is not odd", i.intValue() % 2 != 0);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenIntegerStream_whenCheckingIntegerParityWithStreamFilter_thenEnsureCorrectParity() {
|
||||
List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
|
||||
|
||||
Stream<Integer> evenIntegers = ints.stream()
|
||||
.filter(i -> i.intValue() % 2 == 0);
|
||||
Stream<Integer> oddIntegers = ints.stream()
|
||||
.filter(i -> i.intValue() % 2 != 0);
|
||||
|
||||
evenIntegers.forEach(i -> Assert.assertTrue(i.intValue() + " is not even", i.intValue() % 2 == 0));
|
||||
oddIntegers.forEach(i -> Assert.assertTrue(i.intValue() + " is not odd", i.intValue() % 2 != 0));
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -1,97 +0,0 @@
|
|||
package com.baeldung.streamordering;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.infra.Blackhole;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
import org.openjdk.jmh.runner.options.TimeValue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
|
||||
public class BenchmarkUnitTest
|
||||
{
|
||||
|
||||
@Test
|
||||
public void
|
||||
launchBenchmark() throws Exception {
|
||||
|
||||
Options opt = new OptionsBuilder()
|
||||
// Specify which benchmarks to run.
|
||||
// You can be more specific if you'd like to run only one benchmark per test.
|
||||
.include(this.getClass().getName() + ".*")
|
||||
// Set the following options as needed
|
||||
.mode (Mode.AverageTime)
|
||||
.timeUnit(TimeUnit.MICROSECONDS)
|
||||
.warmupTime(TimeValue.seconds(1))
|
||||
.warmupIterations(2)
|
||||
.measurementTime(TimeValue.seconds(1))
|
||||
.measurementIterations(2)
|
||||
.threads(2)
|
||||
.forks(1)
|
||||
.shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
//.jvmArgs("-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintInlining")
|
||||
//.addProfiler(WinPerfAsmProfiler.class)
|
||||
.build();
|
||||
|
||||
new Runner(opt).run();
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void givenOrderedStreamInput_whenStreamFiltered_showOpsPerMS(){
|
||||
IntStream.range(1, 100_000_000).parallel().filter(i -> i % 10 == 0).toArray();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void givenUnorderedStreamInput_whenStreamFiltered_showOpsPerMS(){
|
||||
IntStream.range(1,100_000_000).unordered().parallel().filter(i -> i % 10 == 0).toArray();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void givenUnorderedStreamInput_whenStreamDistinct_showOpsPerMS(){
|
||||
IntStream.range(1, 1_000_000).unordered().parallel().distinct().toArray();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void givenOrderedStreamInput_whenStreamDistinct_showOpsPerMS() {
|
||||
//section 5.1.
|
||||
IntStream.range(1, 1_000_000).parallel().distinct().toArray();
|
||||
}
|
||||
|
||||
|
||||
// The JMH samples are the best documentation for how to use it
|
||||
// http://hg.openjdk.java.net/code-tools/jmh/file/tip/jmh-samples/src/main/java/org/openjdk/jmh/samples/
|
||||
@State(Scope.Thread)
|
||||
public static class BenchmarkState
|
||||
{
|
||||
List<Integer> list;
|
||||
|
||||
@Setup(Level.Trial) public void
|
||||
initialize() {
|
||||
|
||||
Random rand = new Random();
|
||||
|
||||
list = new ArrayList<>();
|
||||
for (int i = 0; i < 1000; i++)
|
||||
list.add (rand.nextInt());
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark public void
|
||||
benchmark1 (BenchmarkState state, Blackhole bh) {
|
||||
|
||||
List<Integer> list = state.list;
|
||||
|
||||
for (int i = 0; i < 1000; i++)
|
||||
bh.consume (list.get (i));
|
||||
}
|
||||
}
|
|
@ -1,149 +0,0 @@
|
|||
package com.baeldung.streamordering;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StreamsOrderingUnitTest {
|
||||
|
||||
Logger logger = Logger.getLogger( StreamsOrderingUnitTest.class.getName());
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
logger.setLevel(Level.ALL);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoCollections_whenStreamed_thenCheckOutputDifferent(){
|
||||
|
||||
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
|
||||
Set<String> set = new TreeSet<>(Arrays.asList("B", "A", "C", "D", "F"));
|
||||
|
||||
Object[] listOutput = list.stream().toArray();
|
||||
Object[] setOutput = set.stream().toArray();
|
||||
|
||||
assertEquals("[B, A, C, D, F]", Arrays.toString(listOutput));
|
||||
assertEquals("[A, B, C, D, F]", Arrays.toString(setOutput));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoCollections_whenStreamedInParallel_thenCheckOutputDifferent(){
|
||||
|
||||
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
|
||||
Set<String> set = new TreeSet<>(Arrays.asList("B", "A", "C", "D", "F"));
|
||||
|
||||
Object[] listOutput = list.stream().parallel().toArray();
|
||||
Object[] setOutput = set.stream().parallel().toArray();
|
||||
|
||||
assertEquals("[B, A, C, D, F]", Arrays.toString(listOutput));
|
||||
assertEquals("[A, B, C, D, F]", Arrays.toString(setOutput));
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
public void givenOrderedInput_whenUnorderedAndOrderedCompared_thenCheckUnorderedOutputChanges(){
|
||||
Set<Integer> set = new TreeSet<>(
|
||||
Arrays.asList(-9, -5, -4, -2, 1, 2, 4, 5, 7, 9, 12, 13, 16, 29, 23, 34, 57, 68, 90, 102, 230));
|
||||
|
||||
Object[] orderedArray = set.stream()
|
||||
.parallel()
|
||||
.limit(5)
|
||||
.toArray();
|
||||
Object[] unorderedArray = set.stream()
|
||||
.unordered()
|
||||
.parallel()
|
||||
.limit(5)
|
||||
.toArray();
|
||||
|
||||
logger.info(Arrays.toString(orderedArray));
|
||||
logger.info(Arrays.toString(unorderedArray));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenUnsortedStreamInput_whenStreamSorted_thenCheckOrderChanged(){
|
||||
|
||||
List<Integer> list = Arrays.asList(-3,10,-4,1,3);
|
||||
|
||||
Object[] listOutput = list.stream().toArray();
|
||||
Object[] listOutputSorted = list.stream().sorted().toArray();
|
||||
|
||||
assertEquals("[-3, 10, -4, 1, 3]", Arrays.toString(listOutput));
|
||||
assertEquals("[-4, -3, 1, 3, 10]", Arrays.toString(listOutputSorted));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedStreamInput_whenStreamDistinct_thenShowTimeTaken(){
|
||||
long start, end;
|
||||
start = System.currentTimeMillis();
|
||||
IntStream.range(1,1_000_000).unordered().parallel().distinct().toArray();
|
||||
end = System.currentTimeMillis();
|
||||
System.out.println(String.format("Time taken when unordered: %d ms", (end - start)));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenSameCollection_whenStreamTerminated_thenCheckEachVsEachOrdered(){
|
||||
|
||||
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
|
||||
|
||||
list.stream().parallel().forEach(e -> logger.log(Level.INFO, e));
|
||||
list.stream().parallel().forEachOrdered(e -> logger.log(Level.INFO, e));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSameCollection_whenStreamCollected_thenCheckOutput(){
|
||||
|
||||
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
|
||||
|
||||
List<String> collectionList = list.stream().parallel().collect(Collectors.toList());
|
||||
Set<String> collectionSet = list.stream().parallel().collect(Collectors.toCollection(TreeSet::new));
|
||||
|
||||
assertEquals("[B, A, C, D, F]", collectionList.toString());
|
||||
assertEquals("[A, B, C, D, F]", collectionSet.toString());
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenListIterationOrder_whenStreamCollectedToMap_thenCeckOrderChanged() {
|
||||
List<String> list = Arrays.asList("A", "BB", "CCC");
|
||||
|
||||
Map<String, Integer> hashMap = list.stream().collect(Collectors.toMap(Function.identity(), String::length));
|
||||
|
||||
Object[] keySet = hashMap.keySet().toArray();
|
||||
|
||||
assertEquals("[BB, A, CCC]", Arrays.toString(keySet));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListIteration_whenStreamCollectedtoHashMap_thenCheckOrderMaintained() {
|
||||
List<String> list = Arrays.asList("A", "BB", "CCC", "CCC");
|
||||
|
||||
Map<String, Integer> linkedHashMap = list.stream().collect(Collectors.toMap(
|
||||
Function.identity(),
|
||||
String::length,
|
||||
(u, v) -> u,
|
||||
LinkedHashMap::new
|
||||
));
|
||||
|
||||
Object[] keySet = linkedHashMap.keySet().toArray();
|
||||
|
||||
assertEquals("[A, BB, CCC]", Arrays.toString(keySet));
|
||||
}
|
||||
|
||||
}
|
|
@ -24,3 +24,5 @@
|
|||
- [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional)
|
||||
- [Java 9 java.lang.Module API](http://www.baeldung.com/java-9-module-api)
|
||||
- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range)
|
||||
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
|
||||
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
|
||||
|
|
|
@ -0,0 +1,15 @@
|
|||
# compile logging module
|
||||
# javac --module-path mods -d mods/com.baeldung.logging src/modules/com.baeldung.logging/module-info.java src/modules/com.baeldung.logging/com/baeldung/logging/*.java
|
||||
|
||||
# compile logging slf4j module
|
||||
javac --module-path mods -d mods/com.baeldung.logging.slf4j src/modules/com.baeldung.logging.slf4j/module-info.java src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/*.java
|
||||
|
||||
|
||||
# compile logging main app module
|
||||
javac --module-path mods -d mods/com.baeldung.logging.app src/modules/com.baeldung.logging.app/module-info.java src/modules/com.baeldung.logging.app/com/baeldung/logging/app/*.java
|
||||
|
||||
# run logging main app
|
||||
# java --module-path mods -m com.baeldung.logging.app/com.baeldung.logging.app.MainApp
|
||||
|
||||
# run looging main app using logback
|
||||
java --module-path mods -Dlogback.configurationFile=mods/logback.xml -m com.baeldung.logging.app/com.baeldung.logging.app.MainApp
|
|
@ -0,0 +1,16 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
|
||||
<pattern>
|
||||
%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} -- %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root>
|
||||
<appender-ref ref="STDOUT"/>
|
||||
</root>
|
||||
|
||||
</configuration>
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.logging.app;
|
||||
|
||||
import static java.lang.System.Logger.*;
|
||||
|
||||
public class MainApp {
|
||||
|
||||
private static System.Logger LOGGER = System.getLogger("MainApp");
|
||||
|
||||
public static void main(String[] args) {
|
||||
LOGGER.log(Level.ERROR, "error test");
|
||||
LOGGER.log(Level.INFO, "info test");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
module com.baeldung.logging.app {
|
||||
}
|
|
@ -0,0 +1,99 @@
|
|||
package com.baeldung.logging.slf4j;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.ResourceBundle;
|
||||
|
||||
public class Slf4jLogger implements System.Logger {
|
||||
|
||||
private final String name;
|
||||
private final Logger logger;
|
||||
|
||||
public Slf4jLogger(String name) {
|
||||
this.name = name;
|
||||
logger = LoggerFactory.getLogger(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isLoggable(Level level) {
|
||||
switch (level) {
|
||||
case OFF:
|
||||
return false;
|
||||
case TRACE:
|
||||
return logger.isTraceEnabled();
|
||||
case DEBUG:
|
||||
return logger.isDebugEnabled();
|
||||
case INFO:
|
||||
return logger.isInfoEnabled();
|
||||
case WARNING:
|
||||
return logger.isWarnEnabled();
|
||||
case ERROR:
|
||||
return logger.isErrorEnabled();
|
||||
case ALL:
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void log(Level level, ResourceBundle bundle, String msg, Throwable thrown) {
|
||||
if (!isLoggable(level)) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (level) {
|
||||
case TRACE:
|
||||
logger.trace(msg, thrown);
|
||||
break;
|
||||
case DEBUG:
|
||||
logger.debug(msg, thrown);
|
||||
break;
|
||||
case INFO:
|
||||
logger.info(msg, thrown);
|
||||
break;
|
||||
case WARNING:
|
||||
logger.warn(msg, thrown);
|
||||
break;
|
||||
case ERROR:
|
||||
logger.error(msg, thrown);
|
||||
break;
|
||||
case ALL:
|
||||
default:
|
||||
logger.info(msg, thrown);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void log(Level level, ResourceBundle bundle, String format, Object... params) {
|
||||
if (!isLoggable(level)) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (level) {
|
||||
case TRACE:
|
||||
logger.trace(format, params);
|
||||
break;
|
||||
case DEBUG:
|
||||
logger.debug(format, params);
|
||||
break;
|
||||
case INFO:
|
||||
logger.info(format, params);
|
||||
break;
|
||||
case WARNING:
|
||||
logger.warn(format, params);
|
||||
break;
|
||||
case ERROR:
|
||||
logger.error(format, params);
|
||||
break;
|
||||
case ALL:
|
||||
default:
|
||||
logger.info(format, params);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.logging.slf4j;
|
||||
|
||||
public class Slf4jLoggerFinder extends System.LoggerFinder {
|
||||
@Override
|
||||
public System.Logger getLogger(String name, Module module) {
|
||||
return new Slf4jLogger(name);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
module com.baeldung.logging.slf4j {
|
||||
requires org.slf4j;
|
||||
provides java.lang.System.LoggerFinder
|
||||
with com.baeldung.logging.slf4j.Slf4jLoggerFinder;
|
||||
exports com.baeldung.logging.slf4j;
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.logging;
|
||||
|
||||
import java.text.MessageFormat;
|
||||
import java.util.ResourceBundle;
|
||||
|
||||
public class ConsoleLogger implements System.Logger {
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "ConsoleLogger";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isLoggable(Level level) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void log(Level level, ResourceBundle bundle, String msg, Throwable thrown) {
|
||||
System.out.printf("ConsoleLogger [%s]: %s - %s%n", level, msg, thrown);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void log(Level level, ResourceBundle bundle, String format, Object... params) {
|
||||
System.out.printf("ConsoleLogger [%s]: %s%n", level, MessageFormat.format(format, params));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.logging;
|
||||
|
||||
public class CustomLoggerFinder extends System.LoggerFinder {
|
||||
|
||||
@Override
|
||||
public System.Logger getLogger(String name, Module module) {
|
||||
return new ConsoleLogger();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
module com.baeldung.logging {
|
||||
provides java.lang.System.LoggerFinder
|
||||
with com.baeldung.logging.CustomLoggerFinder;
|
||||
exports com.baeldung.logging;
|
||||
}
|
|
@ -48,7 +48,7 @@ class ProcessUnderstandingTest {
|
|||
}
|
||||
|
||||
//@Test - windows specific
|
||||
public void givenSubProcess_thenStartSuccessIsAlive() throws IOException {
|
||||
public void givenSubProcess_whenStarted_thenStartSuccessIsAlive() throws IOException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
assertTrue(builder.start().isAlive());
|
||||
}
|
||||
|
@ -75,7 +75,7 @@ class ProcessUnderstandingTest {
|
|||
}
|
||||
|
||||
//@Test - windows specific
|
||||
public void givenSubProcess_checkAlive() throws IOException, InterruptedException {
|
||||
public void givenSubProcess_whenDestroyed_thenCheckIfAlive() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
Thread.sleep(10000);
|
||||
|
|
|
@ -37,3 +37,18 @@
|
|||
- [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map)
|
||||
- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset)
|
||||
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
|
||||
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
|
||||
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
|
||||
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
|
||||
- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table)
|
||||
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
|
||||
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
|
||||
- [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections)
|
||||
- [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list)
|
||||
- [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)
|
||||
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
|
||||
- [Differences Between Collection.clear() and Collection.removeAll()](https://www.baeldung.com/java-collection-clear-vs-removeall)
|
||||
- [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance)
|
||||
- [Get the Key for a Value from a Java Map](https://www.baeldung.com/java-map-key-from-value)
|
||||
- [Time Complexity of Java Collections](https://www.baeldung.com/java-collections-complexity)
|
||||
|
|
|
@ -63,6 +63,17 @@
|
|||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${openjdk.jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-exec</artifactId>
|
||||
<version>1.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>one.util</groupId>
|
||||
<artifactId>streamex</artifactId>
|
||||
<version>0.6.5</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.list;
|
||||
package com.baeldung.java.list;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
|
@ -0,0 +1,44 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.java.map;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* @author swpraman
|
||||
*
|
||||
*/
|
||||
public class MapUtil {
|
||||
|
||||
public static <K, V> Stream<K> keys(Map<K, V> map, V value) {
|
||||
return map.entrySet()
|
||||
.stream()
|
||||
.filter(entry -> value.equals(entry.getValue()))
|
||||
.map(Map.Entry::getKey);
|
||||
}
|
||||
|
||||
public static <K, V> Set<K> getKeys(Map<K, V> map, V value) {
|
||||
Set<K> keys = new HashSet<>();
|
||||
for (Entry<K, V> entry : map.entrySet()) {
|
||||
if (entry.getValue().equals(value)) {
|
||||
keys.add(entry.getKey());
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
public static <K, V> K getKey(Map<K, V> map, V value) {
|
||||
for (Entry<K, V> entry : map.entrySet()) {
|
||||
if (entry.getValue().equals(value)) {
|
||||
return entry.getKey();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,105 @@
|
|||
package com.baeldung.map.java_8;
|
||||
|
||||
import com.baeldung.sort.Employee;
|
||||
import one.util.streamex.EntryStream;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class MergeMaps {
|
||||
|
||||
private static Map<String, Employee> map1 = new HashMap<>();
|
||||
private static Map<String, Employee> map2 = new HashMap<>();
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
initialize();
|
||||
|
||||
mergeFunction();
|
||||
|
||||
streamConcat();
|
||||
|
||||
streamOf();
|
||||
|
||||
streamEx();
|
||||
|
||||
streamMerge();
|
||||
}
|
||||
|
||||
private static void streamMerge() {
|
||||
|
||||
Map<String, Employee> map3 = map2.entrySet()
|
||||
.stream()
|
||||
.collect(
|
||||
Collectors.toMap(
|
||||
Map.Entry::getKey,
|
||||
Map.Entry::getValue,
|
||||
(v1, v2) -> new Employee(v1.getId(), v2.getName()),
|
||||
() -> new HashMap<>(map1)
|
||||
)
|
||||
);
|
||||
|
||||
System.out.println(map3);
|
||||
}
|
||||
|
||||
private static void streamEx() {
|
||||
Map<String, Employee> map3 = EntryStream.of(map1)
|
||||
.append(EntryStream.of(map2))
|
||||
.toMap((e1, e2) -> e1);
|
||||
|
||||
System.out.println(map3);
|
||||
|
||||
}
|
||||
|
||||
private static void streamOf() {
|
||||
Map<String, Employee> map3 = Stream.of(map1, map2)
|
||||
.flatMap(map -> map.entrySet().stream())
|
||||
.collect(
|
||||
Collectors.toMap(
|
||||
Map.Entry::getKey,
|
||||
Map.Entry::getValue,
|
||||
(v1, v2) -> new Employee(v1.getId(), v2.getName())
|
||||
)
|
||||
);
|
||||
|
||||
map3.entrySet().forEach(System.out::println);
|
||||
}
|
||||
|
||||
private static void streamConcat() {
|
||||
Map<String, Employee> result = Stream.concat(map1.entrySet().stream(), map2.entrySet().stream()).collect(Collectors.toMap(
|
||||
Map.Entry::getKey,
|
||||
Map.Entry::getValue,
|
||||
(value1, value2) -> new Employee(value2.getId(), value1.getName())
|
||||
));
|
||||
|
||||
result.entrySet().forEach(System.out::println);
|
||||
}
|
||||
|
||||
private static void mergeFunction() {
|
||||
Map<String, Employee> map3 = new HashMap<>(map1);
|
||||
|
||||
map2.forEach(
|
||||
(key, value) -> map3.merge(key, value, (v1, v2) ->
|
||||
new Employee(v1.getId(), v2.getName()))
|
||||
);
|
||||
|
||||
map3.entrySet().forEach(System.out::println);
|
||||
}
|
||||
|
||||
|
||||
private static void initialize() {
|
||||
Employee employee1 = new Employee(1L, "Henry");
|
||||
map1.put(employee1.getName(), employee1);
|
||||
Employee employee2 = new Employee(22L, "Annie");
|
||||
map1.put(employee2.getName(), employee2);
|
||||
Employee employee3 = new Employee(8L, "John");
|
||||
map1.put(employee3.getName(), employee3);
|
||||
|
||||
Employee employee4 = new Employee(2L, "George");
|
||||
map2.put(employee4.getName(), employee4);
|
||||
Employee employee5 = new Employee(3L, "Henry");
|
||||
map2.put(employee5.getName(), employee5);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,96 @@
|
|||
package com.baeldung.map.util;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Optional;
|
||||
|
||||
public class MapMax {
|
||||
|
||||
public <K, V extends Comparable<V>> V maxUsingIteration(Map<K, V> map) {
|
||||
|
||||
Map.Entry<K, V> maxEntry = null;
|
||||
|
||||
for (Map.Entry<K, V> entry : map.entrySet()) {
|
||||
|
||||
if (maxEntry == null || entry.getValue()
|
||||
.compareTo(maxEntry.getValue()) > 0) {
|
||||
maxEntry = entry;
|
||||
}
|
||||
}
|
||||
|
||||
return maxEntry.getValue();
|
||||
}
|
||||
|
||||
public <K, V extends Comparable<V>> V maxUsingCollectionsMax(Map<K, V> map) {
|
||||
|
||||
Entry<K, V> maxEntry = Collections.max(map.entrySet(), new Comparator<Entry<K, V>>() {
|
||||
public int compare(Entry<K, V> e1, Entry<K, V> e2) {
|
||||
return e1.getValue()
|
||||
.compareTo(e2.getValue());
|
||||
}
|
||||
});
|
||||
|
||||
return maxEntry.getValue();
|
||||
}
|
||||
|
||||
public <K, V extends Comparable<V>> V maxUsingCollectionsMaxAndLambda(Map<K, V> map) {
|
||||
|
||||
Entry<K, V> maxEntry = Collections.max(map.entrySet(), (Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue()
|
||||
.compareTo(e2.getValue()));
|
||||
|
||||
return maxEntry.getValue();
|
||||
}
|
||||
|
||||
public <K, V extends Comparable<V>> V maxUsingCollectionsMaxAndMethodReference(Map<K, V> map) {
|
||||
|
||||
Entry<K, V> maxEntry = Collections.max(map.entrySet(), Comparator.comparing(Map.Entry::getValue));
|
||||
|
||||
return maxEntry.getValue();
|
||||
}
|
||||
|
||||
public <K, V extends Comparable<V>> V maxUsingStreamAndLambda(Map<K, V> map) {
|
||||
|
||||
Optional<Entry<K, V>> maxEntry = map.entrySet()
|
||||
.stream()
|
||||
.max((Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue()
|
||||
.compareTo(e2.getValue()));
|
||||
|
||||
return maxEntry.get()
|
||||
.getValue();
|
||||
}
|
||||
|
||||
public <K, V extends Comparable<V>> V maxUsingStreamAndMethodReference(Map<K, V> map) {
|
||||
|
||||
Optional<Entry<K, V>> maxEntry = map.entrySet()
|
||||
.stream()
|
||||
.max(Comparator.comparing(Map.Entry::getValue));
|
||||
|
||||
return maxEntry.get()
|
||||
.getValue();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
|
||||
|
||||
map.put(1, 3);
|
||||
map.put(2, 4);
|
||||
map.put(3, 5);
|
||||
map.put(4, 6);
|
||||
map.put(5, 7);
|
||||
|
||||
MapMax mapMax = new MapMax();
|
||||
|
||||
System.out.println(mapMax.maxUsingIteration(map));
|
||||
System.out.println(mapMax.maxUsingCollectionsMax(map));
|
||||
System.out.println(mapMax.maxUsingCollectionsMaxAndLambda(map));
|
||||
System.out.println(mapMax.maxUsingCollectionsMaxAndMethodReference(map));
|
||||
System.out.println(mapMax.maxUsingStreamAndLambda(map));
|
||||
System.out.println(mapMax.maxUsingStreamAndMethodReference(map));
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,77 @@
|
|||
package com.baeldung.performance;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
@Warmup(iterations = 10)
|
||||
public class ArrayListBenchmark {
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class MyState {
|
||||
|
||||
List<Employee> employeeList = new ArrayList<>();
|
||||
//LinkedList<Employee> employeeList = new LinkedList<>();
|
||||
|
||||
long iterations = 100000;
|
||||
|
||||
Employee employee = new Employee(100L, "Harry");
|
||||
|
||||
int employeeIndex = -1;
|
||||
|
||||
@Setup(Level.Trial)
|
||||
public void setUp() {
|
||||
for (long i = 0; i < iterations; i++) {
|
||||
employeeList.add(new Employee(i, "John"));
|
||||
}
|
||||
|
||||
employeeList.add(employee);
|
||||
employeeIndex = employeeList.indexOf(employee);
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void testAddAt(ArrayListBenchmark.MyState state) {
|
||||
state.employeeList.add((int) (state.iterations), new Employee(state.iterations, "John"));
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testContains(ArrayListBenchmark.MyState state) {
|
||||
return state.employeeList.contains(state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int testIndexOf(ArrayListBenchmark.MyState state) {
|
||||
return state.employeeList.indexOf(state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Employee testGet(ArrayListBenchmark.MyState state) {
|
||||
return state.employeeList.get(state.employeeIndex);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testRemove(ArrayListBenchmark.MyState state) {
|
||||
return state.employeeList.remove(state.employee);
|
||||
}
|
||||
|
||||
// @Benchmark
|
||||
// public void testAdd(ArrayListBenchmark.MyState state) {
|
||||
// state.employeeList.add(new Employee(state.iterations + 1, "John"));
|
||||
// }
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Options options = new OptionsBuilder()
|
||||
.include(ArrayListBenchmark.class.getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
new Runner(options).run();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,78 @@
|
|||
package com.baeldung.performance;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
@Warmup(iterations = 10)
|
||||
public class CopyOnWriteBenchmark {
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class MyState {
|
||||
|
||||
CopyOnWriteArrayList<Employee> employeeList = new CopyOnWriteArrayList<>();
|
||||
|
||||
long iterations = 100000;
|
||||
|
||||
Employee employee = new Employee(100L, "Harry");
|
||||
|
||||
int employeeIndex = -1;
|
||||
|
||||
@Setup(Level.Trial)
|
||||
public void setUp() {
|
||||
for (long i = 0; i < iterations; i++) {
|
||||
employeeList.add(new Employee(i, "John"));
|
||||
}
|
||||
|
||||
employeeList.add(employee);
|
||||
|
||||
employeeIndex = employeeList.indexOf(employee);
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void testAdd(CopyOnWriteBenchmark.MyState state) {
|
||||
state.employeeList.add(new Employee(state.iterations + 1, "John"));
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void testAddAt(CopyOnWriteBenchmark.MyState state) {
|
||||
state.employeeList.add((int) (state.iterations), new Employee(state.iterations, "John"));
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testContains(CopyOnWriteBenchmark.MyState state) {
|
||||
return state.employeeList.contains(state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int testIndexOf(CopyOnWriteBenchmark.MyState state) {
|
||||
return state.employeeList.indexOf(state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Employee testGet(CopyOnWriteBenchmark.MyState state) {
|
||||
return state.employeeList.get(state.employeeIndex);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testRemove(CopyOnWriteBenchmark.MyState state) {
|
||||
return state.employeeList.remove(state.employee);
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Options options = new OptionsBuilder()
|
||||
.include(CopyOnWriteBenchmark.class.getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
new Runner(options).run();
|
||||
}
|
||||
}
|
|
@ -10,6 +10,22 @@ public class Employee {
|
|||
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;
|
||||
|
@ -28,4 +44,12 @@ public class Employee {
|
|||
result = 31 * result + name.hashCode();
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Employee{" +
|
||||
"id=" + id +
|
||||
", name='" + name + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,73 @@
|
|||
package com.baeldung.performance;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
@Warmup(iterations = 10)
|
||||
public class HashMapBenchmark {
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class MyState {
|
||||
|
||||
Map<Long, Employee> employeeMap = new HashMap<>();
|
||||
//LinkedHashMap<Long, Employee> employeeMap = new LinkedHashMap<>();
|
||||
//IdentityHashMap<Long, Employee> employeeMap = new IdentityHashMap<>();
|
||||
//WeakHashMap<Long, Employee> employeeMap = new WeakHashMap<>();
|
||||
//ConcurrentHashMap<Long, Employee> employeeMap = new ConcurrentHashMap<>();
|
||||
//ConcurrentSkipListMap<Long, Employee> employeeMap = new ConcurrentSkipListMap <>();
|
||||
|
||||
// TreeMap
|
||||
|
||||
long iterations = 100000;
|
||||
|
||||
Employee employee = new Employee(100L, "Harry");
|
||||
|
||||
int employeeIndex = -1;
|
||||
|
||||
@Setup(Level.Trial)
|
||||
public void setUp() {
|
||||
for (long i = 0; i < iterations; i++) {
|
||||
employeeMap.put(i, new Employee(i, "John"));
|
||||
}
|
||||
|
||||
//employeeMap.put(iterations, employee);
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Employee testGet(HashMapBenchmark.MyState state) {
|
||||
return state.employeeMap.get(state.iterations);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Employee testRemove(HashMapBenchmark.MyState state) {
|
||||
return state.employeeMap.remove(state.iterations);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Employee testPut(HashMapBenchmark.MyState state) {
|
||||
return state.employeeMap.put(state.employee.getId(), state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Boolean testContainsKey(HashMapBenchmark.MyState state) {
|
||||
return state.employeeMap.containsKey(state.employee.getId());
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Options options = new OptionsBuilder()
|
||||
.include(HashMapBenchmark.class.getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
new Runner(options).run();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,66 @@
|
|||
package com.baeldung.performance;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.concurrent.ConcurrentSkipListSet;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
@Warmup(iterations = 10)
|
||||
public class SetBenchMark {
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class MyState {
|
||||
|
||||
//Set<Employee> employeeSet = new HashSet<>();
|
||||
LinkedHashSet<Employee> employeeSet = new LinkedHashSet<>();
|
||||
//ConcurrentSkipListSet<Employee> employeeSet = new ConcurrentSkipListSet <>();
|
||||
|
||||
// TreeSet
|
||||
|
||||
long iterations = 1000;
|
||||
Employee employee = new Employee(100L, "Harry");
|
||||
|
||||
@Setup(Level.Trial)
|
||||
public void setUp() {
|
||||
for (long i = 0; i < iterations; i++) {
|
||||
employeeSet.add(new Employee(i, "John"));
|
||||
}
|
||||
|
||||
//employeeSet.add(employee);
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testAdd(SetBenchMark.MyState state) {
|
||||
return state.employeeSet.add(state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Boolean testContains(SetBenchMark.MyState state) {
|
||||
return state.employeeSet.contains(state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testRemove(SetBenchMark.MyState state) {
|
||||
return state.employeeSet.remove(state.employee);
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Options options = new OptionsBuilder()
|
||||
.include(SetBenchMark.class.getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
new Runner(options).run();
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue