commit
72f692d735
24
.travis.yml
24
.travis.yml
|
@ -1,24 +0,0 @@
|
|||
language: java
|
||||
|
||||
before_install:
|
||||
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
|
||||
|
||||
install: skip
|
||||
script: travis_wait 60 mvn -q install -Pdefault-first,default-second -Dgib.enabled=true
|
||||
|
||||
sudo: required
|
||||
|
||||
jdk:
|
||||
- oraclejdk8
|
||||
|
||||
addons:
|
||||
apt:
|
||||
packages:
|
||||
- oracle-java8-installer
|
||||
|
||||
cache:
|
||||
directories:
|
||||
- .autoconf
|
||||
- $HOME/.m2
|
||||
|
||||
|
|
@ -7,3 +7,4 @@
|
|||
- [Checking If a List Is Sorted in Java](https://www.baeldung.com/java-check-if-list-sorted)
|
||||
- [Checking if a Java Graph has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle)
|
||||
- [A Guide to the Folding Technique in Java](https://www.baeldung.com/folding-hashing-technique)
|
||||
- [Creating a Triangle with for Loops in Java](https://www.baeldung.com/java-print-triangle)
|
||||
|
|
|
@ -0,0 +1,70 @@
|
|||
package com.baeldung.bucketsort;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
public class IntegerBucketSorter implements Sorter<Integer> {
|
||||
|
||||
private final Comparator<Integer> comparator;
|
||||
|
||||
public IntegerBucketSorter(Comparator<Integer> comparator) {
|
||||
this.comparator = comparator;
|
||||
}
|
||||
|
||||
public IntegerBucketSorter() {
|
||||
comparator = Comparator.naturalOrder();
|
||||
}
|
||||
|
||||
public List<Integer> sort(List<Integer> arrayToSort) {
|
||||
|
||||
List<List<Integer>> buckets = splitIntoUnsortedBuckets(arrayToSort);
|
||||
|
||||
for(List<Integer> bucket : buckets){
|
||||
bucket.sort(comparator);
|
||||
}
|
||||
|
||||
return concatenateSortedBuckets(buckets);
|
||||
}
|
||||
|
||||
private List<Integer> concatenateSortedBuckets(List<List<Integer>> buckets){
|
||||
List<Integer> sortedArray = new ArrayList<>();
|
||||
int index = 0;
|
||||
for(List<Integer> bucket : buckets){
|
||||
for(int number : bucket){
|
||||
sortedArray.add(index++, number);
|
||||
}
|
||||
}
|
||||
return sortedArray;
|
||||
}
|
||||
|
||||
private List<List<Integer>> splitIntoUnsortedBuckets(List<Integer> initialList){
|
||||
|
||||
final int[] codes = createHashes(initialList);
|
||||
|
||||
List<List<Integer>> buckets = new ArrayList<>(codes[1]);
|
||||
for(int i = 0; i < codes[1]; i++) buckets.add(new ArrayList<>());
|
||||
|
||||
//distribute the data
|
||||
for (int i : initialList) {
|
||||
buckets.get(hash(i, codes)).add(i);
|
||||
}
|
||||
return buckets;
|
||||
|
||||
}
|
||||
|
||||
private int[] createHashes(List<Integer> input){
|
||||
int m = input.get(0);
|
||||
for (int i = 1; i < input.size(); i++) {
|
||||
if (m < input.get(i)) {
|
||||
m = input.get(i);
|
||||
}
|
||||
}
|
||||
return new int[]{m, (int) Math.sqrt(input.size())};
|
||||
}
|
||||
|
||||
private static int hash(int i, int[] code) {
|
||||
return (int) ((double) i / code[0] * (code[1] - 1));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.bucketsort;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface Sorter<T> {
|
||||
|
||||
List<T> sort(List<T> arrayToSort);
|
||||
}
|
|
@ -4,7 +4,7 @@ import org.apache.commons.lang3.StringUtils;
|
|||
|
||||
public class PrintTriangleExamples {
|
||||
|
||||
public static String printARightAngledTriangle(int N) {
|
||||
public static String printARightTriangle(int N) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (int r = 1; r <= N; r++) {
|
||||
for (int j = 1; j <= r; j++) {
|
||||
|
@ -29,6 +29,17 @@ public class PrintTriangleExamples {
|
|||
return result.toString();
|
||||
}
|
||||
|
||||
public static String printAnIsoscelesTriangleUsingStringUtils(int N) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
for (int r = 1; r <= N; r++) {
|
||||
result.append(StringUtils.repeat(' ', N - r));
|
||||
result.append(StringUtils.repeat('*', 2 * r - 1));
|
||||
result.append(System.lineSeparator());
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public static String printAnIsoscelesTriangleUsingSubstring(int N) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
String helperString = StringUtils.repeat(' ', N - 1) + StringUtils.repeat('*', N * 2 - 1);
|
||||
|
@ -41,8 +52,9 @@ public class PrintTriangleExamples {
|
|||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println(printARightAngledTriangle(5));
|
||||
System.out.println(printARightTriangle(5));
|
||||
System.out.println(printAnIsoscelesTriangle(5));
|
||||
System.out.println(printAnIsoscelesTriangleUsingStringUtils(5));
|
||||
System.out.println(printAnIsoscelesTriangleUsingSubstring(5));
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.bucketsort;
|
||||
|
||||
import com.baeldung.bucketsort.IntegerBucketSorter;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class IntegerBucketSorterUnitTest {
|
||||
|
||||
private IntegerBucketSorter sorter;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
sorter = new IntegerBucketSorter();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedList_whenSortedUsingBucketSorter_checkSortingCorrect() {
|
||||
|
||||
List<Integer> unsorted = Arrays.asList(80,50,60,30,20,10,70,0,40,500,600,602,200,15);
|
||||
List<Integer> expected = Arrays.asList(0,10,15,20,30,40,50,60,70,80,200,500,600,602);
|
||||
|
||||
List<Integer> actual = sorter.sort(unsorted);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
|
||||
|
||||
}
|
||||
}
|
|
@ -9,9 +9,9 @@ import static org.junit.Assert.assertEquals;
|
|||
|
||||
@RunWith(JUnitParamsRunner.class)
|
||||
public class PrintTriangleExamplesUnitTest {
|
||||
|
||||
private static Object[][] rightAngledTriangles() {
|
||||
String expected0 = "";
|
||||
|
||||
private static Object[][] rightTriangles() {
|
||||
String expected0 = "";
|
||||
|
||||
String expected2 = "*" + System.lineSeparator()
|
||||
+ "**" + System.lineSeparator();
|
||||
|
@ -39,9 +39,9 @@ public class PrintTriangleExamplesUnitTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
@Parameters(method = "rightAngledTriangles")
|
||||
public void whenPrintARightAngledTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
|
||||
String actual = PrintTriangleExamples.printARightAngledTriangle(nrOfRows);
|
||||
@Parameters(method = "rightTriangles")
|
||||
public void whenPrintARightTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
|
||||
String actual = PrintTriangleExamples.printARightTriangle(nrOfRows);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
@ -81,6 +81,14 @@ public class PrintTriangleExamplesUnitTest {
|
|||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Parameters(method = "isoscelesTriangles")
|
||||
public void whenPrintAnIsoscelesTriangleUsingStringUtilsIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
|
||||
String actual = PrintTriangleExamples.printAnIsoscelesTriangleUsingStringUtils(nrOfRows);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Parameters(method = "isoscelesTriangles")
|
||||
|
|
|
@ -6,3 +6,4 @@
|
|||
- [Insertion Sort in Java](https://www.baeldung.com/java-insertion-sort)
|
||||
- [Heap Sort in Java](https://www.baeldung.com/java-heap-sort)
|
||||
- [Shell Sort in Java](https://www.baeldung.com/java-shell-sort)
|
||||
- [Counting Sort in Java](https://www.baeldung.com/java-counting-sort)
|
||||
|
|
|
@ -0,0 +1,48 @@
|
|||
package com.baeldung.algorithms.counting;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class CountingSort {
|
||||
|
||||
public static int[] sort(int[] input, int k) {
|
||||
verifyPreconditions(input, k);
|
||||
if (input.length == 0) return input;
|
||||
|
||||
int[] c = countElements(input, k);
|
||||
int[] sorted = new int[input.length];
|
||||
for (int i = input.length - 1; i >= 0; i--) {
|
||||
int current = input[i];
|
||||
sorted[c[current] - 1] = current;
|
||||
c[current] -= 1;
|
||||
}
|
||||
|
||||
return sorted;
|
||||
}
|
||||
|
||||
static int[] countElements(int[] input, int k) {
|
||||
int[] c = new int[k + 1];
|
||||
Arrays.fill(c, 0);
|
||||
for (int i : input) {
|
||||
c[i] += 1;
|
||||
}
|
||||
|
||||
for (int i = 1; i < c.length; i++) {
|
||||
c[i] += c[i - 1];
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
private static void verifyPreconditions(int[] input, int k) {
|
||||
if (input == null) {
|
||||
throw new IllegalArgumentException("Input is required");
|
||||
}
|
||||
|
||||
int min = IntStream.of(input).min().getAsInt();
|
||||
int max = IntStream.of(input).max().getAsInt();
|
||||
|
||||
if (min < 0 || max > k) {
|
||||
throw new IllegalArgumentException("The input numbers should be between zero and " + k);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,53 @@
|
|||
package com.baeldung.algorithms.radixsort;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class RadixSort {
|
||||
|
||||
public static void sort(int numbers[]) {
|
||||
int maximumNumber = findMaximumNumberIn(numbers);
|
||||
|
||||
int numberOfDigits = calculateNumberOfDigitsIn(maximumNumber);
|
||||
|
||||
int placeValue = 1;
|
||||
|
||||
while (numberOfDigits-- > 0) {
|
||||
applyCountingSortOn(numbers, placeValue);
|
||||
placeValue *= 10;
|
||||
}
|
||||
}
|
||||
|
||||
private static void applyCountingSortOn(int[] numbers, int placeValue) {
|
||||
int range = 10; // radix or the base
|
||||
|
||||
int length = numbers.length;
|
||||
int[] frequency = new int[range];
|
||||
int[] sortedValues = new int[length];
|
||||
|
||||
for (int i = 0; i < length; i++) {
|
||||
int digit = (numbers[i] / placeValue) % range;
|
||||
frequency[digit]++;
|
||||
}
|
||||
|
||||
for (int i = 1; i < 10; i++) {
|
||||
frequency[i] += frequency[i - 1];
|
||||
}
|
||||
|
||||
for (int i = length - 1; i >= 0; i--) {
|
||||
int digit = (numbers[i] / placeValue) % range;
|
||||
sortedValues[frequency[digit] - 1] = numbers[i];
|
||||
frequency[digit]--;
|
||||
}
|
||||
|
||||
System.arraycopy(sortedValues, 0, numbers, 0, length);
|
||||
}
|
||||
|
||||
private static int calculateNumberOfDigitsIn(int number) {
|
||||
return (int) Math.log10(number) + 1; // valid only if number > 0
|
||||
}
|
||||
|
||||
private static int findMaximumNumberIn(int[] arr) {
|
||||
return Arrays.stream(arr).max().getAsInt();
|
||||
}
|
||||
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.algorithms.stringsortingbynumber;
|
||||
package com.baeldung.algorithms.sort.bynumber;
|
||||
|
||||
import java.util.Comparator;
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.algorithms.counting;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class CountingSortUnitTest {
|
||||
|
||||
@Test
|
||||
void countElements_GivenAnArray_ShouldCalculateTheFrequencyArrayAsExpected() {
|
||||
int k = 5;
|
||||
int[] input = { 4, 3, 2, 5, 4, 3, 5, 1, 0, 2, 5 };
|
||||
|
||||
int[] c = CountingSort.countElements(input, k);
|
||||
int[] expected = { 1, 2, 4, 6, 8, 11 };
|
||||
assertArrayEquals(expected, c);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sort_GivenAnArray_ShouldSortTheInputAsExpected() {
|
||||
int k = 5;
|
||||
int[] input = { 4, 3, 2, 5, 4, 3, 5, 1, 0, 2, 5 };
|
||||
|
||||
int[] sorted = CountingSort.sort(input, k);
|
||||
|
||||
// Our sorting algorithm and Java's should return the same result
|
||||
Arrays.sort(input);
|
||||
assertArrayEquals(input, sorted);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.algorithms.radixsort;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RadixSortUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenUnsortedArrayWhenRadixSortThenArraySorted() {
|
||||
int[] numbers = { 387, 468, 134, 123, 68, 221, 769, 37, 7 };
|
||||
RadixSort.sort(numbers);
|
||||
int[] numbersSorted = { 7, 37, 68, 123, 134, 221, 387, 468, 769 };
|
||||
assertArrayEquals(numbersSorted, numbers);
|
||||
}
|
||||
}
|
|
@ -1,6 +1,6 @@
|
|||
package com.baeldung.algorithms.stringsortingbynumber;
|
||||
package com.baeldung.algorithms.sort.bynumber;
|
||||
|
||||
import com.baeldung.algorithms.stringsortingbynumber.NaturalOrderComparators;
|
||||
import com.baeldung.algorithms.sort.bynumber.NaturalOrderComparators;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
|
@ -4,9 +4,9 @@
|
|||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.baeldung.examples.olingo2</groupId>
|
||||
<artifactId>olingo2-sample</artifactId>
|
||||
<artifactId>olingo2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>olingo2-sample</name>
|
||||
<name>olingo2</name>
|
||||
<description>Sample Olingo 2 Project</description>
|
||||
|
||||
<parent>
|
||||
|
|
|
@ -0,0 +1,150 @@
|
|||
5.1,3.5,1.4,0.2,Iris-setosa
|
||||
4.9,3.0,1.4,0.2,Iris-setosa
|
||||
4.7,3.2,1.3,0.2,Iris-setosa
|
||||
4.6,3.1,1.5,0.2,Iris-setosa
|
||||
5.0,3.6,1.4,0.2,Iris-setosa
|
||||
5.4,3.9,1.7,0.4,Iris-setosa
|
||||
4.6,3.4,1.4,0.3,Iris-setosa
|
||||
5.0,3.4,1.5,0.2,Iris-setosa
|
||||
4.4,2.9,1.4,0.2,Iris-setosa
|
||||
4.9,3.1,1.5,0.1,Iris-setosa
|
||||
5.4,3.7,1.5,0.2,Iris-setosa
|
||||
4.8,3.4,1.6,0.2,Iris-setosa
|
||||
4.8,3.0,1.4,0.1,Iris-setosa
|
||||
4.3,3.0,1.1,0.1,Iris-setosa
|
||||
5.8,4.0,1.2,0.2,Iris-setosa
|
||||
5.7,4.4,1.5,0.4,Iris-setosa
|
||||
5.4,3.9,1.3,0.4,Iris-setosa
|
||||
5.1,3.5,1.4,0.3,Iris-setosa
|
||||
5.7,3.8,1.7,0.3,Iris-setosa
|
||||
5.1,3.8,1.5,0.3,Iris-setosa
|
||||
5.4,3.4,1.7,0.2,Iris-setosa
|
||||
5.1,3.7,1.5,0.4,Iris-setosa
|
||||
4.6,3.6,1.0,0.2,Iris-setosa
|
||||
5.1,3.3,1.7,0.5,Iris-setosa
|
||||
4.8,3.4,1.9,0.2,Iris-setosa
|
||||
5.0,3.0,1.6,0.2,Iris-setosa
|
||||
5.0,3.4,1.6,0.4,Iris-setosa
|
||||
5.2,3.5,1.5,0.2,Iris-setosa
|
||||
5.2,3.4,1.4,0.2,Iris-setosa
|
||||
4.7,3.2,1.6,0.2,Iris-setosa
|
||||
4.8,3.1,1.6,0.2,Iris-setosa
|
||||
5.4,3.4,1.5,0.4,Iris-setosa
|
||||
5.2,4.1,1.5,0.1,Iris-setosa
|
||||
5.5,4.2,1.4,0.2,Iris-setosa
|
||||
4.9,3.1,1.5,0.1,Iris-setosa
|
||||
5.0,3.2,1.2,0.2,Iris-setosa
|
||||
5.5,3.5,1.3,0.2,Iris-setosa
|
||||
4.9,3.1,1.5,0.1,Iris-setosa
|
||||
4.4,3.0,1.3,0.2,Iris-setosa
|
||||
5.1,3.4,1.5,0.2,Iris-setosa
|
||||
5.0,3.5,1.3,0.3,Iris-setosa
|
||||
4.5,2.3,1.3,0.3,Iris-setosa
|
||||
4.4,3.2,1.3,0.2,Iris-setosa
|
||||
5.0,3.5,1.6,0.6,Iris-setosa
|
||||
5.1,3.8,1.9,0.4,Iris-setosa
|
||||
4.8,3.0,1.4,0.3,Iris-setosa
|
||||
5.1,3.8,1.6,0.2,Iris-setosa
|
||||
4.6,3.2,1.4,0.2,Iris-setosa
|
||||
5.3,3.7,1.5,0.2,Iris-setosa
|
||||
5.0,3.3,1.4,0.2,Iris-setosa
|
||||
7.0,3.2,4.7,1.4,Iris-versicolor
|
||||
6.4,3.2,4.5,1.5,Iris-versicolor
|
||||
6.9,3.1,4.9,1.5,Iris-versicolor
|
||||
5.5,2.3,4.0,1.3,Iris-versicolor
|
||||
6.5,2.8,4.6,1.5,Iris-versicolor
|
||||
5.7,2.8,4.5,1.3,Iris-versicolor
|
||||
6.3,3.3,4.7,1.6,Iris-versicolor
|
||||
4.9,2.4,3.3,1.0,Iris-versicolor
|
||||
6.6,2.9,4.6,1.3,Iris-versicolor
|
||||
5.2,2.7,3.9,1.4,Iris-versicolor
|
||||
5.0,2.0,3.5,1.0,Iris-versicolor
|
||||
5.9,3.0,4.2,1.5,Iris-versicolor
|
||||
6.0,2.2,4.0,1.0,Iris-versicolor
|
||||
6.1,2.9,4.7,1.4,Iris-versicolor
|
||||
5.6,2.9,3.6,1.3,Iris-versicolor
|
||||
6.7,3.1,4.4,1.4,Iris-versicolor
|
||||
5.6,3.0,4.5,1.5,Iris-versicolor
|
||||
5.8,2.7,4.1,1.0,Iris-versicolor
|
||||
6.2,2.2,4.5,1.5,Iris-versicolor
|
||||
5.6,2.5,3.9,1.1,Iris-versicolor
|
||||
5.9,3.2,4.8,1.8,Iris-versicolor
|
||||
6.1,2.8,4.0,1.3,Iris-versicolor
|
||||
6.3,2.5,4.9,1.5,Iris-versicolor
|
||||
6.1,2.8,4.7,1.2,Iris-versicolor
|
||||
6.4,2.9,4.3,1.3,Iris-versicolor
|
||||
6.6,3.0,4.4,1.4,Iris-versicolor
|
||||
6.8,2.8,4.8,1.4,Iris-versicolor
|
||||
6.7,3.0,5.0,1.7,Iris-versicolor
|
||||
6.0,2.9,4.5,1.5,Iris-versicolor
|
||||
5.7,2.6,3.5,1.0,Iris-versicolor
|
||||
5.5,2.4,3.8,1.1,Iris-versicolor
|
||||
5.5,2.4,3.7,1.0,Iris-versicolor
|
||||
5.8,2.7,3.9,1.2,Iris-versicolor
|
||||
6.0,2.7,5.1,1.6,Iris-versicolor
|
||||
5.4,3.0,4.5,1.5,Iris-versicolor
|
||||
6.0,3.4,4.5,1.6,Iris-versicolor
|
||||
6.7,3.1,4.7,1.5,Iris-versicolor
|
||||
6.3,2.3,4.4,1.3,Iris-versicolor
|
||||
5.6,3.0,4.1,1.3,Iris-versicolor
|
||||
5.5,2.5,4.0,1.3,Iris-versicolor
|
||||
5.5,2.6,4.4,1.2,Iris-versicolor
|
||||
6.1,3.0,4.6,1.4,Iris-versicolor
|
||||
5.8,2.6,4.0,1.2,Iris-versicolor
|
||||
5.0,2.3,3.3,1.0,Iris-versicolor
|
||||
5.6,2.7,4.2,1.3,Iris-versicolor
|
||||
5.7,3.0,4.2,1.2,Iris-versicolor
|
||||
5.7,2.9,4.2,1.3,Iris-versicolor
|
||||
6.2,2.9,4.3,1.3,Iris-versicolor
|
||||
5.1,2.5,3.0,1.1,Iris-versicolor
|
||||
5.7,2.8,4.1,1.3,Iris-versicolor
|
||||
6.3,3.3,6.0,2.5,Iris-virginica
|
||||
5.8,2.7,5.1,1.9,Iris-virginica
|
||||
7.1,3.0,5.9,2.1,Iris-virginica
|
||||
6.3,2.9,5.6,1.8,Iris-virginica
|
||||
6.5,3.0,5.8,2.2,Iris-virginica
|
||||
7.6,3.0,6.6,2.1,Iris-virginica
|
||||
4.9,2.5,4.5,1.7,Iris-virginica
|
||||
7.3,2.9,6.3,1.8,Iris-virginica
|
||||
6.7,2.5,5.8,1.8,Iris-virginica
|
||||
7.2,3.6,6.1,2.5,Iris-virginica
|
||||
6.5,3.2,5.1,2.0,Iris-virginica
|
||||
6.4,2.7,5.3,1.9,Iris-virginica
|
||||
6.8,3.0,5.5,2.1,Iris-virginica
|
||||
5.7,2.5,5.0,2.0,Iris-virginica
|
||||
5.8,2.8,5.1,2.4,Iris-virginica
|
||||
6.4,3.2,5.3,2.3,Iris-virginica
|
||||
6.5,3.0,5.5,1.8,Iris-virginica
|
||||
7.7,3.8,6.7,2.2,Iris-virginica
|
||||
7.7,2.6,6.9,2.3,Iris-virginica
|
||||
6.0,2.2,5.0,1.5,Iris-virginica
|
||||
6.9,3.2,5.7,2.3,Iris-virginica
|
||||
5.6,2.8,4.9,2.0,Iris-virginica
|
||||
7.7,2.8,6.7,2.0,Iris-virginica
|
||||
6.3,2.7,4.9,1.8,Iris-virginica
|
||||
6.7,3.3,5.7,2.1,Iris-virginica
|
||||
7.2,3.2,6.0,1.8,Iris-virginica
|
||||
6.2,2.8,4.8,1.8,Iris-virginica
|
||||
6.1,3.0,4.9,1.8,Iris-virginica
|
||||
6.4,2.8,5.6,2.1,Iris-virginica
|
||||
7.2,3.0,5.8,1.6,Iris-virginica
|
||||
7.4,2.8,6.1,1.9,Iris-virginica
|
||||
7.9,3.8,6.4,2.0,Iris-virginica
|
||||
6.4,2.8,5.6,2.2,Iris-virginica
|
||||
6.3,2.8,5.1,1.5,Iris-virginica
|
||||
6.1,2.6,5.6,1.4,Iris-virginica
|
||||
7.7,3.0,6.1,2.3,Iris-virginica
|
||||
6.3,3.4,5.6,2.4,Iris-virginica
|
||||
6.4,3.1,5.5,1.8,Iris-virginica
|
||||
6.0,3.0,4.8,1.8,Iris-virginica
|
||||
6.9,3.1,5.4,2.1,Iris-virginica
|
||||
6.7,3.1,5.6,2.4,Iris-virginica
|
||||
6.9,3.1,5.1,2.3,Iris-virginica
|
||||
5.8,2.7,5.1,1.9,Iris-virginica
|
||||
6.8,3.2,5.9,2.3,Iris-virginica
|
||||
6.7,3.3,5.7,2.5,Iris-virginica
|
||||
6.7,3.0,5.2,2.3,Iris-virginica
|
||||
6.3,2.5,5.0,1.9,Iris-virginica
|
||||
6.5,3.0,5.2,2.0,Iris-virginica
|
||||
6.2,3.4,5.4,2.3,Iris-virginica
|
||||
5.9,3.0,5.1,1.8,Iris-virginica
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
@ -0,0 +1 @@
|
|||
{"class":"org.apache.spark.mllib.classification.LogisticRegressionModel","version":"1.0","numFeatures":4,"numClasses":3}
|
|
@ -1,31 +1,32 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-spark</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>apache-spark</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-spark</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>apache-spark</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.spark</groupId>
|
||||
<artifactId>spark-core_2.11</artifactId>
|
||||
<version>${org.apache.spark.spark-core.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.spark</groupId>
|
||||
<artifactId>spark-sql_2.11</artifactId>
|
||||
<version>${org.apache.spark.spark-sql.version}</version>
|
||||
<scope>provided</scope>
|
||||
<groupId>org.apache.spark</groupId>
|
||||
<artifactId>spark-core_2.11</artifactId>
|
||||
<version>${org.apache.spark.spark-core.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.spark</groupId>
|
||||
<artifactId>spark-sql_2.11</artifactId>
|
||||
<version>${org.apache.spark.spark-sql.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.spark</groupId>
|
||||
|
@ -33,6 +34,12 @@
|
|||
<version>${org.apache.spark.spark-streaming.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.spark</groupId>
|
||||
<artifactId>spark-mllib_2.11</artifactId>
|
||||
<version>${org.apache.spark.spark-mllib.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.spark</groupId>
|
||||
<artifactId>spark-streaming-kafka-0-10_2.11</artifactId>
|
||||
|
@ -48,46 +55,47 @@
|
|||
<artifactId>spark-cassandra-connector-java_2.11</artifactId>
|
||||
<version>${com.datastax.spark.spark-cassandra-connector-java.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${java.version}</source>
|
||||
<target>${java.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${java.version}</source>
|
||||
<target>${java.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<org.apache.spark.spark-core.version>2.3.0</org.apache.spark.spark-core.version>
|
||||
<org.apache.spark.spark-sql.version>2.3.0</org.apache.spark.spark-sql.version>
|
||||
<org.apache.spark.spark-streaming.version>2.3.0</org.apache.spark.spark-streaming.version>
|
||||
<org.apache.spark.spark-streaming-kafka.version>2.3.0</org.apache.spark.spark-streaming-kafka.version>
|
||||
<com.datastax.spark.spark-cassandra-connector.version>2.3.0</com.datastax.spark.spark-cassandra-connector.version>
|
||||
<com.datastax.spark.spark-cassandra-connector-java.version>1.5.2</com.datastax.spark.spark-cassandra-connector-java.version>
|
||||
<properties>
|
||||
<org.apache.spark.spark-core.version>2.3.0</org.apache.spark.spark-core.version>
|
||||
<org.apache.spark.spark-sql.version>2.3.0</org.apache.spark.spark-sql.version>
|
||||
<org.apache.spark.spark-streaming.version>2.3.0</org.apache.spark.spark-streaming.version>
|
||||
<org.apache.spark.spark-mllib.version>2.3.0</org.apache.spark.spark-mllib.version>
|
||||
<org.apache.spark.spark-streaming-kafka.version>2.3.0</org.apache.spark.spark-streaming-kafka.version>
|
||||
<com.datastax.spark.spark-cassandra-connector.version>2.3.0</com.datastax.spark.spark-cassandra-connector.version>
|
||||
<com.datastax.spark.spark-cassandra-connector-java.version>1.5.2</com.datastax.spark.spark-cassandra-connector-java.version>
|
||||
<maven-compiler-plugin.version>3.2</maven-compiler-plugin.version>
|
||||
</properties>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,111 @@
|
|||
package com.baeldung.ml;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.log4j.Level;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.apache.spark.SparkConf;
|
||||
import org.apache.spark.api.java.JavaPairRDD;
|
||||
import org.apache.spark.api.java.JavaRDD;
|
||||
import org.apache.spark.api.java.JavaSparkContext;
|
||||
import org.apache.spark.mllib.classification.LogisticRegressionModel;
|
||||
import org.apache.spark.mllib.classification.LogisticRegressionWithLBFGS;
|
||||
import org.apache.spark.mllib.evaluation.MulticlassMetrics;
|
||||
import org.apache.spark.mllib.linalg.Matrix;
|
||||
import org.apache.spark.mllib.linalg.Vector;
|
||||
import org.apache.spark.mllib.linalg.Vectors;
|
||||
import org.apache.spark.mllib.regression.LabeledPoint;
|
||||
import org.apache.spark.mllib.stat.MultivariateStatisticalSummary;
|
||||
import org.apache.spark.mllib.stat.Statistics;
|
||||
|
||||
import scala.Tuple2;
|
||||
|
||||
public class MachineLearningApp {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
// 1. Setting the Spark Context
|
||||
SparkConf conf = new SparkConf().setAppName("Main")
|
||||
.setMaster("local[2]")
|
||||
.set("spark.executor.memory", "3g")
|
||||
.set("spark.driver.memory", "3g");
|
||||
JavaSparkContext sc = new JavaSparkContext(conf);
|
||||
Logger.getLogger("org")
|
||||
.setLevel(Level.OFF);
|
||||
Logger.getLogger("akka")
|
||||
.setLevel(Level.OFF);
|
||||
|
||||
// 2. Loading the Data-set
|
||||
String dataFile = "data\\iris.data";
|
||||
JavaRDD<String> data = sc.textFile(dataFile);
|
||||
|
||||
// 3. Exploratory Data Analysis
|
||||
// 3.1. Creating Vector of Input Data
|
||||
JavaRDD<Vector> inputData = data.map(line -> {
|
||||
String[] parts = line.split(",");
|
||||
double[] v = new double[parts.length - 1];
|
||||
for (int i = 0; i < parts.length - 1; i++) {
|
||||
v[i] = Double.parseDouble(parts[i]);
|
||||
}
|
||||
return Vectors.dense(v);
|
||||
});
|
||||
// 3.2. Performing Statistical Analysis
|
||||
MultivariateStatisticalSummary summary = Statistics.colStats(inputData.rdd());
|
||||
System.out.println("Summary Mean:");
|
||||
System.out.println(summary.mean());
|
||||
System.out.println("Summary Variance:");
|
||||
System.out.println(summary.variance());
|
||||
System.out.println("Summary Non-zero:");
|
||||
System.out.println(summary.numNonzeros());
|
||||
// 3.3. Performing Correlation Analysis
|
||||
Matrix correlMatrix = Statistics.corr(inputData.rdd(), "pearson");
|
||||
System.out.println("Correlation Matrix:");
|
||||
System.out.println(correlMatrix.toString());
|
||||
|
||||
// 4. Data Preparation
|
||||
// 4.1. Creating Map for Textual Output Labels
|
||||
Map<String, Integer> map = new HashMap<String, Integer>();
|
||||
map.put("Iris-setosa", 0);
|
||||
map.put("Iris-versicolor", 1);
|
||||
map.put("Iris-virginica", 2);
|
||||
// 4.2. Creating LabeledPoint of Input and Output Data
|
||||
JavaRDD<LabeledPoint> parsedData = data.map(line -> {
|
||||
String[] parts = line.split(",");
|
||||
double[] v = new double[parts.length - 1];
|
||||
for (int i = 0; i < parts.length - 1; i++) {
|
||||
v[i] = Double.parseDouble(parts[i]);
|
||||
}
|
||||
return new LabeledPoint(map.get(parts[parts.length - 1]), Vectors.dense(v));
|
||||
});
|
||||
|
||||
// 5. Data Splitting into 80% Training and 20% Test Sets
|
||||
JavaRDD<LabeledPoint>[] splits = parsedData.randomSplit(new double[] { 0.8, 0.2 }, 11L);
|
||||
JavaRDD<LabeledPoint> trainingData = splits[0].cache();
|
||||
JavaRDD<LabeledPoint> testData = splits[1];
|
||||
|
||||
// 6. Modeling
|
||||
// 6.1. Model Training
|
||||
LogisticRegressionModel model = new LogisticRegressionWithLBFGS().setNumClasses(3)
|
||||
.run(trainingData.rdd());
|
||||
// 6.2. Model Evaluation
|
||||
JavaPairRDD<Object, Object> predictionAndLabels = testData.mapToPair(p -> new Tuple2<>(model.predict(p.features()), p.label()));
|
||||
MulticlassMetrics metrics = new MulticlassMetrics(predictionAndLabels.rdd());
|
||||
double accuracy = metrics.accuracy();
|
||||
System.out.println("Model Accuracy on Test Data: " + accuracy);
|
||||
|
||||
// 7. Model Saving and Loading
|
||||
// 7.1. Model Saving
|
||||
model.save(sc.sc(), "model\\logistic-regression");
|
||||
// 7.2. Model Loading
|
||||
LogisticRegressionModel sameModel = LogisticRegressionModel.load(sc.sc(), "model\\logistic-regression");
|
||||
// 7.3. Prediction on New Data
|
||||
Vector newData = Vectors.dense(new double[] { 1, 1, 1, 1 });
|
||||
double prediction = sameModel.predict(newData);
|
||||
System.out.println("Model Prediction on New Data = " + prediction);
|
||||
|
||||
// 8. Clean-up
|
||||
sc.close();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
## Relevant Articles:
|
||||
|
||||
- [Building Java Applications with Bazel](https://www.baeldung.com/bazel-build-tool)
|
|
@ -0,0 +1,31 @@
|
|||
|
||||
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_jar")
|
||||
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
|
||||
|
||||
|
||||
RULES_JVM_EXTERNAL_TAG = "2.0.1"
|
||||
RULES_JVM_EXTERNAL_SHA = "55e8d3951647ae3dffde22b4f7f8dee11b3f70f3f89424713debd7076197eaca"
|
||||
|
||||
http_archive(
|
||||
name = "rules_jvm_external",
|
||||
strip_prefix = "rules_jvm_external-%s" % RULES_JVM_EXTERNAL_TAG,
|
||||
sha256 = RULES_JVM_EXTERNAL_SHA,
|
||||
url = "https://github.com/bazelbuild/rules_jvm_external/archive/%s.zip" % RULES_JVM_EXTERNAL_TAG,
|
||||
)
|
||||
|
||||
load("@rules_jvm_external//:defs.bzl", "maven_install")
|
||||
|
||||
maven_install(
|
||||
artifacts = [
|
||||
"org.apache.commons:commons-lang3:3.9"
|
||||
],
|
||||
repositories = [
|
||||
"https://repo1.maven.org/maven2",
|
||||
]
|
||||
)
|
||||
|
||||
http_jar (
|
||||
name = "apache-commons-lang",
|
||||
url = "https://repo1.maven.org/maven2/org/apache/commons/commons-lang3/3.9/commons-lang3-3.9.jar"
|
||||
)
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
|
||||
java_binary (
|
||||
name = "BazelApp",
|
||||
srcs = glob(["src/main/java/com/baeldung/*.java"]),
|
||||
main_class = "com.baeldung.BazelApp",
|
||||
deps = ["//bazelgreeting:greeter", "@maven//:org_apache_commons_commons_lang3"]
|
||||
)
|
|
@ -0,0 +1,29 @@
|
|||
<?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>bazelapp</artifactId>
|
||||
<name>bazelapp</name>
|
||||
|
||||
<parent>
|
||||
<artifactId>bazel</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>bazelgreeting</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.9</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
</project>
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung;
|
||||
|
||||
import com.baeldung.Greetings;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
public class BazelApp {
|
||||
|
||||
public static void main(String ... args) {
|
||||
Greetings greetings = new Greetings();
|
||||
|
||||
System.out.println(greetings.greet("Bazel"));
|
||||
|
||||
System.out.println(StringUtils.lowerCase("Bazel"));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
|
||||
java_library (
|
||||
name = "greeter",
|
||||
srcs = glob(["src/main/java/com/baeldung/*.java"]),
|
||||
visibility = ["//bazelapp:__pkg__"]
|
||||
)
|
|
@ -0,0 +1,16 @@
|
|||
<?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>bazelgreeting</artifactId>
|
||||
<name>bazelgreeting</name>
|
||||
|
||||
<parent>
|
||||
<artifactId>bazel</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
|
||||
</project>
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung;
|
||||
|
||||
public class Greetings {
|
||||
|
||||
public String greet(String name) {
|
||||
return "Hello ".concat(name);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
<?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>bazel</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
<name>bazel</name>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
<module>bazelgreeting</module>
|
||||
<module>bazelapp</module>
|
||||
</modules>
|
||||
|
||||
|
||||
</project>
|
|
@ -48,6 +48,11 @@
|
|||
<version>${spock-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.groovy-wslite</groupId>
|
||||
<artifactId>groovy-wslite</artifactId>
|
||||
<version>${groovy-wslite.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -175,6 +180,7 @@
|
|||
<junit.platform.version>1.0.0</junit.platform.version>
|
||||
<hsqldb.version>2.4.0</hsqldb.version>
|
||||
<spock-core.version>1.1-groovy-2.4</spock-core.version>
|
||||
<groovy-wslite.version>1.1.3</groovy-wslite.version>
|
||||
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
|
||||
<logback.version>1.2.3</logback.version>
|
||||
<groovy.version>2.5.7</groovy.version>
|
||||
|
|
|
@ -0,0 +1,152 @@
|
|||
package com.baeldung.webservice
|
||||
|
||||
import groovy.json.JsonSlurper
|
||||
import wslite.rest.ContentType
|
||||
import wslite.rest.RESTClient
|
||||
import wslite.rest.RESTClientException
|
||||
import wslite.soap.SOAPClient
|
||||
import wslite.soap.SOAPMessageBuilder
|
||||
import wslite.http.auth.HTTPBasicAuthorization
|
||||
import org.junit.Test
|
||||
|
||||
class WebserviceUnitTest extends GroovyTestCase {
|
||||
|
||||
JsonSlurper jsonSlurper = new JsonSlurper()
|
||||
|
||||
static RESTClient client = new RESTClient("https://postman-echo.com")
|
||||
|
||||
static {
|
||||
client.defaultAcceptHeader = ContentType.JSON
|
||||
client.httpClient.sslTrustAllCerts = true
|
||||
}
|
||||
|
||||
void test_whenSendingGet_thenRespose200() {
|
||||
def postmanGet = new URL('https://postman-echo.com/get')
|
||||
def getConnection = postmanGet.openConnection()
|
||||
getConnection.requestMethod = 'GET'
|
||||
assert getConnection.responseCode == 200
|
||||
if (getConnection.responseCode == 200) {
|
||||
assert jsonSlurper.parseText(getConnection.content.text)?.headers?.host == "postman-echo.com"
|
||||
}
|
||||
}
|
||||
|
||||
void test_whenSendingPost_thenRespose200() {
|
||||
def postmanPost = new URL('https://postman-echo.com/post')
|
||||
def query = "q=This is post request form parameter."
|
||||
def postConnection = postmanPost.openConnection()
|
||||
postConnection.requestMethod = 'POST'
|
||||
assert postConnection.responseCode == 200
|
||||
}
|
||||
|
||||
void test_whenSendingPostWithParams_thenRespose200() {
|
||||
def postmanPost = new URL('https://postman-echo.com/post')
|
||||
def form = "param1=This is request parameter."
|
||||
def postConnection = postmanPost.openConnection()
|
||||
postConnection.requestMethod = 'POST'
|
||||
postConnection.doOutput = true
|
||||
def text
|
||||
postConnection.with {
|
||||
outputStream.withWriter { outputStreamWriter ->
|
||||
outputStreamWriter << form
|
||||
}
|
||||
text = content.text
|
||||
}
|
||||
assert postConnection.responseCode == 200
|
||||
assert jsonSlurper.parseText(text)?.json.param1 == "This is request parameter."
|
||||
}
|
||||
|
||||
void test_whenReadingRSS_thenReceiveFeed() {
|
||||
def rssFeed = new XmlParser().parse("https://news.google.com/rss?hl=en-US&gl=US&ceid=US:en")
|
||||
def stories = []
|
||||
(0..4).each {
|
||||
def item = rssFeed.channel.item.get(it)
|
||||
stories << item.title.text()
|
||||
}
|
||||
assert stories.size() == 5
|
||||
}
|
||||
|
||||
void test_whenReadingAtom_thenReceiveFeed() {
|
||||
def atomFeed = new XmlParser().parse("https://news.google.com/atom?hl=en-US&gl=US&ceid=US:en")
|
||||
def stories = []
|
||||
(0..4).each {
|
||||
def entry = atomFeed.entry.get(it)
|
||||
stories << entry.title.text()
|
||||
}
|
||||
assert stories.size() == 5
|
||||
}
|
||||
|
||||
void test_whenConsumingSoap_thenReceiveResponse() {
|
||||
def url = "http://www.dataaccess.com/webservicesserver/numberconversion.wso"
|
||||
def soapClient = new SOAPClient(url)
|
||||
def message = new SOAPMessageBuilder().build({
|
||||
body {
|
||||
NumberToWords(xmlns: "http://www.dataaccess.com/webservicesserver/") {
|
||||
ubiNum(1234)
|
||||
}
|
||||
}
|
||||
})
|
||||
def response = soapClient.send(message.toString());
|
||||
def words = response.NumberToWordsResponse
|
||||
assert words == "one thousand two hundred and thirty four "
|
||||
}
|
||||
|
||||
void test_whenConsumingRestGet_thenReceiveResponse() {
|
||||
def path = "/get"
|
||||
def response
|
||||
try {
|
||||
response = client.get(path: path)
|
||||
assert response.statusCode == 200
|
||||
assert response.json?.headers?.host == "postman-echo.com"
|
||||
} catch (RESTClientException e) {
|
||||
assert e?.response?.statusCode != 200
|
||||
}
|
||||
}
|
||||
|
||||
void test_whenConsumingRestPost_thenReceiveResponse() {
|
||||
def path = "/post"
|
||||
def params = ["foo":1,"bar":2]
|
||||
def response
|
||||
try {
|
||||
response = client.post(path: path) {
|
||||
type ContentType.JSON
|
||||
json params
|
||||
}
|
||||
assert response.json?.data == params
|
||||
} catch (RESTClientException e) {
|
||||
e.printStackTrace()
|
||||
assert e?.response?.statusCode != 200
|
||||
}
|
||||
}
|
||||
|
||||
void test_whenBasicAuthentication_thenReceive200() {
|
||||
def path = "/basic-auth"
|
||||
def response
|
||||
try {
|
||||
client.authorization = new HTTPBasicAuthorization("postman", "password")
|
||||
response = client.get(path: path)
|
||||
assert response.statusCode == 200
|
||||
assert response.json?.authenticated == true
|
||||
} catch (RESTClientException e) {
|
||||
e.printStackTrace()
|
||||
assert e?.response?.statusCode != 200
|
||||
}
|
||||
}
|
||||
|
||||
void test_whenOAuth_thenReceive200() {
|
||||
RESTClient oAuthClient = new RESTClient("https://postman-echo.com")
|
||||
oAuthClient.defaultAcceptHeader = ContentType.JSON
|
||||
oAuthClient.httpClient.sslTrustAllCerts = true
|
||||
|
||||
def path = "/oauth1"
|
||||
def params = [oauth_consumer_key: "RKCGzna7bv9YD57c", oauth_signature_method: "HMAC-SHA1", oauth_timestamp:1567089944, oauth_nonce: "URT7v4", oauth_version: 1.0, oauth_signature: 'RGgR/ktDmclkM0ISWaFzebtlO0A=']
|
||||
def response
|
||||
try {
|
||||
response = oAuthClient.get(path: path, query: params)
|
||||
assert response.statusCode == 200
|
||||
assert response.statusMessage == "OK"
|
||||
assert response.json.status == "pass"
|
||||
} catch (RESTClientException e) {
|
||||
assert e?.response?.statusCode != 200
|
||||
}
|
||||
}
|
||||
}
|
|
@ -20,7 +20,6 @@
|
|||
- [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max)
|
||||
- [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization)
|
||||
- [Java Optional – orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get)
|
||||
- [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection)
|
||||
- [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic)
|
||||
- [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference)
|
||||
- [Overriding System Time for Testing in Java](http://www.baeldung.com/java-override-system-time)
|
||||
|
|
|
@ -134,16 +134,6 @@
|
|||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<compilerArgument>-parameters</compilerArgument>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
|
@ -192,7 +182,6 @@
|
|||
<jmh-generator.version>1.19</jmh-generator.version>
|
||||
<spring-boot-maven-plugin.version>2.0.4.RELEASE</spring-boot-maven-plugin.version>
|
||||
<!-- plugins -->
|
||||
<maven-compiler-plugin.version>3.8.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.22.1</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.java8;
|
||||
package com.baeldung.java_8_features.groupingby;
|
||||
|
||||
import com.baeldung.java_8_features.groupingby.BlogPost;
|
||||
import com.baeldung.java_8_features.groupingby.BlogPostType;
|
|
@ -0,0 +1,40 @@
|
|||
package com.baeldung.java.list;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
public class RemoveFromList {
|
||||
|
||||
public static void main(String[] args) {
|
||||
List<String> sports = new ArrayList<>();
|
||||
sports.add("Football");
|
||||
sports.add("Basketball");
|
||||
sports.add("Baseball");
|
||||
sports.add("Boxing");
|
||||
sports.add("Cycling");
|
||||
|
||||
System.out.println("List before removing: " + sports);
|
||||
|
||||
// Remove with index
|
||||
sports.remove(1);
|
||||
|
||||
// Remove with an element
|
||||
sports.remove("Baseball");
|
||||
|
||||
// Iterator remove method
|
||||
Iterator<String> iterator = sports.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
if (iterator.next().equals("Boxing")) {
|
||||
iterator.remove();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ArrayList removeIf method (Java 8)
|
||||
sports.removeIf(p -> p.equals("Cycling"));
|
||||
|
||||
System.out.println("List after removing: " + sports);
|
||||
}
|
||||
|
||||
}
|
|
@ -10,8 +10,4 @@
|
|||
- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
|
||||
- [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list)
|
||||
- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)
|
||||
- [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection)
|
||||
- [Determine If All Elements Are the Same in a Java List](https://www.baeldung.com/java-list-all-equal)
|
||||
- [List of Primitive Integer Values in Java](https://www.baeldung.com/java-list-primitive-int)
|
||||
- [Performance Comparison of Primitive Lists in Java](https://www.baeldung.com/java-list-primitive-performance)
|
||||
- [Filtering a Java Collection by a List](https://www.baeldung.com/java-filter-collection-by-list)
|
||||
- [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection)
|
|
@ -36,41 +36,11 @@
|
|||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.sf.trove4j</groupId>
|
||||
<artifactId>trove4j</artifactId>
|
||||
<version>${trove4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>it.unimi.dsi</groupId>
|
||||
<artifactId>fastutil</artifactId>
|
||||
<version>${fastutil.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>colt</groupId>
|
||||
<artifactId>colt</artifactId>
|
||||
<version>${colt.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<assertj.version>3.11.1</assertj.version>
|
||||
<trove4j.version>3.0.2</trove4j.version>
|
||||
<fastutil.version>8.1.0</fastutil.version>
|
||||
<colt.version>1.2.0</colt.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,11 @@
|
|||
=========
|
||||
|
||||
## Core Java Collections List Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list)
|
||||
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
|
||||
- [Determine If All Elements Are the Same in a Java List](https://www.baeldung.com/java-list-all-equal)
|
||||
- [List of Primitive Integer Values in Java](https://www.baeldung.com/java-list-primitive-int)
|
||||
- [Performance Comparison of Primitive Lists in Java](https://www.baeldung.com/java-list-primitive-performance)
|
||||
- [Filtering a Java Collection by a List](https://www.baeldung.com/java-filter-collection-by-list)
|
|
@ -0,0 +1,76 @@
|
|||
<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>core-java-collections-list-3</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-collections-list-3</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.sf.trove4j</groupId>
|
||||
<artifactId>trove4j</artifactId>
|
||||
<version>${trove4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>it.unimi.dsi</groupId>
|
||||
<artifactId>fastutil</artifactId>
|
||||
<version>${fastutil.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>colt</groupId>
|
||||
<artifactId>colt</artifactId>
|
||||
<version>${colt.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<assertj.version>3.11.1</assertj.version>
|
||||
<trove4j.version>3.0.2</trove4j.version>
|
||||
<fastutil.version>8.1.0</fastutil.version>
|
||||
<colt.version>1.2.0</colt.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -10,7 +10,5 @@
|
|||
- [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards)
|
||||
- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list)
|
||||
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
|
||||
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
|
||||
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
|
||||
- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list)
|
||||
- [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list)
|
|
@ -1,11 +1,12 @@
|
|||
package com.baeldung.concurrent.mutex;
|
||||
|
||||
public class SequenceGenerator {
|
||||
|
||||
private int currentValue = 0;
|
||||
|
||||
public int getNextSequence() throws InterruptedException {
|
||||
public int getNextSequence() {
|
||||
currentValue = currentValue + 1;
|
||||
Thread.sleep(500);
|
||||
return currentValue;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -4,15 +4,16 @@ import com.google.common.util.concurrent.Monitor;
|
|||
|
||||
public class SequenceGeneratorUsingMonitor extends SequenceGenerator {
|
||||
|
||||
private Monitor monitor = new Monitor();
|
||||
private Monitor mutex = new Monitor();
|
||||
|
||||
@Override
|
||||
public int getNextSequence() throws InterruptedException {
|
||||
monitor.enter();
|
||||
public int getNextSequence() {
|
||||
mutex.enter();
|
||||
try {
|
||||
return super.getNextSequence();
|
||||
} finally {
|
||||
monitor.leave();
|
||||
mutex.leave();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -7,7 +7,7 @@ public class SequenceGeneratorUsingReentrantLock extends SequenceGenerator {
|
|||
private ReentrantLock mutex = new ReentrantLock();
|
||||
|
||||
@Override
|
||||
public int getNextSequence() throws InterruptedException {
|
||||
public int getNextSequence() {
|
||||
try {
|
||||
mutex.lock();
|
||||
return super.getNextSequence();
|
||||
|
@ -15,4 +15,5 @@ public class SequenceGeneratorUsingReentrantLock extends SequenceGenerator {
|
|||
mutex.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -7,12 +7,15 @@ public class SequenceGeneratorUsingSemaphore extends SequenceGenerator {
|
|||
private Semaphore mutex = new Semaphore(1);
|
||||
|
||||
@Override
|
||||
public int getNextSequence() throws InterruptedException {
|
||||
public int getNextSequence() {
|
||||
try {
|
||||
mutex.acquire();
|
||||
return super.getNextSequence();
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException("Exception in critical section.", e);
|
||||
} finally {
|
||||
mutex.release();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -2,9 +2,11 @@ package com.baeldung.concurrent.mutex;
|
|||
|
||||
public class SequenceGeneratorUsingSynchronizedBlock extends SequenceGenerator {
|
||||
|
||||
private Object mutex = new Object();
|
||||
|
||||
@Override
|
||||
public int getNextSequence() throws InterruptedException {
|
||||
synchronized (this) {
|
||||
public int getNextSequence() {
|
||||
synchronized (mutex) {
|
||||
return super.getNextSequence();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,7 +3,7 @@ package com.baeldung.concurrent.mutex;
|
|||
public class SequenceGeneratorUsingSynchronizedMethod extends SequenceGenerator {
|
||||
|
||||
@Override
|
||||
public synchronized int getNextSequence() throws InterruptedException {
|
||||
public synchronized int getNextSequence() {
|
||||
return super.getNextSequence();
|
||||
}
|
||||
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.java8;
|
||||
package com.baeldung.concurrent.executorservice;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
|
@ -1,7 +1,7 @@
|
|||
package com.baeldung.concurrent.mutex;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
|
@ -12,59 +12,58 @@ import java.util.concurrent.TimeUnit;
|
|||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.concurrent.mutex.SequenceGenerator;
|
||||
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingMonitor;
|
||||
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingReentrantLock;
|
||||
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingSemaphore;
|
||||
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingSynchronizedBlock;
|
||||
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingSynchronizedMethod;
|
||||
|
||||
public class MutexUnitTest {
|
||||
|
||||
private final int RANGE = 30;
|
||||
|
||||
@Test
|
||||
// @Test
|
||||
// This test verifies the race condition use case, it may pass or fail based on execution environment
|
||||
// Uncomment @Test to run it
|
||||
public void givenUnsafeSequenceGenerator_whenRaceCondition_thenUnexpectedBehavior() throws Exception {
|
||||
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGenerator());
|
||||
Assert.assertNotEquals(RANGE, uniqueSequences.size());
|
||||
int count = 1000;
|
||||
Set<Integer> uniqueSequences = getUniqueSequences(new SequenceGenerator(), count);
|
||||
Assert.assertNotEquals(count, uniqueSequences.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSequenceGeneratorUsingSynchronizedMethod_whenRaceCondition_thenSuccess() throws Exception {
|
||||
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingSynchronizedMethod());
|
||||
Assert.assertEquals(RANGE, uniqueSequences.size());
|
||||
int count = 1000;
|
||||
Set<Integer> uniqueSequences = getUniqueSequences(new SequenceGeneratorUsingSynchronizedMethod(), count);
|
||||
Assert.assertEquals(count, uniqueSequences.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSequenceGeneratorUsingSynchronizedBlock_whenRaceCondition_thenSuccess() throws Exception {
|
||||
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingSynchronizedBlock());
|
||||
Assert.assertEquals(RANGE, uniqueSequences.size());
|
||||
int count = 1000;
|
||||
Set<Integer> uniqueSequences = getUniqueSequences(new SequenceGeneratorUsingSynchronizedBlock(), count);
|
||||
Assert.assertEquals(count, uniqueSequences.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSequenceGeneratorUsingReentrantLock_whenRaceCondition_thenSuccess() throws Exception {
|
||||
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingReentrantLock());
|
||||
Assert.assertEquals(RANGE, uniqueSequences.size());
|
||||
int count = 1000;
|
||||
Set<Integer> uniqueSequences = getUniqueSequences(new SequenceGeneratorUsingReentrantLock(), count);
|
||||
Assert.assertEquals(count, uniqueSequences.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSequenceGeneratorUsingSemaphore_whenRaceCondition_thenSuccess() throws Exception {
|
||||
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingSemaphore());
|
||||
Assert.assertEquals(RANGE, uniqueSequences.size());
|
||||
int count = 1000;
|
||||
Set<Integer> uniqueSequences = getUniqueSequences(new SequenceGeneratorUsingSemaphore(), count);
|
||||
Assert.assertEquals(count, uniqueSequences.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSequenceGeneratorUsingMonitor_whenRaceCondition_thenSuccess() throws Exception {
|
||||
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingMonitor());
|
||||
Assert.assertEquals(RANGE, uniqueSequences.size());
|
||||
int count = 1000;
|
||||
Set<Integer> uniqueSequences = getUniqueSequences(new SequenceGeneratorUsingMonitor(), count);
|
||||
Assert.assertEquals(count, uniqueSequences.size());
|
||||
}
|
||||
|
||||
private Set<Integer> getASetOFUniqueSequences(SequenceGenerator generator) throws Exception {
|
||||
private Set<Integer> getUniqueSequences(SequenceGenerator generator, int count) throws Exception {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(3);
|
||||
Set<Integer> uniqueSequences = new HashSet<>();
|
||||
Set<Integer> uniqueSequences = new LinkedHashSet<>();
|
||||
List<Future<Integer>> futures = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < RANGE; i++) {
|
||||
for (int i = 0; i < count; i++) {
|
||||
futures.add(executor.submit(generator::getNextSequence));
|
||||
}
|
||||
|
||||
|
@ -72,7 +71,7 @@ public class MutexUnitTest {
|
|||
uniqueSequences.add(future.get());
|
||||
}
|
||||
|
||||
executor.awaitTermination(15, TimeUnit.SECONDS);
|
||||
executor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
executor.shutdown();
|
||||
|
||||
return uniqueSequences;
|
||||
|
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.exceptions;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
|
||||
public class CheckedUncheckedExceptions {
|
||||
public static void checkedExceptionWithThrows() throws FileNotFoundException {
|
||||
File file = new File("not_existing_file.txt");
|
||||
FileInputStream stream = new FileInputStream(file);
|
||||
}
|
||||
|
||||
public static void checkedExceptionWithTryCatch() {
|
||||
File file = new File("not_existing_file.txt");
|
||||
try {
|
||||
FileInputStream stream = new FileInputStream(file);
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static int divideByZero() {
|
||||
int numerator = 1;
|
||||
int denominator = 0;
|
||||
return numerator / denominator;
|
||||
}
|
||||
|
||||
public static void checkFile(String fileName) throws IncorrectFileNameException {
|
||||
if (fileName == null || fileName.isEmpty()) {
|
||||
throw new NullOrEmptyException("The filename is null.");
|
||||
}
|
||||
if (!isCorrectFileName(fileName)) {
|
||||
throw new IncorrectFileNameException("Incorrect filename : " + fileName);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isCorrectFileName(String fileName) {
|
||||
if (fileName.equals("wrongFileName.txt"))
|
||||
return false;
|
||||
else
|
||||
return true;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.exceptions;
|
||||
|
||||
public class IncorrectFileNameException extends Exception {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public IncorrectFileNameException(String errorMessage) {
|
||||
super(errorMessage);
|
||||
}
|
||||
|
||||
public IncorrectFileNameException(String errorMessage, Throwable thr) {
|
||||
super(errorMessage, thr);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.exceptions;
|
||||
|
||||
public class NullOrEmptyException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public NullOrEmptyException(String errorMessage) {
|
||||
super(errorMessage);
|
||||
}
|
||||
|
||||
public NullOrEmptyException(String errorMessage, Throwable thr) {
|
||||
super(errorMessage, thr);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
package com.baeldung.exceptions;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Tests the {@link CheckedUncheckedExceptions}.
|
||||
*/
|
||||
public class CheckedUncheckedExceptionsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenFileNotExist_thenThrowException() {
|
||||
assertThrows(FileNotFoundException.class, () -> {
|
||||
CheckedUncheckedExceptions.checkedExceptionWithThrows();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTryCatchExcetpion_thenSuccess() {
|
||||
try {
|
||||
CheckedUncheckedExceptions.checkedExceptionWithTryCatch();
|
||||
} catch (Exception e) {
|
||||
Assertions.fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDivideByZero_thenThrowException() {
|
||||
assertThrows(ArithmeticException.class, () -> {
|
||||
CheckedUncheckedExceptions.divideByZero();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInvalidFile_thenThrowException() {
|
||||
|
||||
assertThrows(IncorrectFileNameException.class, () -> {
|
||||
CheckedUncheckedExceptions.checkFile("wrongFileName.txt");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNullOrEmptyFile_thenThrowException() {
|
||||
assertThrows(NullOrEmptyException.class, () -> {
|
||||
CheckedUncheckedExceptions.checkFile(null);
|
||||
});
|
||||
assertThrows(NullOrEmptyException.class, () -> {
|
||||
CheckedUncheckedExceptions.checkFile("");
|
||||
});
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
# Intellij
|
||||
.idea/
|
||||
*.iml
|
|
@ -0,0 +1,279 @@
|
|||
<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>core-java-io-2</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-io-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>net.sourceforge.collections</groupId>
|
||||
<artifactId>collections-generic</artifactId>
|
||||
<version>${collections-generic.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>${commons-io.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.decimal4j</groupId>
|
||||
<artifactId>decimal4j</artifactId>
|
||||
<version>${decimal4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk15on</artifactId>
|
||||
<version>${bouncycastle.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.unix4j</groupId>
|
||||
<artifactId>unix4j-command</artifactId>
|
||||
<version>${unix4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.googlecode.grep4j</groupId>
|
||||
<artifactId>grep4j</artifactId>
|
||||
<version>${grep4j.version}</version>
|
||||
</dependency>
|
||||
<!-- web -->
|
||||
<!-- marshalling -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<!-- logging -->
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jayway.awaitility</groupId>
|
||||
<artifactId>awaitility</artifactId>
|
||||
<version>${avaitility.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.javamoney</groupId>
|
||||
<artifactId>moneta</artifactId>
|
||||
<version>${moneta.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.owasp.esapi</groupId>
|
||||
<artifactId>esapi</artifactId>
|
||||
<version>${esapi.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.sun.messaging.mq</groupId>
|
||||
<artifactId>fscontext</artifactId>
|
||||
<version>${fscontext.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.codepoetics</groupId>
|
||||
<artifactId>protonpack</artifactId>
|
||||
<version>${protonpack.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>one.util</groupId>
|
||||
<artifactId>streamex</artifactId>
|
||||
<version>${streamex.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.vavr</groupId>
|
||||
<artifactId>vavr</artifactId>
|
||||
<version>${vavr.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-generator-annprocess.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
<artifactId>hsqldb</artifactId>
|
||||
<version>${hsqldb.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.asynchttpclient/async-http-client -->
|
||||
<dependency>
|
||||
<groupId>org.asynchttpclient</groupId>
|
||||
<artifactId>async-http-client</artifactId>
|
||||
<version>${async-http-client.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.opencsv</groupId>
|
||||
<artifactId>opencsv</artifactId>
|
||||
<version>${opencsv.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- Mime Type Resolution Libraries -->
|
||||
<dependency>
|
||||
<groupId>org.apache.tika</groupId>
|
||||
<artifactId>tika-core</artifactId>
|
||||
<version>${tika.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.sf.jmimemagic</groupId>
|
||||
<artifactId>jmimemagic</artifactId>
|
||||
<version>${jmime-magic.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-io-2</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
<configuration>
|
||||
<executable>java</executable>
|
||||
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
|
||||
<arguments>
|
||||
<argument>-Xmx300m</argument>
|
||||
<argument>-XX:+UseParallelGC</argument>
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
<version>${maven-javadoc-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>integration</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
|
||||
<executions>
|
||||
<execution>
|
||||
<id>run-benchmarks</id>
|
||||
<!-- <phase>integration-test</phase> -->
|
||||
<phase>none</phase>
|
||||
<goals>
|
||||
<goal>exec</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classpathScope>test</classpathScope>
|
||||
<executable>java</executable>
|
||||
<arguments>
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
<argument>org.openjdk.jmh.Main</argument>
|
||||
<argument>.*</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
|
||||
<!-- util -->
|
||||
<bouncycastle.version>1.55</bouncycastle.version>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<decimal4j.version>1.0.3</decimal4j.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<collections-generic.version>4.01</collections-generic.version>
|
||||
<unix4j.version>0.4</unix4j.version>
|
||||
<grep4j.version>1.8.7</grep4j.version>
|
||||
<fscontext.version>4.6-b01</fscontext.version>
|
||||
<protonpack.version>1.13</protonpack.version>
|
||||
<streamex.version>0.6.5</streamex.version>
|
||||
<vavr.version>0.9.0</vavr.version>
|
||||
<opencsv.version>4.1</opencsv.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
|
||||
<!-- maven plugins -->
|
||||
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
|
||||
<hsqldb.version>2.4.0</hsqldb.version>
|
||||
<esapi.version>2.1.0.1</esapi.version>
|
||||
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
|
||||
<async-http-client.version>2.4.5</async-http-client.version>
|
||||
<!-- Mime Type Libraries -->
|
||||
<tika.version>1.18</tika.version>
|
||||
<jmime-magic.version>0.1.5</jmime-magic.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,57 @@
|
|||
package com.baeldung.filereader;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
public class FileReaderExample {
|
||||
|
||||
public static String readAllCharactersOneByOne(Reader reader) throws IOException {
|
||||
StringBuilder content = new StringBuilder();
|
||||
int nextChar;
|
||||
while ((nextChar = reader.read()) != -1) {
|
||||
content.append((char) nextChar);
|
||||
}
|
||||
return String.valueOf(content);
|
||||
}
|
||||
|
||||
public static String readMultipleCharacters(Reader reader, int length) throws IOException {
|
||||
char[] buffer = new char[length];
|
||||
int charactersRead = reader.read(buffer, 0, length);
|
||||
|
||||
|
||||
if (charactersRead != -1) {
|
||||
return new String(buffer, 0, charactersRead);
|
||||
} else {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
public static String readFile(String path) {
|
||||
FileReader fileReader = null;
|
||||
try {
|
||||
fileReader = new FileReader(path);
|
||||
return readAllCharactersOneByOne(fileReader);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (fileReader != null) {
|
||||
try {
|
||||
fileReader.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String readFileUsingTryWithResources(String path) {
|
||||
try (FileReader fileReader = new FileReader(path)) {
|
||||
return readAllCharactersOneByOne(fileReader);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
package com.baeldung.filereader;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
|
||||
public class FileReaderExampleUnitTest {
|
||||
|
||||
|
||||
private static final String FILE_PATH = "src/test/resources/HelloWorld.txt";
|
||||
|
||||
|
||||
@Test
|
||||
public void givenFileReader_whenReadAllCharacters_thenReturnsContent() throws IOException {
|
||||
String expectedText = "Hello, World!";
|
||||
File file = new File(FILE_PATH);
|
||||
try (FileReader fileReader = new FileReader(file)) {
|
||||
String content = FileReaderExample.readAllCharactersOneByOne(fileReader);
|
||||
Assert.assertEquals(expectedText, content);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileReader_whenReadMultipleCharacters_thenReturnsContent() throws IOException {
|
||||
String expectedText = "Hello";
|
||||
File file = new File(FILE_PATH);
|
||||
try (FileReader fileReader = new FileReader(file)) {
|
||||
String content = FileReaderExample.readMultipleCharacters(fileReader, 5);
|
||||
Assert.assertEquals(expectedText, content);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadFile_thenReturnsContent() {
|
||||
String expectedText = "Hello, World!";
|
||||
String content = FileReaderExample.readFile(FILE_PATH);
|
||||
Assert.assertEquals(expectedText, content);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadFileUsingTryWithResources_thenReturnsContent() {
|
||||
String expectedText = "Hello, World!";
|
||||
String content = FileReaderExample.readFileUsingTryWithResources(FILE_PATH);
|
||||
Assert.assertEquals(expectedText, content);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
Hello, World!
|
|
@ -207,6 +207,21 @@
|
|||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<!-- Build an executable JAR -->
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>${maven-jar-plugin.version}</version>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
<mainClass>com.baeldung.resource.MyResourceLoader</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
@ -274,6 +289,8 @@
|
|||
<!-- Mime Type Libraries -->
|
||||
<tika.version>1.18</tika.version>
|
||||
<jmime-magic.version>0.1.5</jmime-magic.version>
|
||||
<maven-jar-plugin.version>3.1.0</maven-jar-plugin.version>
|
||||
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.resource;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class MyResourceLoader {
|
||||
|
||||
private void loadFileWithReader() throws IOException {
|
||||
|
||||
try (FileReader fileReader = new FileReader("src/main/resources/input.txt");
|
||||
BufferedReader reader = new BufferedReader(fileReader)) {
|
||||
String contents = reader.lines()
|
||||
.collect(Collectors.joining(System.lineSeparator()));
|
||||
System.out.println(contents);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void loadFileAsResource() throws IOException {
|
||||
|
||||
try (InputStream inputStream = getClass().getResourceAsStream("/input.txt");
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
|
||||
String contents = reader.lines()
|
||||
.collect(Collectors.joining(System.lineSeparator()));
|
||||
System.out.println(contents);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
|
||||
MyResourceLoader resourceLoader = new MyResourceLoader();
|
||||
|
||||
resourceLoader.loadFileAsResource();
|
||||
resourceLoader.loadFileWithReader();
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung.java.io;
|
||||
package org.baeldung.writetofile;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
|
@ -7,6 +7,7 @@
|
|||
<groupId>com.baeldung.jndi</groupId>
|
||||
<artifactId>core-java-jndi</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>core-java-jndi</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.systemgc;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Scanner;
|
||||
|
||||
import static java.util.UUID.randomUUID;
|
||||
|
||||
public class DemoApplication {
|
||||
|
||||
private static final Map<String, String> cache = new HashMap<String, String>();
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
|
||||
while (scanner.hasNext()) {
|
||||
final String next = scanner.next();
|
||||
if ("fill".equals(next)) {
|
||||
for (int i = 0; i < 1000000; i++) {
|
||||
cache.put(randomUUID().toString(), randomUUID().toString());
|
||||
}
|
||||
} else if ("invalidate".equals(next)) {
|
||||
cache.clear();
|
||||
} else if ("gc".equals(next)) {
|
||||
System.gc();
|
||||
} else if ("exit".equals(next)) {
|
||||
System.exit(0);
|
||||
} else {
|
||||
System.out.println("unknown");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -5,7 +5,7 @@
|
|||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-lambdas</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java</name>
|
||||
<name>core-java-lambdas</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
|
|
|
@ -0,0 +1,25 @@
|
|||
*.class
|
||||
|
||||
0.*
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
.resourceCache
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# Files generated by integration tests
|
||||
backup-pom.xml
|
||||
/bin/
|
||||
/temp
|
||||
|
||||
#IntelliJ specific
|
||||
.idea/
|
||||
*.iml
|
|
@ -0,0 +1,5 @@
|
|||
=========
|
||||
|
||||
## Core Java Lang Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
|
@ -0,0 +1,33 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>core-java-lang-2</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-lang-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-lang-2</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.commandlinearguments;
|
||||
|
||||
public class CliExample {
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println("Argument count: " + args.length);
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
System.out.println("Argument " + i + ": " + args[i]);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.commandlinearguments;
|
||||
|
||||
public class CliExampleWithVarargs {
|
||||
|
||||
public static void main(String... args) {
|
||||
System.out.println("Argument count: " + args.length);
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
System.out.println("Argument " + i + ": " + args[i]);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -14,6 +14,19 @@
|
|||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<h2.version>1.4.199</h2.version>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-lang-oop-2</finalName>
|
||||
<resources>
|
||||
|
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.accessmodifiers.publicmodifier;
|
||||
|
||||
import java.util.AbstractList;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class ListOfThree<E> extends AbstractList<E> {
|
||||
|
||||
private static final int LENGTH = 3;
|
||||
private Object[] elements;
|
||||
|
||||
public ListOfThree(E[] data) {
|
||||
if(data == null
|
||||
|| data.length != LENGTH)
|
||||
throw new IllegalArgumentException();
|
||||
|
||||
this.elements = Arrays.copyOf(data, data.length); //shallow copy
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public E get(int index) {
|
||||
return (E)elements[index];
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return LENGTH;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.accessmodifiers.publicmodifier;
|
||||
|
||||
public class SpecialCharacters {
|
||||
|
||||
public static final String SLASH = "/";
|
||||
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
package com.baeldung.accessmodifiers.publicmodifier;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Date;
|
||||
|
||||
public class Student {
|
||||
|
||||
private StudentGrade grade; //new data representation
|
||||
// private int grade; //old data representation
|
||||
private String name;
|
||||
private int age;
|
||||
|
||||
public void setGrade(int grade) {
|
||||
this.grade = new StudentGrade(grade);
|
||||
}
|
||||
|
||||
public int getGrade() {
|
||||
return this.grade.getGrade().intValue(); //int is returned for backward compatibility
|
||||
}
|
||||
|
||||
public Connection getConnection() throws SQLException {
|
||||
|
||||
final String URL = "jdbc:h2:~/test";
|
||||
return DriverManager.getConnection(URL, "sa", "");
|
||||
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
if (age < 0 || age > 150) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
private class StudentGrade {
|
||||
private BigDecimal grade = BigDecimal.ZERO;
|
||||
private Date updatedAt;
|
||||
|
||||
public StudentGrade(int grade) {
|
||||
this.grade = new BigDecimal(grade);
|
||||
this.updatedAt = new Date();
|
||||
}
|
||||
|
||||
public BigDecimal getGrade() {
|
||||
return grade;
|
||||
}
|
||||
|
||||
public Date getDate() {
|
||||
return updatedAt;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package com.baeldung.copyconstructor;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class Employee {
|
||||
|
||||
protected int id;
|
||||
protected String name;
|
||||
protected Date startDate;
|
||||
|
||||
public Employee(int id, String name, Date startDate) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.startDate = startDate;
|
||||
}
|
||||
|
||||
public Employee(Employee employee) {
|
||||
this.id = employee.id;
|
||||
this.name = employee.name;
|
||||
this.startDate = new Date(employee.startDate.getTime());
|
||||
}
|
||||
|
||||
Date getStartDate() {
|
||||
return startDate;
|
||||
}
|
||||
|
||||
public Employee copy() {
|
||||
return new Employee(this);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.copyconstructor;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class Manager extends Employee {
|
||||
|
||||
private List<Employee> directReports;
|
||||
|
||||
public Manager(int id, String name, Date startDate, List<Employee> directReports) {
|
||||
super(id, name, startDate);
|
||||
this.directReports = directReports;
|
||||
}
|
||||
|
||||
public Manager(Manager manager) {
|
||||
super(manager.id, manager.name, manager.startDate);
|
||||
this.directReports = manager.directReports.stream()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Employee copy() {
|
||||
return new Manager(this);
|
||||
}
|
||||
|
||||
List<Employee> getDirectReport() {
|
||||
return this.directReports;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,59 @@
|
|||
package com.baeldung.core.modifiers;
|
||||
|
||||
public class Employee {
|
||||
|
||||
private String privateId;
|
||||
private String name;
|
||||
private boolean manager;
|
||||
|
||||
public Employee(String id, String name) {
|
||||
setPrivateId(id);
|
||||
setName(name);
|
||||
}
|
||||
|
||||
private Employee(String id, String name, boolean managerAttribute) {
|
||||
this.privateId = id;
|
||||
this.name = name;
|
||||
this.privateId = id + "_ID-MANAGER";
|
||||
}
|
||||
|
||||
public void setPrivateId(String customId) {
|
||||
if (customId.endsWith("_ID")) {
|
||||
this.privateId = customId;
|
||||
} else {
|
||||
this.privateId = customId + "_ID";
|
||||
}
|
||||
}
|
||||
|
||||
public String getPrivateId() {
|
||||
return privateId;
|
||||
}
|
||||
|
||||
public boolean isManager() {
|
||||
return manager;
|
||||
}
|
||||
|
||||
public void elevateToManager() {
|
||||
if ("Carl".equals(this.name)) {
|
||||
setManager(true);
|
||||
}
|
||||
}
|
||||
|
||||
private void setManager(boolean manager) {
|
||||
this.manager = manager;
|
||||
}
|
||||
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public static Employee buildManager(String id, String name) {
|
||||
return new Employee(id, name, true);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung.core.modifiers;
|
||||
|
||||
public class ExampleClass {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Employee employee = new Employee("Bob","ABC123");
|
||||
employee.setPrivateId("BCD234");
|
||||
System.out.println(employee.getPrivateId());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.core.modifiers;
|
||||
|
||||
public class PublicOuterClass {
|
||||
|
||||
public PrivateInnerClass getInnerClassInstance() {
|
||||
PrivateInnerClass myPrivateClassInstance = this.new PrivateInnerClass();
|
||||
myPrivateClassInstance.id = "ID1";
|
||||
myPrivateClassInstance.name = "Bob";
|
||||
return myPrivateClassInstance;
|
||||
}
|
||||
|
||||
private class PrivateInnerClass {
|
||||
public String name;
|
||||
public String id;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,93 @@
|
|||
package com.baeldung.accessmodifiers;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
import org.junit.jupiter.api.TestInstance.Lifecycle;
|
||||
import com.baeldung.accessmodifiers.publicmodifier.ListOfThree;
|
||||
import com.baeldung.accessmodifiers.publicmodifier.Student;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@TestInstance(Lifecycle.PER_CLASS)
|
||||
public class PublicAccessModifierUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenUsingBigDecimalIntValueMethod_correspondingIntIsReturned() {
|
||||
assertEquals(0, new BigDecimal(0).intValue()); //instance member
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingIntegerMaxValueField_maxPossibleIntValueIsReturned() {
|
||||
assertEquals(2147483647, Integer.MAX_VALUE); //static field
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenChangingStudentInternalRepresentation_clientCodeWillNotBreak() {
|
||||
|
||||
Student student = new Student();
|
||||
student.setGrade(100);
|
||||
|
||||
assertEquals(100, student.getGrade());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingEntrySet_keyValuePairsAreReturned() {
|
||||
|
||||
Map<String, String> mapObject = new HashMap<String, String>();
|
||||
mapObject.put("name", "Alex");
|
||||
|
||||
for(Map.Entry<String, String> entry : mapObject.entrySet()) {
|
||||
assertEquals("name", entry.getKey());
|
||||
assertEquals("Alex", entry.getValue());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingStringToLowerCase_stringTurnsToLowerCase() {
|
||||
assertEquals("alex", "ALEX".toLowerCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenParsingStringOne_parseIntReturns1() {
|
||||
assertEquals(1, Integer.parseInt("1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConnectingToH2_connectionInstanceIsReturned() throws SQLException {
|
||||
|
||||
final String url = "jdbc:h2:~/test";
|
||||
Connection conn = DriverManager.getConnection(url, "sa", "");
|
||||
assertNotNull(conn);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingCustomList_concreteAndInheritedMethodsWork() {
|
||||
|
||||
String[] dataSet1 = new String[] {"zero", "one", "two"};
|
||||
|
||||
List<String> list1 = new ListOfThree<String>(dataSet1);
|
||||
|
||||
//our implemented methods
|
||||
assertEquals("one", list1.get(1));
|
||||
assertEquals(3, list1.size());
|
||||
|
||||
//inherited implementations
|
||||
assertEquals(1, list1.indexOf("one"));
|
||||
|
||||
String[] dataSet2 = new String[] {"two", "zero", "one"};
|
||||
List<String> list2 = new ListOfThree<String>(dataSet2);
|
||||
|
||||
assertTrue(list1.containsAll(list2));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.copyconstructor;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class EmployeeUnitTest {
|
||||
@Test
|
||||
public void givenCopyConstructor_whenDeepCopy_thenDistinct() {
|
||||
Date d1 = new Date(123);
|
||||
Employee e1 = new Employee(1, "Baeldung", d1);
|
||||
Employee e2 = new Employee(e1);
|
||||
assertEquals(d1, e1.getStartDate());
|
||||
assertEquals(d1, e2.getStartDate());
|
||||
|
||||
d1.setTime(456);
|
||||
assertEquals(d1, e1.getStartDate());
|
||||
assertNotEquals(d1, e2.getStartDate());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCopyMethod_whenCopy_thenDistinct() {
|
||||
Date d1 = new Date(123);
|
||||
Employee e1 = new Employee(1, "Baeldung", d1);
|
||||
Employee e2 = e1.copy();
|
||||
assertEquals(d1, e1.getStartDate());
|
||||
assertEquals(d1, e2.getStartDate());
|
||||
|
||||
d1.setTime(456);
|
||||
assertEquals(d1, e1.getStartDate());
|
||||
assertNotEquals(d1, e2.getStartDate());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
package com.baeldung.copyconstructor;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ManagerUnitTest {
|
||||
@Test
|
||||
public void givenCopyConstructor_whenDeepCopy_thenDistinct() {
|
||||
Date startDate = new Date(123);
|
||||
Employee e1 = new Employee(1, "Baeldung", startDate);
|
||||
Employee e2 = new Employee(e1);
|
||||
List<Employee> directReports = new ArrayList<Employee>();
|
||||
directReports.add(e1);
|
||||
directReports.add(e2);
|
||||
|
||||
Manager m1 = new Manager(1, "Baeldung Manager", startDate, directReports);
|
||||
Manager m2 = new Manager(m1);
|
||||
List<Employee> directReports1 = m1.getDirectReport();
|
||||
List<Employee> directReports2 = m2.getDirectReport();
|
||||
assertEquals(directReports1.size(), directReports2.size());
|
||||
assertArrayEquals(directReports1.toArray(), directReports2.toArray());
|
||||
|
||||
// clear m1's direct reports list. m2's list should not be affected
|
||||
directReports.clear();
|
||||
directReports1 = m1.getDirectReport();
|
||||
directReports2 = m2.getDirectReport();
|
||||
assertEquals(0, directReports1.size());
|
||||
assertEquals(2, directReports2.size());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCopyMethod_whenCopy_thenDistinct() {
|
||||
Date startDate = new Date(123);
|
||||
Employee e1 = new Employee(1, "Baeldung", startDate);
|
||||
Employee e2 = new Employee(e1);
|
||||
List<Employee> directReports = new ArrayList<Employee>();
|
||||
directReports.add(e1);
|
||||
directReports.add(e2);
|
||||
|
||||
// a Manager object whose declaration type is Employee.
|
||||
Employee source = new Manager(1, "Baeldung Manager", startDate, directReports);
|
||||
Employee clone = source.copy();
|
||||
|
||||
// after copy, clone should be still a Manager object.
|
||||
assertTrue(clone instanceof Manager);
|
||||
List<Employee> directReports1 = ((Manager) source).getDirectReport();
|
||||
List<Employee> directReports2 = ((Manager) clone).getDirectReport();
|
||||
assertEquals(directReports1.size(), directReports2.size());
|
||||
assertArrayEquals(directReports1.toArray(), directReports2.toArray());
|
||||
|
||||
// clear source's direct reports list. clone's list should not be affected
|
||||
directReports.clear();
|
||||
directReports1 = ((Manager) source).getDirectReport();
|
||||
directReports2 = ((Manager) clone).getDirectReport();
|
||||
assertEquals(0, directReports1.size());
|
||||
assertEquals(2, directReports2.size());
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.booleanoperators;
|
||||
|
||||
public class Car {
|
||||
|
||||
private boolean diesel;
|
||||
private boolean manual;
|
||||
|
||||
public Car(boolean diesel, boolean manual) {
|
||||
this.diesel = diesel;
|
||||
this.manual = manual;
|
||||
}
|
||||
|
||||
public boolean isDiesel() {
|
||||
return diesel;
|
||||
}
|
||||
|
||||
public boolean isManual() {
|
||||
return manual;
|
||||
}
|
||||
|
||||
static Car dieselAndManualCar() {
|
||||
return new Car(true, true);
|
||||
}
|
||||
|
||||
static Car dieselAndAutomaticCar() {
|
||||
return new Car(true, false);
|
||||
}
|
||||
|
||||
static Car oilAndManualCar() {
|
||||
return new Car(false, true);
|
||||
}
|
||||
|
||||
static Car oilAndAutomaticCar() {
|
||||
return new Car(false, false);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,69 @@
|
|||
package com.baeldung.booleanoperators;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class XorUnitTest {
|
||||
|
||||
@Test
|
||||
void givenDieselManualCar_whenXorOldSchool_thenFalse() {
|
||||
Car car = Car.dieselAndManualCar();
|
||||
boolean dieselXorManual = (car.isDiesel() && !car.isManual()) || (!car.isDiesel() && car.isManual());
|
||||
assertThat(dieselXorManual).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDieselAutomaticCar_whenXorOldSchool_thenTrue() {
|
||||
Car car = Car.dieselAndAutomaticCar();
|
||||
boolean dieselXorManual = (car.isDiesel() && !car.isManual()) || (!car.isDiesel() && car.isManual());
|
||||
assertThat(dieselXorManual).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNonDieselManualCar_whenXorOldSchool_thenTrue() {
|
||||
Car car = Car.oilAndManualCar();
|
||||
boolean dieselXorManual = (car.isDiesel() && !car.isManual()) || (!car.isDiesel() && car.isManual());
|
||||
assertThat(dieselXorManual).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNonDieselAutomaticCar_whenXorOldSchool_thenFalse() {
|
||||
Car car = Car.oilAndAutomaticCar();
|
||||
boolean dieselXorManual = (car.isDiesel() && !car.isManual()) || (!car.isDiesel() && car.isManual());
|
||||
assertThat(dieselXorManual).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDieselManualCar_whenXor_thenFalse() {
|
||||
Car car = Car.dieselAndManualCar();
|
||||
boolean dieselXorManual = car.isDiesel() ^ car.isManual();
|
||||
assertThat(dieselXorManual).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDieselAutomaticCar_whenXor_thenTrue() {
|
||||
Car car = Car.dieselAndAutomaticCar();
|
||||
boolean dieselXorManual = car.isDiesel() ^ car.isManual();
|
||||
assertThat(dieselXorManual).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNonDieselManualCar_whenXor_thenTrue() {
|
||||
Car car = Car.oilAndManualCar();
|
||||
boolean dieselXorManual = car.isDiesel() ^ car.isManual();
|
||||
assertThat(dieselXorManual).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNonDieselAutomaticCar_whenXor_thenFalse() {
|
||||
Car car = Car.oilAndAutomaticCar();
|
||||
boolean dieselXorManual = car.isDiesel() ^ car.isManual();
|
||||
assertThat(dieselXorManual).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNumbersOneAndThree_whenXor_thenTwo() {
|
||||
assertThat(1 ^ 3).isEqualTo(2);
|
||||
}
|
||||
}
|
|
@ -3,13 +3,10 @@
|
|||
## Core Java Lang Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
|
||||
|
||||
- [Generate equals() and hashCode() with Eclipse](http://www.baeldung.com/java-eclipse-equals-and-hashcode)
|
||||
- [Chained Exceptions in Java](http://www.baeldung.com/java-chained-exceptions)
|
||||
- [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection)
|
||||
- [Iterating Over Enum Values in Java](http://www.baeldung.com/java-enum-iteration)
|
||||
- [Changing Annotation Parameters At Runtime](http://www.baeldung.com/java-reflection-change-annotation-params)
|
||||
- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)
|
||||
- [Java Double Brace Initialization](http://www.baeldung.com/java-double-brace-initialization)
|
||||
- [Guide to the Diamond Operator in Java](http://www.baeldung.com/java-diamond-operator)
|
||||
- [Comparator and Comparable in Java](http://www.baeldung.com/java-comparator-comparable)
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue