This commit is contained in:
Sandip Singh 2018-10-12 20:47:51 +05:30
commit 76d08376f3
2114 changed files with 39940 additions and 11685 deletions

2
.gitignore vendored
View File

@ -62,3 +62,5 @@ jmeter/src/main/resources/*-JMeter.csv
**/dist
**/tmp
**/out-tsc
**/nbproject/
**/nb-configuration.xml

View File

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

View File

@ -2,41 +2,27 @@
The "REST with Spring" Classes
==============================
After 5 months of work, here's the Master Class of REST With Spring: <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)
Building a single module
====================
To build a specific module run the command: `mvn clean install -Dgib.enabled=false` in the module directory

View File

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

View File

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

View File

@ -16,4 +16,8 @@ public class Employee extends Model {
set("created_by",createdBy);
}
public String getLastName() {
return getString("last_name");
}
}

View File

@ -15,4 +15,8 @@ public class Role extends Model {
set("role_name",role);
set("created_by",createdBy);
}
public String getRoleName() {
return getString("role_name");
}
}

View File

@ -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() {

View File

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

View File

@ -0,0 +1 @@
/bin/

View File

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

View File

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

View File

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

View File

@ -0,0 +1,41 @@
package com.baeldung.algorithms.insertionsort;
public class InsertionSort {
public static void insertionSortImperative(int[] input) {
for (int i = 1; i < input.length; i++) {
int key = input[i];
int j = i - 1;
while (j >= 0 && input[j] > key) {
input[j + 1] = input[j];
j = j - 1;
}
input[j + 1] = key;
}
}
public static void insertionSortRecursive(int[] input) {
insertionSortRecursive(input, input.length);
}
private static void insertionSortRecursive(int[] input, int i) {
// base case
if (i <= 1) {
return;
}
// sort the first i - 1 elements of the array
insertionSortRecursive(input, i - 1);
// then find the correct position of the element at position i
int key = input[i - 1];
int j = i - 2;
// shifting the elements from their position by 1
while (j >= 0 && input[j] > key) {
input[j + 1] = input[j];
j = j - 1;
}
// inserting the key at the appropriate position
input[j + 1] = key;
}
}

View File

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

View File

@ -0,0 +1,21 @@
package com.baeldung.algorithms.linesintersection;
import java.awt.Point;
import java.util.Optional;
public class LinesIntersectionService {
public Optional<Point> calculateIntersectionPoint(double m1, double b1, double m2, double b2) {
if (m1 == m2) {
return Optional.empty();
}
double x = (b2 - b1) / (m1 - m2);
double y = m1 * x + b1;
Point point = new Point();
point.setLocation(x, y);
return Optional.of(point);
}
}

View File

@ -87,7 +87,7 @@ public class State {
void randomPlay() {
List<Position> availablePositions = this.board.getEmptyPositions();
int totalPossibilities = availablePositions.size();
int selectRandom = (int) (Math.random() * ((totalPossibilities - 1) + 1));
int selectRandom = (int) (Math.random() * totalPossibilities);
this.board.performMove(this.playerNo, availablePositions.get(selectRandom));
}

View File

@ -65,7 +65,7 @@ public class Node {
public Node getRandomChildNode() {
int noOfPossibleMoves = this.childArray.size();
int selectRandom = (int) (Math.random() * ((noOfPossibleMoves - 1) + 1));
int selectRandom = (int) (Math.random() * noOfPossibleMoves);
return this.childArray.get(selectRandom);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,35 @@
package com.baeldung.algorithms.string;
public class EnglishAlphabetLetters {
public static boolean checkStringForAllTheLetters(String input) {
boolean[] visited = new boolean[26];
int index = 0;
for (int id = 0; id < input.length(); id++) {
if ('a' <= input.charAt(id) && input.charAt(id) <= 'z') {
index = input.charAt(id) - 'a';
} else if ('A' <= input.charAt(id) && input.charAt(id) <= 'Z') {
index = input.charAt(id) - 'A';
}
visited[index] = true;
}
for (int id = 0; id < 26; id++) {
if (!visited[id]) {
return false;
}
}
return true;
}
public static boolean checkStringForAllLetterUsingStream(String input) {
long c = input.toLowerCase().chars().filter(ch -> ch >= 'a' && ch <= 'z').distinct().count();
return c == 26;
}
public static void main(String[] args) {
checkStringForAllLetterUsingStream("intit");
}
}

View File

@ -1,4 +1,4 @@
package algorithms;
package com.baeldung.algorithms;
import org.junit.Assert;
import org.junit.Test;

View File

@ -1,4 +1,4 @@
package algorithms;
package com.baeldung.algorithms;
import org.junit.Assert;
import org.junit.Test;

View File

@ -1,4 +1,4 @@
package algorithms;
package com.baeldung.algorithms;
import com.baeldung.algorithms.hillclimbing.HillClimbing;
import com.baeldung.algorithms.hillclimbing.State;

View File

@ -1,4 +1,4 @@
package algorithms;
package com.baeldung.algorithms;
import com.baeldung.algorithms.middleelementlookup.MiddleElementLookup;
import com.baeldung.algorithms.middleelementlookup.Node;

View File

@ -1,4 +1,4 @@
package algorithms;
package com.baeldung.algorithms;
import com.baeldung.algorithms.automata.*;
import org.junit.Test;

View File

@ -1,4 +1,4 @@
package algorithms;
package com.baeldung.algorithms;
import org.junit.Assert;
import org.junit.Test;

View File

@ -1,4 +1,4 @@
package algorithms;
package com.baeldung.algorithms;
import org.junit.Assert;

View File

@ -1,4 +1,4 @@
package algorithms.binarysearch;
package com.baeldung.algorithms.binarysearch;
import java.util.Arrays;
import java.util.List;

View File

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

View File

@ -0,0 +1,25 @@
package com.baeldung.algorithms.insertionsort;
import com.baeldung.algorithms.insertionsort.InsertionSort;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
public class InsertionSortUnitTest {
@Test
public void givenUnsortedArray_whenInsertionSortImperative_thenSortedAsc() {
int[] input = {6, 2, 3, 4, 5, 1};
InsertionSort.insertionSortImperative(input);
int[] expected = {1, 2, 3, 4, 5, 6};
assertArrayEquals("the two arrays are not equal", expected, input);
}
@Test
public void givenUnsortedArray_whenInsertionSortRecursive_thenSortedAsc() {
int[] input = {6, 4, 5, 2, 3, 1};
InsertionSort.insertionSortRecursive(input);
int[] expected = {1, 2, 3, 4, 5, 6};
assertArrayEquals("the two arrays are not equal", expected, input);
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.algorithms.linesintersection;
import java.awt.Point;
import java.util.Optional;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertEquals;
public class LinesIntersectionServiceUnitTest {
private LinesIntersectionService service = new LinesIntersectionService();
@Test
public void givenNotParallelLines_whenCalculatePoint_thenPresent() {
double m1 = 0;
double b1 = 0;
double m2 = 1;
double b2 = -1;
Optional<Point> point = service.calculateIntersectionPoint(m1, b1, m2, b2);
assertTrue(point.isPresent());
assertEquals(point.get().getX(), 1, 0.001);
assertEquals(point.get().getY(), 0, 0.001);
}
@Test
public void givenParallelLines_whenCalculatePoint_thenEmpty() {
double m1 = 1;
double b1 = 0;
double m2 = 1;
double b2 = -1;
Optional<Point> point = service.calculateIntersectionPoint(m1, b1, m2, b2);
assertFalse(point.isPresent());
}
}

View File

@ -1,4 +1,4 @@
package algorithms.mcts;
package com.baeldung.algorithms.mcts;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

View File

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

View File

@ -1,4 +1,4 @@
package algorithms.minimax;
package com.baeldung.algorithms.minimax;
import org.junit.Before;
import org.junit.Test;

View File

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

View File

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

View File

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

View File

@ -0,0 +1,20 @@
package com.baeldung.algorithms.string;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class EnglishAlphabetLettersUnitTest {
@Test
void givenString_whenContainsAllCharacter_thenTrue() {
String input = "Farmer jack realized that big yellow quilts were expensive";
Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllTheLetters(input));
}
@Test
void givenString_whenContainsAllCharacter_thenUsingStreamExpectTrue() {
String input = "Farmer jack realized that big yellow quilts were expensive";
Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllLetterUsingStream(input));
}
}

View File

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

View File

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

View File

@ -5,29 +5,37 @@ import org.apache.avro.io.DatumReader;
import org.apache.avro.io.Decoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.specific.SpecificDatumReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class AvroDeSerealizer {
public AvroHttpRequest deSerealizeAvroHttpRequestJSON(byte[] data){
DatumReader<AvroHttpRequest> reader = new SpecificDatumReader<>(AvroHttpRequest.class);
Decoder decoder = null;
try {
decoder = DecoderFactory.get().jsonDecoder(AvroHttpRequest.getClassSchema(), new String(data));
return reader.read(null, decoder);
} catch (IOException e) {
return null;
}
}
private static Logger logger = LoggerFactory.getLogger(AvroDeSerealizer.class);
public AvroHttpRequest deSerealizeAvroHttpRequestBinary(byte[] data){
DatumReader<AvroHttpRequest> employeeReader = new SpecificDatumReader<>(AvroHttpRequest.class);
Decoder decoder = DecoderFactory.get().binaryDecoder(data, null);
try {
return employeeReader.read(null, decoder);
} catch (IOException e) {
public AvroHttpRequest deSerealizeAvroHttpRequestJSON(byte[] data) {
DatumReader<AvroHttpRequest> reader = new SpecificDatumReader<>(AvroHttpRequest.class);
Decoder decoder = null;
try {
decoder = DecoderFactory.get()
.jsonDecoder(AvroHttpRequest.getClassSchema(), new String(data));
return reader.read(null, decoder);
} catch (IOException e) {
logger.error("Deserialization error" + e.getMessage());
}
return null;
}
public AvroHttpRequest deSerealizeAvroHttpRequestBinary(byte[] data) {
DatumReader<AvroHttpRequest> employeeReader = new SpecificDatumReader<>(AvroHttpRequest.class);
Decoder decoder = DecoderFactory.get()
.binaryDecoder(data, null);
try {
return employeeReader.read(null, decoder);
} catch (IOException e) {
logger.error("Deserialization error" + e.getMessage());
}
return null;
}
}
}

View File

@ -3,42 +3,48 @@ package com.baeldung.avro.util.serealization;
import com.baeldung.avro.util.model.AvroHttpRequest;
import org.apache.avro.io.*;
import org.apache.avro.specific.SpecificDatumWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class AvroSerealizer {
public byte[] serealizeAvroHttpRequestJSON(AvroHttpRequest request){
DatumWriter<AvroHttpRequest> writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
byte[] data = new byte[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Encoder jsonEncoder = null;
try {
jsonEncoder = EncoderFactory.get().jsonEncoder(AvroHttpRequest.getClassSchema(), stream);
writer.write(request, jsonEncoder);
jsonEncoder.flush();
data = stream.toByteArray();
} catch (IOException e) {
data =null;
}
return data;
}
private static final Logger logger = LoggerFactory.getLogger(AvroSerealizer.class);
public byte[] serealizeAvroHttpRequestBinary(AvroHttpRequest request){
DatumWriter<AvroHttpRequest> writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
byte[] data = new byte[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Encoder jsonEncoder = EncoderFactory.get().binaryEncoder(stream,null);
try {
writer.write(request, jsonEncoder);
jsonEncoder.flush();
data = stream.toByteArray();
} catch (IOException e) {
data = null;
public byte[] serealizeAvroHttpRequestJSON(AvroHttpRequest request) {
DatumWriter<AvroHttpRequest> writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
byte[] data = new byte[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Encoder jsonEncoder = null;
try {
jsonEncoder = EncoderFactory.get()
.jsonEncoder(AvroHttpRequest.getClassSchema(), stream);
writer.write(request, jsonEncoder);
jsonEncoder.flush();
data = stream.toByteArray();
} catch (IOException e) {
logger.error("Serialization error " + e.getMessage());
}
return data;
}
return data;
}
public byte[] serealizeAvroHttpRequestBinary(AvroHttpRequest request) {
DatumWriter<AvroHttpRequest> writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
byte[] data = new byte[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Encoder jsonEncoder = EncoderFactory.get()
.binaryEncoder(stream, null);
try {
writer.write(request, jsonEncoder);
jsonEncoder.flush();
data = stream.toByteArray();
} catch (IOException e) {
logger.error("Serialization error " + e.getMessage());
}
return data;
}
}

View File

@ -1,75 +0,0 @@
package com.baeldung.avro.util.serealization;
import com.baeldung.avro.util.model.Active;
import com.baeldung.avro.util.model.AvroHttpRequest;
import com.baeldung.avro.util.model.ClientIdentifier;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static org.junit.Assert.*;
public class AvroSerealizerDeSerealizerTest {
AvroSerealizer serealizer;
AvroDeSerealizer deSerealizer;
AvroHttpRequest request;
@Before
public void setUp() throws Exception {
serealizer = new AvroSerealizer();
deSerealizer = new AvroDeSerealizer();
ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder().
setHostName("localhost").setIpAddress("255.255.255.0").build();
List<CharSequence> employees = new ArrayList();
employees.add("James");
employees.add("Alice");
employees.add("David");
employees.add("Han");
request = AvroHttpRequest.newBuilder().setRequestTime(01l)
.setActive(Active.YES).setClientIdentifier(clientIdentifier)
.setEmployeeNames(employees).build();
}
@After
public void tearDown() throws Exception {
}
@Test
public void WhenSerialized_UsingJSONEncoder_ObjectGetsSerialized(){
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
assertTrue(Objects.nonNull(data));
assertTrue(data.length > 0);
}
@Test
public void WhenSerialized_UsingBinaryEncoder_ObjectGetsSerialized(){
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
assertTrue(Objects.nonNull(data));
assertTrue(data.length > 0);
}
@Test
public void WhenDeserialize_UsingJSONDecoder_ActualAndExpectedObjectsAreEqual(){
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data);
assertEquals(actualRequest,request);
assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime()));
}
@Test
public void WhenDeserialize_UsingBinaryecoder_ActualAndExpectedObjectsAreEqual(){
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data);
assertEquals(actualRequest,request);
assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime()));
}
}

View File

@ -0,0 +1,83 @@
package com.baeldung.avro.util.serealization;
import com.baeldung.avro.util.model.Active;
import com.baeldung.avro.util.model.AvroHttpRequest;
import com.baeldung.avro.util.model.ClientIdentifier;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static org.junit.Assert.*;
public class AvroSerealizerDeSerealizerUnitTest {
AvroSerealizer serealizer;
AvroDeSerealizer deSerealizer;
AvroHttpRequest request;
@Before
public void setUp() throws Exception {
serealizer = new AvroSerealizer();
deSerealizer = new AvroDeSerealizer();
ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder()
.setHostName("localhost")
.setIpAddress("255.255.255.0")
.build();
List<CharSequence> employees = new ArrayList();
employees.add("James");
employees.add("Alice");
employees.add("David");
employees.add("Han");
request = AvroHttpRequest.newBuilder()
.setRequestTime(01l)
.setActive(Active.YES)
.setClientIdentifier(clientIdentifier)
.setEmployeeNames(employees)
.build();
}
@After
public void tearDown() throws Exception {
}
@Test
public void WhenSerializedUsingJSONEncoder_thenObjectGetsSerialized() {
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
assertTrue(Objects.nonNull(data));
assertTrue(data.length > 0);
}
@Test
public void WhenSerializedUsingBinaryEncoder_thenObjectGetsSerialized() {
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
assertTrue(Objects.nonNull(data));
assertTrue(data.length > 0);
}
@Test
public void WhenDeserializeUsingJSONDecoder_thenActualAndExpectedObjectsAreEqual() {
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data);
assertEquals(actualRequest, request);
assertTrue(actualRequest.getRequestTime()
.equals(request.getRequestTime()));
}
@Test
public void WhenDeserializeUsingBinaryecoder_thenActualAndExpectedObjectsAreEqual() {
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data);
assertEquals(actualRequest, request);
assertTrue(actualRequest.getRequestTime()
.equals(request.getRequestTime()));
}
}

View File

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

View File

@ -20,7 +20,7 @@
</properties>
<build>
<finalName>${artifactId}</finalName>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>net.wasdev.wlp.maven.plugins</groupId>

View File

@ -2,7 +2,7 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>

View File

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

View File

@ -39,6 +39,7 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>${build-helper-maven-plugin.version}</version>
<executions>
<execution>
<phase>generate-sources</phase>
@ -60,6 +61,7 @@
<thrift.version>0.10.0</thrift.version>
<maven-thrift.version>0.1.11</maven-thrift.version>
<org.slf4j.slf4j-simple.version>1.7.12</org.slf4j.slf4j-simple.version>
<build-helper-maven-plugin.version>3.0.0</build-helper-maven-plugin.version>
</properties>
</project>

View File

@ -2,7 +2,7 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>

View File

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

View File

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

View File

@ -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() {

View File

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

View File

@ -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
aws/.gitignore vendored
View File

@ -1 +1,2 @@
/target/
.idea/

View File

@ -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>
@ -137,14 +117,13 @@
<aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version>
<gson.version>2.8.0</gson.version>
<aws-java-sdk.version>1.11.290</aws-java-sdk.version>
<mockito-core.version>2.8.9</mockito-core.version>
<mockito-core.version>2.21.0</mockito-core.version>
<assertj-core.version>3.8.0</assertj-core.version>
<dynamodblocal.version>1.11.86</dynamodblocal.version>
<dynamodblocal.repository.url>https://s3-us-west-2.amazonaws.com/dynamodb-local/release</dynamodblocal.repository.url>
<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>

View File

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

View File

@ -0,0 +1,4 @@
db_hostname=<RDS EndPoint>
db_username=username
db_password=password
db_database=mydb

View File

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

View File

@ -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,14 +195,12 @@
<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>
</project>
</project>

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,2 @@
com.baeldung.cdi.extension.FlywayExtension

View File

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

View File

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

View File

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

View File

@ -0,0 +1,4 @@
create table PERSON (
ID int not null,
NAME varchar(100) not null
);

View File

@ -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');

View File

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

View File

@ -1,70 +1,91 @@
package com.baeldung.test.dependencyinjection;
import com.baeldung.dependencyinjection.imagefileeditors.GifFileEditor;
import com.baeldung.dependencyinjection.imagefileeditors.JpgFileEditor;
import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor;
import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor;
import com.baeldung.dependencyinjection.loggers.TimeLogger;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.within;
import java.text.ParseException;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor;
import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor;
import com.baeldung.dependencyinjection.loggers.TimeLogger;
public class ImageProcessorUnitTest {
private static ImageFileProcessor imageFileProcessor;
private static SimpleDateFormat dateFormat;
private static Calendar calendar;
@BeforeClass
public static void setImageProcessorInstance() {
Weld weld = new Weld();
WeldContainer container = weld.initialize();
imageFileProcessor = container.select(ImageFileProcessor.class).get();
imageFileProcessor = container.select(ImageFileProcessor.class)
.get();
container.shutdown();
}
@BeforeClass
public static void setSimpleDateFormatInstance() {
dateFormat = new SimpleDateFormat("HH:mm");
}
@BeforeClass
public static void setCalendarInstance() {
calendar = Calendar.getInstance();
}
@Test
public void givenImageProcessorInstance_whenInjectedPngFileEditorandTimeLoggerInstances_thenTwoAssertions() {
assertThat(imageFileProcessor.getImageFileditor()).isInstanceOf(PngFileEditor.class);
assertThat(imageFileProcessor.getTimeLogger()).isInstanceOf(TimeLogger.class);
}
@Test
public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() {
String currentTime = dateFormat.format(calendar.getTime());
assertThat(imageFileProcessor.openFile("file1.png")).isEqualTo("Opening PNG file file1.png at: " + currentTime);
public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() throws ParseException {
LocalTime currentTime = LocalTime.now();
String openFileLog = imageFileProcessor.openFile("file1.png");
assertThat(openFileLog).contains("Opening PNG file file1.png at: ");
LocalTime loggedTime = getLoggedTime(openFileLog);
assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
}
@Test
public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() {
String currentTime = dateFormat.format(calendar.getTime());
assertThat(imageFileProcessor.editFile("file1.png")).isEqualTo("Editing PNG file file1.png at: " + currentTime);
public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() throws ParseException {
LocalTime currentTime = LocalTime.now();
String editFileLog = imageFileProcessor.editFile("file1.png");
assertThat(editFileLog).contains("Editing PNG file file1.png at: ");
LocalTime loggedTime = getLoggedTime(editFileLog);
assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
}
@Test
public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() {
String currentTime = dateFormat.format(calendar.getTime());
assertThat(imageFileProcessor.writeFile("file1.png")).isEqualTo("Writing PNG file file1.png at: " + currentTime);
public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() throws ParseException {
LocalTime currentTime = LocalTime.now();
String writeFileLog = imageFileProcessor.writeFile("file1.png");
assertThat(writeFileLog).contains("Writing PNG file file1.png at: ");
LocalTime loggedTime = getLoggedTime(writeFileLog);
assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
}
@Test
public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() {
String currentTime = dateFormat.format(calendar.getTime());
assertThat(imageFileProcessor.saveFile("file1.png")).isEqualTo("Saving PNG file file1.png at: " + currentTime);
public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() throws ParseException {
LocalTime currentTime = LocalTime.now();
String saveFileLog = imageFileProcessor.saveFile("file1.png");
assertThat(saveFileLog).contains("Saving PNG file file1.png at: ");
LocalTime loggedTime = getLoggedTime(saveFileLog);
assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
}
private LocalTime getLoggedTime(String log) throws ParseException {
String logTimeString = log.split("at: ")[1];
int hour = Integer.valueOf(logTimeString.split(":")[0]);
int minutes = Integer.valueOf(logTimeString.split(":")[1]);
LocalTime loggedTime = LocalTime.of(hour, minutes);
return loggedTime;
}
}

View File

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

View File

@ -9,54 +9,26 @@
- [Java 8 New Features](http://www.baeldung.com/java-8-new-features)
- [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips)
- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator)
- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams)
- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction)
- [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector)
- [Strategy Design Pattern in Java 8](http://www.baeldung.com/java-strategy-pattern)
- [Java 8 and Infinite Streams](http://www.baeldung.com/java-inifinite-streams)
- [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings)
- [Exceptions in Java 8 Lambda Expressions](http://www.baeldung.com/java-lambda-exceptions)
- [Java 8 Stream findFirst() vs. findAny()](http://www.baeldung.com/java-stream-findfirst-vs-findany)
- [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing)
- [How to Get the Last Element of a Stream in Java?](http://www.baeldung.com/java-stream-last-element)
- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro)
- [Migrating to the New Java 8 Date Time API](http://www.baeldung.com/migrating-to-java-8-date-time-api)
- [Guide To Java 8 Optional](http://www.baeldung.com/java-optional)
- [Guide to the Java 8 forEach](http://www.baeldung.com/foreach-java)
- [Get the Current Date, Time and Timestamp in Java 8](http://www.baeldung.com/current-date-time-and-timestamp-in-java-8)
- [TemporalAdjuster in Java](http://www.baeldung.com/java-temporal-adjuster)
- [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)
- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams)
- [“Stream has already been operated upon or closed” Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception)
- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones)
- [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)
- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream)
- [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream)
- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices)
- [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency)
- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams)
- [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)
- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner)
- [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)
- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time)
- [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)
- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end)
- [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference)
- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string)
- [Calculate Age in Java](http://www.baeldung.com/java-get-age)
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
- [Increment Date in Java](http://www.baeldung.com/java-increment-date)
- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date)
- [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)

View File

@ -89,11 +89,6 @@
<artifactId>vavr</artifactId>
<version>${vavr.version}</version>
</dependency>
<dependency>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>${streamex.version}</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
@ -121,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>
@ -151,6 +129,7 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot-maven-plugin.version}</version>
<executions>
<execution>
<goals>
@ -176,7 +155,6 @@
<lombok.version>1.16.12</lombok.version>
<vavr.version>0.9.0</vavr.version>
<protonpack.version>1.13</protonpack.version>
<streamex.version>0.6.5</streamex.version>
<joda.version>2.10</joda.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
@ -184,6 +162,6 @@
<avaitility.version>1.7.0</avaitility.version>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator.version>1.19</jmh-generator.version>
<spring-boot-maven-plugin.version>2.0.4.RELEASE</spring-boot-maven-plugin.version>
</properties>
</project>
</project>

View File

@ -0,0 +1,9 @@
package com.baeldung.optional;
public class PersonRepository {
public String findNameById(String id) {
return id == null ? null : "Name";
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.primitive;
public class BenchmarkRunner {
public static void main(String[] args) throws Exception {
new IntPrimitiveLookup().run();
new IntegerWrapperLookup().run();
new FloatPrimitiveLookup().run();
new FloatWrapperLookup().run();
new DoublePrimitiveLookup().run();
new DoubleWrapperLookup().run();
new ShortPrimitiveLookup().run();
new ShortWrapperLookup().run();
new BooleanPrimitiveLookup().run();
new BooleanWrapperLookup().run();
new CharPrimitiveLookup().run();
new CharacterWrapperLookup().run();
new BytePrimitiveLookup().run();
new ByteWrapperLookup().run();
new LongPrimitiveLookup().run();
new LongWrapperLookup().run();
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class BooleanPrimitiveLookup extends Lookup {
private boolean[] elements;
private final boolean pivot = false;
@Setup
@Override
public void prepare() {
elements = new boolean[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = true;
}
elements[s - 1] = pivot;
}
@TearDown
@Override
public void clean() {
elements = null;
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
while (pivot != elements[index]) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return BooleanPrimitiveLookup.class.getSimpleName();
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class BooleanWrapperLookup extends Lookup {
private Boolean[] elements;
private final boolean pivot = false;
@Override
@Setup
public void prepare() {
elements = new Boolean[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = true;
}
elements[s - 1] = pivot;
}
@Override
@TearDown
public void clean() {
elements = null;
}
@Override
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
Boolean pivotWrapper = pivot;
while (!pivotWrapper.equals(elements[index])) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return BooleanWrapperLookup.class.getSimpleName();
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class BytePrimitiveLookup extends Lookup {
private byte[] elements;
private final byte pivot = 2;
@Setup
@Override
public void prepare() {
byte common = 1;
elements = new byte[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@TearDown
@Override
public void clean() {
elements = null;
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
while (pivot != elements[index]) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return BytePrimitiveLookup.class.getSimpleName();
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class ByteWrapperLookup extends Lookup {
private Byte[] elements;
private final byte pivot = 2;
@Override
@Setup
public void prepare() {
byte common = 1;
elements = new Byte[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@Override
@TearDown
public void clean() {
elements = null;
}
@Override
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
Byte pivotWrapper = pivot;
while (!pivotWrapper.equals(elements[index])) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return ByteWrapperLookup.class.getSimpleName();
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class CharPrimitiveLookup extends Lookup {
private char[] elements;
private final char pivot = 'b';
@Setup
@Override
public void prepare() {
char common = 'a';
elements = new char[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@TearDown
@Override
public void clean() {
elements = null;
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
while (pivot != elements[index]) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return CharPrimitiveLookup.class.getSimpleName();
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class CharacterWrapperLookup extends Lookup {
private Character[] elements;
private final char pivot = 'b';
@Override
@Setup
public void prepare() {
char common = 'a';
elements = new Character[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@Override
@TearDown
public void clean() {
elements = null;
}
@Override
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
Character pivotWrapper = pivot;
while (!pivotWrapper.equals(elements[index])) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return CharacterWrapperLookup.class.getSimpleName();
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class DoublePrimitiveLookup extends Lookup {
private double[] elements;
private final double pivot = 2;
@Setup
@Override
public void prepare() {
double common = 1;
elements = new double[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@TearDown
@Override
public void clean() {
elements = null;
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
while (pivot != elements[index]) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return DoublePrimitiveLookup.class.getSimpleName();
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class DoubleWrapperLookup extends Lookup {
private Double[] elements;
private final double pivot = 2d;
@Override
@Setup
public void prepare() {
double common = 1;
elements = new Double[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@Override
@TearDown
public void clean() {
elements = null;
}
@Override
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
Double pivotWrapper = pivot;
while (!pivotWrapper.equals(elements[index])) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return DoubleWrapperLookup.class.getSimpleName();
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class FloatPrimitiveLookup extends Lookup {
private float[] elements;
private final float pivot = 2;
@Setup
@Override
public void prepare() {
int common = 1;
elements = new float[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@TearDown
@Override
public void clean() {
elements = null;
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
while (pivot != elements[index]) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return FloatPrimitiveLookup.class.getSimpleName();
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class FloatWrapperLookup extends Lookup {
private Float[] elements;
private final float pivot = 2;
@Override
@Setup
public void prepare() {
float common = 1;
elements = new Float[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@Override
@TearDown
public void clean() {
elements = null;
}
@Override
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
Float pivotWrapper = pivot;
while (!pivotWrapper.equals(elements[index])) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return FloatWrapperLookup.class.getSimpleName();
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class IntPrimitiveLookup extends Lookup {
private int[] elements;
private final int pivot = 2;
@Setup
@Override
public void prepare() {
int common = 1;
elements = new int[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@TearDown
@Override
public void clean() {
elements = null;
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
while (pivot != elements[index]) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return IntPrimitiveLookup.class.getSimpleName();
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class IntegerWrapperLookup extends Lookup {
private Integer[] elements;
private final int pivot = 2;
@Override
@Setup
public void prepare() {
int common = 1;
elements = new Integer[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@Override
@TearDown
public void clean() {
elements = null;
}
@Override
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
Integer pivotWrapper = pivot;
while (!pivotWrapper.equals(elements[index])) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return IntegerWrapperLookup.class.getSimpleName();
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class LongPrimitiveLookup extends Lookup {
private long[] elements;
private final long pivot = 2;
@Setup
@Override
public void prepare() {
long common = 1;
elements = new long[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@TearDown
@Override
public void clean() {
elements = null;
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
while (pivot != elements[index]) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return LongPrimitiveLookup.class.getSimpleName();
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class LongWrapperLookup extends Lookup{
private Long[] elements;
private final long pivot = 2;
@Override
@Setup
public void prepare() {
long common = 1;
elements = new Long[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@Override
@TearDown
public void clean() {
elements = null;
}
@Override
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
Long pivotWrapper = pivot;
while (!pivotWrapper.equals(elements[index])) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return LongWrapperLookup.class.getSimpleName();
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.primitive;
import org.openjdk.jmh.results.RunResult;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.Collection;
/**
* An abstract class that is to be extended by the classes that
* perform lookup in the arrays either of Java primitive types or their wrappers.
*/
public abstract class Lookup {
/**
* the array size
*/
final protected int s = 50000000;
/**
* Initialize the array: fill in the array with the same
* elements except for the last one.
*/
abstract public void prepare();
/**
* Free the array's reference.
*/
abstract public void clean();
/**
* Find the position of the element that is different from the others.
* By construction, it is the last array element.
*
* @return array's last element index
*/
abstract public int findPosition();
/**
* Get the name of the class that extends this one. It is needed in order
* to set up the benchmark.
*
* @return
*/
abstract public String getSimpleClassName();
Collection<RunResult> run() throws RunnerException {
Options opt = new OptionsBuilder()
.include(getSimpleClassName())
.forks(1)
.build();
return new Runner(opt).run();
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class ShortPrimitiveLookup extends Lookup {
private short[] elements;
private final short pivot = 2;
@Setup
@Override
public void prepare() {
short common = 1;
elements = new short[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@TearDown
@Override
public void clean() {
elements = null;
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
while (pivot != elements[index]) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return ShortPrimitiveLookup.class.getSimpleName();
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.primitive;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
public class ShortWrapperLookup extends Lookup {
private Short[] elements;
private final short pivot = 2;
@Override
@Setup
public void prepare() {
short common = 1;
elements = new Short[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@Override
@TearDown
public void clean() {
elements = null;
}
@Override
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
Short pivotWrapper = pivot;
while (!pivotWrapper.equals(elements[index])) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return ShortWrapperLookup.class.getSimpleName();
}
}

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