Merge remote-tracking branch 'upstream/master' into JAVA-2305
This commit is contained in:
commit
e14dcda200
@ -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];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
@ -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)
|
- [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)
|
- [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)
|
- [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)
|
|
||||||
|
3
apache-cxf/sse-jaxrs/README.md
Normal file
3
apache-cxf/sse-jaxrs/README.md
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
### Relevant Articles:
|
||||||
|
|
||||||
|
- [Server-Sent Events (SSE) In JAX-RS](https://www.baeldung.com/java-ee-jax-rs-sse)
|
@ -31,6 +31,6 @@ public class UseDateTimeFormatterUnitTest {
|
|||||||
public void givenALocalDate_whenFormattingWithStyleAndLocale_thenPass() {
|
public void givenALocalDate_whenFormattingWithStyleAndLocale_thenPass() {
|
||||||
String result = subject.formatWithStyleAndLocale(localDateTime, FormatStyle.MEDIUM, Locale.UK);
|
String result = subject.formatWithStyleAndLocale(localDateTime, FormatStyle.MEDIUM, Locale.UK);
|
||||||
|
|
||||||
assertThat(result).isEqualTo("25 Jan 2015, 06:30:00");
|
assertThat(result).isEqualTo("25-Jan-2015 06:30:00");
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -3,6 +3,7 @@ package com.baeldung.datetime;
|
|||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
import java.util.Calendar;
|
import java.util.Calendar;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.GregorianCalendar;
|
import java.util.GregorianCalendar;
|
||||||
@ -24,10 +25,11 @@ public class UseToInstantUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenADate_whenConvertingToLocalDate_thenAsExpected() {
|
public void givenADate_whenConvertingToLocalDate_thenAsExpected() {
|
||||||
Date givenDate = new Date(1465817690000L);
|
LocalDateTime currentDateTime = LocalDateTime.now();
|
||||||
|
Date givenDate = Date.from(currentDateTime.atZone(ZoneId.systemDefault()).toInstant());
|
||||||
|
|
||||||
LocalDateTime localDateTime = subject.convertDateToLocalDate(givenDate);
|
LocalDateTime localDateTime = subject.convertDateToLocalDate(givenDate);
|
||||||
|
|
||||||
assertThat(localDateTime).isEqualTo("2016-06-13T13:34:50");
|
assertThat(localDateTime).isEqualTo(currentDateTime);
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -54,7 +54,7 @@ public class UseZonedDateTimeUnitTest {
|
|||||||
@Test
|
@Test
|
||||||
public void givenAStringWithTimeZone_whenParsing_thenEqualsExpected() {
|
public void givenAStringWithTimeZone_whenParsing_thenEqualsExpected() {
|
||||||
ZonedDateTime resultFromString = zonedDateTime.getZonedDateTimeUsingParseMethod("2015-05-03T10:15:30+01:00[Europe/Paris]");
|
ZonedDateTime resultFromString = zonedDateTime.getZonedDateTimeUsingParseMethod("2015-05-03T10:15:30+01:00[Europe/Paris]");
|
||||||
ZonedDateTime resultFromLocalDateTime = ZonedDateTime.of(2015, 5, 3, 11, 15, 30, 0, ZoneId.of("Europe/Paris"));
|
ZonedDateTime resultFromLocalDateTime = ZonedDateTime.of(2015, 5, 3, 10, 15, 30, 0, ZoneId.of("Europe/Paris"));
|
||||||
|
|
||||||
assertThat(resultFromString.getZone()).isEqualTo(ZoneId.of("Europe/Paris"));
|
assertThat(resultFromString.getZone()).isEqualTo(ZoneId.of("Europe/Paris"));
|
||||||
assertThat(resultFromLocalDateTime.getZone()).isEqualTo(ZoneId.of("Europe/Paris"));
|
assertThat(resultFromLocalDateTime.getZone()).isEqualTo(ZoneId.of("Europe/Paris"));
|
||||||
|
@ -14,3 +14,4 @@ This module contains articles about core Java features that have been introduced
|
|||||||
- [Java 9 Reactive Streams](https://www.baeldung.com/java-9-reactive-streams)
|
- [Java 9 Reactive Streams](https://www.baeldung.com/java-9-reactive-streams)
|
||||||
- [Multi-Release JAR Files with Maven](https://www.baeldung.com/maven-multi-release-jars)
|
- [Multi-Release JAR Files with Maven](https://www.baeldung.com/maven-multi-release-jars)
|
||||||
- [The Difference between RxJava API and the Java 9 Flow API](https://www.baeldung.com/rxjava-vs-java-flow-api)
|
- [The Difference between RxJava API and the Java 9 Flow API](https://www.baeldung.com/rxjava-vs-java-flow-api)
|
||||||
|
- [How to Get a Name of a Method Being Executed?](https://www.baeldung.com/java-name-of-executing-method)
|
||||||
|
@ -5,7 +5,16 @@ import org.apache.commons.lang3.ArrayUtils;
|
|||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.util.*;
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
import java.util.Map.Entry;
|
import java.util.Map.Entry;
|
||||||
|
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
@ -138,7 +147,7 @@ public class JavaSortingUnitTest {
|
|||||||
HashSet<Integer> descSortedIntegersSet = new LinkedHashSet<>(Arrays.asList(255, 200, 123, 89, 88, 66, 7, 5, 1));
|
HashSet<Integer> descSortedIntegersSet = new LinkedHashSet<>(Arrays.asList(255, 200, 123, 89, 88, 66, 7, 5, 1));
|
||||||
|
|
||||||
ArrayList<Integer> list = new ArrayList<>(integersSet);
|
ArrayList<Integer> list = new ArrayList<>(integersSet);
|
||||||
list.sort((i1, i2) -> i2 - i1);
|
list.sort(Comparator.reverseOrder());
|
||||||
integersSet = new LinkedHashSet<>(list);
|
integersSet = new LinkedHashSet<>(list);
|
||||||
|
|
||||||
assertTrue(Arrays.equals(integersSet.toArray(), descSortedIntegersSet.toArray()));
|
assertTrue(Arrays.equals(integersSet.toArray(), descSortedIntegersSet.toArray()));
|
||||||
|
@ -21,6 +21,12 @@
|
|||||||
<artifactId>commons-collections4</artifactId>
|
<artifactId>commons-collections4</artifactId>
|
||||||
<version>${commons-collections4.version}</version>
|
<version>${commons-collections4.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.guava</groupId>
|
||||||
|
<artifactId>guava</artifactId>
|
||||||
|
<version>${guava.version}</version>
|
||||||
|
<scope>compile</scope>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.assertj</groupId>
|
<groupId>org.assertj</groupId>
|
||||||
<artifactId>assertj-core</artifactId>
|
<artifactId>assertj-core</artifactId>
|
||||||
|
@ -0,0 +1,96 @@
|
|||||||
|
package com.baeldung.list.difference;
|
||||||
|
|
||||||
|
import com.google.common.collect.Sets;
|
||||||
|
import org.apache.commons.collections4.CollectionUtils;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.assertj.core.api.Assertions.*;
|
||||||
|
|
||||||
|
public class FindDifferencesBetweenListsUnitTest {
|
||||||
|
|
||||||
|
private static final List<String> listOne = Arrays.asList("Jack", "Tom", "Sam", "John", "James", "Jack");
|
||||||
|
private static final List<String> listTwo = Arrays.asList("Jack", "Daniel", "Sam", "Alan", "James", "George");
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLists_whenUsingPlainJavaImpl_thenDifferencesAreFound() {
|
||||||
|
List<String> differences = new ArrayList<>(listOne);
|
||||||
|
differences.removeAll(listTwo);
|
||||||
|
assertEquals(2, differences.size());
|
||||||
|
assertThat(differences).containsExactly("Tom", "John");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenReverseLists_whenUsingPlainJavaImpl_thenDifferencesAreFound() {
|
||||||
|
List<String> differences = new ArrayList<>(listTwo);
|
||||||
|
differences.removeAll(listOne);
|
||||||
|
assertEquals(3, differences.size());
|
||||||
|
assertThat(differences).containsExactly("Daniel", "Alan", "George");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLists_whenUsingJavaStreams_thenDifferencesAreFound() {
|
||||||
|
List<String> differences = listOne.stream()
|
||||||
|
.filter(element -> !listTwo.contains(element))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
assertEquals(2, differences.size());
|
||||||
|
assertThat(differences).containsExactly("Tom", "John");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenReverseLists_whenUsingJavaStreams_thenDifferencesAreFound() {
|
||||||
|
List<String> differences = listTwo.stream()
|
||||||
|
.filter(element -> !listOne.contains(element))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
assertEquals(3, differences.size());
|
||||||
|
assertThat(differences).containsExactly("Daniel", "Alan", "George");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLists_whenUsingGoogleGuava_thenDifferencesAreFound() {
|
||||||
|
List<String> differences = new ArrayList<>(Sets.difference(Sets.newHashSet(listOne), Sets.newHashSet(listTwo)));
|
||||||
|
assertEquals(2, differences.size());
|
||||||
|
assertThat(differences).containsExactlyInAnyOrder("Tom", "John");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenReverseLists_whenUsingGoogleGuava_thenDifferencesAreFound() {
|
||||||
|
List<String> differences = new ArrayList<>(Sets.difference(Sets.newHashSet(listTwo), Sets.newHashSet(listOne)));
|
||||||
|
assertEquals(3, differences.size());
|
||||||
|
assertThat(differences).containsExactlyInAnyOrder("Daniel", "Alan", "George");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLists_whenUsingApacheCommons_thenDifferencesAreFound() {
|
||||||
|
List<String> differences = new ArrayList<>((CollectionUtils.removeAll(listOne, listTwo)));
|
||||||
|
assertEquals(2, differences.size());
|
||||||
|
assertThat(differences).containsExactly("Tom", "John");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenReverseLists_whenUsingApacheCommons_thenDifferencesAreFound() {
|
||||||
|
List<String> differences = new ArrayList<>((CollectionUtils.removeAll(listTwo, listOne)));
|
||||||
|
assertEquals(3, differences.size());
|
||||||
|
assertThat(differences).containsExactly("Daniel", "Alan", "George");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLists_whenUsingPlainJavaImpl_thenDifferencesWithDuplicatesAreFound() {
|
||||||
|
List<String> differences = new ArrayList<>(listOne);
|
||||||
|
listTwo.forEach(differences::remove);
|
||||||
|
assertThat(differences).containsExactly("Tom", "John", "Jack");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLists_whenUsingApacheCommons_thenDifferencesWithDuplicatesAreFound() {
|
||||||
|
List<String> differences = new ArrayList<>(CollectionUtils.subtract(listOne, listTwo));
|
||||||
|
assertEquals(3, differences.size());
|
||||||
|
assertThat(differences).containsExactly("Tom", "John", "Jack");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -21,20 +21,15 @@
|
|||||||
<version>${eclipse-collections.version}</version>
|
<version>${eclipse-collections.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>net.sf.trove4j</groupId>
|
<groupId>com.carrotsearch</groupId>
|
||||||
<artifactId>trove4j</artifactId>
|
<artifactId>hppc</artifactId>
|
||||||
<version>${trove4j.version}</version>
|
<version>${hppc.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>it.unimi.dsi</groupId>
|
<groupId>it.unimi.dsi</groupId>
|
||||||
<artifactId>fastutil</artifactId>
|
<artifactId>fastutil</artifactId>
|
||||||
<version>${fastutil.version}</version>
|
<version>${fastutil.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>colt</groupId>
|
|
||||||
<artifactId>colt</artifactId>
|
|
||||||
<version>${colt.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.commons</groupId>
|
<groupId>org.apache.commons</groupId>
|
||||||
<artifactId>commons-lang3</artifactId>
|
<artifactId>commons-lang3</artifactId>
|
||||||
@ -69,9 +64,8 @@
|
|||||||
<commons-collections4.version>4.1</commons-collections4.version>
|
<commons-collections4.version>4.1</commons-collections4.version>
|
||||||
<avaitility.version>1.7.0</avaitility.version>
|
<avaitility.version>1.7.0</avaitility.version>
|
||||||
<eclipse-collections.version>8.2.0</eclipse-collections.version>
|
<eclipse-collections.version>8.2.0</eclipse-collections.version>
|
||||||
<trove4j.version>3.0.2</trove4j.version>
|
<hppc.version>0.7.2</hppc.version>
|
||||||
<fastutil.version>8.1.0</fastutil.version>
|
<fastutil.version>8.1.0</fastutil.version>
|
||||||
<colt.version>1.2.0</colt.version>
|
|
||||||
<assertj.version>3.11.1</assertj.version>
|
<assertj.version>3.11.1</assertj.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
@ -1,29 +1,68 @@
|
|||||||
package com.baeldung.map.primitives;
|
package com.baeldung.map.primitives;
|
||||||
|
|
||||||
import cern.colt.map.AbstractIntDoubleMap;
|
import com.carrotsearch.hppc.IntLongHashMap;
|
||||||
import cern.colt.map.OpenIntDoubleHashMap;
|
import com.carrotsearch.hppc.IntLongScatterMap;
|
||||||
import gnu.trove.map.TDoubleIntMap;
|
import com.carrotsearch.hppc.IntObjectHashMap;
|
||||||
import gnu.trove.map.hash.TDoubleIntHashMap;
|
import com.carrotsearch.hppc.IntObjectMap;
|
||||||
|
import com.carrotsearch.hppc.IntObjectScatterMap;
|
||||||
|
|
||||||
import it.unimi.dsi.fastutil.ints.Int2BooleanMap;
|
import it.unimi.dsi.fastutil.ints.Int2BooleanMap;
|
||||||
|
import it.unimi.dsi.fastutil.ints.Int2BooleanMaps;
|
||||||
import it.unimi.dsi.fastutil.ints.Int2BooleanOpenHashMap;
|
import it.unimi.dsi.fastutil.ints.Int2BooleanOpenHashMap;
|
||||||
import it.unimi.dsi.fastutil.ints.Int2BooleanSortedMap;
|
import it.unimi.dsi.fastutil.ints.Int2BooleanSortedMap;
|
||||||
import it.unimi.dsi.fastutil.ints.Int2BooleanSortedMaps;
|
import it.unimi.dsi.fastutil.ints.Int2BooleanSortedMaps;
|
||||||
|
import it.unimi.dsi.fastutil.objects.ObjectIterator;
|
||||||
|
|
||||||
import org.eclipse.collections.api.map.primitive.ImmutableIntIntMap;
|
import org.eclipse.collections.api.map.primitive.ImmutableIntIntMap;
|
||||||
import org.eclipse.collections.api.map.primitive.MutableIntIntMap;
|
import org.eclipse.collections.api.map.primitive.MutableIntIntMap;
|
||||||
import org.eclipse.collections.api.map.primitive.MutableObjectDoubleMap;
|
import org.eclipse.collections.api.map.primitive.MutableObjectDoubleMap;
|
||||||
import org.eclipse.collections.impl.factory.primitive.IntIntMaps;
|
import org.eclipse.collections.impl.factory.primitive.IntIntMaps;
|
||||||
import org.eclipse.collections.impl.factory.primitive.ObjectDoubleMaps;
|
import org.eclipse.collections.impl.factory.primitive.ObjectDoubleMaps;
|
||||||
|
|
||||||
|
import static java.lang.String.format;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
public class PrimitiveMaps {
|
public class PrimitiveMaps {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
hppcMap();
|
||||||
eclipseCollectionsMap();
|
eclipseCollectionsMap();
|
||||||
troveMap();
|
|
||||||
coltMap();
|
|
||||||
fastutilMap();
|
fastutilMap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static void hppcMap() {
|
||||||
|
//Regular maps
|
||||||
|
IntLongHashMap intLongHashMap = new IntLongHashMap();
|
||||||
|
intLongHashMap.put(25,1L);
|
||||||
|
intLongHashMap.put(150,Long.MAX_VALUE);
|
||||||
|
intLongHashMap.put(1,0L);
|
||||||
|
|
||||||
|
intLongHashMap.get(150);
|
||||||
|
|
||||||
|
IntObjectMap<BigDecimal> intObjectMap = new IntObjectHashMap<BigDecimal>();
|
||||||
|
intObjectMap.put(1, BigDecimal.valueOf(1));
|
||||||
|
intObjectMap.put(2, BigDecimal.valueOf(2500));
|
||||||
|
|
||||||
|
BigDecimal value = intObjectMap.get(2);
|
||||||
|
|
||||||
|
//Scatter maps
|
||||||
|
IntLongScatterMap intLongScatterMap = new IntLongScatterMap();
|
||||||
|
intLongScatterMap.put(1, 1L);
|
||||||
|
intLongScatterMap.put(2, -2L);
|
||||||
|
intLongScatterMap.put(1000,0L);
|
||||||
|
|
||||||
|
intLongScatterMap.get(1000);
|
||||||
|
|
||||||
|
IntObjectScatterMap<BigDecimal> intObjectScatterMap = new IntObjectScatterMap<BigDecimal>();
|
||||||
|
intObjectScatterMap.put(1, BigDecimal.valueOf(1));
|
||||||
|
intObjectScatterMap.put(2, BigDecimal.valueOf(2500));
|
||||||
|
|
||||||
|
value = intObjectScatterMap.get(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
private static void fastutilMap() {
|
private static void fastutilMap() {
|
||||||
Int2BooleanMap int2BooleanMap = new Int2BooleanOpenHashMap();
|
Int2BooleanMap int2BooleanMap = new Int2BooleanOpenHashMap();
|
||||||
int2BooleanMap.put(1, true);
|
int2BooleanMap.put(1, true);
|
||||||
@ -32,13 +71,19 @@ public class PrimitiveMaps {
|
|||||||
|
|
||||||
boolean value = int2BooleanMap.get(1);
|
boolean value = int2BooleanMap.get(1);
|
||||||
|
|
||||||
Int2BooleanSortedMap int2BooleanSorted = Int2BooleanSortedMaps.EMPTY_MAP;
|
//Lambda style iteration
|
||||||
}
|
Int2BooleanMaps.fastForEach(int2BooleanMap, entry -> {
|
||||||
|
System.out.println(String.format("Key: %d, Value: %b",entry.getIntKey(),entry.getBooleanValue()));
|
||||||
|
});
|
||||||
|
|
||||||
|
//Iterator based loop
|
||||||
|
ObjectIterator<Int2BooleanMap.Entry> iterator = Int2BooleanMaps.fastIterator(int2BooleanMap);
|
||||||
|
while(iterator.hasNext()) {
|
||||||
|
Int2BooleanMap.Entry entry = iterator.next();
|
||||||
|
System.out.println(String.format("Key: %d, Value: %b",entry.getIntKey(),entry.getBooleanValue()));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
private static void coltMap() {
|
|
||||||
AbstractIntDoubleMap map = new OpenIntDoubleHashMap();
|
|
||||||
map.put(1, 4.5);
|
|
||||||
double value = map.get(1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void eclipseCollectionsMap() {
|
private static void eclipseCollectionsMap() {
|
||||||
@ -53,17 +98,5 @@ public class PrimitiveMaps {
|
|||||||
dObject.addToValue("stability", 0.8);
|
dObject.addToValue("stability", 0.8);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void troveMap() {
|
|
||||||
double[] doubles = new double[] {1.2, 4.5, 0.3};
|
|
||||||
int[] ints = new int[] {1, 4, 0};
|
|
||||||
|
|
||||||
TDoubleIntMap doubleIntMap = new TDoubleIntHashMap(doubles, ints);
|
|
||||||
|
|
||||||
doubleIntMap.put(1.2, 22);
|
|
||||||
doubleIntMap.put(4.5, 16);
|
|
||||||
|
|
||||||
doubleIntMap.adjustValue(1.2, 1);
|
|
||||||
doubleIntMap.adjustValue(4.5, 4);
|
|
||||||
doubleIntMap.adjustValue(0.3, 7);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.threadlocal;
|
||||||
|
|
||||||
|
import java.util.concurrent.BlockingQueue;
|
||||||
|
import java.util.concurrent.RejectedExecutionHandler;
|
||||||
|
import java.util.concurrent.ThreadFactory;
|
||||||
|
import java.util.concurrent.ThreadPoolExecutor;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
public class ThreadLocalAwareThreadPool extends ThreadPoolExecutor {
|
||||||
|
|
||||||
|
public ThreadLocalAwareThreadPool(int corePoolSize,
|
||||||
|
int maximumPoolSize,
|
||||||
|
long keepAliveTime,
|
||||||
|
TimeUnit unit,
|
||||||
|
BlockingQueue<Runnable> workQueue,
|
||||||
|
ThreadFactory threadFactory,
|
||||||
|
RejectedExecutionHandler handler) {
|
||||||
|
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void afterExecute(Runnable r, Throwable t) {
|
||||||
|
// Call remove on each ThreadLocal
|
||||||
|
}
|
||||||
|
}
|
34
core-java-modules/core-java-exceptions-3/pom.xml
Normal file
34
core-java-modules/core-java-exceptions-3/pom.xml
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project
|
||||||
|
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>com.baeldung.exceptions</groupId>
|
||||||
|
<artifactId>core-java-exceptions-3</artifactId>
|
||||||
|
<version>0.1.0-SNAPSHOT</version>
|
||||||
|
<name>core-java-exceptions-3</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung.core-java-modules</groupId>
|
||||||
|
<artifactId>core-java-modules</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<!-- test scoped -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>${assertj-core.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<!-- testing -->
|
||||||
|
<assertj-core.version>3.10.0</assertj-core.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1,11 @@
|
|||||||
|
package com.baeldung.exceptions.nosuchmethoderror;
|
||||||
|
|
||||||
|
public class MainMenu {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
System.out.println("Today's Specials: " + getSpecials());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getSpecials() {
|
||||||
|
return SpecialToday.getDesert();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,8 @@
|
|||||||
|
package com.baeldung.exceptions.nosuchmethoderror;
|
||||||
|
public class SpecialToday {
|
||||||
|
private static String desert = "Chocolate Cake";
|
||||||
|
|
||||||
|
public static String getDesert() {
|
||||||
|
return desert;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.exceptions.nosuchmethoderror;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class MainMenuUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenGetSpecials_thenNotNull() {
|
||||||
|
assertNotNull(MainMenu.getSpecials());
|
||||||
|
}
|
||||||
|
}
|
@ -16,10 +16,10 @@ import org.junit.jupiter.api.Test;
|
|||||||
|
|
||||||
public class ApacheCommonsUnitTest {
|
public class ApacheCommonsUnitTest {
|
||||||
|
|
||||||
private final String sourceDirectoryLocation = "src/test/resources/sourceDirectory";
|
private final String sourceDirectoryLocation = "src/test/resources/sourceDirectory3";
|
||||||
private final String subDirectoryName = "/childDirectory";
|
private final String subDirectoryName = "/childDirectory";
|
||||||
private final String fileName = "/file.txt";
|
private final String fileName = "/file.txt";
|
||||||
private final String destinationDirectoryLocation = "src/test/resources/destinationDirectory";
|
private final String destinationDirectoryLocation = "src/test/resources/destinationDirectory3";
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
public void createDirectoryWithSubdirectoryAndFile() throws IOException {
|
public void createDirectoryWithSubdirectoryAndFile() throws IOException {
|
||||||
|
@ -16,10 +16,10 @@ import org.junit.jupiter.api.Test;
|
|||||||
|
|
||||||
public class CoreOldUnitTest {
|
public class CoreOldUnitTest {
|
||||||
|
|
||||||
private final String sourceDirectoryLocation = "src/test/resources/sourceDirectory";
|
private final String sourceDirectoryLocation = "src/test/resources/sourceDirectory1";
|
||||||
private final String subDirectoryName = "/childDirectory";
|
private final String subDirectoryName = "/childDirectory";
|
||||||
private final String fileName = "/file.txt";
|
private final String fileName = "/file.txt";
|
||||||
private final String destinationDirectoryLocation = "src/test/resources/destinationDirectory";
|
private final String destinationDirectoryLocation = "src/test/resources/destinationDirectory1";
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
public void createDirectoryWithSubdirectoryAndFile() throws IOException {
|
public void createDirectoryWithSubdirectoryAndFile() throws IOException {
|
||||||
|
@ -16,10 +16,10 @@ import org.junit.jupiter.api.Test;
|
|||||||
|
|
||||||
public class JavaNioUnitTest {
|
public class JavaNioUnitTest {
|
||||||
|
|
||||||
private final String sourceDirectoryLocation = "src/test/resources/sourceDirectory";
|
private final String sourceDirectoryLocation = "src/test/resources/sourceDirectory2";
|
||||||
private final String subDirectoryName = "/childDirectory";
|
private final String subDirectoryName = "/childDirectory";
|
||||||
private final String fileName = "/file.txt";
|
private final String fileName = "/file.txt";
|
||||||
private final String destinationDirectoryLocation = "src/test/resources/destinationDirectory";
|
private final String destinationDirectoryLocation = "src/test/resources/destinationDirectory2";
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
public void createDirectoryWithSubdirectoryAndFile() throws IOException {
|
public void createDirectoryWithSubdirectoryAndFile() throws IOException {
|
||||||
|
@ -0,0 +1,19 @@
|
|||||||
|
package com.baeldung.loadedclasslisting;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
public class Launcher {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
printClassesLoadedBy("BOOTSTRAP");
|
||||||
|
printClassesLoadedBy("SYSTEM");
|
||||||
|
printClassesLoadedBy("EXTENSION");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void printClassesLoadedBy(String classLoaderType) {
|
||||||
|
System.out.println(classLoaderType + " ClassLoader : ");
|
||||||
|
Class<?>[] classes = ListLoadedClassesAgent.listLoadedClasses(classLoaderType);
|
||||||
|
Arrays.asList(classes)
|
||||||
|
.forEach(clazz -> System.out.println(clazz.getCanonicalName()));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,40 @@
|
|||||||
|
package com.baeldung.loadedclasslisting;
|
||||||
|
|
||||||
|
import java.lang.instrument.Instrumentation;
|
||||||
|
|
||||||
|
public class ListLoadedClassesAgent {
|
||||||
|
|
||||||
|
private static Instrumentation instrumentation;
|
||||||
|
|
||||||
|
public static void premain(String agentArgs, Instrumentation instrumentation) {
|
||||||
|
ListLoadedClassesAgent.instrumentation = instrumentation;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Class<?>[] listLoadedClasses(String classLoaderType) {
|
||||||
|
if (instrumentation == null) {
|
||||||
|
throw new IllegalStateException(
|
||||||
|
"ListLoadedClassesAgent is not initialized.");
|
||||||
|
}
|
||||||
|
return instrumentation.getInitiatedClasses(
|
||||||
|
getClassLoader(classLoaderType));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ClassLoader getClassLoader(String classLoaderType) {
|
||||||
|
ClassLoader classLoader = null;
|
||||||
|
switch (classLoaderType) {
|
||||||
|
case "SYSTEM":
|
||||||
|
classLoader = ClassLoader.getSystemClassLoader();
|
||||||
|
break;
|
||||||
|
case "EXTENSION":
|
||||||
|
classLoader = ClassLoader.getSystemClassLoader().getParent();
|
||||||
|
break;
|
||||||
|
// passing a null value to the Instrumentation : getInitiatedClasses method
|
||||||
|
// defaults to the bootstrap class loader
|
||||||
|
case "BOOTSTRAP":
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return classLoader;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1 @@
|
|||||||
|
Premain-Class: com.baeldung.loadedclasslisting.ListLoadedClassesAgent
|
@ -37,7 +37,7 @@ public class Human {
|
|||||||
|
|
||||||
public static int compareByNameThenAge(final Human lhs, final Human rhs) {
|
public static int compareByNameThenAge(final Human lhs, final Human rhs) {
|
||||||
if (lhs.name.equals(rhs.name)) {
|
if (lhs.name.equals(rhs.name)) {
|
||||||
return lhs.age - rhs.age;
|
return Integer.compare(lhs.age, rhs.age);
|
||||||
} else {
|
} else {
|
||||||
return lhs.name.compareTo(rhs.name);
|
return lhs.name.compareTo(rhs.name);
|
||||||
}
|
}
|
||||||
|
@ -54,7 +54,7 @@ public class Java8SortUnitTest {
|
|||||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 12), new Human("Sarah", 10), new Human("Zack", 12));
|
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 12), new Human("Sarah", 10), new Human("Zack", 12));
|
||||||
humans.sort((lhs, rhs) -> {
|
humans.sort((lhs, rhs) -> {
|
||||||
if (lhs.getName().equals(rhs.getName())) {
|
if (lhs.getName().equals(rhs.getName())) {
|
||||||
return lhs.getAge() - rhs.getAge();
|
return Integer.compare(lhs.getAge(), rhs.getAge());
|
||||||
} else {
|
} else {
|
||||||
return lhs.getName().compareTo(rhs.getName());
|
return lhs.getName().compareTo(rhs.getName());
|
||||||
}
|
}
|
||||||
|
@ -45,7 +45,7 @@ public class Player implements Comparable<Player> {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int compareTo(Player otherPlayer) {
|
public int compareTo(Player otherPlayer) {
|
||||||
return (this.getRanking() - otherPlayer.getRanking());
|
return Integer.compare(getRanking(), otherPlayer.getRanking());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -6,7 +6,7 @@ public class PlayerAgeComparator implements Comparator<Player> {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int compare(Player firstPlayer, Player secondPlayer) {
|
public int compare(Player firstPlayer, Player secondPlayer) {
|
||||||
return (firstPlayer.getAge() - secondPlayer.getAge());
|
return Integer.compare(firstPlayer.getAge(), secondPlayer.getAge());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -6,7 +6,7 @@ public class PlayerRankingComparator implements Comparator<Player> {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int compare(Player firstPlayer, Player secondPlayer) {
|
public int compare(Player firstPlayer, Player secondPlayer) {
|
||||||
return (firstPlayer.getRanking() - secondPlayer.getRanking());
|
return Integer.compare(firstPlayer.getRanking(), secondPlayer.getRanking());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,26 @@
|
|||||||
|
package com.baeldung.comparator;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class AvoidingSubtractionUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoPlayers_whenUsingSubtraction_thenOverflow() {
|
||||||
|
Comparator<Player> comparator = (p1, p2) -> p1.getRanking() - p2.getRanking();
|
||||||
|
Player player1 = new Player(59, "John", Integer.MAX_VALUE);
|
||||||
|
Player player2 = new Player(67, "Roger", -1);
|
||||||
|
|
||||||
|
List<Player> players = Arrays.asList(player1, player2);
|
||||||
|
players.sort(comparator);
|
||||||
|
System.out.println(players);
|
||||||
|
|
||||||
|
assertEquals("John", players.get(0).getName());
|
||||||
|
assertEquals("Roger", players.get(1).getName());
|
||||||
|
}
|
||||||
|
}
|
@ -1,14 +1,14 @@
|
|||||||
package com.baeldung.comparator;
|
package com.baeldung.comparator;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import org.junit.Before;
|
import static org.junit.Assert.assertEquals;
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class Java8ComparatorUnitTest {
|
public class Java8ComparatorUnitTest {
|
||||||
|
|
||||||
@ -28,7 +28,7 @@ public class Java8ComparatorUnitTest {
|
|||||||
@Test
|
@Test
|
||||||
public void whenComparing_UsingLambda_thenSorted() {
|
public void whenComparing_UsingLambda_thenSorted() {
|
||||||
System.out.println("************** Java 8 Comaparator **************");
|
System.out.println("************** Java 8 Comaparator **************");
|
||||||
Comparator<Player> byRanking = (Player player1, Player player2) -> player1.getRanking() - player2.getRanking();
|
Comparator<Player> byRanking = (Player player1, Player player2) -> Integer.compare(player1.getRanking(), player2.getRanking());
|
||||||
|
|
||||||
System.out.println("Before Sorting : " + footballTeam);
|
System.out.println("Before Sorting : " + footballTeam);
|
||||||
Collections.sort(footballTeam, byRanking);
|
Collections.sort(footballTeam, byRanking);
|
||||||
|
@ -49,11 +49,11 @@ public class EchoServer {
|
|||||||
if (new String(buffer.array()).trim().equals(POISON_PILL)) {
|
if (new String(buffer.array()).trim().equals(POISON_PILL)) {
|
||||||
client.close();
|
client.close();
|
||||||
System.out.println("Not accepting client messages anymore");
|
System.out.println("Not accepting client messages anymore");
|
||||||
|
} else {
|
||||||
|
buffer.flip();
|
||||||
|
client.write(buffer);
|
||||||
|
buffer.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
buffer.flip();
|
|
||||||
client.write(buffer);
|
|
||||||
buffer.clear();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void register(Selector selector, ServerSocketChannel serverSocket) throws IOException {
|
private static void register(Selector selector, ServerSocketChannel serverSocket) throws IOException {
|
||||||
|
@ -1,13 +1,13 @@
|
|||||||
## Core Java Cookbooks and Examples
|
## Core Java Cookbooks and Examples
|
||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
[Getting Started with Java Properties](http://www.baeldung.com/java-properties)
|
- [Getting Started with Java Properties](http://www.baeldung.com/java-properties)
|
||||||
[Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
|
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
|
||||||
[Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
|
- [Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
|
||||||
[Guide to UUID in Java](http://www.baeldung.com/java-uuid)
|
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
|
||||||
[Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
|
- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
|
||||||
[Introduction to Javadoc](http://www.baeldung.com/javadoc)
|
- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
|
||||||
[Guide to the Externalizable Interface in Java](http://www.baeldung.com/java-externalizable)
|
- [Guide to the Externalizable Interface in Java](http://www.baeldung.com/java-externalizable)
|
||||||
[What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid)
|
- [What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid)
|
||||||
[A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
|
- [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
|
||||||
[Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
|
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
|
||||||
|
@ -22,6 +22,7 @@
|
|||||||
<!-- <module>core-java-11</module> --> <!-- We haven't upgraded to java 11. Fixing in BAEL-10841 -->
|
<!-- <module>core-java-11</module> --> <!-- We haven't upgraded to java 11. Fixing in BAEL-10841 -->
|
||||||
<!-- <module>core-java-12</module> --> <!-- We haven't upgraded to java 12. Fixing in BAEL-10841 -->
|
<!-- <module>core-java-12</module> --> <!-- We haven't upgraded to java 12. Fixing in BAEL-10841 -->
|
||||||
<!-- <module>core-java-13</module> --> <!-- We haven't upgraded to java 12. Fixing in BAEL-10841 -->
|
<!-- <module>core-java-13</module> --> <!-- We haven't upgraded to java 12. Fixing in BAEL-10841 -->
|
||||||
|
<!-- <module>core-java-14</module> --> <!-- We haven't upgraded to java 14.-->
|
||||||
<module>core-java-8</module>
|
<module>core-java-8</module>
|
||||||
<module>core-java-8-2</module>
|
<module>core-java-8-2</module>
|
||||||
|
|
||||||
@ -59,15 +60,20 @@
|
|||||||
<module>core-java-concurrency-basic</module>
|
<module>core-java-concurrency-basic</module>
|
||||||
<module>core-java-concurrency-basic-2</module>
|
<module>core-java-concurrency-basic-2</module>
|
||||||
<module>core-java-concurrency-collections</module>
|
<module>core-java-concurrency-collections</module>
|
||||||
|
<module>core-java-concurrency-collections-2</module>
|
||||||
|
<module>core-java-console</module>
|
||||||
|
|
||||||
|
<!--<module>core-java-8-datetime</module>--> <!-- unit test case failure -->
|
||||||
|
<module>core-java-8-datetime-2</module>
|
||||||
<!-- <module>core-java-date-operations-1</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
|
<!-- <module>core-java-date-operations-1</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
|
||||||
<module>core-java-date-operations-2</module>
|
<module>core-java-date-operations-2</module>
|
||||||
<!-- We haven't upgraded to java 9. -->
|
<!-- We haven't upgraded to java 9. -->
|
||||||
<!-- <module>core-java-datetime-computations</module> <module>core-java-datetime-conversion</module> <module>core-java-datetime-java8</module> <module>core-java-datetime-string</module> -->
|
<!-- <module>core-java-datetime-computations</module> <module>core-java-datetime-conversion</module> <module>core-java-datetime-java8</module> <module>core-java-datetime-string</module> -->
|
||||||
|
<module>core-java-8-datetime</module>
|
||||||
|
|
||||||
<module>core-java-exceptions</module>
|
<module>core-java-exceptions</module>
|
||||||
<module>core-java-exceptions-2</module>
|
<module>core-java-exceptions-2</module>
|
||||||
|
<module>core-java-exceptions-3</module>
|
||||||
<module>core-java-function</module>
|
<module>core-java-function</module>
|
||||||
|
|
||||||
<module>core-java-io</module>
|
<module>core-java-io</module>
|
||||||
|
3
docker/docker-spring-boot/README.md
Normal file
3
docker/docker-spring-boot/README.md
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
### Relevant Article:
|
||||||
|
|
||||||
|
- [Creating Docker Images with Spring Boot](https://www.baeldung.com/spring-boot-docker-images)
|
@ -3,6 +3,3 @@
|
|||||||
This module contains articles about Apache POI
|
This module contains articles about Apache POI
|
||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Working with Microsoft Excel in Java](https://www.baeldung.com/java-microsoft-excel)
|
|
||||||
- [Read Excel Cell Value Rather Than Formula With Apache POI](https://www.baeldung.com/apache-poi-read-cell-value-formula)
|
|
||||||
- [Upload and Display Excel Files with Spring MVC](https://www.baeldung.com/spring-mvc-excel-files)
|
|
||||||
|
@ -144,7 +144,7 @@ public class JavaCollectionConversionUnitTest {
|
|||||||
final Map<Integer, String> sourceMap = createMap();
|
final Map<Integer, String> sourceMap = createMap();
|
||||||
|
|
||||||
final Collection<String> values = sourceMap.values();
|
final Collection<String> values = sourceMap.values();
|
||||||
final String[] targetArray = values.toArray(new String[values.size()]);
|
final String[] targetArray = values.toArray(new String[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -4,7 +4,7 @@ This module contains articles about numbers in Java.
|
|||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
|
|
||||||
- [Generating Random Numbers](https://www.baeldung.com/java-generating-random-numbers)
|
- [Generating Random Numbers in Java](https://www.baeldung.com/java-generating-random-numbers)
|
||||||
- [Convert Double to Long in Java](https://www.baeldung.com/java-convert-double-long)
|
- [Convert Double to Long in Java](https://www.baeldung.com/java-convert-double-long)
|
||||||
- [Check for null Before Calling Parse in Double.parseDouble](https://www.baeldung.com/java-check-null-parse-double)
|
- [Check for null Before Calling Parse in Double.parseDouble](https://www.baeldung.com/java-check-null-parse-double)
|
||||||
- [Generating Random Numbers in a Range in Java](https://www.baeldung.com/java-generating-random-numbers-in-range)
|
- [Generating Random Numbers in a Range in Java](https://www.baeldung.com/java-generating-random-numbers-in-range)
|
||||||
|
@ -6,6 +6,8 @@ import com.baeldung.jgit.helper.Helper;
|
|||||||
import org.eclipse.jgit.api.Git;
|
import org.eclipse.jgit.api.Git;
|
||||||
import org.eclipse.jgit.api.errors.GitAPIException;
|
import org.eclipse.jgit.api.errors.GitAPIException;
|
||||||
import org.eclipse.jgit.lib.Repository;
|
import org.eclipse.jgit.lib.Repository;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Simple snippet which shows how to add a file to the index
|
* Simple snippet which shows how to add a file to the index
|
||||||
@ -14,6 +16,8 @@ import org.eclipse.jgit.lib.Repository;
|
|||||||
*/
|
*/
|
||||||
public class AddFile {
|
public class AddFile {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(AddFile.class);
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException, GitAPIException {
|
public static void main(String[] args) throws IOException, GitAPIException {
|
||||||
// prepare a new test-repository
|
// prepare a new test-repository
|
||||||
try (Repository repository = Helper.createNewRepository()) {
|
try (Repository repository = Helper.createNewRepository()) {
|
||||||
@ -29,7 +33,7 @@ public class AddFile {
|
|||||||
.addFilepattern("testfile")
|
.addFilepattern("testfile")
|
||||||
.call();
|
.call();
|
||||||
|
|
||||||
System.out.println("Added file " + myfile + " to repository at " + repository.getDirectory());
|
logger.debug("Added file " + myfile + " to repository at " + repository.getDirectory());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,6 +7,8 @@ import com.baeldung.jgit.helper.Helper;
|
|||||||
import org.eclipse.jgit.api.Git;
|
import org.eclipse.jgit.api.Git;
|
||||||
import org.eclipse.jgit.api.errors.GitAPIException;
|
import org.eclipse.jgit.api.errors.GitAPIException;
|
||||||
import org.eclipse.jgit.lib.Repository;
|
import org.eclipse.jgit.lib.Repository;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Simple snippet which shows how to commit all files
|
* Simple snippet which shows how to commit all files
|
||||||
@ -15,6 +17,8 @@ import org.eclipse.jgit.lib.Repository;
|
|||||||
*/
|
*/
|
||||||
public class CommitAll {
|
public class CommitAll {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(CommitAll.class);
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException, GitAPIException {
|
public static void main(String[] args) throws IOException, GitAPIException {
|
||||||
// prepare a new test-repository
|
// prepare a new test-repository
|
||||||
try (Repository repository = Helper.createNewRepository()) {
|
try (Repository repository = Helper.createNewRepository()) {
|
||||||
@ -44,7 +48,7 @@ public class CommitAll {
|
|||||||
.call();
|
.call();
|
||||||
|
|
||||||
|
|
||||||
System.out.println("Committed all changes to repository at " + repository.getDirectory());
|
logger.debug("Committed all changes to repository at " + repository.getDirectory());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -9,6 +9,8 @@ import org.eclipse.jgit.lib.Ref;
|
|||||||
import org.eclipse.jgit.lib.Repository;
|
import org.eclipse.jgit.lib.Repository;
|
||||||
import org.eclipse.jgit.revwalk.RevCommit;
|
import org.eclipse.jgit.revwalk.RevCommit;
|
||||||
import org.eclipse.jgit.revwalk.RevWalk;
|
import org.eclipse.jgit.revwalk.RevWalk;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Simple snippet which shows how to create a tag
|
* Simple snippet which shows how to create a tag
|
||||||
@ -17,6 +19,8 @@ import org.eclipse.jgit.revwalk.RevWalk;
|
|||||||
*/
|
*/
|
||||||
public class CreateAndDeleteTag {
|
public class CreateAndDeleteTag {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(CreateAndDeleteTag.class);
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException, GitAPIException {
|
public static void main(String[] args) throws IOException, GitAPIException {
|
||||||
// prepare test-repository
|
// prepare test-repository
|
||||||
try (Repository repository = Helper.openJGitRepository()) {
|
try (Repository repository = Helper.openJGitRepository()) {
|
||||||
@ -26,7 +30,7 @@ public class CreateAndDeleteTag {
|
|||||||
|
|
||||||
// set it on the current HEAD
|
// set it on the current HEAD
|
||||||
Ref tag = git.tag().setName("tag_for_testing").call();
|
Ref tag = git.tag().setName("tag_for_testing").call();
|
||||||
System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory());
|
logger.debug("Created/moved tag " + tag + " to repository at " + repository.getDirectory());
|
||||||
|
|
||||||
// remove the tag again
|
// remove the tag again
|
||||||
git.tagDelete().setTags("tag_for_testing").call();
|
git.tagDelete().setTags("tag_for_testing").call();
|
||||||
@ -36,14 +40,14 @@ public class CreateAndDeleteTag {
|
|||||||
try (RevWalk walk = new RevWalk(repository)) {
|
try (RevWalk walk = new RevWalk(repository)) {
|
||||||
RevCommit commit = walk.parseCommit(id);
|
RevCommit commit = walk.parseCommit(id);
|
||||||
tag = git.tag().setObjectId(commit).setName("tag_for_testing").call();
|
tag = git.tag().setObjectId(commit).setName("tag_for_testing").call();
|
||||||
System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory());
|
logger.debug("Created/moved tag " + tag + " to repository at " + repository.getDirectory());
|
||||||
|
|
||||||
// remove the tag again
|
// remove the tag again
|
||||||
git.tagDelete().setTags("tag_for_testing").call();
|
git.tagDelete().setTags("tag_for_testing").call();
|
||||||
|
|
||||||
// create an annotated tag
|
// create an annotated tag
|
||||||
tag = git.tag().setName("tag_for_testing").setAnnotated(true).call();
|
tag = git.tag().setName("tag_for_testing").setAnnotated(true).call();
|
||||||
System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory());
|
logger.debug("Created/moved tag " + tag + " to repository at " + repository.getDirectory());
|
||||||
|
|
||||||
// remove the tag again
|
// remove the tag again
|
||||||
git.tagDelete().setTags("tag_for_testing").call();
|
git.tagDelete().setTags("tag_for_testing").call();
|
||||||
|
@ -7,6 +7,9 @@ import org.eclipse.jgit.api.errors.GitAPIException;
|
|||||||
import org.eclipse.jgit.lib.Repository;
|
import org.eclipse.jgit.lib.Repository;
|
||||||
import org.eclipse.jgit.revwalk.RevCommit;
|
import org.eclipse.jgit.revwalk.RevCommit;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Simple snippet which shows how to get the commit-ids for a file to provide log information.
|
* Simple snippet which shows how to get the commit-ids for a file to provide log information.
|
||||||
*
|
*
|
||||||
@ -14,6 +17,8 @@ import org.eclipse.jgit.revwalk.RevCommit;
|
|||||||
*/
|
*/
|
||||||
public class Log {
|
public class Log {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(Log.class);
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
public static void main(String[] args) throws IOException, GitAPIException {
|
public static void main(String[] args) throws IOException, GitAPIException {
|
||||||
try (Repository repository = Helper.openJGitRepository()) {
|
try (Repository repository = Helper.openJGitRepository()) {
|
||||||
@ -22,30 +27,30 @@ public class Log {
|
|||||||
.call();
|
.call();
|
||||||
int count = 0;
|
int count = 0;
|
||||||
for (RevCommit rev : logs) {
|
for (RevCommit rev : logs) {
|
||||||
//System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
|
logger.trace("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
|
||||||
count++;
|
count++;
|
||||||
}
|
}
|
||||||
System.out.println("Had " + count + " commits overall on current branch");
|
logger.debug("Had " + count + " commits overall on current branch");
|
||||||
|
|
||||||
logs = git.log()
|
logs = git.log()
|
||||||
.add(repository.resolve(git.getRepository().getFullBranch()))
|
.add(repository.resolve(git.getRepository().getFullBranch()))
|
||||||
.call();
|
.call();
|
||||||
count = 0;
|
count = 0;
|
||||||
for (RevCommit rev : logs) {
|
for (RevCommit rev : logs) {
|
||||||
System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
|
logger.trace("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
|
||||||
count++;
|
count++;
|
||||||
}
|
}
|
||||||
System.out.println("Had " + count + " commits overall on "+git.getRepository().getFullBranch());
|
logger.debug("Had " + count + " commits overall on "+git.getRepository().getFullBranch());
|
||||||
|
|
||||||
logs = git.log()
|
logs = git.log()
|
||||||
.all()
|
.all()
|
||||||
.call();
|
.call();
|
||||||
count = 0;
|
count = 0;
|
||||||
for (RevCommit rev : logs) {
|
for (RevCommit rev : logs) {
|
||||||
//System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
|
logger.trace("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
|
||||||
count++;
|
count++;
|
||||||
}
|
}
|
||||||
System.out.println("Had " + count + " commits overall in repository");
|
logger.debug("Had " + count + " commits overall in repository");
|
||||||
|
|
||||||
logs = git.log()
|
logs = git.log()
|
||||||
// for all log.all()
|
// for all log.all()
|
||||||
@ -53,10 +58,10 @@ public class Log {
|
|||||||
.call();
|
.call();
|
||||||
count = 0;
|
count = 0;
|
||||||
for (RevCommit rev : logs) {
|
for (RevCommit rev : logs) {
|
||||||
//System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
|
logger.trace("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
|
||||||
count++;
|
count++;
|
||||||
}
|
}
|
||||||
System.out.println("Had " + count + " commits on README.md");
|
logger.debug("Had " + count + " commits on README.md");
|
||||||
|
|
||||||
logs = git.log()
|
logs = git.log()
|
||||||
// for all log.all()
|
// for all log.all()
|
||||||
@ -64,10 +69,10 @@ public class Log {
|
|||||||
.call();
|
.call();
|
||||||
count = 0;
|
count = 0;
|
||||||
for (RevCommit rev : logs) {
|
for (RevCommit rev : logs) {
|
||||||
//System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
|
logger.trace("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
|
||||||
count++;
|
count++;
|
||||||
}
|
}
|
||||||
System.out.println("Had " + count + " commits on pom.xml");
|
logger.debug("Had " + count + " commits on pom.xml");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -13,5 +13,6 @@ public class PorcelainUnitTest {
|
|||||||
CreateAndDeleteTag.main(null);
|
CreateAndDeleteTag.main(null);
|
||||||
|
|
||||||
Log.main(null);
|
Log.main(null);
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -3,7 +3,7 @@
|
|||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
<groupId>com.baeldung.jhipster5</groupId>
|
<groupId>com.baeldung.jhipster5</groupId>
|
||||||
<artifactId>bookstore</artifactId>
|
<artifactId>bookstore-monolith</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<packaging>war</packaging>
|
<packaging>war</packaging>
|
||||||
<name>Bookstore</name>
|
<name>Bookstore</name>
|
||||||
|
@ -40,6 +40,6 @@
|
|||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<jib-maven-plugin.version>0.9.10</jib-maven-plugin.version>
|
<jib-maven-plugin.version>2.5.0</jib-maven-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
</project>
|
</project>
|
||||||
|
@ -32,12 +32,6 @@
|
|||||||
<artifactId>pact-jvm-consumer-junit_2.11</artifactId>
|
<artifactId>pact-jvm-consumer-junit_2.11</artifactId>
|
||||||
<version>${pact.version}</version>
|
<version>${pact.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
<exclusions>
|
|
||||||
<exclusion>
|
|
||||||
<groupId>org.codehaus.groovy</groupId>
|
|
||||||
<artifactId>groovy-all</artifactId>
|
|
||||||
</exclusion>
|
|
||||||
</exclusions>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- https://mvnrepository.com/artifact/com.typesafe.akka/akka-actor -->
|
<!-- https://mvnrepository.com/artifact/com.typesafe.akka/akka-actor -->
|
||||||
@ -53,10 +47,10 @@
|
|||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>one.util</groupId>
|
<groupId>one.util</groupId>
|
||||||
<artifactId>streamex</artifactId>
|
<artifactId>streamex</artifactId>
|
||||||
<version>${streamex.version}</version>
|
<version>${streamex.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>net.bytebuddy</groupId>
|
<groupId>net.bytebuddy</groupId>
|
||||||
|
@ -5,8 +5,6 @@ import au.com.dius.pact.consumer.PactProviderRuleMk2;
|
|||||||
import au.com.dius.pact.consumer.PactVerification;
|
import au.com.dius.pact.consumer.PactVerification;
|
||||||
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
|
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
|
||||||
import au.com.dius.pact.model.RequestResponsePact;
|
import au.com.dius.pact.model.RequestResponsePact;
|
||||||
|
|
||||||
import org.junit.Ignore;
|
|
||||||
import org.junit.Rule;
|
import org.junit.Rule;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.springframework.http.HttpEntity;
|
import org.springframework.http.HttpEntity;
|
||||||
@ -28,15 +26,30 @@ public class PactConsumerDrivenContractUnitTest {
|
|||||||
|
|
||||||
@Pact(consumer = "test_consumer")
|
@Pact(consumer = "test_consumer")
|
||||||
public RequestResponsePact createPact(PactDslWithProvider builder) {
|
public RequestResponsePact createPact(PactDslWithProvider builder) {
|
||||||
Map<String, String> headers = new HashMap<String, String>();
|
Map<String, String> headers = new HashMap<>();
|
||||||
headers.put("Content-Type", "application/json");
|
headers.put("Content-Type", "application/json");
|
||||||
|
|
||||||
return builder.given("test GET").uponReceiving("GET REQUEST").path("/pact").method("GET").willRespondWith().status(200).headers(headers).body("{\"condition\": true, \"name\": \"tom\"}").given("test POST").uponReceiving("POST REQUEST").method("POST")
|
return builder
|
||||||
.headers(headers).body("{\"name\": \"Michael\"}").path("/pact").willRespondWith().status(201).toPact();
|
.given("test GET")
|
||||||
|
.uponReceiving("GET REQUEST")
|
||||||
|
.path("/pact")
|
||||||
|
.method("GET")
|
||||||
|
.willRespondWith()
|
||||||
|
.status(200)
|
||||||
|
.headers(headers)
|
||||||
|
.body("{\"condition\": true, \"name\": \"tom\"}")
|
||||||
|
.given("test POST")
|
||||||
|
.uponReceiving("POST REQUEST")
|
||||||
|
.method("POST")
|
||||||
|
.headers(headers)
|
||||||
|
.body("{\"name\": \"Michael\"}")
|
||||||
|
.path("/pact")
|
||||||
|
.willRespondWith()
|
||||||
|
.status(201)
|
||||||
|
.toPact();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@Ignore
|
|
||||||
@PactVerification()
|
@PactVerification()
|
||||||
public void givenGet_whenSendRequest_shouldReturn200WithProperHeaderAndBody() {
|
public void givenGet_whenSendRequest_shouldReturn200WithProperHeaderAndBody() {
|
||||||
// when
|
// when
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>libraries-testing</artifactId>
|
<artifactId>libraries-testing</artifactId>
|
||||||
<name>libraries-testing</name>
|
<name>libraries-testing</name>
|
||||||
@ -158,6 +158,13 @@
|
|||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.tngtech.archunit</groupId>
|
||||||
|
<artifactId>archunit-junit5</artifactId>
|
||||||
|
<version>${archunit.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -193,7 +200,7 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<asciidoctor.version>1.5.7.1</asciidoctor.version>
|
<asciidoctor.version>1.5.7.1</asciidoctor.version>
|
||||||
<serenity.version>1.9.9</serenity.version>
|
<serenity.version>1.9.9</serenity.version>
|
||||||
<serenity.jbehave.version>1.9.0</serenity.jbehave.version>
|
<serenity.jbehave.version>1.9.0</serenity.jbehave.version>
|
||||||
<serenity.jira.version>1.9.0</serenity.jira.version>
|
<serenity.jira.version>1.9.0</serenity.jira.version>
|
||||||
<serenity.plugin.version>1.9.27</serenity.plugin.version>
|
<serenity.plugin.version>1.9.27</serenity.plugin.version>
|
||||||
@ -210,6 +217,7 @@
|
|||||||
<maven-compiler-plugin.target>1.8</maven-compiler-plugin.target>
|
<maven-compiler-plugin.target>1.8</maven-compiler-plugin.target>
|
||||||
<maven-compiler-plugin.source>1.8</maven-compiler-plugin.source>
|
<maven-compiler-plugin.source>1.8</maven-compiler-plugin.source>
|
||||||
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
|
||||||
|
<archunit.version>0.14.1</archunit.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -0,0 +1,38 @@
|
|||||||
|
package com.baeldung.archunit.smurfs.persistence;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.TreeMap;
|
||||||
|
|
||||||
|
import com.baeldung.archunit.smurfs.persistence.domain.Smurf;
|
||||||
|
|
||||||
|
import static java.util.stream.Collectors.toList;
|
||||||
|
|
||||||
|
public class SmurfsRepository {
|
||||||
|
|
||||||
|
private static Map<String,Smurf> smurfs = Collections.synchronizedMap(new TreeMap<>());
|
||||||
|
|
||||||
|
static {
|
||||||
|
// Just a few here. A full list can be found
|
||||||
|
// at https://smurfs.fandom.com/wiki/List_of_Smurf_characters
|
||||||
|
smurfs.put("Papa", new Smurf("Papa", true, true));
|
||||||
|
smurfs.put("Actor", new Smurf("Actor", true, true));
|
||||||
|
smurfs.put("Alchemist", new Smurf("Alchemist", true, true));
|
||||||
|
smurfs.put("Archeologist", new Smurf("Archeologist", true, true));
|
||||||
|
smurfs.put("Architect", new Smurf("Architect", true, true));
|
||||||
|
smurfs.put("Baby", new Smurf("Baby", true, true));
|
||||||
|
smurfs.put("Baker", new Smurf("Baker", true, true));
|
||||||
|
smurfs.put("Baker", new Smurf("Baker", true, true));
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Smurf> findAll() {
|
||||||
|
return Collections.unmodifiableList(smurfs.values().stream().collect(toList()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<Smurf> findByName(String name) {
|
||||||
|
return Optional.of(smurfs.get(name));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,39 @@
|
|||||||
|
package com.baeldung.archunit.smurfs.persistence.domain;
|
||||||
|
|
||||||
|
public class Smurf {
|
||||||
|
private String name;
|
||||||
|
private boolean comic;
|
||||||
|
private boolean cartoon;
|
||||||
|
|
||||||
|
public Smurf() {}
|
||||||
|
|
||||||
|
public Smurf(String name, boolean comic, boolean cartoon) {
|
||||||
|
this.name = name;
|
||||||
|
this.comic = comic;
|
||||||
|
this.cartoon = cartoon;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isComic() {
|
||||||
|
return comic;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCommic(boolean comic) {
|
||||||
|
this.comic = comic;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isCartoon() {
|
||||||
|
return cartoon;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCartoon(boolean cartoon) {
|
||||||
|
this.cartoon = cartoon;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,27 @@
|
|||||||
|
package com.baeldung.archunit.smurfs.presentation;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import com.baeldung.archunit.smurfs.service.SmurfsService;
|
||||||
|
import com.baeldung.archunit.smurfs.service.dto.SmurfDTO;
|
||||||
|
|
||||||
|
@RequestMapping(value = "/smurfs", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
|
||||||
|
@RestController
|
||||||
|
public class SmurfsController {
|
||||||
|
|
||||||
|
private SmurfsService smurfs;
|
||||||
|
|
||||||
|
public SmurfsController(SmurfsService smurfs) {
|
||||||
|
this.smurfs = smurfs;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
public List<SmurfDTO> getSmurfs() {
|
||||||
|
return smurfs.findAll();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,35 @@
|
|||||||
|
|
||||||
|
package com.baeldung.archunit.smurfs.service;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import com.baeldung.archunit.smurfs.persistence.SmurfsRepository;
|
||||||
|
import com.baeldung.archunit.smurfs.persistence.domain.Smurf;
|
||||||
|
import com.baeldung.archunit.smurfs.service.dto.SmurfDTO;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class SmurfsService {
|
||||||
|
|
||||||
|
private SmurfsRepository repository;
|
||||||
|
|
||||||
|
public SmurfsService(SmurfsRepository repository) {
|
||||||
|
this.repository = repository;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<SmurfDTO> findAll() {
|
||||||
|
|
||||||
|
return repository.findAll()
|
||||||
|
.stream()
|
||||||
|
.map(SmurfsService::toDTO)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static SmurfDTO toDTO(Smurf smurf) {
|
||||||
|
return new SmurfDTO(smurf.getName(),smurf.isComic(), smurf.isCartoon());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,41 @@
|
|||||||
|
|
||||||
|
package com.baeldung.archunit.smurfs.service.dto;
|
||||||
|
|
||||||
|
public class SmurfDTO {
|
||||||
|
private String name;
|
||||||
|
private boolean comic;
|
||||||
|
private boolean cartoon;
|
||||||
|
|
||||||
|
public SmurfDTO() {}
|
||||||
|
|
||||||
|
public SmurfDTO(String name, boolean comic, boolean cartoon) {
|
||||||
|
this.name = name;
|
||||||
|
this.comic = comic;
|
||||||
|
this.cartoon = cartoon;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isComic() {
|
||||||
|
return comic;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCommic(boolean comic) {
|
||||||
|
this.comic = comic;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isCartoon() {
|
||||||
|
return cartoon;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCartoon(boolean cartoon) {
|
||||||
|
this.cartoon = cartoon;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,76 @@
|
|||||||
|
package com.baeldung.archunit.smurfs;
|
||||||
|
|
||||||
|
|
||||||
|
import com.tngtech.archunit.core.domain.JavaClasses;
|
||||||
|
import com.tngtech.archunit.core.importer.ClassFileImporter;
|
||||||
|
import com.tngtech.archunit.lang.ArchRule;
|
||||||
|
import com.tngtech.archunit.library.Architectures.LayeredArchitecture;
|
||||||
|
|
||||||
|
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
|
||||||
|
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
|
||||||
|
import static com.tngtech.archunit.library.Architectures.layeredArchitecture;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class SmurfsArchUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPresentationLayerClasses_thenWrongCheckFails() {
|
||||||
|
JavaClasses jc = new ClassFileImporter().importPackages("com.baeldung.archunit.smurfs");
|
||||||
|
|
||||||
|
ArchRule r1 = classes()
|
||||||
|
.that()
|
||||||
|
.resideInAPackage("..presentation..")
|
||||||
|
.should().onlyDependOnClassesThat()
|
||||||
|
.resideInAPackage("..service..");
|
||||||
|
|
||||||
|
assertThrows(AssertionError.class, ()-> r1.check(jc)) ;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPresentationLayerClasses_thenCheckWithFrameworkDependenciesSuccess() {
|
||||||
|
JavaClasses jc = new ClassFileImporter().importPackages("com.baeldung.archunit.smurfs");
|
||||||
|
|
||||||
|
ArchRule r1 = classes()
|
||||||
|
.that()
|
||||||
|
.resideInAPackage("..presentation..")
|
||||||
|
.should().onlyDependOnClassesThat()
|
||||||
|
.resideInAnyPackage("..service..", "java..", "javax..", "org.springframework..");
|
||||||
|
|
||||||
|
r1.check(jc);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPresentationLayerClasses_thenNoPersistenceLayerAccess() {
|
||||||
|
JavaClasses jc = new ClassFileImporter().importPackages("com.baeldung.archunit.smurfs");
|
||||||
|
|
||||||
|
ArchRule r1 = noClasses()
|
||||||
|
.that()
|
||||||
|
.resideInAPackage("..presentation..")
|
||||||
|
.should().dependOnClassesThat()
|
||||||
|
.resideInAPackage("..persistence..");
|
||||||
|
|
||||||
|
r1.check(jc);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenApplicationClasses_thenNoLayerViolationsShouldExist() {
|
||||||
|
|
||||||
|
JavaClasses jc = new ClassFileImporter().importPackages("com.baeldung.archunit.smurfs");
|
||||||
|
|
||||||
|
LayeredArchitecture arch = layeredArchitecture()
|
||||||
|
// Define layers
|
||||||
|
.layer("Presentation").definedBy("..presentation..")
|
||||||
|
.layer("Service").definedBy("..service..")
|
||||||
|
.layer("Persistence").definedBy("..persistence..")
|
||||||
|
// Add constraints
|
||||||
|
.whereLayer("Presentation").mayNotBeAccessedByAnyLayer()
|
||||||
|
.whereLayer("Service").mayOnlyBeAccessedByLayers("Presentation")
|
||||||
|
.whereLayer("Persistence").mayOnlyBeAccessedByLayers("Service");
|
||||||
|
|
||||||
|
arch.check(jc);
|
||||||
|
}
|
||||||
|
}
|
5
libraries-testing/src/test/resources/logback.xml
Normal file
5
libraries-testing/src/test/resources/logback.xml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
<logger name="org.dbunit" level="INFO" />
|
||||||
|
</configuration>
|
||||||
|
|
@ -1,3 +0,0 @@
|
|||||||
### Relevant Articles:
|
|
||||||
|
|
||||||
- [Maven Enforcer Plugin](https://www.baeldung.com/maven-enforcer-plugin)
|
|
@ -66,27 +66,29 @@
|
|||||||
</file>
|
</file>
|
||||||
</activation>
|
</activation>
|
||||||
</profile>
|
</profile>
|
||||||
|
<profile>
|
||||||
|
<id>show-active-profiles</id>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-help-plugin</artifactId>
|
||||||
|
<version>${help.plugin.version}</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>show-profiles</id>
|
||||||
|
<phase>compile</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>active-profiles</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</profile>
|
||||||
</profiles>
|
</profiles>
|
||||||
|
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-help-plugin</artifactId>
|
|
||||||
<version>${help.plugin.version}</version>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<id>show-profiles</id>
|
|
||||||
<phase>compile</phase>
|
|
||||||
<goals>
|
|
||||||
<goal>active-profiles</goal>
|
|
||||||
</goals>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<help.plugin.version>3.2.0</help.plugin.version>
|
<help.plugin.version>3.2.0</help.plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
@ -21,6 +21,7 @@
|
|||||||
<module>dip</module>
|
<module>dip</module>
|
||||||
<module>cqrs-es</module>
|
<module>cqrs-es</module>
|
||||||
<module>front-controller</module>
|
<module>front-controller</module>
|
||||||
|
<module>hexagonal-architecture</module>
|
||||||
<module>intercepting-filter</module>
|
<module>intercepting-filter</module>
|
||||||
<module>solid</module>
|
<module>solid</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
@ -0,0 +1,49 @@
|
|||||||
|
package com.baeldung.jdbcmetadata;
|
||||||
|
|
||||||
|
import org.apache.log4j.Logger;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.DriverManager;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
|
||||||
|
public class DatabaseConfig {
|
||||||
|
private static final Logger LOG = Logger.getLogger(DatabaseConfig.class);
|
||||||
|
|
||||||
|
private Connection connection;
|
||||||
|
|
||||||
|
public DatabaseConfig() {
|
||||||
|
try {
|
||||||
|
Class.forName("org.h2.Driver");
|
||||||
|
String url = "jdbc:h2:mem:testdb";
|
||||||
|
connection = DriverManager.getConnection(url, "sa", "");
|
||||||
|
} catch (ClassNotFoundException | SQLException e) {
|
||||||
|
LOG.error(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Connection getConnection() {
|
||||||
|
return connection;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void init() {
|
||||||
|
createTables();
|
||||||
|
createViews();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createTables() {
|
||||||
|
try {
|
||||||
|
connection.createStatement().executeUpdate("create table CUSTOMER (ID int primary key auto_increment, NAME VARCHAR(45))");
|
||||||
|
connection.createStatement().executeUpdate("create table CUST_ADDRESS (ID VARCHAR(36), CUST_ID int, ADDRESS VARCHAR(45), FOREIGN KEY (CUST_ID) REFERENCES CUSTOMER(ID))");
|
||||||
|
} catch (SQLException e) {
|
||||||
|
LOG.error(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createViews() {
|
||||||
|
try {
|
||||||
|
connection.createStatement().executeUpdate("CREATE VIEW CUSTOMER_VIEW AS SELECT * FROM CUSTOMER");
|
||||||
|
} catch (SQLException e) {
|
||||||
|
LOG.error(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,30 @@
|
|||||||
|
package com.baeldung.jdbcmetadata;
|
||||||
|
|
||||||
|
import org.apache.log4j.Logger;
|
||||||
|
|
||||||
|
import java.sql.SQLException;
|
||||||
|
|
||||||
|
public class JdbcMetadataApplication {
|
||||||
|
|
||||||
|
private static final Logger LOG = Logger.getLogger(JdbcMetadataApplication.class);
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
DatabaseConfig databaseConfig = new DatabaseConfig();
|
||||||
|
databaseConfig.init();
|
||||||
|
try {
|
||||||
|
MetadataExtractor metadataExtractor = new MetadataExtractor(databaseConfig.getConnection());
|
||||||
|
metadataExtractor.extractTableInfo();
|
||||||
|
metadataExtractor.extractSystemTables();
|
||||||
|
metadataExtractor.extractViews();
|
||||||
|
String tableName = "CUSTOMER";
|
||||||
|
metadataExtractor.extractColumnInfo(tableName);
|
||||||
|
metadataExtractor.extractPrimaryKeys(tableName);
|
||||||
|
metadataExtractor.extractForeignKeys("CUST_ADDRESS");
|
||||||
|
metadataExtractor.extractDatabaseInfo();
|
||||||
|
metadataExtractor.extractUserName();
|
||||||
|
metadataExtractor.extractSupportedFeatures();
|
||||||
|
} catch (SQLException e) {
|
||||||
|
LOG.error("Error while executing SQL statements", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,113 @@
|
|||||||
|
package com.baeldung.jdbcmetadata;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.DatabaseMetaData;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
|
||||||
|
public class MetadataExtractor {
|
||||||
|
private final DatabaseMetaData databaseMetaData;
|
||||||
|
|
||||||
|
public MetadataExtractor(Connection connection) throws SQLException {
|
||||||
|
this.databaseMetaData = connection.getMetaData();
|
||||||
|
DatabaseMetaData databaseMetaData = connection.getMetaData();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void extractTableInfo() throws SQLException {
|
||||||
|
ResultSet resultSet = databaseMetaData.getTables(null, null, "CUST%", new String[] { "TABLE" });
|
||||||
|
while (resultSet.next()) {
|
||||||
|
// Print the names of existing tables
|
||||||
|
System.out.println(resultSet.getString("TABLE_NAME"));
|
||||||
|
System.out.println(resultSet.getString("REMARKS"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void extractSystemTables() throws SQLException {
|
||||||
|
ResultSet resultSet = databaseMetaData.getTables(null, null, null, new String[] { "SYSTEM TABLE" });
|
||||||
|
while (resultSet.next()) {
|
||||||
|
// Print the names of system tables
|
||||||
|
System.out.println(resultSet.getString("TABLE_NAME"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void extractViews() throws SQLException {
|
||||||
|
ResultSet resultSet = databaseMetaData.getTables(null, null, null, new String[] { "VIEW" });
|
||||||
|
while (resultSet.next()) {
|
||||||
|
// Print the names of existing views
|
||||||
|
System.out.println(resultSet.getString("TABLE_NAME"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void extractColumnInfo(String tableName) throws SQLException {
|
||||||
|
ResultSet columns = databaseMetaData.getColumns(null, null, tableName, null);
|
||||||
|
|
||||||
|
while (columns.next()) {
|
||||||
|
String columnName = columns.getString("COLUMN_NAME");
|
||||||
|
String columnSize = columns.getString("COLUMN_SIZE");
|
||||||
|
String datatype = columns.getString("DATA_TYPE");
|
||||||
|
String isNullable = columns.getString("IS_NULLABLE");
|
||||||
|
String isAutoIncrement = columns.getString("IS_AUTOINCREMENT");
|
||||||
|
System.out.println(String.format("ColumnName: %s, columnSize: %s, datatype: %s, isColumnNullable: %s, isAutoIncrementEnabled: %s", columnName, columnSize, datatype, isNullable, isAutoIncrement));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void extractPrimaryKeys(String tableName) throws SQLException {
|
||||||
|
ResultSet primaryKeys = databaseMetaData.getPrimaryKeys(null, null, tableName);
|
||||||
|
while (primaryKeys.next()) {
|
||||||
|
String primaryKeyColumnName = primaryKeys.getString("COLUMN_NAME");
|
||||||
|
String primaryKeyName = primaryKeys.getString("PK_NAME");
|
||||||
|
System.out.println(String.format("columnName:%s, pkName:%s", primaryKeyColumnName, primaryKeyName));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void fun() throws SQLException {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public void extractForeignKeys(String tableName) throws SQLException {
|
||||||
|
ResultSet foreignKeys = databaseMetaData.getImportedKeys(null, null, tableName);
|
||||||
|
while (foreignKeys.next()) {
|
||||||
|
String pkTableName = foreignKeys.getString("PKTABLE_NAME");
|
||||||
|
String fkTableName = foreignKeys.getString("FKTABLE_NAME");
|
||||||
|
String pkColumnName = foreignKeys.getString("PKCOLUMN_NAME");
|
||||||
|
String fkColumnName = foreignKeys.getString("FKCOLUMN_NAME");
|
||||||
|
System.out.println(String.format("pkTableName:%s, fkTableName:%s, pkColumnName:%s, fkColumnName:%s", pkTableName, fkTableName, pkColumnName, fkColumnName));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void extractDatabaseInfo() throws SQLException {
|
||||||
|
String productName = databaseMetaData.getDatabaseProductName();
|
||||||
|
String productVersion = databaseMetaData.getDatabaseProductVersion();
|
||||||
|
|
||||||
|
String driverName = databaseMetaData.getDriverName();
|
||||||
|
String driverVersion = databaseMetaData.getDriverVersion();
|
||||||
|
|
||||||
|
System.out.println(String.format("Product name:%s, Product version:%s", productName, productVersion));
|
||||||
|
System.out.println(String.format("Driver name:%s, Driver Version:%s", driverName, driverVersion));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void extractUserName() throws SQLException {
|
||||||
|
String userName = databaseMetaData.getUserName();
|
||||||
|
System.out.println(userName);
|
||||||
|
ResultSet schemas = databaseMetaData.getSchemas();
|
||||||
|
while (schemas.next()) {
|
||||||
|
String table_schem = schemas.getString("TABLE_SCHEM");
|
||||||
|
String table_catalog = schemas.getString("TABLE_CATALOG");
|
||||||
|
System.out.println(String.format("Table_schema:%s, Table_catalog:%s", table_schem, table_catalog));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void extractSupportedFeatures() throws SQLException {
|
||||||
|
System.out.println("Supports scrollable & Updatable Result Set: " + databaseMetaData.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE));
|
||||||
|
System.out.println("Supports Full Outer Joins: " + databaseMetaData.supportsFullOuterJoins());
|
||||||
|
System.out.println("Supports Stored Procedures: " + databaseMetaData.supportsStoredProcedures());
|
||||||
|
System.out.println("Supports Subqueries in 'EXISTS': " + databaseMetaData.supportsSubqueriesInExists());
|
||||||
|
System.out.println("Supports Transactions: " + databaseMetaData.supportsTransactions());
|
||||||
|
System.out.println("Supports Core SQL Grammar: " + databaseMetaData.supportsCoreSQLGrammar());
|
||||||
|
System.out.println("Supports Batch Updates: " + databaseMetaData.supportsBatchUpdates());
|
||||||
|
System.out.println("Supports Column Aliasing: " + databaseMetaData.supportsColumnAliasing());
|
||||||
|
System.out.println("Supports Savepoints: " + databaseMetaData.supportsSavepoints());
|
||||||
|
System.out.println("Supports Union All: " + databaseMetaData.supportsUnionAll());
|
||||||
|
System.out.println("Supports Union: " + databaseMetaData.supportsUnion());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,34 @@
|
|||||||
|
package com.baeldung.hibernate.hilo;
|
||||||
|
|
||||||
|
import org.hibernate.annotations.GenericGenerator;
|
||||||
|
import org.hibernate.annotations.Parameter;
|
||||||
|
|
||||||
|
import javax.persistence.Entity;
|
||||||
|
import javax.persistence.GeneratedValue;
|
||||||
|
import javax.persistence.GenerationType;
|
||||||
|
import javax.persistence.Id;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
public class RestaurantOrder {
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "hilo_sequence_generator")
|
||||||
|
@GenericGenerator(
|
||||||
|
name = "hilo_sequence_generator",
|
||||||
|
strategy = "sequence",
|
||||||
|
parameters = {
|
||||||
|
@Parameter(name = "sequence_name", value = "hilo_seqeunce"),
|
||||||
|
@Parameter(name = "initial_value", value = "1"),
|
||||||
|
@Parameter(name = "increment_size", value = "3"),
|
||||||
|
@Parameter(name = "optimizer", value = "hilo")
|
||||||
|
}
|
||||||
|
)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
public long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,99 @@
|
|||||||
|
package com.baeldung.hibernate.hilo;
|
||||||
|
|
||||||
|
import org.apache.log4j.BasicConfigurator;
|
||||||
|
import org.apache.log4j.Level;
|
||||||
|
import org.apache.log4j.LogManager;
|
||||||
|
import org.hibernate.HibernateException;
|
||||||
|
import org.hibernate.Session;
|
||||||
|
import org.hibernate.SessionFactory;
|
||||||
|
import org.hibernate.Transaction;
|
||||||
|
import org.hibernate.boot.Metadata;
|
||||||
|
import org.hibernate.boot.MetadataSources;
|
||||||
|
import org.hibernate.boot.SessionFactoryBuilder;
|
||||||
|
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||||
|
import org.hibernate.service.ServiceRegistry;
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
|
public class HibernateHiloUnitTest {
|
||||||
|
private Session session;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void init() {
|
||||||
|
try {
|
||||||
|
configureLogger();
|
||||||
|
|
||||||
|
ServiceRegistry serviceRegistry = configureServiceRegistry();
|
||||||
|
SessionFactory factory = getSessionFactoryBuilder(serviceRegistry).build();
|
||||||
|
session = factory.openSession();
|
||||||
|
} catch (HibernateException | IOException e) {
|
||||||
|
fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void configureLogger() {
|
||||||
|
BasicConfigurator.configure();
|
||||||
|
LogManager.getLogger("org.hibernate").setLevel(Level.ERROR);
|
||||||
|
LogManager.getLogger("org.hibernate.id.enhanced.SequenceStructure").setLevel(Level.DEBUG);
|
||||||
|
LogManager.getLogger("org.hibernate.event.internal.AbstractSaveEventListener").setLevel(Level.DEBUG);
|
||||||
|
LogManager.getLogger("org.hibernate.SQL").setLevel(Level.DEBUG);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) {
|
||||||
|
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
|
||||||
|
metadataSources.addAnnotatedClass(RestaurantOrder.class);
|
||||||
|
Metadata metadata = metadataSources.buildMetadata();
|
||||||
|
|
||||||
|
return metadata.getSessionFactoryBuilder();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ServiceRegistry configureServiceRegistry() throws IOException {
|
||||||
|
Properties properties = getProperties();
|
||||||
|
|
||||||
|
return new StandardServiceRegistryBuilder().applySettings(properties)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Properties getProperties() throws IOException {
|
||||||
|
Properties properties = new Properties();
|
||||||
|
URL propertiesURL = getPropertiesURL();
|
||||||
|
|
||||||
|
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
|
||||||
|
properties.load(inputStream);
|
||||||
|
}
|
||||||
|
|
||||||
|
return properties;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static URL getPropertiesURL() {
|
||||||
|
return Thread.currentThread()
|
||||||
|
.getContextClassLoader()
|
||||||
|
.getResource("hibernate-hilo.properties");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenHiLoAlgorithm_when9EntitiesArePersisted_Then3callsToDBForNextValueShouldBeMade() {
|
||||||
|
Transaction transaction = session.beginTransaction();
|
||||||
|
|
||||||
|
for (int i = 0; i < 9; i++) {
|
||||||
|
session.persist(new RestaurantOrder());
|
||||||
|
session.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
transaction.commit();
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void cleanup() {
|
||||||
|
session.close();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
hibernate.connection.driver_class=org.h2.Driver
|
||||||
|
hibernate.connection.url=jdbc:h2:mem:hilo_db;DB_CLOSE_DELAY=-1
|
||||||
|
hibernate.connection.username=sa
|
||||||
|
hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||||
|
hibernate.show_sql=true
|
||||||
|
hibernate.hbm2ddl.auto=create-drop
|
||||||
|
hibernate.c3p0.min_size=5
|
||||||
|
hibernate.c3p0.max_size=20
|
||||||
|
hibernate.c3p0.acquire_increment=5
|
||||||
|
hibernate.c3p0.timeout=1800
|
3
persistence-modules/java-jpa-3/README.md
Normal file
3
persistence-modules/java-jpa-3/README.md
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
## JPA in Java
|
||||||
|
|
||||||
|
This module contains articles about the Java Persistence API (JPA) in Java.
|
83
persistence-modules/java-jpa-3/pom.xml
Normal file
83
persistence-modules/java-jpa-3/pom.xml
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
<?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>java-jpa-3</artifactId>
|
||||||
|
<name>java-jpa-3</name>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>persistence-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.hibernate</groupId>
|
||||||
|
<artifactId>hibernate-core</artifactId>
|
||||||
|
<version>${hibernate.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.hibernate</groupId>
|
||||||
|
<artifactId>hibernate-jpamodelgen</artifactId>
|
||||||
|
<version>${hibernate.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.h2database</groupId>
|
||||||
|
<artifactId>h2</artifactId>
|
||||||
|
<version>${h2.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!--Compile time JPA API -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.persistence</groupId>
|
||||||
|
<artifactId>javax.persistence-api</artifactId>
|
||||||
|
<version>${javax.persistence-api.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!--Runtime JPA implementation -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.eclipse.persistence</groupId>
|
||||||
|
<artifactId>eclipselink</artifactId>
|
||||||
|
<version>${eclipselink.version}</version>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.postgresql</groupId>
|
||||||
|
<artifactId>postgresql</artifactId>
|
||||||
|
<version>${postgres.version}</version>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>${assertj.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<compilerArgument>-proc:none</compilerArgument>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<hibernate.version>5.4.14.Final</hibernate.version>
|
||||||
|
<eclipselink.version>2.7.4</eclipselink.version>
|
||||||
|
<postgres.version>42.2.5</postgres.version>
|
||||||
|
<javax.persistence-api.version>2.2</javax.persistence-api.version>
|
||||||
|
<assertj.version>3.11.1</assertj.version>
|
||||||
|
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
||||||
|
<maven-processor-plugin.version>3.3.3</maven-processor-plugin.version>
|
||||||
|
<build-helper-maven-plugin.version>3.0.0</build-helper-maven-plugin.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1,53 @@
|
|||||||
|
package com.baeldung.jpa.equality;
|
||||||
|
|
||||||
|
import javax.persistence.*;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
public class EqualByBusinessKey {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String email;
|
||||||
|
|
||||||
|
public EqualByBusinessKey() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(Long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getEmail() {
|
||||||
|
return email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEmail(String email) {
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return java.util.Objects.hashCode(email);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
if (this == obj) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (obj == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (obj instanceof EqualByBusinessKey) {
|
||||||
|
if (((EqualByBusinessKey) obj).getEmail() == getEmail()) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,55 @@
|
|||||||
|
package com.baeldung.jpa.equality;
|
||||||
|
|
||||||
|
import javax.persistence.*;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
public class EqualById {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String email;
|
||||||
|
|
||||||
|
public EqualById() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(Long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getEmail() {
|
||||||
|
return email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEmail(String email) {
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
final int prime = 31;
|
||||||
|
int result = 1;
|
||||||
|
result = prime * result + ((id == null) ? 0 : id.hashCode());
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
if (this == obj) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (obj == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (obj instanceof EqualById) {
|
||||||
|
return ((EqualById) obj).getId().equals(getId());
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,36 @@
|
|||||||
|
package com.baeldung.jpa.equality;
|
||||||
|
|
||||||
|
import javax.persistence.*;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
public class EqualByJavaDefault implements Cloneable{
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
private String email;
|
||||||
|
|
||||||
|
public EqualByJavaDefault() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(Long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getEmail() {
|
||||||
|
return email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEmail(String email) {
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object clone() throws CloneNotSupportedException {
|
||||||
|
return super.clone();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
|
||||||
|
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
|
||||||
|
version="2.2">
|
||||||
|
<persistence-unit name="jpa-h2-equality">
|
||||||
|
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||||
|
<class>com.baeldung.jpa.equality.EqualByJavaDefault</class>
|
||||||
|
<class>com.baeldung.jpa.equality.EqualById</class>
|
||||||
|
<class>com.baeldung.jpa.equality.EqualByBusinessKey</class>
|
||||||
|
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||||
|
<properties>
|
||||||
|
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
|
||||||
|
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test" />
|
||||||
|
<property name="javax.persistence.jdbc.user" value="sa" />
|
||||||
|
<property name="javax.persistence.jdbc.password" value="" />
|
||||||
|
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
|
||||||
|
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
|
||||||
|
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
|
||||||
|
<property name="show_sql" value="false" />
|
||||||
|
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false" />
|
||||||
|
</properties>
|
||||||
|
</persistence-unit>
|
||||||
|
</persistence>
|
@ -0,0 +1,15 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
<appender name="STDOUT"
|
||||||
|
class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} -
|
||||||
|
%msg%n
|
||||||
|
</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="INFO">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
</configuration>
|
@ -0,0 +1,74 @@
|
|||||||
|
package com.baeldung.jpa.equality;
|
||||||
|
|
||||||
|
import javax.persistence.EntityManager;
|
||||||
|
import javax.persistence.EntityManagerFactory;
|
||||||
|
import javax.persistence.Persistence;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class EqualityUnitTest {
|
||||||
|
|
||||||
|
private static EntityManagerFactory factory;
|
||||||
|
private static EntityManager entityManager;
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void setup() {
|
||||||
|
factory = Persistence.createEntityManagerFactory("jpa-h2-equality");
|
||||||
|
entityManager = factory.createEntityManager();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenObjectBasedEquality_whenUsingEquals_thenEqualIsBasedOnInstance() throws CloneNotSupportedException {
|
||||||
|
EqualByJavaDefault object1 = new EqualByJavaDefault();
|
||||||
|
EqualByJavaDefault object2 = new EqualByJavaDefault();
|
||||||
|
|
||||||
|
object1.setEmail("test.user@domain.com");
|
||||||
|
|
||||||
|
entityManager.getTransaction().begin();
|
||||||
|
entityManager.persist(object1);
|
||||||
|
entityManager.getTransaction().commit();
|
||||||
|
|
||||||
|
object2 = (EqualByJavaDefault) object1.clone();
|
||||||
|
|
||||||
|
Assert.assertNotEquals(object1, object2);
|
||||||
|
Assert.assertEquals(object1.getId(), object2.getId());
|
||||||
|
Assert.assertEquals(object1.getEmail(), object2.getEmail());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIdBasedEquality_whenUsingEquals_thenEqualIsBasedOnId() {
|
||||||
|
EqualById object1 = new EqualById();
|
||||||
|
EqualById object2 = new EqualById();
|
||||||
|
|
||||||
|
object1.setEmail("test.user.1@domain.com");
|
||||||
|
object2.setEmail("test.user.2@domain.com");
|
||||||
|
|
||||||
|
entityManager.getTransaction().begin();
|
||||||
|
entityManager.persist(object1);
|
||||||
|
entityManager.getTransaction().commit();
|
||||||
|
|
||||||
|
object2.setId(object1.getId());
|
||||||
|
|
||||||
|
Assert.assertEquals(object1, object2);
|
||||||
|
Assert.assertEquals(object1.getId(), object2.getId());
|
||||||
|
Assert.assertNotEquals(object1.getEmail(), object2.getEmail());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenBusinessKeyBasedEquality_whenUsingEquals_thenEqualIsBasedOnBusinessKey() {
|
||||||
|
EqualByBusinessKey object1 = new EqualByBusinessKey();
|
||||||
|
EqualByBusinessKey object2 = new EqualByBusinessKey();
|
||||||
|
|
||||||
|
object1.setEmail("test.user@test-domain.com");
|
||||||
|
object2.setEmail("test.user@test-domain.com");
|
||||||
|
|
||||||
|
entityManager.getTransaction().begin();
|
||||||
|
entityManager.persist(object1);
|
||||||
|
entityManager.getTransaction().commit();
|
||||||
|
|
||||||
|
Assert.assertEquals(object1, object2);
|
||||||
|
Assert.assertNotEquals(object1.getId(), object2.getId());
|
||||||
|
}
|
||||||
|
}
|
@ -19,12 +19,14 @@
|
|||||||
<module>core-java-persistence</module>
|
<module>core-java-persistence</module>
|
||||||
<module>deltaspike</module>
|
<module>deltaspike</module>
|
||||||
<module>elasticsearch</module>
|
<module>elasticsearch</module>
|
||||||
|
<module>flyway</module>
|
||||||
<module>flyway-repair</module>
|
<module>flyway-repair</module>
|
||||||
<module>hbase</module>
|
<module>hbase</module>
|
||||||
<module>hibernate5</module>
|
<module>hibernate5</module>
|
||||||
<module>hibernate-mapping</module> <!-- long running -->
|
<module>hibernate-mapping</module> <!-- long running -->
|
||||||
<module>hibernate-ogm</module>
|
<module>hibernate-ogm</module>
|
||||||
<module>hibernate-annotations</module>
|
<module>hibernate-annotations</module>
|
||||||
|
<module>hibernate-exceptions</module>
|
||||||
<module>hibernate-libraries</module>
|
<module>hibernate-libraries</module>
|
||||||
<module>hibernate-jpa</module>
|
<module>hibernate-jpa</module>
|
||||||
<module>hibernate-queries</module>
|
<module>hibernate-queries</module>
|
||||||
@ -53,6 +55,7 @@
|
|||||||
<module>spring-boot-persistence-mongodb</module>
|
<module>spring-boot-persistence-mongodb</module>
|
||||||
<module>spring-data-cassandra</module>
|
<module>spring-data-cassandra</module>
|
||||||
<module>spring-data-cassandra-reactive</module>
|
<module>spring-data-cassandra-reactive</module>
|
||||||
|
<module>spring-data-cosmosdb</module>
|
||||||
<module>spring-data-couchbase-2</module>
|
<module>spring-data-couchbase-2</module>
|
||||||
<module>spring-data-dynamodb</module>
|
<module>spring-data-dynamodb</module>
|
||||||
<module>spring-data-eclipselink</module>
|
<module>spring-data-eclipselink</module>
|
||||||
@ -78,6 +81,7 @@
|
|||||||
<module>spring-hibernate-5</module> <!-- long running -->
|
<module>spring-hibernate-5</module> <!-- long running -->
|
||||||
<module>spring-hibernate4</module>
|
<module>spring-hibernate4</module>
|
||||||
<module>spring-jpa</module>
|
<module>spring-jpa</module>
|
||||||
|
<module>spring-jpa-2</module>
|
||||||
<!-- <module>spring-mybatis</module> --> <!-- needs fixing in BAEL-9021 -->
|
<!-- <module>spring-mybatis</module> --> <!-- needs fixing in BAEL-9021 -->
|
||||||
<module>spring-persistence-simple</module>
|
<module>spring-persistence-simple</module>
|
||||||
<module>spring-persistence-simple-2</module>
|
<module>spring-persistence-simple-2</module>
|
||||||
|
51
persistence-modules/spring-data-cosmosdb/pom.xml
Normal file
51
persistence-modules/spring-data-cosmosdb/pom.xml
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<artifactId>spring-data-cosmosdb</artifactId>
|
||||||
|
<name>spring-data-cosmos-db</name>
|
||||||
|
<description>tutorial for spring-data-cosmosdb</description>
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-boot-2</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../../parent-boot-2</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<java.version>1.8</java.version>
|
||||||
|
<cosmodb.version>2.3.0</cosmodb.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.microsoft.azure</groupId>
|
||||||
|
<artifactId>spring-data-cosmosdb</artifactId>
|
||||||
|
<version>${cosmodb.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok</artifactId>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1,12 @@
|
|||||||
|
package com.baeldung.spring.data.cosmosdb;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
public class AzureCosmosDbApplication {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(AzureCosmosDbApplication.class, args);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,37 @@
|
|||||||
|
package com.baeldung.spring.data.cosmosdb.config;
|
||||||
|
|
||||||
|
import com.azure.data.cosmos.CosmosKeyCredential;
|
||||||
|
import com.microsoft.azure.spring.data.cosmosdb.config.AbstractCosmosConfiguration;
|
||||||
|
import com.microsoft.azure.spring.data.cosmosdb.config.CosmosDBConfig;
|
||||||
|
import com.microsoft.azure.spring.data.cosmosdb.repository.config.EnableCosmosRepositories;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableCosmosRepositories(basePackages = "com.baeldung.spring.data.cosmosdb.repository")
|
||||||
|
public class AzureCosmosDbConfiguration extends AbstractCosmosConfiguration {
|
||||||
|
|
||||||
|
@Value("${azure.cosmosdb.uri}")
|
||||||
|
private String uri;
|
||||||
|
|
||||||
|
@Value("${azure.cosmosdb.key}")
|
||||||
|
private String key;
|
||||||
|
|
||||||
|
@Value("${azure.cosmosdb.secondaryKey}")
|
||||||
|
private String secondaryKey;
|
||||||
|
|
||||||
|
@Value("${azure.cosmosdb.database}")
|
||||||
|
private String dbName;
|
||||||
|
|
||||||
|
private CosmosKeyCredential cosmosKeyCredential;
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public CosmosDBConfig getConfig() {
|
||||||
|
this.cosmosKeyCredential = new CosmosKeyCredential(key);
|
||||||
|
CosmosDBConfig cosmosdbConfig = CosmosDBConfig.builder(uri, this.cosmosKeyCredential, dbName)
|
||||||
|
.build();
|
||||||
|
return cosmosdbConfig;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,53 @@
|
|||||||
|
package com.baeldung.spring.data.cosmosdb.controller;
|
||||||
|
|
||||||
|
import com.baeldung.spring.data.cosmosdb.entity.Product;
|
||||||
|
import com.baeldung.spring.data.cosmosdb.service.ProductService;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
|
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.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/products")
|
||||||
|
public class ProductController {
|
||||||
|
|
||||||
|
private ProductService productService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
public ProductController(ProductService productService) {
|
||||||
|
this.productService = productService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
@ResponseStatus(HttpStatus.CREATED)
|
||||||
|
public void create(@RequestBody Product product) {
|
||||||
|
productService.saveProduct(product);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping(value = "/{id}/category/{category}")
|
||||||
|
public Optional<Product> get(@PathVariable String id, @PathVariable String category) {
|
||||||
|
return productService.findById(id, category);
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping(value = "/{id}/category/{category}")
|
||||||
|
public void delete(@PathVariable String id, @PathVariable String category) {
|
||||||
|
productService.delete(id, category);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
public List<Product> getByName(@RequestParam String name) {
|
||||||
|
return productService.findProductByName(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,26 @@
|
|||||||
|
package com.baeldung.spring.data.cosmosdb.entity;
|
||||||
|
|
||||||
|
import com.microsoft.azure.spring.data.cosmosdb.core.mapping.Document;
|
||||||
|
import com.microsoft.azure.spring.data.cosmosdb.core.mapping.PartitionKey;
|
||||||
|
|
||||||
|
import org.springframework.data.annotation.Id;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@Document(collection = "products")
|
||||||
|
public class Product {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
private String productid;
|
||||||
|
|
||||||
|
private String productName;
|
||||||
|
|
||||||
|
private double price;
|
||||||
|
|
||||||
|
@PartitionKey
|
||||||
|
private String productCategory;
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.spring.data.cosmosdb.repository;
|
||||||
|
|
||||||
|
import com.baeldung.spring.data.cosmosdb.entity.Product;
|
||||||
|
import com.microsoft.azure.spring.data.cosmosdb.repository.CosmosRepository;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public interface ProductRepository extends CosmosRepository<Product, String> {
|
||||||
|
List<Product> findByProductName(String productName);
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,38 @@
|
|||||||
|
package com.baeldung.spring.data.cosmosdb.service;
|
||||||
|
|
||||||
|
import com.azure.data.cosmos.PartitionKey;
|
||||||
|
import com.baeldung.spring.data.cosmosdb.entity.Product;
|
||||||
|
import com.baeldung.spring.data.cosmosdb.repository.ProductRepository;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class ProductService {
|
||||||
|
|
||||||
|
private ProductRepository repository;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
public ProductService(ProductRepository repository) {
|
||||||
|
this.repository = repository;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Product> findProductByName(String productName) {
|
||||||
|
return repository.findByProductName(productName);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<Product> findById(String productId, String category) {
|
||||||
|
return repository.findById(productId, new PartitionKey(category));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void saveProduct(Product product) {
|
||||||
|
repository.save(product);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void delete(String productId, String category) {
|
||||||
|
repository.deleteById(productId, new PartitionKey(category));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,4 @@
|
|||||||
|
azure.cosmosdb.uri=cosmodb-uri
|
||||||
|
azure.cosmosdb.key=cosmodb-primary-key
|
||||||
|
azure.cosmosdb.secondaryKey=cosmodb-second-key
|
||||||
|
azure.cosmosdb.database=cosmodb-name
|
@ -0,0 +1,33 @@
|
|||||||
|
package com.baeldung.spring.data.cosmosdb;
|
||||||
|
|
||||||
|
import com.azure.data.cosmos.PartitionKey;
|
||||||
|
import com.baeldung.spring.data.cosmosdb.entity.Product;
|
||||||
|
import com.baeldung.spring.data.cosmosdb.repository.ProductRepository;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
|
@SpringBootTest
|
||||||
|
public class AzureCosmosDbApplicationManualTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
ProductRepository productRepository;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenProductIsCreated_whenCallFindById_thenProductIsFound() {
|
||||||
|
Product product = new Product();
|
||||||
|
product.setProductid("1001");
|
||||||
|
product.setProductCategory("Shirt");
|
||||||
|
product.setPrice(110.0);
|
||||||
|
product.setProductName("Blue Shirt");
|
||||||
|
|
||||||
|
productRepository.save(product);
|
||||||
|
Product retrievedProduct = productRepository.findById("1001", new PartitionKey("Shirt"))
|
||||||
|
.orElse(null);
|
||||||
|
Assert.notNull(retrievedProduct, "Retrieved Product is Null");
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -6,7 +6,6 @@
|
|||||||
- [Guide to Elasticsearch in Java](https://www.baeldung.com/elasticsearch-java)
|
- [Guide to Elasticsearch in Java](https://www.baeldung.com/elasticsearch-java)
|
||||||
- [Geospatial Support in ElasticSearch](https://www.baeldung.com/elasticsearch-geo-spatial)
|
- [Geospatial Support in ElasticSearch](https://www.baeldung.com/elasticsearch-geo-spatial)
|
||||||
- [A Simple Tagging Implementation with Elasticsearch](https://www.baeldung.com/elasticsearch-tagging)
|
- [A Simple Tagging Implementation with Elasticsearch](https://www.baeldung.com/elasticsearch-tagging)
|
||||||
- [Introduction to Spring Data Elasticsearch (evaluation)](https://www.baeldung.com/spring-data-elasticsearch-test-2)
|
|
||||||
|
|
||||||
### Build the Project with Tests Running
|
### Build the Project with Tests Running
|
||||||
```
|
```
|
||||||
|
@ -6,8 +6,8 @@ import org.springframework.boot.autoconfigure.domain.EntityScan;
|
|||||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
@EnableJpaRepositories("com.baeldung")
|
@EnableJpaRepositories("com.baeldung.boot")
|
||||||
@EntityScan("com.baeldung")
|
@EntityScan("com.baeldung.boot")
|
||||||
public class Application {
|
public class Application {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
|
@ -4,7 +4,7 @@ import javax.persistence.*;
|
|||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
@Table(name = "users")
|
@Table(name = "basic_users")
|
||||||
public class BasicUser {
|
public class BasicUser {
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
|
5
persistence-modules/spring-jpa-2/README.md
Normal file
5
persistence-modules/spring-jpa-2/README.md
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
## Spring JPA (2)
|
||||||
|
|
||||||
|
### Relevant Articles:
|
||||||
|
- [Many-To-Many Relationship in JPA](https://www.baeldung.com/jpa-many-to-many)
|
||||||
|
- More articles: [[<-- prev]](/spring-jpa)
|
62
persistence-modules/spring-jpa-2/pom.xml
Normal file
62
persistence-modules/spring-jpa-2/pom.xml
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
<?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>spring-jpa-2</artifactId>
|
||||||
|
<version>0.1-SNAPSHOT</version>
|
||||||
|
<name>spring-jpa-2</name>
|
||||||
|
<packaging>war</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>persistence-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<!-- Spring -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-orm</artifactId>
|
||||||
|
<version>${org.springframework.version}</version>
|
||||||
|
<exclusions>
|
||||||
|
<exclusion>
|
||||||
|
<artifactId>commons-logging</artifactId>
|
||||||
|
<groupId>commons-logging</groupId>
|
||||||
|
</exclusion>
|
||||||
|
</exclusions>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-context</artifactId>
|
||||||
|
<version>${org.springframework.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- persistence -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.hibernate</groupId>
|
||||||
|
<artifactId>hibernate-entitymanager</artifactId>
|
||||||
|
<version>${hibernate.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.h2database</groupId>
|
||||||
|
<artifactId>h2</artifactId>
|
||||||
|
<version>${h2.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- test scoped -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-test</artifactId>
|
||||||
|
<version>${org.springframework.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<!-- Spring -->
|
||||||
|
<org.springframework.version>5.1.5.RELEASE</org.springframework.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
@ -16,7 +16,7 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
|||||||
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@PropertySource("classpath:/manytomany/test.properties")
|
@PropertySource("manytomany/test.properties")
|
||||||
public class ManyToManyTestConfiguration {
|
public class ManyToManyTestConfiguration {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
@ -1,7 +1,4 @@
|
|||||||
=========
|
## Spring JPA (1)
|
||||||
|
|
||||||
## Spring JPA Example Project
|
|
||||||
|
|
||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [The DAO with JPA and Spring](https://www.baeldung.com/spring-dao-jpa)
|
- [The DAO with JPA and Spring](https://www.baeldung.com/spring-dao-jpa)
|
||||||
@ -10,9 +7,7 @@
|
|||||||
- [Self-Contained Testing Using an In-Memory Database](https://www.baeldung.com/spring-jpa-test-in-memory-database)
|
- [Self-Contained Testing Using an In-Memory Database](https://www.baeldung.com/spring-jpa-test-in-memory-database)
|
||||||
- [A Guide to Spring AbstractRoutingDatasource](https://www.baeldung.com/spring-abstract-routing-data-source)
|
- [A Guide to Spring AbstractRoutingDatasource](https://www.baeldung.com/spring-abstract-routing-data-source)
|
||||||
- [Obtaining Auto-generated Keys in Spring JDBC](https://www.baeldung.com/spring-jdbc-autogenerated-keys)
|
- [Obtaining Auto-generated Keys in Spring JDBC](https://www.baeldung.com/spring-jdbc-autogenerated-keys)
|
||||||
- [Many-To-Many Relationship in JPA](https://www.baeldung.com/jpa-many-to-many)
|
- More articles: [[next -->]](/spring-jpa-2)
|
||||||
- [Spring Persistence (Hibernate and JPA) with a JNDI datasource](https://www.baeldung.com/spring-persistence-hibernate-and-jpa-with-a-jndi-datasource-2)
|
|
||||||
|
|
||||||
|
|
||||||
### Eclipse Config
|
### Eclipse Config
|
||||||
After importing the project into Eclipse, you may see the following error:
|
After importing the project into Eclipse, you may see the following error:
|
||||||
|
2
pom.xml
2
pom.xml
@ -556,6 +556,7 @@
|
|||||||
<module>atomikos</module>
|
<module>atomikos</module>
|
||||||
<module>reactive-systems</module>
|
<module>reactive-systems</module>
|
||||||
<module>slack</module>
|
<module>slack</module>
|
||||||
|
<module>spring-webflux-threads</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
</profile>
|
</profile>
|
||||||
@ -1067,6 +1068,7 @@
|
|||||||
<module>atomikos</module>
|
<module>atomikos</module>
|
||||||
<module>reactive-systems</module>
|
<module>reactive-systems</module>
|
||||||
<module>slack</module>
|
<module>slack</module>
|
||||||
|
<module>spring-webflux-threads</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
</profile>
|
</profile>
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user