Merge branch 'master' of https://github.com/vikasrajput6035/tutorials into BAEL-4936

This commit is contained in:
Vikas Ramsingh Rajput 2021-05-16 09:34:51 +05:30
commit dd73b72fc9
6089 changed files with 116312 additions and 47802 deletions

6
.gitignore vendored
View File

@ -85,5 +85,9 @@ transaction.log
*-shell.log
apache-cxf/cxf-aegis/baeldung.xml
testing-modules/report-*.json
libraries-2/*.db
libraries-2/*.db
# SDKMan
.sdkmanrc

View File

@ -1,5 +1,3 @@
**UPDATE**: The price of "Learn Spring Security OAuth" will permanently change on the 11th of December, along with the upcoming OAuth2 material: http://bit.ly/github-lss
The Courses
==============================

View File

@ -38,8 +38,6 @@
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<akka.http.version>10.0.11</akka.http.version>
<akka.stream.version>2.5.11</akka.stream.version>
</properties>

View File

@ -5,6 +5,6 @@ This module contains articles about genetic algorithms.
### Relevant articles:
- [Introduction to Jenetics Library](https://www.baeldung.com/jenetics)
- [Ant Colony Optimization](https://www.baeldung.com/java-ant-colony-optimization)
- [Ant Colony Optimization with a Java Example](https://www.baeldung.com/java-ant-colony-optimization)
- [Design a Genetic Algorithm in Java](https://www.baeldung.com/java-genetic-algorithm)
- [The Traveling Salesman Problem in Java](https://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)

View File

@ -44,18 +44,6 @@
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<properties>
<commons-math3.version>3.6.1</commons-math3.version>
<io.jenetics.version>3.7.0</io.jenetics.version>

View File

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

View File

@ -49,18 +49,6 @@
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<reporting>
<plugins>
<plugin>

View File

@ -14,4 +14,4 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
- [Displaying Money Amounts in Words](https://www.baeldung.com/java-money-into-words)
- [A Collaborative Filtering Recommendation System in Java](https://www.baeldung.com/java-collaborative-filtering-recommendations)
- [Implementing A* Pathfinding in Java](https://www.baeldung.com/java-a-star-pathfinding)
- More articles: [[<-- prev]](/../algorithms-miscellaneous-1) [[next -->]](/../algorithms-miscellaneous-3)
- More articles: [[<-- prev]](/algorithms-miscellaneous-1) [[next -->]](/algorithms-miscellaneous-3)

View File

@ -54,18 +54,6 @@
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<reporting>
<plugins>
<plugin>

View File

@ -74,25 +74,11 @@
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<properties>
<org.assertj.core.version>3.9.0</org.assertj.core.version>
<commons-collections4.version>4.3</commons-collections4.version>
<guava.version>28.0-jre</guava.version>
<retrofit.version>2.6.0</retrofit.version>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator.version>1.19</jmh-generator.version>
<commons.lang3.version>3.8.1</commons.lang3.version>
<JUnitParams.version>1.1.0</JUnitParams.version>
</properties>

View File

@ -5,8 +5,8 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
### Relevant articles:
- [Multi-Swarm Optimization Algorithm in Java](https://www.baeldung.com/java-multi-swarm-algorithm)
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
- [Find the Middle Element of a Linked List](https://www.baeldung.com/java-linked-list-middle-element)
- [Check If a String Contains All The Letters of The Alphabet with Java](https://www.baeldung.com/java-string-contains-all-letters)
- [Find the Middle Element of a Linked List in Java](https://www.baeldung.com/java-linked-list-middle-element)
- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)
- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)

View File

@ -34,18 +34,6 @@
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<properties>
<org.assertj.core.version>3.9.0</org.assertj.core.version>
<guava.version>27.0.1-jre</guava.version>

View File

@ -9,11 +9,11 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
- [Reversing a Binary Tree in Java](https://www.baeldung.com/java-reversing-a-binary-tree)
- [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers)
- [Knapsack Problem Implementation in Java](https://www.baeldung.com/java-knapsack)
- [How to Determine if a Binary Tree is Balanced](https://www.baeldung.com/java-balanced-binary-tree)
- [How to Determine if a Binary Tree is Balanced in Java](https://www.baeldung.com/java-balanced-binary-tree)
- [Overview of Combinatorial Problems in Java](https://www.baeldung.com/java-combinatorial-algorithms)
- [Prims Algorithm](https://www.baeldung.com/java-prim-algorithm)
- [Maximum Subarray Problem](https://www.baeldung.com/java-maximum-subarray)
- [How to Merge Two Sorted Arrays](https://www.baeldung.com/java-merge-sorted-arrays)
- [Median of Stream of Integers using Heap](https://www.baeldung.com/java-stream-integers-median-using-heap)
- More articles: [[<-- prev]](/../algorithms-miscellaneous-4) [[next -->]](/../algorithms-miscellaneous-6)
- [Prims Algorithm with a Java Implementation](https://www.baeldung.com/java-prim-algorithm)
- [Maximum Subarray Problem in Java](https://www.baeldung.com/java-maximum-subarray)
- [How to Merge Two Sorted Arrays in Java](https://www.baeldung.com/java-merge-sorted-arrays)
- [Median of Stream of Integers using Heap in Java](https://www.baeldung.com/java-stream-integers-median-using-heap)
- More articles: [[<-- prev]](/algorithms-miscellaneous-4) [[next -->]](/algorithms-miscellaneous-6)

View File

@ -49,18 +49,6 @@
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<properties>
<tradukisto.version>1.0.1</tradukisto.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version>

View File

@ -13,22 +13,22 @@ public class KadaneAlgorithm {
int start = 0;
int end = 0;
int maxSoFar = 0, maxEndingHere = 0;
int maxSoFar = arr[0], maxEndingHere = arr[0];
for (int i = 0; i < size; i++) {
if (arr[i] > maxEndingHere + arr[i]) {
start = i;
maxEndingHere = arr[i];
} else
} else {
maxEndingHere = maxEndingHere + arr[i];
}
if (maxSoFar < maxEndingHere) {
maxSoFar = maxEndingHere;
end = i;
}
}
logger.info("Found Maximum Subarray between {} and {}", start, end);
logger.info("Found Maximum Subarray between {} and {}", Math.min(start, end), end);
return maxSoFar;
}
}

View File

@ -9,11 +9,22 @@ class KadaneAlgorithmUnitTest {
@Test
void givenArrayWithNegativeNumberWhenMaximumSubarrayThenReturns6() {
//given
int[] arr = new int[]{-3, 1, -8, 4, -1, 2, 1, -5, 5};
int[] arr = new int[] { -3, 1, -8, 4, -1, 2, 1, -5, 5 };
//when
KadaneAlgorithm algorithm = new KadaneAlgorithm();
int maxSum = algorithm.maxSubArraySum(arr);
//then
assertEquals(6, maxSum);
}
@Test
void givenArrayWithAllNegativeNumbersWhenMaximumSubarrayThenReturnsExpectedResult() {
//given
int[] arr = new int[] { -8, -7, -5, -4, -3, -1, -2 };
//when
KadaneAlgorithm algorithm = new KadaneAlgorithm();
int maxSum = algorithm.maxSubArraySum(arr);
//then
assertEquals(-1, maxSum);
}
}

View File

@ -1,10 +1,13 @@
### Relevant Articles:
- [Boruvkas Algorithm for Minimum Spanning Trees](https://www.baeldung.com/java-boruvka-algorithm)
- [Boruvkas Algorithm for Minimum Spanning Trees in Java](https://www.baeldung.com/java-boruvka-algorithm)
- [Gradient Descent in Java](https://www.baeldung.com/java-gradient-descent)
- [Kruskals Algorithm for Spanning Trees](https://www.baeldung.com/java-spanning-trees-kruskal)
- [Kruskals Algorithm for Spanning Trees with a Java Implementation](https://www.baeldung.com/java-spanning-trees-kruskal)
- [Balanced Brackets Algorithm in Java](https://www.baeldung.com/java-balanced-brackets-algorithm)
- [Efficiently Merge Sorted Java Sequences](https://www.baeldung.com/java-merge-sorted-sequences)
- [Introduction to Greedy Algorithms with Java](https://www.baeldung.com/java-greedy-algorithms)
- [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher)
- More articles: [[<-- prev]](/../algorithms-miscellaneous-5)
- [Implementing a 2048 Solver in Java](https://www.baeldung.com/2048-java-solver)
- [Finding Top K Elements in a Java Array](https://www.baeldung.com/java-array-top-elements)
- [Reversing a Linked List in Java](https://www.baeldung.com/java-reverse-linked-list)
- More articles: [[<-- prev]](/algorithms-miscellaneous-5)

View File

@ -0,0 +1,30 @@
package com.baeldung.algorithms.linkedlist;
public class LinkedListReversal {
ListNode reverseList(ListNode head) {
ListNode previous = null;
ListNode current = head;
while (current != null) {
ListNode nextElement = current.getNext();
current.setNext(previous);
previous = current;
current = nextElement;
}
return previous;
}
ListNode reverseListRecursive(ListNode head) {
if (head == null) {
return null;
}
if (head.getNext() == null) {
return head;
}
ListNode node = reverseListRecursive(head.getNext());
head.getNext().setNext(head);
head.setNext(null);
return node;
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.algorithms.linkedlist;
public class ListNode {
private int data;
private ListNode next;
ListNode(int data) {
this.data = data;
this.next = null;
}
public int getData() {
return data;
}
public ListNode getNext() {
return next;
}
public void setData(int data) {
this.data = data;
}
public void setNext(ListNode next) {
this.next = next;
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.algorithms.topkelements;
import java.util.ArrayList;
import java.util.List;
public class BruteForceTopKElementsFinder implements TopKElementsFinder<Integer> {
public List<Integer> findTopK(List<Integer> input, int k) {
List<Integer> array = new ArrayList<>(input);
List<Integer> topKList = new ArrayList<>();
for (int i = 0; i < k; i++) {
int maxIndex = 0;
for (int j = 1; j < array.size(); j++) {
if (array.get(j) > array.get(maxIndex)) {
maxIndex = j;
}
}
topKList.add(array.remove(maxIndex));
}
return topKList;
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.algorithms.topkelements;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;
public class MaxHeapTopKElementsFinder implements TopKElementsFinder<Integer> {
public List<Integer> findTopK(List<Integer> input, int k) {
PriorityQueue<Integer> maxHeap = new PriorityQueue<>();
input.forEach(number -> {
maxHeap.add(number);
if (maxHeap.size() > k) {
maxHeap.poll();
}
});
List<Integer> topKList = new ArrayList<>(maxHeap);
Collections.reverse(topKList);
return topKList;
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.algorithms.topkelements;
import java.util.List;
public interface TopKElementsFinder<T extends Comparable<T>> {
List<T> findTopK(List<T> input, int k);
}

View File

@ -0,0 +1,17 @@
package com.baeldung.algorithms.topkelements;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class TreeSetTopKElementsFinder implements TopKElementsFinder<Integer> {
public List<Integer> findTopK(List<Integer> input, int k) {
Set<Integer> sortedSet = new TreeSet<>(Comparator.reverseOrder());
sortedSet.addAll(input);
return sortedSet.stream().limit(k).collect(Collectors.toList());
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.algorithms.linkedlist;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class LinkedListReversalUnitTest {
@Test
public void givenLinkedList_whenIterativeReverse_thenOutputCorrectResult() {
ListNode head = constructLinkedList();
ListNode node = head;
for (int i = 1; i <= 5; i++) {
assertNotNull(node);
assertEquals(i, node.getData());
node = node.getNext();
}
LinkedListReversal reversal = new LinkedListReversal();
node = reversal.reverseList(head);
for (int i = 5; i >= 1; i--) {
assertNotNull(node);
assertEquals(i, node.getData());
node = node.getNext();
}
}
@Test
public void givenLinkedList_whenRecursiveReverse_thenOutputCorrectResult() {
ListNode head = constructLinkedList();
ListNode node = head;
for (int i = 1; i <= 5; i++) {
assertNotNull(node);
assertEquals(i, node.getData());
node = node.getNext();
}
LinkedListReversal reversal = new LinkedListReversal();
node = reversal.reverseListRecursive(head);
for (int i = 5; i >= 1; i--) {
assertNotNull(node);
assertEquals(i, node.getData());
node = node.getNext();
}
}
private ListNode constructLinkedList() {
ListNode head = null;
ListNode tail = null;
for (int i = 1; i <= 5; i++) {
ListNode node = new ListNode(i);
if (head == null) {
head = node;
} else {
tail.setNext(node);
}
tail = node;
}
return head;
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.algorithms.topkelements;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Java6Assertions.assertThat;
public class TopKElementsFinderUnitTest {
private final TopKElementsFinder<Integer> bruteForceFinder = new BruteForceTopKElementsFinder();
private final TopKElementsFinder<Integer> maxHeapFinder = new MaxHeapTopKElementsFinder();
private final TopKElementsFinder<Integer> treeSetFinder = new TreeSetTopKElementsFinder();
private final int k = 4;
private final List<Integer> distinctIntegers = Arrays.asList(1, 2, 3, 9, 7, 6, 12);
private final List<Integer> distinctIntegersTopK = Arrays.asList(9, 7, 6, 12);
private final List<Integer> nonDistinctIntegers = Arrays.asList(1, 2, 3, 3, 9, 9, 7, 6, 12);
private final List<Integer> nonDistinctIntegersTopK = Arrays.asList(9, 9, 7, 12);
@Test
public void givenArrayDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() {
assertThat(bruteForceFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK);
}
@Test
public void givenArrayDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() {
assertThat(maxHeapFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK);
}
@Test
public void givenArrayDistinctIntegers_whenTreeSetFindTopK_thenReturnKLargest() {
assertThat(treeSetFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK);
}
@Test
public void givenArrayNonDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() {
assertThat(bruteForceFinder.findTopK(nonDistinctIntegers, k)).containsOnlyElementsOf(nonDistinctIntegersTopK);
}
@Test
public void givenArrayNonDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() {
assertThat(maxHeapFinder.findTopK(nonDistinctIntegers, k)).containsOnlyElementsOf(nonDistinctIntegersTopK);
}
}

View File

@ -3,11 +3,13 @@
This module contains articles about searching algorithms.
### Relevant articles:
- [Binary Search Algorithm in Java](https://www.baeldung.com/java-binary-search)
- [Depth First Search in Java](https://www.baeldung.com/java-depth-first-search)
- [Interpolation Search in Java](https://www.baeldung.com/java-interpolation-search)
- [Breadth-First Search Algorithm in Java](https://www.baeldung.com/java-breadth-first-search)
- [String Search Algorithms for Large Texts](https://www.baeldung.com/java-full-text-search-algorithms)
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](https://www.baeldung.com/java-monte-carlo-tree-search)
- [String Search Algorithms for Large Texts with Java](https://www.baeldung.com/java-full-text-search-algorithms)
- [Monte Carlo Tree Search for Tic-Tac-Toe Game in Java](https://www.baeldung.com/java-monte-carlo-tree-search)
- [Range Search Algorithm in Java](https://www.baeldung.com/java-range-search)
- [Fast Pattern Matching of Strings Using Suffix Tree](https://www.baeldung.com/java-pattern-matching-suffix-tree)
- [Fast Pattern Matching of Strings Using Suffix Tree in Java](https://www.baeldung.com/java-pattern-matching-suffix-tree)
- [Find the Kth Smallest Element in Two Sorted Arrays in Java](https://www.baeldung.com/java-kth-smallest-element-in-sorted-arrays)

View File

@ -0,0 +1,126 @@
package com.baeldung.algorithms.kthsmallest;
import java.util.Arrays;
import java.util.NoSuchElementException;
import static java.lang.Math.max;
import static java.lang.Math.min;
public class KthSmallest {
public static int findKthSmallestElement(int k, int[] list1, int[] list2) throws NoSuchElementException, IllegalArgumentException {
checkInput(k, list1, list2);
// we are looking for the minimum value
if(k == 1) {
return min(list1[0], list2[0]);
}
// we are looking for the maximum value
if(list1.length + list2.length == k) {
return max(list1[list1.length-1], list2[list2.length-1]);
}
// swap lists if needed to make sure we take at least one element from list1
if(k <= list2.length && list2[k-1] < list1[0]) {
int[] list1_ = list1;
list1 = list2;
list2 = list1_;
}
// correct left boundary if k is bigger than the size of list2
int left = k < list2.length ? 0 : k - list2.length - 1;
// the inital right boundary cannot exceed the list1
int right = min(k-1, list1.length - 1);
int nElementsList1, nElementsList2;
// binary search
do {
nElementsList1 = ((left + right) / 2) + 1;
nElementsList2 = k - nElementsList1;
if(nElementsList2 > 0) {
if (list1[nElementsList1 - 1] > list2[nElementsList2 - 1]) {
right = nElementsList1 - 2;
} else {
left = nElementsList1;
}
}
} while(!kthSmallesElementFound(list1, list2, nElementsList1, nElementsList2));
return nElementsList2 == 0 ? list1[nElementsList1-1] : max(list1[nElementsList1-1], list2[nElementsList2-1]);
}
private static boolean kthSmallesElementFound(int[] list1, int[] list2, int nElementsList1, int nElementsList2) {
// we do not take any element from the second list
if(nElementsList2 < 1) {
return true;
}
if(list1[nElementsList1-1] == list2[nElementsList2-1]) {
return true;
}
if(nElementsList1 == list1.length) {
return list1[nElementsList1-1] <= list2[nElementsList2];
}
if(nElementsList2 == list2.length) {
return list2[nElementsList2-1] <= list1[nElementsList1];
}
return list1[nElementsList1-1] <= list2[nElementsList2] && list2[nElementsList2-1] <= list1[nElementsList1];
}
private static void checkInput(int k, int[] list1, int[] list2) throws NoSuchElementException, IllegalArgumentException {
if(list1 == null || list2 == null || k < 1) {
throw new IllegalArgumentException();
}
if(list1.length == 0 || list2.length == 0) {
throw new IllegalArgumentException();
}
if(k > list1.length + list2.length) {
throw new NoSuchElementException();
}
}
public static int getKthElementSorted(int[] list1, int[] list2, int k) {
int length1 = list1.length, length2 = list2.length;
int[] combinedArray = new int[length1 + length2];
System.arraycopy(list1, 0, combinedArray, 0, list1.length);
System.arraycopy(list2, 0, combinedArray, list1.length, list2.length);
Arrays.sort(combinedArray);
return combinedArray[k-1];
}
public static int getKthElementMerge(int[] list1, int[] list2, int k) {
int i1 = 0, i2 = 0;
while(i1 < list1.length && i2 < list2.length && (i1 + i2) < k) {
if(list1[i1] < list2[i2]) {
i1++;
} else {
i2++;
}
}
if((i1 + i2) < k) {
return i1 < list1.length ? list1[k - i2 - 1] : list2[k - i1 - 1];
} else if(i1 > 0 && i2 > 0) {
return Math.max(list1[i1-1], list2[i2-1]);
} else {
return i1 == 0 ? list2[i2-1] : list1[i1-1];
}
}
}

View File

@ -0,0 +1,288 @@
package com.baeldung.algorithms.kthsmallest;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.util.*;
import static com.baeldung.algorithms.kthsmallest.KthSmallest.*;
import static org.junit.jupiter.api.Assertions.*;
public class KthSmallestUnitTest {
@Nested
class Exceptions {
@Test
public void when_at_least_one_list_is_null_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(1, null, null);
Executable executable2 = () -> findKthSmallestElement(1, new int[]{2}, null);
Executable executable3 = () -> findKthSmallestElement(1, null, new int[]{2});
assertThrows(IllegalArgumentException.class, executable1);
assertThrows(IllegalArgumentException.class, executable2);
assertThrows(IllegalArgumentException.class, executable3);
}
@Test
public void when_at_least_one_list_is_empty_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(1, new int[]{}, new int[]{2});
Executable executable2 = () -> findKthSmallestElement(1, new int[]{2}, new int[]{});
Executable executable3 = () -> findKthSmallestElement(1, new int[]{}, new int[]{});
assertThrows(IllegalArgumentException.class, executable1);
assertThrows(IllegalArgumentException.class, executable2);
assertThrows(IllegalArgumentException.class, executable3);
}
@Test
public void when_k_is_smaller_than_0_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(-1, new int[]{2}, new int[]{2});
assertThrows(IllegalArgumentException.class, executable1);
}
@Test
public void when_k_is_smaller_than_1_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(0, new int[]{2}, new int[]{2});
assertThrows(IllegalArgumentException.class, executable1);
}
@Test
public void when_k_bigger_then_the_two_lists_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(6, new int[]{1, 5, 6}, new int[]{2, 5});
assertThrows(NoSuchElementException.class, executable1);
}
}
@Nested
class K_is_smaller_than_the_size_of_list1_and_the_size_of_list2 {
@Test
public void when_k_is_1_then_the_smallest_element_is_returned_from_list1() {
int result = findKthSmallestElement(1, new int[]{2, 7}, new int[]{3, 5});
assertEquals(2, result);
}
@Test
public void when_k_is_1_then_the_smallest_element_is_returned_list2() {
int result = findKthSmallestElement(1, new int[]{3, 5}, new int[]{2, 7});
assertEquals(2, result);
}
@Test
public void when_kth_element_is_smallest_element_and_occurs_in_both_lists() {
int[] list1 = new int[]{1, 2, 3};
int[] list2 = new int[]{1, 2, 3};
int result = findKthSmallestElement(1, list1, list2);
assertEquals(1, result);
}
@Test
public void when_kth_element_is_smallest_element_and_occurs_in_both_lists2() {
int[] list1 = new int[]{1, 2, 3};
int[] list2 = new int[]{1, 2, 3};
int result = findKthSmallestElement(2, list1, list2);
assertEquals(1, result);
}
@Test
public void when_kth_element_is_largest_element_and_occurs_in_both_lists_1() {
int[] list1 = new int[]{1, 2, 3};
int[] list2 = new int[]{1, 2, 3};
int result = findKthSmallestElement(5, list1, list2);
assertEquals(3, result);
}
@Test
public void when_kth_element_is_largest_element_and_occurs_in_both_lists_2() {
int[] list1 = new int[]{1, 2, 3};
int[] list2 = new int[]{1, 2, 3};
int result = findKthSmallestElement(6, list1, list2);
assertEquals(3, result);
}
@Test
public void when_kth_element_and_occurs_in_both_lists() {
int[] list1 = new int[]{1, 2, 3};
int[] list2 = new int[]{0, 2, 3};
int result = findKthSmallestElement(3, list1, list2);
assertEquals(2, result);
}
@Test
public void and_kth_element_is_in_first_list() {
int[] list1 = new int[]{1,2,3,4};
int[] list2 = new int[]{1,3,4,5};
int result = findKthSmallestElement(3, list1, list2);
assertEquals(2, result);
}
@Test
public void and_kth_is_in_second_list() {
int[] list1 = new int[]{1,3,4,4};
int[] list2 = new int[]{1,2,4,5};
int result = findKthSmallestElement(3, list1, list2);
assertEquals(2, result);
}
@Test
public void and_elements_in_first_list_are_all_smaller_than_second_list() {
int[] list1 = new int[]{1,3,7,9};
int[] list2 = new int[]{11,12,14,15};
int result = findKthSmallestElement(3, list1, list2);
assertEquals(7, result);
}
@Test
public void and_elements_in_first_list_are_all_smaller_than_second_list2() {
int[] list1 = new int[]{1,3,7,9};
int[] list2 = new int[]{11,12,14,15};
int result = findKthSmallestElement(4, list1, list2);
assertEquals(9, result);
}
@Test
public void and_only_elements_from_second_list_are_part_of_result() {
int[] list1 = new int[]{11,12,14,15};
int[] list2 = new int[]{1,3,7,9};
int result = findKthSmallestElement(3, list1, list2);
assertEquals(7, result);
}
@Test
public void and_only_elements_from_second_list_are_part_of_result2() {
int[] list1 = new int[]{11,12,14,15};
int[] list2 = new int[]{1,3,7,9};
int result = findKthSmallestElement(4, list1, list2);
assertEquals(9, result);
}
}
@Nested
class K_is_bigger_than_the_size_of_at_least_one_of_the_lists {
@Test
public void k_is_smaller_than_list1_and_bigger_than_list2() {
int[] list1 = new int[]{1, 2, 3, 4, 7, 9};
int[] list2 = new int[]{1, 2, 3};
int result = findKthSmallestElement(5, list1, list2);
assertEquals(3, result);
}
@Test
public void k_is_bigger_than_list1_and_smaller_than_list2() {
int[] list1 = new int[]{1, 2, 3};
int[] list2 = new int[]{1, 2, 3, 4, 7, 9};
int result = findKthSmallestElement(5, list1, list2);
assertEquals(3, result);
}
@Test
public void when_k_is_bigger_than_the_size_of_both_lists_and_elements_in_second_list_are_all_smaller_than_first_list() {
int[] list1 = new int[]{9, 11, 13, 55};
int[] list2 = new int[]{1, 2, 3, 7};
int result = findKthSmallestElement(6, list1, list2);
assertEquals(11, result);
}
@Test
public void when_k_is_bigger_than_the_size_of_both_lists_and_elements_in_second_list_are_all_bigger_than_first_list() {
int[] list1 = new int[]{1, 2, 3, 7};
int[] list2 = new int[]{9, 11, 13, 55};
int result = findKthSmallestElement(6, list1, list2);
assertEquals(11, result);
}
@Test
public void when_k_is_bigger_than_the_size_of_both_lists() {
int[] list1 = new int[]{3, 7, 9, 11, 55};
int[] list2 = new int[]{1, 2, 3, 7, 13};
int result = findKthSmallestElement(7, list1, list2);
assertEquals(9, result);
}
@Test
public void when_k_is_bigger_than_the_size_of_both_lists_and_list1_has_more_elements_than_list2() {
int[] list1 = new int[]{3, 7, 9, 11, 55, 77, 100, 200};
int[] list2 = new int[]{1, 2, 3, 7, 13};
int result = findKthSmallestElement(11, list1, list2);
assertEquals(77, result);
}
@Test
public void max_test() {
int[] list1 = new int[]{100, 200};
int[] list2 = new int[]{1, 2, 3};
int result = findKthSmallestElement(4, list1, list2);
assertEquals(100, result);
}
@Test
public void max_test2() {
int[] list1 = new int[]{100, 200};
int[] list2 = new int[]{1, 2, 3};
int result = findKthSmallestElement(5, list1, list2);
assertEquals(200, result);
}
@Test
public void when_k_is_smaller_than_the_size_of_both_lists_and_kth_element_in_list2() {
int[] list1 = new int[]{1, 2, 5};
int[] list2 = new int[]{1, 3, 4, 7};
int result = findKthSmallestElement(4, list1, list2);
assertEquals(3, result);
}
@Test
public void when_k_is_smaller_than_the_size_of_both_lists_and_kth_element_is_smallest_in_list2() {
int[] list1 = new int[]{1, 2, 5};
int[] list2 = new int[]{3, 4, 7};
int result = findKthSmallestElement(3, list1, list2);
assertEquals(3, result);
}
@Test
public void when_k_is_smaller_than_the_size_of_both_lists_and_kth_element_is_smallest_in_list23() {
int[] list1 = new int[]{3, 11, 27, 53, 90};
int[] list2 = new int[]{4, 20, 21, 100};
int result = findKthSmallestElement(5, list1, list2);
assertEquals(21, result);
}
}
// @Test
// public void randomTests() {
// IntStream.range(1, 100000).forEach(i -> random());
// }
private void random() {
Random random = new Random();
int length1 = (Math.abs(random.nextInt())) % 1000 + 1;
int length2 = (Math.abs(random.nextInt())) % 1000 + 1;
int[] list1 = sortedRandomIntArrayOfLength(length1);
int[] list2 = sortedRandomIntArrayOfLength(length2);
int k = (Math.abs(random.nextInt()) % (length1 + length2)) + 1 ;
int result = findKthSmallestElement(k, list1, list2);
int result2 = getKthElementSorted(list1, list2, k);
int result3 = getKthElementMerge(list1, list2, k);
assertEquals(result2, result);
assertEquals(result2, result3);
}
private int[] sortedRandomIntArrayOfLength(int length) {
int[] intArray = new Random().ints(length).toArray();
Arrays.sort(intArray);
return intArray;
}
}

View File

@ -2,6 +2,6 @@
- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically)
- [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers)
- [How an In-Place Sorting Algorithm Works](https://www.baeldung.com/java-in-place-sorting)
- [Partitioning and Sorting Arrays with Many Repeated Entries](https://www.baeldung.com/java-sorting-arrays-with-repeated-entries)
- [Guide to In-Place Sorting Algorithm Works with a Java Implementation](https://www.baeldung.com/java-in-place-sorting)
- [Partitioning and Sorting Arrays with Many Repeated Entries with Java Examples](https://www.baeldung.com/java-sorting-arrays-with-repeated-entries)
- More articles: [[<-- prev]](/algorithms-sorting)

View File

@ -44,18 +44,6 @@
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<properties>
<commons-math3.version>3.6.1</commons-math3.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version>

View File

@ -45,18 +45,6 @@
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<properties>
<commons-math3.version>3.6.1</commons-math3.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version>

View File

@ -7,4 +7,3 @@ This module contains articles about Apache CXF
- [Apache CXF Support for RESTful Web Services](https://www.baeldung.com/apache-cxf-rest-api)
- [A Guide to Apache CXF with Spring](https://www.baeldung.com/apache-cxf-with-spring)
- [Introduction to Apache CXF](https://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

@ -30,7 +30,6 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Server-Sent Events (SSE) In JAX-RS](https://www.baeldung.com/java-ee-jax-rs-sse)

View File

@ -129,6 +129,11 @@
<artifactId>zookeeper</artifactId>
<version>${zookeeper.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>

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 AvroSerealizerDeSerealizerIntegrationTest {
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

@ -1,83 +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 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

@ -0,0 +1,41 @@
package com.baeldung.meecrowave;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.apache.meecrowave.Meecrowave;
import org.apache.meecrowave.junit.MonoMeecrowave;
import org.apache.meecrowave.testing.ConfigurationInject;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(MonoMeecrowave.Runner.class)
public class ArticleEndpointsIntegrationTest {
@ConfigurationInject
private Meecrowave.Builder config;
private static OkHttpClient client;
@BeforeClass
public static void setup() {
client = new OkHttpClient();
}
@Test
public void whenRetunedArticle_thenCorrect() throws IOException {
final String base = "http://localhost:"+config.getHttpPort();
Request request = new Request.Builder()
.url(base+"/article")
.build();
Response response = client.newCall(request).execute();
assertEquals(200, response.code());
}
}

View File

@ -1,41 +0,0 @@
package com.baeldung.meecrowave;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.apache.meecrowave.Meecrowave;
import org.apache.meecrowave.junit.MonoMeecrowave;
import org.apache.meecrowave.testing.ConfigurationInject;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(MonoMeecrowave.Runner.class)
public class ArticleEndpointsUnitTest {
@ConfigurationInject
private Meecrowave.Builder config;
private static OkHttpClient client;
@BeforeClass
public static void setup() {
client = new OkHttpClient();
}
@Test
public void whenRetunedArticle_thenCorrect() throws IOException {
final String base = "http://localhost:"+config.getHttpPort();
Request request = new Request.Builder()
.url(base+"/article")
.build();
Response response = client.newCall(request).execute();
assertEquals(200, response.code());
}
}

View File

@ -3,9 +3,12 @@
This module contains articles about Apache POI
### Relevant Articles:
- [Microsoft Word Processing in Java with Apache POI](https://www.baeldung.com/java-microsoft-word-with-apache-poi)
- [Working with Microsoft Excel in Java](https://www.baeldung.com/java-microsoft-excel)
- [Creating a MS PowerPoint Presentation in Java](https://www.baeldung.com/apache-poi-slideshow)
- [Merge Cells in Excel Using Apache POI](https://www.baeldung.com/java-apache-poi-merge-cells)
- [Get String Value of Excel Cell with Apache POI](https://www.baeldung.com/java-apache-poi-cell-string-value)
- [Read Excel Cell Value Rather Than Formula With Apache POI](https://www.baeldung.com/apache-poi-read-cell-value-formula)
- [Setting Formulas in Excel with Apache POI](https://www.baeldung.com/java-apache-poi-set-formulas)
- [Insert a Row in Excel Using Apache POI](https://www.baeldung.com/apache-poi-insert-excel-row)

View File

@ -0,0 +1,26 @@
package com.baeldung.poi.excel.setformula;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExcelFormula {
public double setFormula(String fileLocation, XSSFWorkbook wb, String formula) throws IOException {
XSSFSheet sheet = wb.getSheetAt(0);
int lastCellNum = sheet.getRow(0).getLastCellNum();
XSSFCell formulaCell = sheet.getRow(0).createCell(lastCellNum);
formulaCell.setCellFormula(formula);
XSSFFormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
formulaEvaluator.evaluateFormulaCell(formulaCell);
FileOutputStream fileOut = new FileOutputStream(new File(fileLocation));
wb.write(fileOut);
wb.close();
fileOut.close();
return formulaCell.getNumericCellValue();
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.poi.excel.insert;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Paths;
public class ExcelInsertRowUnitTest {
private static final String FILE_NAME = "test.xlsx";
private static final String NEW_FILE_NAME = "new_test.xlsx";
private String fileLocation;
@Before
public void setup() throws URISyntaxException {
fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME).toURI()).toString();
}
@Test
public void givenWorkbook_whenInsertRowBetween_thenRowCreated() throws IOException {
int startRow = 2;
int rowNumber = 1;
Workbook workbook = new XSSFWorkbook(fileLocation);
Sheet sheet = workbook.getSheetAt(0);
int lastRow = sheet.getLastRowNum();
if (lastRow < startRow) {
sheet.createRow(startRow);
}
sheet.shiftRows(startRow, lastRow, rowNumber, true, true);
sheet.createRow(startRow);
FileOutputStream outputStream = new FileOutputStream(NEW_FILE_NAME);
workbook.write(outputStream);
File file = new File(NEW_FILE_NAME);
final int expectedRowResult = 5;
Assertions.assertEquals(expectedRowResult, workbook.getSheetAt(0).getLastRowNum());
outputStream.close();
file.delete();
workbook.close();
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.poi.excel.setformula;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Assert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Paths;
class ExcelFormulaUnitTest {
private static String FILE_NAME = "com/baeldung/poi/excel/setformula/SetFormulaTest.xlsx";
private String fileLocation;
private ExcelFormula excelFormula;
@BeforeEach
public void setup() throws URISyntaxException {
fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME).toURI()).toString();
excelFormula = new ExcelFormula();
}
@Test
void givenExcelData_whenSetFormula_thenSuccess() throws IOException {
FileInputStream inputStream = new FileInputStream(new File(fileLocation));
XSSFWorkbook wb = new XSSFWorkbook(inputStream);
XSSFSheet sheet = wb.getSheetAt(0);
double resultColumnA = 0;
double resultColumnB = 0;
for (int row = 0; row <= sheet.getLastRowNum(); row++) {
resultColumnA += sheet.getRow(row).getCell(0).getNumericCellValue();
resultColumnB += sheet.getRow(row).getCell(1).getNumericCellValue();
}
String colNameA = CellReference.convertNumToColString(0);
String colNameB = CellReference.convertNumToColString(1);
String startCellA = colNameA + 1;
String stopCellA = colNameA + (sheet.getLastRowNum() + 1);
String sumFormulaForColumnA = String.format("SUM(%s:%s)", startCellA, stopCellA);
String startCellB = colNameB + 1;
String stopCellB = colNameB + (sheet.getLastRowNum() + 1);
String sumFormulaForColumnB = String.format("SUM(%s:%s)", startCellB, stopCellB);
double resultValue = excelFormula.setFormula(fileLocation, wb, sumFormulaForColumnA + "-" + sumFormulaForColumnB);
Assert.assertEquals(resultColumnA - resultColumnB, resultValue, 0d);
}
}

View File

@ -6,4 +6,4 @@ This module contains articles about Apache Shiro
- [Introduction to Apache Shiro](https://www.baeldung.com/apache-shiro)
- [Permissions-Based Access Control with Apache Shiro](https://www.baeldung.com/apache-shiro-access-control)
- [Spring Security vs Apache Shiro](https://www.baeldung.com/spring-security-vs-apache-shiro)

View File

@ -8,3 +8,4 @@ This module contains articles about Apache Spark
- [Building a Data Pipeline with Kafka, Spark Streaming and Cassandra](https://www.baeldung.com/kafka-spark-data-pipeline)
- [Machine Learning with Spark MLlib](https://www.baeldung.com/spark-mlib-machine-learning)
- [Introduction to Spark Graph Processing with GraphFrames](https://www.baeldung.com/spark-graph-graphframes)
- [Apache Spark: Differences between Dataframes, Datasets and RDDs](https://www.baeldung.com/java-spark-dataframe-dataset-rdd)

File diff suppressed because it is too large Load Diff

View File

@ -74,6 +74,7 @@
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<phase>package</phase>

View File

@ -0,0 +1,75 @@
package com.baeldung.differences.dataframe.dataset.rdd;
public class TouristData {
private String region;
private String country;
private String year;
private String series;
private Double value;
private String footnotes;
private String source;
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getSeries() {
return series;
}
public void setSeries(String series) {
this.series = series;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public String getFootnotes() {
return footnotes;
}
public void setFootnotes(String footnotes) {
this.footnotes = footnotes;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
@Override
public String toString() {
return "TouristData [region=" + region + ", country=" + country + ", year=" + year + ", series=" + series + ", value=" + value + ", footnotes=" + footnotes + ", source=" + source + "]";
}
}

View File

@ -0,0 +1,67 @@
package com.baeldung.differences.rdd;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import scala.Tuple2;
public class ActionsUnitTest {
private static JavaRDD<String> tourists;
private static JavaSparkContext sc;
public static final String COMMA_DELIMITER = ",(?=([^\"]*\"[^\"]*\")*[^\"]*$)";
@BeforeClass
public static void init() {
SparkConf conf = new SparkConf().setAppName("reduce")
.setMaster("local[*]");
sc = new JavaSparkContext(conf);
tourists = sc.textFile("data/Tourist.csv").filter(line -> !line.startsWith("Region"));
}
@AfterClass
public static void cleanup() {
sc.close();
}
@Test
public void whenDistinctCount_thenReturnDistinctNumRecords() {
JavaRDD<String> countries = tourists.map(line -> {
String[] columns = line.split(COMMA_DELIMITER);
return columns[1];
})
.distinct();
Long numberOfCountries = countries.count();
System.out.println("Count: " + numberOfCountries);
assertEquals(Long.valueOf(220), numberOfCountries);
}
@Test
public void whenReduceByKeySum_thenTotalValuePerKey() {
JavaRDD<String> touristsExpenditure = tourists.filter(line -> line.split(COMMA_DELIMITER)[3].contains("expenditure"));
JavaPairRDD<String, Double> expenditurePairRdd = touristsExpenditure.mapToPair(line -> {
String[] columns = line.split(COMMA_DELIMITER);
return new Tuple2<>(columns[1], Double.valueOf(columns[6]));
});
List<Tuple2<String, Double>> totalByCountry = expenditurePairRdd.reduceByKey((x, y) -> x + y)
.collect();
System.out.println("Total per Country: " + totalByCountry);
for(Tuple2<String, Double> tuple : totalByCountry) {
if (tuple._1.equals("Mexico")) {
assertEquals(Double.valueOf(99164), tuple._2);
}
}
}
}

View File

@ -0,0 +1,74 @@
package com.baeldung.differences.rdd;
import static org.apache.spark.sql.functions.col;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import org.apache.spark.sql.DataFrameReader;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class DataFrameUnitTest {
private static SparkSession session;
private static Dataset<Row> data;
@BeforeClass
public static void init() {
session = SparkSession.builder()
.appName("TouristDataFrameExample")
.master("local[*]")
.getOrCreate();
DataFrameReader dataFrameReader = session.read();
data = dataFrameReader.option("header", "true")
.csv("data/Tourist.csv");
}
@AfterClass
public static void cleanup() {
session.stop();
}
@Test
public void whenSelectSpecificColumns_thenColumnsFiltered() {
Dataset<Row> selectedData = data.select(col("country"), col("year"), col("value"));
selectedData.show();
List<String> resultList = Arrays.asList(selectedData.columns());
assertTrue(resultList.contains("country"));
assertTrue(resultList.contains("year"));
assertTrue(resultList.contains("value"));
assertFalse(resultList.contains("Series"));
}
@Test
public void whenFilteringByCountry_thenCountryRecordsSelected() {
Dataset<Row> filteredData = data.filter(col("country").equalTo("Mexico"));
filteredData.show();
filteredData.foreach(record -> {
assertEquals("Mexico", record.get(1));
});
}
@Test
public void whenGroupCountByCountry_thenContryTotalRecords() {
Dataset<Row> recordsPerCountry = data.groupBy(col("country"))
.count();
recordsPerCountry.show();
Dataset<Row> filteredData = recordsPerCountry.filter(col("country").equalTo("Sweden"));
assertEquals(new Long(12), filteredData.first()
.get(1));
}
}

View File

@ -0,0 +1,83 @@
package com.baeldung.differences.rdd;
import static org.apache.spark.sql.functions.col;
import static org.apache.spark.sql.functions.sum;
import static org.junit.Assert.assertEquals;
import org.apache.spark.api.java.function.FilterFunction;
import org.apache.spark.sql.DataFrameReader;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Encoders;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.differences.dataframe.dataset.rdd.TouristData;
public class DatasetUnitTest {
private static SparkSession session;
private static Dataset<TouristData> typedDataset;
@BeforeClass
public static void init() {
session = SparkSession.builder()
.appName("TouristDatasetExample")
.master("local[*]")
.getOrCreate();
DataFrameReader dataFrameReader = session.read();
Dataset<Row> data = dataFrameReader.option("header", "true")
.csv("data/Tourist.csv");
Dataset<Row> responseWithSelectedColumns = data.select(col("region"),
col("country"), col("year"), col("series"), col("value").cast("double"),
col("footnotes"), col("source"));
typedDataset = responseWithSelectedColumns.as(Encoders.bean(TouristData.class));
}
@AfterClass
public static void cleanup() {
session.stop();
}
@Test
public void whenFilteringByCountry_thenCountryRecordsSelected() {
Dataset<TouristData> selectedData = typedDataset
.filter((FilterFunction<TouristData>) record -> record.getCountry()
.equals("Norway"));
selectedData.show();
selectedData.foreach(record -> {
assertEquals("Norway", record.getCountry());
});
}
@Test
public void whenGroupCountByCountry_thenContryTotalRecords() {
Dataset<Row> countriesCount = typedDataset.groupBy(typedDataset.col("country"))
.count();
countriesCount.show();
assertEquals(Long.valueOf(220), Long.valueOf(countriesCount.count()));
}
@Test
public void whenFilteredByPropertyRange_thenRetreiveValidRecords() {
// Filter records with existing data for years between 2010 and 2017
typedDataset.filter((FilterFunction<TouristData>) record -> record.getYear() != null
&& (Long.valueOf(record.getYear()) > 2010 && Long.valueOf(record.getYear()) < 2017))
.show();
}
@Test
public void whenSumValue_thenRetreiveTotalValue() {
// Total tourist expenditure by country
typedDataset.filter((FilterFunction<TouristData>) record -> record.getValue() != null
&& record.getSeries()
.contains("expenditure"))
.groupBy("country")
.agg(sum("value"))
.show();
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.differences.rdd;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.apache.commons.lang3.StringUtils;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class TransformationsUnitTest {
public static final String COMMA_DELIMITER = ",(?=([^\"]*\"[^\"]*\")*[^\"]*$)";
private static JavaSparkContext sc;
private static JavaRDD<String> tourists;
@BeforeClass
public static void init() {
SparkConf conf = new SparkConf().setAppName("uppercaseCountries")
.setMaster("local[*]");
sc = new JavaSparkContext(conf);
tourists = sc.textFile("data/Tourist.csv")
.filter(line -> !line.startsWith("Region")); //filter header row
}
@AfterClass
public static void cleanup() {
sc.close();
}
@Test
public void whenMapUpperCase_thenCountryNameUppercased() {
JavaRDD<String> upperCaseCountries = tourists.map(line -> {
String[] columns = line.split(COMMA_DELIMITER);
return columns[1].toUpperCase();
})
.distinct();
upperCaseCountries.saveAsTextFile("data/output/uppercase.txt");
upperCaseCountries.foreach(country -> {
//replace non alphanumerical characters
country = country.replaceAll("[^a-zA-Z]", "");
assertTrue(StringUtils.isAllUpperCase(country));
});
}
@Test
public void whenFilterByCountry_thenShowRequestedCountryRecords() {
JavaRDD<String> touristsInMexico = tourists.filter(line -> line.split(COMMA_DELIMITER)[1].equals("Mexico"));
touristsInMexico.saveAsTextFile("data/output/touristInMexico.txt");
touristsInMexico.foreach(record -> {
assertEquals("Mexico", record.split(COMMA_DELIMITER)[1]);
});
}
}

View File

@ -51,7 +51,7 @@
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
<scope>provided</scope>
<exclusions>

View File

@ -5,3 +5,4 @@ This module contains articles about AWS Lambda
### Relevant Articles:
- [Using AWS Lambda with API Gateway](https://www.baeldung.com/aws-lambda-api-gateway)
- [Introduction to AWS Serverless Application Model](https://www.baeldung.com/aws-serverless)
- [How to Implement Hibernate in an AWS Lambda Function in Java](https://www.baeldung.com/java-aws-lambda-hibernate)

99
aws-lambda/lambda/pom.xml Normal file
View File

@ -0,0 +1,99 @@
<?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>lambda</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>lambda</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-dynamodb</artifactId>
<version>${aws-java-sdk.version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-core</artifactId>
<version>${aws-java-sdk.version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>${aws-lambda-java-core.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-events</artifactId>
<version>${aws-lambda-java-events.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>${json-simple.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<json-simple.version>1.1.1</json-simple.version>
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
<aws-lambda-java-core.version>1.2.0</aws-lambda-java-core.version>
<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>
</properties>
</project>

View File

@ -5,95 +5,19 @@
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>aws-lambda</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>aws-lambda</name>
<packaging>jar</packaging>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-dynamodb</artifactId>
<version>${aws-java-sdk.version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-core</artifactId>
<version>${aws-java-sdk.version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>${aws-lambda-java-core.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-events</artifactId>
<version>${aws-lambda-java-events.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>${json-simple.version}</version>
</dependency>
</dependencies>
<modules>
<module>lambda</module>
<module>shipping-tracker/ShippingFunction</module>
</modules>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<json-simple.version>1.1.1</json-simple.version>
<commons-io.version>2.5</commons-io.version>
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
<aws-lambda-java-core.version>1.2.0</aws-lambda-java-core.version>
<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>
</properties>
</project>
</project>

View File

@ -0,0 +1 @@
.aws-sam/

View File

@ -0,0 +1,73 @@
<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.baeldung</groupId>
<artifactId>ShippingFunction</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>ShippingFunction</name>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<hibernate.version>5.4.21.Final</hibernate.version>
</properties>
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-events</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-hikaricp</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.16</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.1</version>
<configuration>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,121 @@
package com.baeldung.lambda.shipping;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zaxxer.hikari.HikariDataSource;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import java.util.HashMap;
import java.util.Map;
import static org.hibernate.cfg.AvailableSettings.*;
import static org.hibernate.cfg.AvailableSettings.PASS;
/**
* Handler for requests to Lambda function.
*/
public class App implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private SessionFactory sessionFactory = createSessionFactory();
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
try {
ShippingService service = new ShippingService(sessionFactory, new ShippingDao());
return routeRequest(input, service);
} finally {
flushConnectionPool();
}
}
private APIGatewayProxyResponseEvent routeRequest(APIGatewayProxyRequestEvent input, ShippingService service) {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("X-Custom-Header", "application/json");
Object result = "OK";
switch (input.getResource()) {
case "/consignment":
result = service.createConsignment(
fromJson(input.getBody(), Consignment.class));
break;
case "/consignment/{id}":
result = service.view(input.getPathParameters().get("id"));
break;
case "/consignment/{id}/item":
service.addItem(input.getPathParameters().get("id"),
fromJson(input.getBody(), Item.class));
break;
case "/consignment/{id}/checkin":
service.checkIn(input.getPathParameters().get("id"),
fromJson(input.getBody(), Checkin.class));
break;
}
return new APIGatewayProxyResponseEvent()
.withHeaders(headers)
.withStatusCode(200)
.withBody(toJson(result));
}
private static <T> String toJson(T object) {
try {
return OBJECT_MAPPER.writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
private static <T> T fromJson(String json, Class<T> type) {
try {
return OBJECT_MAPPER.readValue(json, type);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
private static SessionFactory createSessionFactory() {
Map<String, String> settings = new HashMap<>();
settings.put(URL, System.getenv("DB_URL"));
settings.put(DIALECT, "org.hibernate.dialect.PostgreSQLDialect");
settings.put(DEFAULT_SCHEMA, "shipping");
settings.put(DRIVER, "org.postgresql.Driver");
settings.put(USER, System.getenv("DB_USER"));
settings.put(PASS, System.getenv("DB_PASSWORD"));
settings.put("hibernate.hikari.connectionTimeout", "20000");
settings.put("hibernate.hikari.minimumIdle", "1");
settings.put("hibernate.hikari.maximumPoolSize", "2");
settings.put("hibernate.hikari.idleTimeout", "30000");
// commented out as we only need them on first use
// settings.put(HBM2DDL_AUTO, "create-only");
// settings.put(HBM2DDL_DATABASE_ACTION, "create");
StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.applySettings(settings)
.build();
return new MetadataSources(registry)
.addAnnotatedClass(Consignment.class)
.addAnnotatedClass(Item.class)
.addAnnotatedClass(Checkin.class)
.buildMetadata()
.buildSessionFactory();
}
private void flushConnectionPool() {
ConnectionProvider connectionProvider = sessionFactory.getSessionFactoryOptions()
.getServiceRegistry()
.getService(ConnectionProvider.class);
HikariDataSource hikariDataSource = connectionProvider.unwrap(HikariDataSource.class);
hikariDataSource.getHikariPoolMXBean().softEvictConnections();
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.lambda.shipping;
import javax.persistence.Column;
import javax.persistence.Embeddable;
@Embeddable
public class Checkin {
private String timeStamp;
private String location;
@Column(name = "timestamp")
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
@Column(name = "location")
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}

View File

@ -0,0 +1,77 @@
package com.baeldung.lambda.shipping;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import static javax.persistence.FetchType.EAGER;
@Entity(name = "consignment")
@Table(name = "consignment")
public class Consignment {
private String id;
private String source;
private String destination;
private boolean isDelivered;
private List<Item> items = new ArrayList<>();
private List<Checkin> checkins = new ArrayList<>();
@Id
@Column(name = "consignment_id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Column(name = "source")
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
@Column(name = "destination")
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
@Column(name = "delivered", columnDefinition = "boolean")
public boolean isDelivered() {
return isDelivered;
}
public void setDelivered(boolean delivered) {
isDelivered = delivered;
}
@ElementCollection(fetch = EAGER)
@CollectionTable(name = "consignment_item", joinColumns = @JoinColumn(name = "consignment_id"))
@OrderColumn(name = "item_index")
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
@ElementCollection(fetch = EAGER)
@CollectionTable(name = "consignment_checkin", joinColumns = @JoinColumn(name = "consignment_id"))
@OrderColumn(name = "checkin_index")
public List<Checkin> getCheckins() {
return checkins;
}
public void setCheckins(List<Checkin> checkins) {
this.checkins = checkins;
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.lambda.shipping;
import javax.persistence.Column;
import javax.persistence.Embeddable;
@Embeddable
public class Item {
private String location;
private String description;
private String timeStamp;
@Column(name = "location")
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
@Column(name = "description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Column(name = "timestamp")
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.lambda.shipping;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.Optional;
public class ShippingDao {
/**
* Save a consignment to the database
* @param consignment the consignment to save
*/
public void save(Session session, Consignment consignment) {
Transaction transaction = session.beginTransaction();
session.save(consignment);
transaction.commit();
}
/**
* Find a consignment in the database by id
*/
public Optional<Consignment> find(Session session, String id) {
return Optional.ofNullable(session.get(Consignment.class, id));
}
}

View File

@ -0,0 +1,62 @@
package com.baeldung.lambda.shipping;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import java.util.Comparator;
import java.util.UUID;
public class ShippingService {
private SessionFactory sessionFactory;
private ShippingDao shippingDao;
public ShippingService(SessionFactory sessionFactory, ShippingDao shippingDao) {
this.sessionFactory = sessionFactory;
this.shippingDao = shippingDao;
}
public String createConsignment(Consignment consignment) {
try (Session session = sessionFactory.openSession()) {
consignment.setDelivered(false);
consignment.setId(UUID.randomUUID().toString());
shippingDao.save(session, consignment);
return consignment.getId();
}
}
public void addItem(String consignmentId, Item item) {
try (Session session = sessionFactory.openSession()) {
shippingDao.find(session, consignmentId)
.ifPresent(consignment -> addItem(session, consignment, item));
}
}
private void addItem(Session session, Consignment consignment, Item item) {
consignment.getItems()
.add(item);
shippingDao.save(session, consignment);
}
public void checkIn(String consignmentId, Checkin checkin) {
try (Session session = sessionFactory.openSession()) {
shippingDao.find(session, consignmentId)
.ifPresent(consignment -> checkIn(session, consignment, checkin));
}
}
private void checkIn(Session session, Consignment consignment, Checkin checkin) {
consignment.getCheckins().add(checkin);
consignment.getCheckins().sort(Comparator.comparing(Checkin::getTimeStamp));
if (checkin.getLocation().equals(consignment.getDestination())) {
consignment.setDelivered(true);
}
shippingDao.save(session, consignment);
}
public Consignment view(String consignmentId) {
try (Session session = sessionFactory.openSession()) {
return shippingDao.find(session, consignmentId)
.orElseGet(Consignment::new);
}
}
}

View File

@ -0,0 +1,47 @@
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
shipping-tracker
Sample SAM Template for shipping-tracker
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 20
Resources:
ShippingFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ShippingFunction
Handler: com.baeldung.lambda.shipping.App::handleRequest
Runtime: java8
MemorySize: 512
Environment:
Variables:
DB_URL: jdbc:postgresql://postgres/postgres
DB_USER: postgres
DB_PASSWORD: password
Events:
CreateConsignment:
Type: Api
Properties:
Path: /consignment
Method: post
AddItem:
Type: Api
Properties:
Path: /consignment/{id}/item
Method: post
CheckIn:
Type: Api
Properties:
Path: /consignment/{id}/checkin
Method: post
ViewConsignment:
Type: Api
Properties:
Path: /consignment/{id}
Method: get

View File

@ -100,7 +100,6 @@
</build>
<properties>
<java.version>1.8</java.version>
<spring.version>2.2.1.RELEASE</spring.version>
<awssdk.version>2.10.27</awssdk.version>
</properties>

View File

@ -5,3 +5,4 @@ This module contains articles about Axon
### Relevant articles
- [A Guide to the Axon Framework](https://www.baeldung.com/axon-cqrs-event-sourcing)
- [Multi-Entity Aggregates in Axon](https://www.baeldung.com/java-axon-multi-entity-aggregates)

View File

@ -53,7 +53,7 @@
</dependencies>
<properties>
<axon.version>4.1.2</axon.version>
<axon.version>4.4.7</axon.version>
</properties>
</project>

View File

@ -1,59 +0,0 @@
package com.baeldung.axon.commandmodel;
import static org.axonframework.modelling.command.AggregateLifecycle.apply;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.axonframework.modelling.command.AggregateIdentifier;
import org.axonframework.spring.stereotype.Aggregate;
import com.baeldung.axon.coreapi.commands.ConfirmOrderCommand;
import com.baeldung.axon.coreapi.commands.PlaceOrderCommand;
import com.baeldung.axon.coreapi.commands.ShipOrderCommand;
import com.baeldung.axon.coreapi.events.OrderConfirmedEvent;
import com.baeldung.axon.coreapi.events.OrderPlacedEvent;
import com.baeldung.axon.coreapi.events.OrderShippedEvent;
import com.baeldung.axon.coreapi.exceptions.UnconfirmedOrderException;
@Aggregate
public class OrderAggregate {
@AggregateIdentifier
private String orderId;
private boolean orderConfirmed;
@CommandHandler
public OrderAggregate(PlaceOrderCommand command) {
apply(new OrderPlacedEvent(command.getOrderId(), command.getProduct()));
}
@CommandHandler
public void handle(ConfirmOrderCommand command) {
apply(new OrderConfirmedEvent(orderId));
}
@CommandHandler
public void handle(ShipOrderCommand command) {
if (!orderConfirmed) {
throw new UnconfirmedOrderException();
}
apply(new OrderShippedEvent(orderId));
}
@EventSourcingHandler
public void on(OrderPlacedEvent event) {
this.orderId = event.getOrderId();
this.orderConfirmed = false;
}
@EventSourcingHandler
public void on(OrderConfirmedEvent event) {
this.orderConfirmed = true;
}
protected OrderAggregate() {
// Required by Axon to build a default Aggregate prior to Event Sourcing
}
}

View File

@ -0,0 +1,98 @@
package com.baeldung.axon.commandmodel.order;
import com.baeldung.axon.coreapi.commands.AddProductCommand;
import com.baeldung.axon.coreapi.commands.ConfirmOrderCommand;
import com.baeldung.axon.coreapi.commands.CreateOrderCommand;
import com.baeldung.axon.coreapi.commands.ShipOrderCommand;
import com.baeldung.axon.coreapi.events.OrderConfirmedEvent;
import com.baeldung.axon.coreapi.events.OrderCreatedEvent;
import com.baeldung.axon.coreapi.events.OrderShippedEvent;
import com.baeldung.axon.coreapi.events.ProductAddedEvent;
import com.baeldung.axon.coreapi.events.ProductRemovedEvent;
import com.baeldung.axon.coreapi.exceptions.DuplicateOrderLineException;
import com.baeldung.axon.coreapi.exceptions.OrderAlreadyConfirmedException;
import com.baeldung.axon.coreapi.exceptions.UnconfirmedOrderException;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.axonframework.modelling.command.AggregateIdentifier;
import org.axonframework.modelling.command.AggregateMember;
import org.axonframework.spring.stereotype.Aggregate;
import java.util.HashMap;
import java.util.Map;
import static org.axonframework.modelling.command.AggregateLifecycle.apply;
@Aggregate
public class OrderAggregate {
@AggregateIdentifier
private String orderId;
private boolean orderConfirmed;
@AggregateMember
private Map<String, OrderLine> orderLines;
@CommandHandler
public OrderAggregate(CreateOrderCommand command) {
apply(new OrderCreatedEvent(command.getOrderId()));
}
@CommandHandler
public void handle(AddProductCommand command) {
if (orderConfirmed) {
throw new OrderAlreadyConfirmedException(orderId);
}
String productId = command.getProductId();
if (orderLines.containsKey(productId)) {
throw new DuplicateOrderLineException(productId);
}
apply(new ProductAddedEvent(orderId, productId));
}
@CommandHandler
public void handle(ConfirmOrderCommand command) {
if (orderConfirmed) {
return;
}
apply(new OrderConfirmedEvent(orderId));
}
@CommandHandler
public void handle(ShipOrderCommand command) {
if (!orderConfirmed) {
throw new UnconfirmedOrderException();
}
apply(new OrderShippedEvent(orderId));
}
@EventSourcingHandler
public void on(OrderCreatedEvent event) {
this.orderId = event.getOrderId();
this.orderConfirmed = false;
this.orderLines = new HashMap<>();
}
@EventSourcingHandler
public void on(OrderConfirmedEvent event) {
this.orderConfirmed = true;
}
@EventSourcingHandler
public void on(ProductAddedEvent event) {
String productId = event.getProductId();
this.orderLines.put(productId, new OrderLine(productId));
}
@EventSourcingHandler
public void on(ProductRemovedEvent event) {
this.orderLines.remove(event.getProductId());
}
protected OrderAggregate() {
// Required by Axon to build a default Aggregate prior to Event Sourcing
}
}

View File

@ -0,0 +1,83 @@
package com.baeldung.axon.commandmodel.order;
import com.baeldung.axon.coreapi.commands.DecrementProductCountCommand;
import com.baeldung.axon.coreapi.commands.IncrementProductCountCommand;
import com.baeldung.axon.coreapi.events.OrderConfirmedEvent;
import com.baeldung.axon.coreapi.events.ProductCountDecrementedEvent;
import com.baeldung.axon.coreapi.events.ProductCountIncrementedEvent;
import com.baeldung.axon.coreapi.events.ProductRemovedEvent;
import com.baeldung.axon.coreapi.exceptions.OrderAlreadyConfirmedException;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.axonframework.modelling.command.EntityId;
import java.util.Objects;
import static org.axonframework.modelling.command.AggregateLifecycle.apply;
public class OrderLine {
@EntityId
private final String productId;
private Integer count;
private boolean orderConfirmed;
public OrderLine(String productId) {
this.productId = productId;
this.count = 1;
}
@CommandHandler
public void handle(IncrementProductCountCommand command) {
if (orderConfirmed) {
throw new OrderAlreadyConfirmedException(command.getOrderId());
}
apply(new ProductCountIncrementedEvent(command.getOrderId(), productId));
}
@CommandHandler
public void handle(DecrementProductCountCommand command) {
if (orderConfirmed) {
throw new OrderAlreadyConfirmedException(command.getOrderId());
}
if (count <= 1) {
apply(new ProductRemovedEvent(command.getOrderId(), productId));
} else {
apply(new ProductCountDecrementedEvent(command.getOrderId(), productId));
}
}
@EventSourcingHandler
public void on(ProductCountIncrementedEvent event) {
this.count++;
}
@EventSourcingHandler
public void on(ProductCountDecrementedEvent event) {
this.count--;
}
@EventSourcingHandler
public void on(OrderConfirmedEvent event) {
this.orderConfirmed = true;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
OrderLine orderLine = (OrderLine) o;
return Objects.equals(productId, orderLine.productId) && Objects.equals(count, orderLine.count);
}
@Override
public int hashCode() {
return Objects.hash(productId, count);
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.axon.coreapi.commands;
import org.axonframework.modelling.command.TargetAggregateIdentifier;
import java.util.Objects;
public class AddProductCommand {
@TargetAggregateIdentifier
private final String orderId;
private final String productId;
public AddProductCommand(String orderId, String productId) {
this.orderId = orderId;
this.productId = productId;
}
public String getOrderId() {
return orderId;
}
public String getProductId() {
return productId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AddProductCommand that = (AddProductCommand) o;
return Objects.equals(orderId, that.orderId) && Objects.equals(productId, that.productId);
}
@Override
public int hashCode() {
return Objects.hash(orderId, productId);
}
@Override
public String toString() {
return "AddProductCommand{" +
"orderId='" + orderId + '\'' +
", productId='" + productId + '\'' +
'}';
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.axon.coreapi.commands;
import org.axonframework.modelling.command.TargetAggregateIdentifier;
import java.util.Objects;
public class CreateOrderCommand {
@TargetAggregateIdentifier
private final String orderId;
public CreateOrderCommand(String orderId) {
this.orderId = orderId;
}
public String getOrderId() {
return orderId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CreateOrderCommand that = (CreateOrderCommand) o;
return Objects.equals(orderId, that.orderId);
}
@Override
public int hashCode() {
return Objects.hash(orderId);
}
@Override
public String toString() {
return "CreateOrderCommand{" +
"orderId='" + orderId + '\'' +
'}';
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.axon.coreapi.commands;
import org.axonframework.modelling.command.TargetAggregateIdentifier;
import java.util.Objects;
public class DecrementProductCountCommand {
@TargetAggregateIdentifier
private final String orderId;
private final String productId;
public DecrementProductCountCommand(String orderId, String productId) {
this.orderId = orderId;
this.productId = productId;
}
public String getOrderId() {
return orderId;
}
public String getProductId() {
return productId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DecrementProductCountCommand that = (DecrementProductCountCommand) o;
return Objects.equals(orderId, that.orderId) && Objects.equals(productId, that.productId);
}
@Override
public int hashCode() {
return Objects.hash(orderId, productId);
}
@Override
public String toString() {
return "DecrementProductCountCommand{" +
"orderId='" + orderId + '\'' +
", productId='" + productId + '\'' +
'}';
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.axon.coreapi.commands;
import org.axonframework.modelling.command.TargetAggregateIdentifier;
import java.util.Objects;
public class IncrementProductCountCommand {
@TargetAggregateIdentifier
private final String orderId;
private final String productId;
public IncrementProductCountCommand(String orderId, String productId) {
this.orderId = orderId;
this.productId = productId;
}
public String getOrderId() {
return orderId;
}
public String getProductId() {
return productId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
IncrementProductCountCommand that = (IncrementProductCountCommand) o;
return Objects.equals(orderId, that.orderId) && Objects.equals(productId, that.productId);
}
@Override
public int hashCode() {
return Objects.hash(orderId, productId);
}
@Override
public String toString() {
return "IncrementProductCountCommand{" +
"orderId='" + orderId + '\'' +
", productId='" + productId + '\'' +
'}';
}
}

View File

@ -1,51 +0,0 @@
package com.baeldung.axon.coreapi.commands;
import java.util.Objects;
import org.axonframework.modelling.command.TargetAggregateIdentifier;
public class PlaceOrderCommand {
@TargetAggregateIdentifier
private final String orderId;
private final String product;
public PlaceOrderCommand(String orderId, String product) {
this.orderId = orderId;
this.product = product;
}
public String getOrderId() {
return orderId;
}
public String getProduct() {
return product;
}
@Override
public int hashCode() {
return Objects.hash(orderId, product);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final PlaceOrderCommand other = (PlaceOrderCommand) obj;
return Objects.equals(this.orderId, other.orderId)
&& Objects.equals(this.product, other.product);
}
@Override
public String toString() {
return "PlaceOrderCommand{" +
"orderId='" + orderId + '\'' +
", product='" + product + '\'' +
'}';
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.axon.coreapi.events;
import java.util.Objects;
public class OrderCreatedEvent {
private final String orderId;
public OrderCreatedEvent(String orderId) {
this.orderId = orderId;
}
public String getOrderId() {
return orderId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
OrderCreatedEvent that = (OrderCreatedEvent) o;
return Objects.equals(orderId, that.orderId);
}
@Override
public int hashCode() {
return Objects.hash(orderId);
}
@Override
public String toString() {
return "OrderCreatedEvent{" +
"orderId='" + orderId + '\'' +
'}';
}
}

View File

@ -1,48 +0,0 @@
package com.baeldung.axon.coreapi.events;
import java.util.Objects;
public class OrderPlacedEvent {
private final String orderId;
private final String product;
public OrderPlacedEvent(String orderId, String product) {
this.orderId = orderId;
this.product = product;
}
public String getOrderId() {
return orderId;
}
public String getProduct() {
return product;
}
@Override
public int hashCode() {
return Objects.hash(orderId, product);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final OrderPlacedEvent other = (OrderPlacedEvent) obj;
return Objects.equals(this.orderId, other.orderId)
&& Objects.equals(this.product, other.product);
}
@Override
public String toString() {
return "OrderPlacedEvent{" +
"orderId='" + orderId + '\'' +
", product='" + product + '\'' +
'}';
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.axon.coreapi.events;
import java.util.Objects;
public class ProductAddedEvent {
private final String orderId;
private final String productId;
public ProductAddedEvent(String orderId, String productId) {
this.orderId = orderId;
this.productId = productId;
}
public String getOrderId() {
return orderId;
}
public String getProductId() {
return productId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ProductAddedEvent that = (ProductAddedEvent) o;
return Objects.equals(orderId, that.orderId) && Objects.equals(productId, that.productId);
}
@Override
public int hashCode() {
return Objects.hash(orderId, productId);
}
@Override
public String toString() {
return "ProductAddedEvent{" +
"orderId='" + orderId + '\'' +
", productId='" + productId + '\'' +
'}';
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.axon.coreapi.events;
import java.util.Objects;
public class ProductCountDecrementedEvent {
private final String orderId;
private final String productId;
public ProductCountDecrementedEvent(String orderId, String productId) {
this.orderId = orderId;
this.productId = productId;
}
public String getOrderId() {
return orderId;
}
public String getProductId() {
return productId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ProductCountDecrementedEvent that = (ProductCountDecrementedEvent) o;
return Objects.equals(orderId, that.orderId) && Objects.equals(productId, that.productId);
}
@Override
public int hashCode() {
return Objects.hash(orderId, productId);
}
@Override
public String toString() {
return "ProductCountDecrementedEvent{" +
"orderId='" + orderId + '\'' +
", productId='" + productId + '\'' +
'}';
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.axon.coreapi.events;
import java.util.Objects;
public class ProductCountIncrementedEvent {
private final String orderId;
private final String productId;
public ProductCountIncrementedEvent(String orderId, String productId) {
this.orderId = orderId;
this.productId = productId;
}
public String getOrderId() {
return orderId;
}
public String getProductId() {
return productId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ProductCountIncrementedEvent that = (ProductCountIncrementedEvent) o;
return Objects.equals(orderId, that.orderId) && Objects.equals(productId, that.productId);
}
@Override
public int hashCode() {
return Objects.hash(orderId, productId);
}
@Override
public String toString() {
return "ProductCountIncrementedEvent{" +
"orderId='" + orderId + '\'' +
", productId='" + productId + '\'' +
'}';
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.axon.coreapi.events;
import java.util.Objects;
public class ProductRemovedEvent {
private final String orderId;
private final String productId;
public ProductRemovedEvent(String orderId, String productId) {
this.orderId = orderId;
this.productId = productId;
}
public String getOrderId() {
return orderId;
}
public String getProductId() {
return productId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ProductRemovedEvent that = (ProductRemovedEvent) o;
return Objects.equals(orderId, that.orderId) && Objects.equals(productId, that.productId);
}
@Override
public int hashCode() {
return Objects.hash(orderId, productId);
}
@Override
public String toString() {
return "ProductRemovedEvent{" +
"orderId='" + orderId + '\'' +
", productId='" + productId + '\'' +
'}';
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.axon.coreapi.exceptions;
public class DuplicateOrderLineException extends IllegalStateException {
public DuplicateOrderLineException(String productId) {
super("Cannot duplicate order line for product identifier [" + productId + "]");
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.axon.coreapi.exceptions;
public class OrderAlreadyConfirmedException extends IllegalStateException {
public OrderAlreadyConfirmedException(String orderId) {
super("Cannot perform operation because order [" + orderId + "] is already confirmed.");
}
}

View File

@ -0,0 +1,83 @@
package com.baeldung.axon.coreapi.queries;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class Order {
private final String orderId;
private final Map<String, Integer> products;
private OrderStatus orderStatus;
public Order(String orderId) {
this.orderId = orderId;
this.products = new HashMap<>();
orderStatus = OrderStatus.CREATED;
}
public String getOrderId() {
return orderId;
}
public Map<String, Integer> getProducts() {
return products;
}
public OrderStatus getOrderStatus() {
return orderStatus;
}
public void addProduct(String productId) {
products.putIfAbsent(productId, 1);
}
public void incrementProductInstance(String productId) {
products.computeIfPresent(productId, (id, count) -> ++count);
}
public void decrementProductInstance(String productId) {
products.computeIfPresent(productId, (id, count) -> --count);
}
public void removeProduct(String productId) {
products.remove(productId);
}
public void setOrderConfirmed() {
this.orderStatus = OrderStatus.CONFIRMED;
}
public void setOrderShipped() {
this.orderStatus = OrderStatus.SHIPPED;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Order that = (Order) o;
return Objects.equals(orderId, that.orderId)
&& Objects.equals(products, that.products)
&& orderStatus == that.orderStatus;
}
@Override
public int hashCode() {
return Objects.hash(orderId, products, orderStatus);
}
@Override
public String toString() {
return "Order{" +
"orderId='" + orderId + '\'' +
", products=" + products +
", orderStatus=" + orderStatus +
'}';
}
}

View File

@ -2,6 +2,5 @@ package com.baeldung.axon.coreapi.queries;
public enum OrderStatus {
PLACED, CONFIRMED, SHIPPED
CREATED, CONFIRMED, SHIPPED
}

View File

@ -1,64 +0,0 @@
package com.baeldung.axon.coreapi.queries;
import java.util.Objects;
public class OrderedProduct {
private final String orderId;
private final String product;
private OrderStatus orderStatus;
public OrderedProduct(String orderId, String product) {
this.orderId = orderId;
this.product = product;
orderStatus = OrderStatus.PLACED;
}
public String getOrderId() {
return orderId;
}
public String getProduct() {
return product;
}
public OrderStatus getOrderStatus() {
return orderStatus;
}
public void setOrderConfirmed() {
this.orderStatus = OrderStatus.CONFIRMED;
}
public void setOrderShipped() {
this.orderStatus = OrderStatus.SHIPPED;
}
@Override
public int hashCode() {
return Objects.hash(orderId, product, orderStatus);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final OrderedProduct other = (OrderedProduct) obj;
return Objects.equals(this.orderId, other.orderId)
&& Objects.equals(this.product, other.product)
&& Objects.equals(this.orderStatus, other.orderStatus);
}
@Override
public String toString() {
return "OrderedProduct{" +
"orderId='" + orderId + '\'' +
", product='" + product + '\'' +
", orderStatus=" + orderStatus +
'}';
}
}

View File

@ -1,20 +1,24 @@
package com.baeldung.axon.gui;
import java.util.List;
import java.util.UUID;
import com.baeldung.axon.coreapi.commands.AddProductCommand;
import com.baeldung.axon.coreapi.commands.ConfirmOrderCommand;
import com.baeldung.axon.coreapi.commands.CreateOrderCommand;
import com.baeldung.axon.coreapi.commands.DecrementProductCountCommand;
import com.baeldung.axon.coreapi.commands.IncrementProductCountCommand;
import com.baeldung.axon.coreapi.commands.ShipOrderCommand;
import com.baeldung.axon.coreapi.queries.FindAllOrderedProductsQuery;
import com.baeldung.axon.coreapi.queries.Order;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.axonframework.messaging.responsetypes.ResponseTypes;
import org.axonframework.queryhandling.QueryGateway;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.axon.coreapi.commands.ConfirmOrderCommand;
import com.baeldung.axon.coreapi.commands.PlaceOrderCommand;
import com.baeldung.axon.coreapi.commands.ShipOrderCommand;
import com.baeldung.axon.coreapi.queries.FindAllOrderedProductsQuery;
import com.baeldung.axon.coreapi.queries.OrderedProduct;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@RestController
public class OrderRestEndpoint {
@ -28,25 +32,63 @@ public class OrderRestEndpoint {
}
@PostMapping("/ship-order")
public void shipOrder() {
public CompletableFuture<Void> shipOrder() {
String orderId = UUID.randomUUID().toString();
commandGateway.send(new PlaceOrderCommand(orderId, "Deluxe Chair"));
commandGateway.send(new ConfirmOrderCommand(orderId));
commandGateway.send(new ShipOrderCommand(orderId));
return commandGateway.send(new CreateOrderCommand(orderId))
.thenCompose(result -> commandGateway.send(new AddProductCommand(orderId, "Deluxe Chair")))
.thenCompose(result -> commandGateway.send(new ConfirmOrderCommand(orderId)))
.thenCompose(result -> commandGateway.send(new ShipOrderCommand(orderId)));
}
@PostMapping("/ship-unconfirmed-order")
public void shipUnconfirmedOrder() {
public CompletableFuture<Void> shipUnconfirmedOrder() {
String orderId = UUID.randomUUID().toString();
commandGateway.send(new PlaceOrderCommand(orderId, "Deluxe Chair"));
// This throws an exception, as an Order cannot be shipped if it has not been confirmed yet.
commandGateway.send(new ShipOrderCommand(orderId));
return commandGateway.send(new CreateOrderCommand(orderId))
.thenCompose(result -> commandGateway.send(new AddProductCommand(orderId, "Deluxe Chair")))
// This throws an exception, as an Order cannot be shipped if it has not been confirmed yet.
.thenCompose(result -> commandGateway.send(new ShipOrderCommand(orderId)));
}
@PostMapping("/order")
public CompletableFuture<String> createOrder() {
return createOrder(UUID.randomUUID().toString());
}
@PostMapping("/order/{order-id}")
public CompletableFuture<String> createOrder(@PathVariable("order-id") String orderId) {
return commandGateway.send(new CreateOrderCommand(orderId));
}
@PostMapping("/order/{order-id}/product/{product-id}")
public CompletableFuture<Void> addProduct(@PathVariable("order-id") String orderId,
@PathVariable("product-id") String productId) {
return commandGateway.send(new AddProductCommand(orderId, productId));
}
@PostMapping("/order/{order-id}/product/{product-id}/increment")
public CompletableFuture<Void> incrementProduct(@PathVariable("order-id") String orderId,
@PathVariable("product-id") String productId) {
return commandGateway.send(new IncrementProductCountCommand(orderId, productId));
}
@PostMapping("/order/{order-id}/product/{product-id}/decrement")
public CompletableFuture<Void> decrementProduct(@PathVariable("order-id") String orderId,
@PathVariable("product-id") String productId) {
return commandGateway.send(new DecrementProductCountCommand(orderId, productId));
}
@PostMapping("/order/{order-id}/confirm")
public CompletableFuture<Void> confirmOrder(@PathVariable("order-id") String orderId) {
return commandGateway.send(new ConfirmOrderCommand(orderId));
}
@PostMapping("/order/{order-id}/ship")
public CompletableFuture<Void> shipOrder(@PathVariable("order-id") String orderId) {
return commandGateway.send(new ShipOrderCommand(orderId));
}
@GetMapping("/all-orders")
public List<OrderedProduct> findAllOrderedProducts() {
return queryGateway.query(new FindAllOrderedProductsQuery(), ResponseTypes.multipleInstancesOf(OrderedProduct.class))
.join();
public CompletableFuture<List<Order>> findAllOrders() {
return queryGateway.query(new FindAllOrderedProductsQuery(), ResponseTypes.multipleInstancesOf(Order.class));
}
}

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