Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
commit
c113737496
7
.gitignore
vendored
7
.gitignore
vendored
@ -56,4 +56,9 @@ core-java-io/hard_link.txt
|
||||
core-java-io/target_link.txt
|
||||
core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF
|
||||
ethereum/logs/
|
||||
jmeter/src/main/resources/*-JMeter.csv
|
||||
jmeter/src/main/resources/*-JMeter.csv
|
||||
|
||||
**/node_modules/
|
||||
**/dist
|
||||
**/tmp
|
||||
**/out-tsc
|
||||
|
@ -56,3 +56,4 @@
|
||||
- [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference)
|
||||
- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string)
|
||||
- [Calculate Age in Java](http://www.baeldung.com/java-get-age)
|
||||
- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date)
|
||||
|
@ -1,208 +0,0 @@
|
||||
package com.baeldung.list;
|
||||
|
||||
import static com.baeldung.list.RemoveAll.removeWithCallingRemoveUntilModifies;
|
||||
import static com.baeldung.list.RemoveAll.removeWithCollectingAndReturningRemainingElements;
|
||||
import static com.baeldung.list.RemoveAll.removeWithCollectingRemainingElementsAndAddingToOriginalList;
|
||||
import static com.baeldung.list.RemoveAll.removeWithForEachLoop;
|
||||
import static com.baeldung.list.RemoveAll.removeWithForLoopDecrementOnRemove;
|
||||
import static com.baeldung.list.RemoveAll.removeWithForLoopIncrementIfRemains;
|
||||
import static com.baeldung.list.RemoveAll.removeWithIterator;
|
||||
import static com.baeldung.list.RemoveAll.removeWithRemoveIf;
|
||||
import static com.baeldung.list.RemoveAll.removeWithStandardForLoopUsingIndex;
|
||||
import static com.baeldung.list.RemoveAll.removeWithStreamFilter;
|
||||
import static com.baeldung.list.RemoveAll.*;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.ConcurrentModificationException;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RemoveAllUnitTest {
|
||||
|
||||
private List<Integer> list(Integer... elements) {
|
||||
return new ArrayList<>(Arrays.asList(elements));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenRemovingElementsWithWhileLoopUsingPrimitiveElement_thenTheResultCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
assertThatThrownBy(() -> removeWithWhileLoopPrimitiveElement(list, valueToRemove))
|
||||
.isInstanceOf(IndexOutOfBoundsException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenRemovingElementsWithWhileLoopUsingNonPrimitiveElement_thenTheResultCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
removeWithWhileLoopNonPrimitiveElement(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(list).isEqualTo(list(2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenRemovingElementsWithWhileLoopStoringFirstOccurrenceIndex_thenTheResultCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
removeWithWhileLoopStoringFirstOccurrenceIndex(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(list).isEqualTo(list(2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenRemovingElementsWithCallingRemoveUntilModifies_thenTheResultIsCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
removeWithCallingRemoveUntilModifies(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(list).isEqualTo(list(2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListWithoutDuplication_whenRemovingElementsWithStandardForLoopUsingIndex_thenTheResultIsCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
removeWithStandardForLoopUsingIndex(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(list).isEqualTo(list(2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListWithAdjacentElements_whenRemovingElementsWithStandardForLoop_thenTheResultIsInCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
removeWithStandardForLoopUsingIndex(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(list).isEqualTo(list(1, 2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListWithAdjacentElements_whenRemovingElementsWithForLoopAndDecrementOnRemove_thenTheResultIsCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
removeWithForLoopDecrementOnRemove(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(list).isEqualTo(list(2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListWithAdjacentElements_whenRemovingElementsWithForLoopAndIncrementIfRemains_thenTheResultIsCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
removeWithForLoopIncrementIfRemains(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(list).isEqualTo(list(2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenRemovingElementsWithForEachLoop_thenExceptionIsThrown() {
|
||||
// given
|
||||
List<Integer> list = list(1, 1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
assertThatThrownBy(() -> removeWithForEachLoop(list, valueToRemove))
|
||||
.isInstanceOf(ConcurrentModificationException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenRemovingElementsWithIterator_thenTheResultIsCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
removeWithIterator(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(list).isEqualTo(list(2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenRemovingElementsWithCollectingAndReturningRemainingElements_thenTheResultIsCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
List<Integer> result = removeWithCollectingAndReturningRemainingElements(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(list(2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenRemovingElementsWithCollectingRemainingAndAddingToOriginalList_thenTheResultIsCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
removeWithCollectingRemainingElementsAndAddingToOriginalList(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(list).isEqualTo(list(2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenRemovingElementsWithStreamFilter_thenTheResultIsCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
List<Integer> result = removeWithStreamFilter(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(list(2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenRemovingElementsWithCallingRemoveIf_thenTheResultIsCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
removeWithRemoveIf(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(list).isEqualTo(list(2, 3));
|
||||
}
|
||||
|
||||
}
|
@ -36,11 +36,6 @@
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.collections</groupId>
|
||||
<artifactId>eclipse-collections-api</artifactId>
|
||||
<version>${eclipse.collections.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.collections</groupId>
|
||||
<artifactId>eclipse-collections</artifactId>
|
||||
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.list;
|
||||
package com.baeldung.list.removeall;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
@ -0,0 +1,36 @@
|
||||
package com.baeldung.thread_safe_lifo;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
|
||||
/**
|
||||
* Deque Based Stack implementation.
|
||||
*/
|
||||
public class DequeBasedSynchronizedStack<T> {
|
||||
|
||||
// Internal Deque which gets decorated for synchronization.
|
||||
private ArrayDeque<T> dequeStore = new ArrayDeque<>();
|
||||
|
||||
public DequeBasedSynchronizedStack(int initialCapacity) {
|
||||
this.dequeStore = new ArrayDeque<>(initialCapacity);
|
||||
}
|
||||
|
||||
public DequeBasedSynchronizedStack() {
|
||||
|
||||
}
|
||||
|
||||
public synchronized T pop() {
|
||||
return this.dequeStore.pop();
|
||||
}
|
||||
|
||||
public synchronized void push(T element) {
|
||||
this.dequeStore.push(element);
|
||||
}
|
||||
|
||||
public synchronized T peek() {
|
||||
return this.dequeStore.peek();
|
||||
}
|
||||
|
||||
public synchronized int size() {
|
||||
return this.dequeStore.size();
|
||||
}
|
||||
}
|
@ -0,0 +1,210 @@
|
||||
package com.baeldung.list.removeall;
|
||||
|
||||
import static com.baeldung.list.removeall.RemoveAll.removeWithCallingRemoveUntilModifies;
|
||||
import static com.baeldung.list.removeall.RemoveAll.removeWithCollectingAndReturningRemainingElements;
|
||||
import static com.baeldung.list.removeall.RemoveAll.removeWithCollectingRemainingElementsAndAddingToOriginalList;
|
||||
import static com.baeldung.list.removeall.RemoveAll.removeWithForEachLoop;
|
||||
import static com.baeldung.list.removeall.RemoveAll.removeWithForLoopDecrementOnRemove;
|
||||
import static com.baeldung.list.removeall.RemoveAll.removeWithForLoopIncrementIfRemains;
|
||||
import static com.baeldung.list.removeall.RemoveAll.removeWithIterator;
|
||||
import static com.baeldung.list.removeall.RemoveAll.removeWithRemoveIf;
|
||||
import static com.baeldung.list.removeall.RemoveAll.removeWithStandardForLoopUsingIndex;
|
||||
import static com.baeldung.list.removeall.RemoveAll.removeWithStreamFilter;
|
||||
import static com.baeldung.list.removeall.RemoveAll.removeWithWhileLoopNonPrimitiveElement;
|
||||
import static com.baeldung.list.removeall.RemoveAll.removeWithWhileLoopPrimitiveElement;
|
||||
import static com.baeldung.list.removeall.RemoveAll.removeWithWhileLoopStoringFirstOccurrenceIndex;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.ConcurrentModificationException;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RemoveAllUnitTest {
|
||||
|
||||
private List<Integer> list(Integer... elements) {
|
||||
return new ArrayList<>(Arrays.asList(elements));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenRemovingElementsWithWhileLoopUsingPrimitiveElement_thenTheResultCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
assertThatThrownBy(() -> removeWithWhileLoopPrimitiveElement(list, valueToRemove))
|
||||
.isInstanceOf(IndexOutOfBoundsException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenRemovingElementsWithWhileLoopUsingNonPrimitiveElement_thenTheResultCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
removeWithWhileLoopNonPrimitiveElement(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(list).isEqualTo(list(2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenRemovingElementsWithWhileLoopStoringFirstOccurrenceIndex_thenTheResultCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
removeWithWhileLoopStoringFirstOccurrenceIndex(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(list).isEqualTo(list(2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenRemovingElementsWithCallingRemoveUntilModifies_thenTheResultIsCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
removeWithCallingRemoveUntilModifies(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(list).isEqualTo(list(2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListWithoutDuplication_whenRemovingElementsWithStandardForLoopUsingIndex_thenTheResultIsCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
removeWithStandardForLoopUsingIndex(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(list).isEqualTo(list(2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListWithAdjacentElements_whenRemovingElementsWithStandardForLoop_thenTheResultIsInCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
removeWithStandardForLoopUsingIndex(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(list).isEqualTo(list(1, 2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListWithAdjacentElements_whenRemovingElementsWithForLoopAndDecrementOnRemove_thenTheResultIsCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
removeWithForLoopDecrementOnRemove(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(list).isEqualTo(list(2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListWithAdjacentElements_whenRemovingElementsWithForLoopAndIncrementIfRemains_thenTheResultIsCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
removeWithForLoopIncrementIfRemains(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(list).isEqualTo(list(2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenRemovingElementsWithForEachLoop_thenExceptionIsThrown() {
|
||||
// given
|
||||
List<Integer> list = list(1, 1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
assertThatThrownBy(() -> removeWithForEachLoop(list, valueToRemove))
|
||||
.isInstanceOf(ConcurrentModificationException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenRemovingElementsWithIterator_thenTheResultIsCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
removeWithIterator(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(list).isEqualTo(list(2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenRemovingElementsWithCollectingAndReturningRemainingElements_thenTheResultIsCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
List<Integer> result = removeWithCollectingAndReturningRemainingElements(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(list(2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenRemovingElementsWithCollectingRemainingAndAddingToOriginalList_thenTheResultIsCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
removeWithCollectingRemainingElementsAndAddingToOriginalList(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(list).isEqualTo(list(2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenRemovingElementsWithStreamFilter_thenTheResultIsCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
List<Integer> result = removeWithStreamFilter(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(list(2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenRemovingElementsWithCallingRemoveIf_thenTheResultIsCorrect() {
|
||||
// given
|
||||
List<Integer> list = list(1, 1, 2, 3);
|
||||
int valueToRemove = 1;
|
||||
|
||||
// when
|
||||
removeWithRemoveIf(list, valueToRemove);
|
||||
|
||||
// then
|
||||
assertThat(list).isEqualTo(list(2, 3));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,101 @@
|
||||
package com.baeldung.stack_tests;
|
||||
|
||||
import com.baeldung.thread_safe_lifo.DequeBasedSynchronizedStack;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.concurrent.ConcurrentLinkedDeque;
|
||||
|
||||
import static java.util.stream.IntStream.range;
|
||||
|
||||
/**
|
||||
* Correctness tests for Stack in multi threaded environment.
|
||||
*/
|
||||
public class MultithreadingCorrectnessStackUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenSynchronizedDeque_whenExecutedParallel_thenWorkRight() {
|
||||
|
||||
DequeBasedSynchronizedStack<Integer> deque = new DequeBasedSynchronizedStack<>();
|
||||
|
||||
// Serial execution of push on ConcurrentLinkedQueue will always result in correct execution.
|
||||
range(1, 10000).forEach(value -> deque.push(value));
|
||||
|
||||
int sum = 0;
|
||||
while(deque.peek() != null) {
|
||||
sum += deque.pop();
|
||||
}
|
||||
|
||||
Assert.assertEquals(49995000, sum);
|
||||
|
||||
// Parallel execution of push on ConcurrentLinkedQueue will always result in correct execution.
|
||||
range(1, 10000).parallel().forEach(value -> deque.push(value));
|
||||
|
||||
sum = 0;
|
||||
while(deque.peek() != null) {
|
||||
sum += deque.pop();
|
||||
}
|
||||
|
||||
Assert.assertEquals(49995000, sum);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenConcurrentLinkedQueue_whenExecutedParallel_thenWorkRight() {
|
||||
|
||||
ConcurrentLinkedDeque<Integer> deque = new ConcurrentLinkedDeque<>();
|
||||
|
||||
// Serial execution of push on ConcurrentLinkedQueue will always result in correct execution.
|
||||
range(1, 10000).forEach(value -> deque.push(value));
|
||||
|
||||
int sum = 0;
|
||||
while(deque.peek() != null) {
|
||||
sum += deque.pop();
|
||||
}
|
||||
|
||||
Assert.assertEquals(49995000, sum);
|
||||
|
||||
// Parallel execution of push on ConcurrentLinkedQueue will always result in correct execution.
|
||||
range(1, 10000).parallel().forEach(value -> deque.push(value));
|
||||
|
||||
sum = 0;
|
||||
while(deque.peek() != null) {
|
||||
sum += deque.pop();
|
||||
}
|
||||
|
||||
Assert.assertEquals(49995000, sum);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayDeque_whenExecutedParallel_thenShouldFail() {
|
||||
|
||||
ArrayDeque<Integer> deque = new ArrayDeque<>();
|
||||
|
||||
// Serial execution of push on ArrayDeque will always result in correct execution.
|
||||
range(1, 10000).forEach(value -> deque.push(value));
|
||||
|
||||
int sum = 0;
|
||||
while(deque.peek() != null) {
|
||||
sum += deque.pop();
|
||||
}
|
||||
|
||||
Assert.assertEquals(49995000, sum);
|
||||
|
||||
// Parallel execution of push on ArrayDeque will not result in correct execution.
|
||||
range(1, 10000).parallel().forEach(value -> deque.push(value));
|
||||
|
||||
sum = 0;
|
||||
while(deque.peek() != null) {
|
||||
sum += deque.pop();
|
||||
}
|
||||
|
||||
// This shouldn't happen.
|
||||
if(sum == 49995000) {
|
||||
System.out.println("Something wrong in the environment, Please try some big value and check");
|
||||
// To safe-guard build without test failures.
|
||||
return;
|
||||
}
|
||||
|
||||
Assert.assertNotEquals(49995000, sum);
|
||||
}
|
||||
}
|
@ -0,0 +1,63 @@
|
||||
package com.baeldung.stack_tests;
|
||||
|
||||
import com.baeldung.thread_safe_lifo.DequeBasedSynchronizedStack;
|
||||
import com.google.common.collect.Streams;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Stack;
|
||||
import java.util.concurrent.ConcurrentLinkedDeque;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static java.util.stream.IntStream.range;
|
||||
|
||||
/**
|
||||
* These tests are to understand the Stack implementation in Java Collections.
|
||||
*/
|
||||
public class StackUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenStack_whenPushPopPeek_thenWorkRight() {
|
||||
Stack<String> namesStack = new Stack<>();
|
||||
|
||||
namesStack.push("Bill Gates");
|
||||
namesStack.push("Elon Musk");
|
||||
|
||||
Assert.assertEquals("Elon Musk", namesStack.peek());
|
||||
Assert.assertEquals("Elon Musk", namesStack.pop());
|
||||
Assert.assertEquals("Bill Gates", namesStack.pop());
|
||||
|
||||
Assert.assertEquals(0, namesStack.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSynchronizedDeque_whenPushPopPeek_thenWorkRight() {
|
||||
DequeBasedSynchronizedStack<String> namesStack = new DequeBasedSynchronizedStack<>();
|
||||
|
||||
namesStack.push("Bill Gates");
|
||||
namesStack.push("Elon Musk");
|
||||
|
||||
Assert.assertEquals("Elon Musk", namesStack.peek());
|
||||
Assert.assertEquals("Elon Musk", namesStack.pop());
|
||||
Assert.assertEquals("Bill Gates", namesStack.pop());
|
||||
|
||||
Assert.assertEquals(0, namesStack.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenConcurrentLinkedDeque_whenPushPopPeek_thenWorkRight() {
|
||||
ConcurrentLinkedDeque<String> namesStack = new ConcurrentLinkedDeque<>();
|
||||
|
||||
namesStack.push("Bill Gates");
|
||||
namesStack.push("Elon Musk");
|
||||
|
||||
Assert.assertEquals("Elon Musk", namesStack.peek());
|
||||
Assert.assertEquals("Elon Musk", namesStack.pop());
|
||||
Assert.assertEquals("Bill Gates", namesStack.pop());
|
||||
|
||||
Assert.assertEquals(0, namesStack.size());
|
||||
}
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
package com.baeldung.file;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FilenameFilter;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FilenameFilterManualTest {
|
||||
|
||||
private static File directory;
|
||||
|
||||
@BeforeClass
|
||||
public static void setupClass() {
|
||||
directory = new File(FilenameFilterManualTest.class.getClassLoader()
|
||||
.getResource("testFolder")
|
||||
.getFile());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilteringFilesEndingWithJson_thenEqualExpectedFiles() {
|
||||
FilenameFilter filter = (dir, name) -> name.endsWith(".json");
|
||||
|
||||
String[] expectedFiles = { "people.json", "students.json" };
|
||||
String[] actualFiles = directory.list(filter);
|
||||
|
||||
Assert.assertArrayEquals(expectedFiles, actualFiles);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilteringFilesEndingWithXml_thenEqualExpectedFiles() {
|
||||
Predicate<String> predicate = (name) -> name.endsWith(".xml");
|
||||
|
||||
String[] expectedFiles = { "teachers.xml", "workers.xml" };
|
||||
List<String> files = Arrays.stream(directory.list())
|
||||
.filter(predicate)
|
||||
.collect(Collectors.toList());
|
||||
String[] actualFiles = files.toArray(new String[files.size()]);
|
||||
|
||||
Assert.assertArrayEquals(expectedFiles, actualFiles);
|
||||
}
|
||||
|
||||
}
|
1
core-java-io/src/test/resources/testFolder/people.json
Normal file
1
core-java-io/src/test/resources/testFolder/people.json
Normal file
@ -0,0 +1 @@
|
||||
{}
|
1
core-java-io/src/test/resources/testFolder/students.json
Normal file
1
core-java-io/src/test/resources/testFolder/students.json
Normal file
@ -0,0 +1 @@
|
||||
{}
|
1
core-java-io/src/test/resources/testFolder/teachers.xml
Normal file
1
core-java-io/src/test/resources/testFolder/teachers.xml
Normal file
@ -0,0 +1 @@
|
||||
<xml></xml>
|
1
core-java-io/src/test/resources/testFolder/workers.xml
Normal file
1
core-java-io/src/test/resources/testFolder/workers.xml
Normal file
@ -0,0 +1 @@
|
||||
<xml></xml>
|
@ -0,0 +1,212 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class Exceptions {
|
||||
|
||||
private final static Logger logger = Logger.getLogger("ExceptionLogging");
|
||||
|
||||
public static List<Player> getPlayers() throws IOException {
|
||||
Path path = Paths.get("players.dat");
|
||||
List<String> players = Files.readAllLines(path);
|
||||
|
||||
return players.stream()
|
||||
.map(Player::new)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayers(String playersFile) throws IOException{
|
||||
try {
|
||||
throw new IOException();
|
||||
} catch(IOException ex) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreThrows(String playerFile) throws FileNotFoundException {
|
||||
Scanner contents = new Scanner(new File(playerFile));
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
}
|
||||
|
||||
public int getPlayerScoreTryCatch(String playerFile) {
|
||||
try {
|
||||
Scanner contents = new Scanner(new File(playerFile));
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch (FileNotFoundException noFile) {
|
||||
throw new IllegalArgumentException("File not found");
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreTryCatchRecovery(String playerFile) {
|
||||
try {
|
||||
Scanner contents = new Scanner(new File(playerFile));
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch ( FileNotFoundException noFile ) {
|
||||
logger.warning("File not found, resetting score.");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreFinally(String playerFile) throws FileNotFoundException {
|
||||
Scanner contents = null;
|
||||
try {
|
||||
contents = new Scanner(new File(playerFile));
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} finally {
|
||||
if (contents != null) {
|
||||
contents.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreTryWithResources(String playerFile) {
|
||||
try (Scanner contents = new Scanner(new File(playerFile))) {
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch (FileNotFoundException e ) {
|
||||
logger.warning("File not found, resetting score.");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreMultipleCatchBlocks(String playerFile) {
|
||||
try (Scanner contents = new Scanner(new File(playerFile))) {
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch (IOException e) {
|
||||
logger.warning("Player file wouldn't load!");
|
||||
return 0;
|
||||
} catch (NumberFormatException e) {
|
||||
logger.warning("Player file was corrupted!");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreMultipleCatchBlocksAlternative(String playerFile) {
|
||||
try (Scanner contents = new Scanner(new File(playerFile)) ) {
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch (FileNotFoundException e) {
|
||||
logger.warning("Player file not found!");
|
||||
return 0;
|
||||
} catch (IOException e) {
|
||||
logger.warning("Player file wouldn't load!");
|
||||
return 0;
|
||||
} catch (NumberFormatException e) {
|
||||
logger.warning("Player file was corrupted!");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreUnionCatchBlocks(String playerFile) {
|
||||
try (Scanner contents = new Scanner(new File(playerFile))) {
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch (IOException | NumberFormatException e) {
|
||||
logger.warning("Failed to load score!");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayersThrowingChecked(String playersFile) throws TimeoutException {
|
||||
boolean tooLong = true;
|
||||
|
||||
while (!tooLong) {
|
||||
// ... potentially long operation
|
||||
}
|
||||
throw new TimeoutException("This operation took too long");
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayersThrowingUnchecked(String playersFile) throws TimeoutException {
|
||||
if(!isFilenameValid(playersFile)) {
|
||||
throw new IllegalArgumentException("Filename isn't valid!");
|
||||
}
|
||||
return null;
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayersWrapping(String playersFile) throws IOException {
|
||||
try {
|
||||
throw new IOException();
|
||||
} catch (IOException io) {
|
||||
throw io;
|
||||
}
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayersRethrowing(String playersFile) throws PlayerLoadException {
|
||||
try {
|
||||
throw new IOException();
|
||||
} catch (IOException io) {
|
||||
throw new PlayerLoadException(io);
|
||||
}
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayersThrowable(String playersFile) {
|
||||
try {
|
||||
throw new NullPointerException();
|
||||
} catch ( Throwable t ) {
|
||||
throw t;
|
||||
}
|
||||
}
|
||||
|
||||
class FewerExceptions extends Exceptions {
|
||||
@Override
|
||||
public List<Player> loadAllPlayers(String playersFile) { //can't add "throws MyCheckedException
|
||||
return null;
|
||||
// overridden
|
||||
}
|
||||
}
|
||||
|
||||
public void throwAsGotoAntiPattern() {
|
||||
try {
|
||||
// bunch of code
|
||||
throw new MyException();
|
||||
// second bunch of code
|
||||
} catch ( MyException e ) {
|
||||
// third bunch of code
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreSwallowingExceptionAntiPattern(String playerFile) {
|
||||
try {
|
||||
// ...
|
||||
} catch (Exception e) {} // <== catch and swallow
|
||||
return 0;
|
||||
}
|
||||
|
||||
public int getPlayerScoreSwallowingExceptionAntiPatternAlternative(String playerFile) {
|
||||
try {
|
||||
// ...
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public int getPlayerScoreSwallowingExceptionAntiPatternAlternative2(String playerFile) throws PlayerScoreException {
|
||||
try {
|
||||
throw new IOException();
|
||||
} catch (IOException e) {
|
||||
throw new PlayerScoreException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreReturnInFinallyAntiPattern(String playerFile) {
|
||||
int score = 0;
|
||||
try {
|
||||
throw new IOException();
|
||||
} finally {
|
||||
return score; // <== the IOException is dropped
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isFilenameValid(String name) {
|
||||
return false;
|
||||
}
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
public class MyException extends Throwable {
|
||||
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
public class Player {
|
||||
|
||||
public int id;
|
||||
public String name;
|
||||
|
||||
public Player(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class PlayerLoadException extends Exception {
|
||||
|
||||
public PlayerLoadException(IOException io) {
|
||||
super(io);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
public class PlayerScoreException extends Exception {
|
||||
|
||||
public PlayerScoreException(Exception e) {
|
||||
super(e);
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
public class TimeoutException extends Exception {
|
||||
|
||||
public TimeoutException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
@ -1,16 +0,0 @@
|
||||
package com.baeldung.logging;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class LogUsingSlf4J {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Logger logger = LoggerFactory.getLogger(LogUsingSlf4J.class);
|
||||
|
||||
logger.error("An exception occurred!");
|
||||
logger.error("An exception occurred!", new Exception("Custom exception"));
|
||||
logger.error("{}, {}! An exception occurred!", "Hello", "World", new Exception("Custom exception"));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package com.baeldung.objectsize;
|
||||
|
||||
import java.lang.instrument.Instrumentation;
|
||||
|
||||
public class InstrumentationAgent {
|
||||
private static volatile Instrumentation globalInstrumentation;
|
||||
|
||||
public static void premain(final String agentArgs, final Instrumentation inst) {
|
||||
globalInstrumentation = inst;
|
||||
}
|
||||
|
||||
public static long getObjectSize(final Object object) {
|
||||
if (globalInstrumentation == null) {
|
||||
throw new IllegalStateException("Agent not initialized.");
|
||||
}
|
||||
return globalInstrumentation.getObjectSize(object);
|
||||
}
|
||||
}
|
@ -0,0 +1,59 @@
|
||||
package com.baeldung.objectsize;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class InstrumentationExample {
|
||||
|
||||
public static void printObjectSize(Object object) {
|
||||
System.out.println("Object type: " + object.getClass() + ", size: " + InstrumentationAgent.getObjectSize(object) + " bytes");
|
||||
}
|
||||
|
||||
public static void main(String[] arguments) {
|
||||
String emptyString = "";
|
||||
String string = "Estimating Object Size Using Instrumentation";
|
||||
String[] stringArray = { emptyString, string, "com.baeldung" };
|
||||
String[] anotherStringArray = new String[100];
|
||||
List<String> stringList = new ArrayList<>();
|
||||
StringBuilder stringBuilder = new StringBuilder(100);
|
||||
int maxIntPrimitive = Integer.MAX_VALUE;
|
||||
int minIntPrimitive = Integer.MIN_VALUE;
|
||||
Integer maxInteger = Integer.MAX_VALUE;
|
||||
Integer minInteger = Integer.MIN_VALUE;
|
||||
long zeroLong = 0L;
|
||||
double zeroDouble = 0.0;
|
||||
boolean falseBoolean = false;
|
||||
Object object = new Object();
|
||||
|
||||
class EmptyClass {
|
||||
}
|
||||
EmptyClass emptyClass = new EmptyClass();
|
||||
|
||||
class StringClass {
|
||||
public String s;
|
||||
}
|
||||
StringClass stringClass = new StringClass();
|
||||
|
||||
printObjectSize(emptyString);
|
||||
printObjectSize(string);
|
||||
printObjectSize(stringArray);
|
||||
printObjectSize(anotherStringArray);
|
||||
printObjectSize(stringList);
|
||||
printObjectSize(stringBuilder);
|
||||
printObjectSize(maxIntPrimitive);
|
||||
printObjectSize(minIntPrimitive);
|
||||
printObjectSize(maxInteger);
|
||||
printObjectSize(minInteger);
|
||||
printObjectSize(zeroLong);
|
||||
printObjectSize(zeroDouble);
|
||||
printObjectSize(falseBoolean);
|
||||
printObjectSize(Day.TUESDAY);
|
||||
printObjectSize(object);
|
||||
printObjectSize(emptyClass);
|
||||
printObjectSize(stringClass);
|
||||
}
|
||||
|
||||
public enum Day {
|
||||
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
|
||||
}
|
||||
}
|
@ -0,0 +1 @@
|
||||
Premain-class: com.baeldung.objectsize.InstrumentationAgent
|
@ -0,0 +1,42 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class RemoveFirstElementUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenStringArray_whenRemovingFirstElement_thenArrayIsSmallerAndElementRemoved() {
|
||||
String[] stringArray = {"foo", "bar", "baz"};
|
||||
|
||||
String[] modifiedArray = Arrays.copyOfRange(stringArray, 1, stringArray.length);
|
||||
|
||||
assertThat(modifiedArray.length).isEqualTo(2);
|
||||
assertThat(modifiedArray[0]).isEqualTo("bar");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayList_whenRemovingFirstElement_thenListSmallerAndElementRemoved() {
|
||||
List<String> stringList = new ArrayList<>(Arrays.asList("foo", "bar", "baz"));
|
||||
stringList.remove(0);
|
||||
|
||||
assertThat(stringList.size()).isEqualTo(2);
|
||||
assertThat(stringList.get(0)).isEqualTo("bar");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLinkedList_whenRemovingFirstElement_thenListSmallerAndElementRemoved() {
|
||||
List<String> stringList = new LinkedList<>(Arrays.asList("foo", "bar", "baz"));
|
||||
stringList.remove(0);
|
||||
|
||||
assertThat(stringList.size()).isEqualTo(2);
|
||||
assertThat(stringList.get(0)).isEqualTo("bar");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,86 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.NoSuchFileException;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
public class ExceptionsUnitTest {
|
||||
|
||||
Exceptions exceptions = new Exceptions();
|
||||
|
||||
@Test
|
||||
public void getPlayers() {
|
||||
assertThatThrownBy(() -> exceptions.getPlayers())
|
||||
.isInstanceOf(NoSuchFileException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadAllPlayers() {
|
||||
assertThatThrownBy(() -> exceptions.loadAllPlayers(""))
|
||||
.isInstanceOf(IOException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getPlayerScoreThrows() {
|
||||
assertThatThrownBy(() -> exceptions.getPlayerScoreThrows(""))
|
||||
.isInstanceOf(FileNotFoundException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getPlayerScoreTryCatch() {
|
||||
assertThatThrownBy(() -> exceptions.getPlayerScoreTryCatch(""))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getPlayerScoreFinally() {
|
||||
assertThatThrownBy(() -> exceptions.getPlayerScoreFinally(""))
|
||||
.isInstanceOf(FileNotFoundException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadAllPlayersThrowingChecked() {
|
||||
assertThatThrownBy(() -> exceptions.loadAllPlayersThrowingChecked(""))
|
||||
.isInstanceOf(TimeoutException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadAllPlayersThrowingUnchecked() {
|
||||
assertThatThrownBy(() -> exceptions.loadAllPlayersThrowingUnchecked(""))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadAllPlayersWrapping() {
|
||||
assertThatThrownBy(() -> exceptions.loadAllPlayersWrapping(""))
|
||||
.isInstanceOf(IOException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadAllPlayersRethrowing() {
|
||||
assertThatThrownBy(() -> exceptions.loadAllPlayersRethrowing(""))
|
||||
.isInstanceOf(PlayerLoadException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadAllPlayersThrowable() {
|
||||
assertThatThrownBy(() -> exceptions.loadAllPlayersThrowable(""))
|
||||
.isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void throwAsGotoAntiPattern() {
|
||||
assertThatThrownBy(() -> exceptions.throwAsGotoAntiPattern())
|
||||
.isInstanceOf(MyException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getPlayerScoreSwallowingExceptionAntiPatternAlternative2() {
|
||||
assertThatThrownBy(() -> exceptions.getPlayerScoreSwallowingExceptionAntiPatternAlternative2(""))
|
||||
.isInstanceOf(PlayerScoreException.class);
|
||||
}
|
||||
}
|
@ -0,0 +1,73 @@
|
||||
package com.baeldung.java.listInitialization;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import lombok.extern.java.Log;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
|
||||
@Log
|
||||
public class ListInitializationUnitTest {
|
||||
|
||||
@Rule
|
||||
public ExpectedException exception = ExpectedException.none();
|
||||
|
||||
@Test
|
||||
public void givenAnonymousInnerClass_thenInitialiseList() {
|
||||
List<String> cities = new ArrayList() {
|
||||
// Inside declaration of the subclass
|
||||
|
||||
// You can have multiple initializer block
|
||||
{
|
||||
log.info("Inside the first initializer block.");
|
||||
}
|
||||
|
||||
{
|
||||
log.info("Inside the second initializer block.");
|
||||
add("New York");
|
||||
add("Rio");
|
||||
add("Tokyo");
|
||||
}
|
||||
};
|
||||
|
||||
Assert.assertTrue(cities.contains("New York"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArraysAsList_thenInitialiseList() {
|
||||
List<String> list = Arrays.asList("foo", "bar");
|
||||
|
||||
Assert.assertTrue(list.contains("foo"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArraysAsList_whenAdd_thenUnsupportedException() {
|
||||
List<String> list = Arrays.asList("foo", "bar");
|
||||
|
||||
exception.expect(UnsupportedOperationException.class);
|
||||
list.add("baz");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayAsList_whenCreated_thenShareReference() {
|
||||
String[] array = { "foo", "bar" };
|
||||
List<String> list = Arrays.asList(array);
|
||||
array[0] = "baz";
|
||||
Assert.assertEquals("baz", list.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStream_thenInitializeList() {
|
||||
List<String> list = Stream.of("foo", "bar")
|
||||
.collect(Collectors.toList());
|
||||
|
||||
Assert.assertTrue(list.contains("foo"));
|
||||
}
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
package com.baeldung.builder
|
||||
|
||||
class FoodOrder private constructor(builder: FoodOrder.Builder) {
|
||||
|
||||
val bread: String?
|
||||
val condiments: String?
|
||||
val meat: String?
|
||||
val fish: String?
|
||||
|
||||
init {
|
||||
this.bread = builder.bread
|
||||
this.condiments = builder.condiments
|
||||
this.meat = builder.meat
|
||||
this.fish = builder.fish
|
||||
}
|
||||
|
||||
class Builder {
|
||||
|
||||
var bread: String? = null
|
||||
private set
|
||||
var condiments: String? = null
|
||||
private set
|
||||
var meat: String? = null
|
||||
private set
|
||||
var fish: String? = null
|
||||
private set
|
||||
|
||||
fun bread(bread: String) = apply { this.bread = bread }
|
||||
|
||||
fun condiments(condiments: String) = apply { this.condiments = condiments }
|
||||
|
||||
fun meat(meat: String) = apply { this.meat = meat }
|
||||
|
||||
fun fish(fish: String) = apply { this.fish = fish }
|
||||
|
||||
fun build() = FoodOrder(this)
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package com.baeldung.builder
|
||||
|
||||
class FoodOrderApply {
|
||||
var bread: String? = null
|
||||
var condiments: String? = null
|
||||
var meat: String? = null
|
||||
var fish: String? = null
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package com.baeldung.builder
|
||||
|
||||
data class FoodOrderNamed(
|
||||
val bread: String? = null,
|
||||
val condiments: String? = null,
|
||||
val meat: String? = null,
|
||||
val fish: String? = null)
|
@ -0,0 +1,139 @@
|
||||
package com.baeldung.builder
|
||||
|
||||
import org.junit.jupiter.api.Assertions
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
internal class BuilderPatternUnitTest {
|
||||
|
||||
@Test
|
||||
fun whenBuildingFoodOrderSettingValues_thenFieldsNotNull() {
|
||||
|
||||
val foodOrder = FoodOrder.Builder()
|
||||
.bread("white bread")
|
||||
.meat("bacon")
|
||||
.fish("salmon")
|
||||
.condiments("olive oil")
|
||||
.build()
|
||||
|
||||
Assertions.assertNotNull(foodOrder.bread)
|
||||
Assertions.assertNotNull(foodOrder.meat)
|
||||
Assertions.assertNotNull(foodOrder.condiments)
|
||||
Assertions.assertNotNull(foodOrder.fish)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenBuildingFoodOrderSettingValues_thenFieldsContainsValues() {
|
||||
|
||||
val foodOrder = FoodOrder.Builder()
|
||||
.bread("white bread")
|
||||
.meat("bacon")
|
||||
.fish("salmon")
|
||||
.condiments("olive oil")
|
||||
.build()
|
||||
|
||||
Assertions.assertEquals("white bread", foodOrder.bread)
|
||||
Assertions.assertEquals("bacon", foodOrder.meat)
|
||||
Assertions.assertEquals("olive oil", foodOrder.condiments)
|
||||
Assertions.assertEquals("salmon", foodOrder.fish)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenBuildingFoodOrderWithoutSettingValues_thenFieldsNull() {
|
||||
|
||||
val foodOrder = FoodOrder.Builder()
|
||||
.build()
|
||||
|
||||
Assertions.assertNull(foodOrder.bread)
|
||||
Assertions.assertNull(foodOrder.meat)
|
||||
Assertions.assertNull(foodOrder.condiments)
|
||||
Assertions.assertNull(foodOrder.fish)
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
fun whenBuildingFoodOrderNamedSettingValues_thenFieldsNotNull() {
|
||||
|
||||
val foodOrder = FoodOrderNamed(
|
||||
meat = "bacon",
|
||||
fish = "salmon",
|
||||
condiments = "olive oil",
|
||||
bread = "white bread"
|
||||
)
|
||||
|
||||
Assertions.assertNotNull(foodOrder.bread)
|
||||
Assertions.assertNotNull(foodOrder.meat)
|
||||
Assertions.assertNotNull(foodOrder.condiments)
|
||||
Assertions.assertNotNull(foodOrder.fish)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenBuildingFoodOrderNamedSettingValues_thenFieldsContainsValues() {
|
||||
|
||||
val foodOrder = FoodOrderNamed(
|
||||
meat = "bacon",
|
||||
fish = "salmon",
|
||||
condiments = "olive oil",
|
||||
bread = "white bread"
|
||||
)
|
||||
|
||||
Assertions.assertEquals("white bread", foodOrder.bread)
|
||||
Assertions.assertEquals("bacon", foodOrder.meat)
|
||||
Assertions.assertEquals("olive oil", foodOrder.condiments)
|
||||
Assertions.assertEquals("salmon", foodOrder.fish)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenBuildingFoodOrderNamedWithoutSettingValues_thenFieldsNull() {
|
||||
|
||||
val foodOrder = FoodOrderNamed()
|
||||
|
||||
Assertions.assertNull(foodOrder.bread)
|
||||
Assertions.assertNull(foodOrder.meat)
|
||||
Assertions.assertNull(foodOrder.condiments)
|
||||
Assertions.assertNull(foodOrder.fish)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenBuildingFoodOrderApplySettingValues_thenFieldsNotNull() {
|
||||
|
||||
val foodOrder = FoodOrderApply().apply {
|
||||
meat = "bacon"
|
||||
fish = "salmon"
|
||||
condiments = "olive oil"
|
||||
bread = "white bread"
|
||||
}
|
||||
|
||||
Assertions.assertNotNull(foodOrder.bread)
|
||||
Assertions.assertNotNull(foodOrder.meat)
|
||||
Assertions.assertNotNull(foodOrder.condiments)
|
||||
Assertions.assertNotNull(foodOrder.fish)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenBuildingFoodOrderApplySettingValues_thenFieldsContainsValues() {
|
||||
|
||||
val foodOrder = FoodOrderApply().apply {
|
||||
meat = "bacon"
|
||||
fish = "salmon"
|
||||
condiments = "olive oil"
|
||||
bread = "white bread"
|
||||
}
|
||||
|
||||
Assertions.assertEquals("white bread", foodOrder.bread)
|
||||
Assertions.assertEquals("bacon", foodOrder.meat)
|
||||
Assertions.assertEquals("olive oil", foodOrder.condiments)
|
||||
Assertions.assertEquals("salmon", foodOrder.fish)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenBuildingFoodOrderApplyWithoutSettingValues_thenFieldsNull() {
|
||||
|
||||
val foodOrder = FoodOrderApply()
|
||||
|
||||
Assertions.assertNull(foodOrder.bread)
|
||||
Assertions.assertNull(foodOrder.meat)
|
||||
Assertions.assertNull(foodOrder.condiments)
|
||||
Assertions.assertNull(foodOrder.fish)
|
||||
}
|
||||
|
||||
}
|
@ -1,3 +1,4 @@
|
||||
## Relevant articles:
|
||||
|
||||
- [Microbenchmarking with Java](http://www.baeldung.com/java-microbenchmark-harness)
|
||||
|
||||
|
9
libraries-server/.gitignore
vendored
Normal file
9
libraries-server/.gitignore
vendored
Normal file
@ -0,0 +1,9 @@
|
||||
*.class
|
||||
|
||||
# Folders #
|
||||
/gensrc
|
||||
/target
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
/bin/
|
19
libraries-server/pom.xml
Normal file
19
libraries-server/pom.xml
Normal file
@ -0,0 +1,19 @@
|
||||
<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>libraries-server</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.paho</groupId>
|
||||
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
|
||||
<version>1.2.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
@ -778,13 +778,6 @@
|
||||
<version>${snakeyaml.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.eclipse.paho</groupId>
|
||||
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
|
||||
<version>1.2.0</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
</dependencies>
|
||||
|
||||
<repositories>
|
||||
|
@ -0,0 +1,16 @@
|
||||
package com.baeldung.slf4j;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class SLF4JLogExceptions {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Logger logger = LoggerFactory.getLogger(SLF4JLogExceptions.class);
|
||||
|
||||
logger.error("An exception occurred!");
|
||||
logger.error("An exception occurred!", new Exception("Custom exception"));
|
||||
logger.error("{}, {}! An exception occurred!", "Hello", "World", new Exception("Custom exception"));
|
||||
}
|
||||
|
||||
}
|
154
pom.xml
154
pom.xml
@ -197,7 +197,7 @@
|
||||
</extensions>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<!--This plugin's configuration is used to store Eclipse m2e settings
|
||||
<!--This plugin's configuration is used to store Eclipse m2e settings
|
||||
only. It has no influence on the Maven build itself. -->
|
||||
<plugin>
|
||||
<groupId>org.eclipse.m2e</groupId>
|
||||
@ -551,7 +551,9 @@
|
||||
<module>apache-meecrowave</module>
|
||||
<module>spring-reactive-kotlin</module>
|
||||
<module>jnosql</module>
|
||||
<module>testing-modules/junit-abstract</module>
|
||||
<module>testing-modules/junit-abstract</module>
|
||||
<module>sse-jaxrs</module>
|
||||
<module>spring-boot-angular-ecommerce</module>
|
||||
</modules>
|
||||
|
||||
</profile>
|
||||
@ -600,35 +602,35 @@
|
||||
|
||||
<!-- <module>core-java-9</module> --> <!-- Commented because we have still not upgraded to java 9 -->
|
||||
|
||||
<!-- <module>asm</module> <module>atomix</module> <module>apache-cayenne</module>
|
||||
<module>aws</module> <module>aws-lambda</module> <module>akka-streams</module>
|
||||
<module>algorithms</module> <module>annotations</module> <module>apache-cxf</module>
|
||||
<module>apache-fop</module> <module>apache-poi</module> <module>apache-tika</module>
|
||||
<module>apache-thrift</module> <module>apache-curator</module> <module>apache-zookeeper</module>
|
||||
<module>apache-opennlp</module> <module>autovalue</module> <module>axon</module>
|
||||
<module>azure</module> <module>bootique</module> <module>cdi</module> <module>core-java</module>
|
||||
<module>core-java-collections</module> <module>core-java-io</module> <module>core-java-8</module>
|
||||
<module>core-kotlin</module> <module>core-groovy</module> <module>core-java-concurrency</module>
|
||||
<module>couchbase</module> <module>deltaspike</module> <module>dozer</module>
|
||||
<module>ethereum</module> <module>ejb</module> <module>feign</module> <module>flips</module>
|
||||
<module>geotools</module> <module>testing-modules/groovy-spock</module> <module>testing-modules/gatling</module>
|
||||
<module>google-cloud</module> <module>google-web-toolkit</module> <module>gson</module>
|
||||
<module>guava</module> <module>guava-modules/guava-18</module> <module>guava-modules/guava-19</module>
|
||||
<module>guava-modules/guava-21</module> <module>guice</module> <module>disruptor</module>
|
||||
<module>spring-static-resources</module> <module>hazelcast</module> <module>hbase</module>
|
||||
<module>hibernate5</module> <module>httpclient</module> <module>hystrix</module>
|
||||
<module>image-processing</module> <module>immutables</module> <module>influxdb</module>
|
||||
<module>jackson</module> <module>persistence-modules/java-cassandra</module>
|
||||
<module>vavr</module> <module>java-lite</module> <module>java-numbers</module>
|
||||
<module>java-rmi</module> <module>java-vavr-stream</module> <module>javax-servlets</module>
|
||||
<module>javaxval</module> <module>jaxb</module> <module>javafx</module> <module>jgroups</module>
|
||||
<module>jee-7</module> <module>jhipster/jhipster-monolithic</module> <module>jjwt</module>
|
||||
<module>jpa-storedprocedure</module> <module>jsf</module> <module>json-path</module>
|
||||
<module>json</module> <module>jsoup</module> <module>testing-modules/junit-5</module>
|
||||
<module>jws</module> <module>libraries-data</module> <module>linkrest</module>
|
||||
<module>logging-modules/log-mdc</module> <module>logging-modules/log4j</module>
|
||||
<module>logging-modules/log4j2</module> <module>logging-modules/logback</module>
|
||||
<module>lombok</module> <module>mapstruct</module> <module>metrics</module>
|
||||
<!-- <module>asm</module> <module>atomix</module> <module>apache-cayenne</module>
|
||||
<module>aws</module> <module>aws-lambda</module> <module>akka-streams</module>
|
||||
<module>algorithms</module> <module>annotations</module> <module>apache-cxf</module>
|
||||
<module>apache-fop</module> <module>apache-poi</module> <module>apache-tika</module>
|
||||
<module>apache-thrift</module> <module>apache-curator</module> <module>apache-zookeeper</module>
|
||||
<module>apache-opennlp</module> <module>autovalue</module> <module>axon</module>
|
||||
<module>azure</module> <module>bootique</module> <module>cdi</module> <module>core-java</module>
|
||||
<module>core-java-collections</module> <module>core-java-io</module> <module>core-java-8</module>
|
||||
<module>core-kotlin</module> <module>core-groovy</module> <module>core-java-concurrency</module>
|
||||
<module>couchbase</module> <module>deltaspike</module> <module>dozer</module>
|
||||
<module>ethereum</module> <module>ejb</module> <module>feign</module> <module>flips</module>
|
||||
<module>geotools</module> <module>testing-modules/groovy-spock</module> <module>testing-modules/gatling</module>
|
||||
<module>google-cloud</module> <module>google-web-toolkit</module> <module>gson</module>
|
||||
<module>guava</module> <module>guava-modules/guava-18</module> <module>guava-modules/guava-19</module>
|
||||
<module>guava-modules/guava-21</module> <module>guice</module> <module>disruptor</module>
|
||||
<module>spring-static-resources</module> <module>hazelcast</module> <module>hbase</module>
|
||||
<module>hibernate5</module> <module>httpclient</module> <module>hystrix</module>
|
||||
<module>image-processing</module> <module>immutables</module> <module>influxdb</module>
|
||||
<module>jackson</module> <module>persistence-modules/java-cassandra</module>
|
||||
<module>vavr</module> <module>java-lite</module> <module>java-numbers</module>
|
||||
<module>java-rmi</module> <module>java-vavr-stream</module> <module>javax-servlets</module>
|
||||
<module>javaxval</module> <module>jaxb</module> <module>javafx</module> <module>jgroups</module>
|
||||
<module>jee-7</module> <module>jhipster/jhipster-monolithic</module> <module>jjwt</module>
|
||||
<module>jpa-storedprocedure</module> <module>jsf</module> <module>json-path</module>
|
||||
<module>json</module> <module>jsoup</module> <module>testing-modules/junit-5</module>
|
||||
<module>jws</module> <module>libraries-data</module> <module>linkrest</module>
|
||||
<module>logging-modules/log-mdc</module> <module>logging-modules/log4j</module>
|
||||
<module>logging-modules/log4j2</module> <module>logging-modules/logback</module>
|
||||
<module>lombok</module> <module>mapstruct</module> <module>metrics</module>
|
||||
<module>maven</module> <module>mesos-marathon</module> <module>msf4j</module> -->
|
||||
|
||||
<!-- group 1 - OK, 27min, 7911Kb log, 8 failusres -->
|
||||
@ -672,7 +674,7 @@
|
||||
<module>spring-apache-camel</module>
|
||||
<module>spring-batch</module>
|
||||
<module>testing-modules/junit-abstract</module>
|
||||
|
||||
<module>jmh</module>
|
||||
|
||||
<!-- group 2 - Pass, 11-16 min, 42 test failures, 4,020 KB -->
|
||||
|
||||
@ -751,37 +753,37 @@
|
||||
|
||||
<!-- group 4 -->
|
||||
|
||||
<!-- <module>spring-security-acl</module> <module>spring-security-cache-control</module>
|
||||
<module>spring-security-client/spring-security-jsp-authentication</module>
|
||||
<module>spring-security-client/spring-security-jsp-authorize</module> <module>spring-security-client/spring-security-jsp-config</module>
|
||||
<module>spring-security-client/spring-security-mvc</module> <module>spring-security-client/spring-security-thymeleaf-authentication</module>
|
||||
<module>spring-security-client/spring-security-thymeleaf-authorize</module>
|
||||
<module>spring-security-client/spring-security-thymeleaf-config</module>
|
||||
<module>spring-security-core</module> <module>spring-security-mvc-boot</module>
|
||||
<module>spring-security-mvc-custom</module> <module>spring-security-mvc-digest-auth</module>
|
||||
<module>spring-security-mvc-ldap</module> <module>spring-security-mvc-login</module>
|
||||
<module>spring-security-mvc-persisted-remember-me</module> <module>spring-security-mvc-session</module>
|
||||
<module>spring-security-mvc-socket</module> <module>spring-security-openid</module>
|
||||
<module>spring-security-react</module> <module>spring-security-rest-basic-auth</module>
|
||||
<module>spring-security-rest-custom</module> <module>spring-security-rest</module>
|
||||
<module>spring-security-sso</module> <module>spring-security-x509</module>
|
||||
<module>spring-session</module> <module>spring-sleuth</module> <module>spring-social-login</module>
|
||||
<module>spring-spel</module> <module>spring-state-machine</module> <module>spring-thymeleaf</module>
|
||||
<module>spring-userservice</module> <module>spring-zuul</module> <module>spring-reactor</module>
|
||||
<module>spring-vertx</module> <module>spring-jinq</module> <module>spring-rest-embedded-tomcat</module>
|
||||
<module>testing-modules/testing</module> <module>testing-modules/testng</module>
|
||||
<module>video-tutorials</module> <module>xml</module> <module>xmlunit-2</module>
|
||||
<module>struts-2</module> <module>apache-velocity</module> <module>apache-solrj</module>
|
||||
<module>rabbitmq</module> <module>vertx</module> <module>persistence-modules/spring-data-gemfire</module>
|
||||
<module>mybatis</module> <module>spring-drools</module> <module>drools</module>
|
||||
<module>persistence-modules/liquibase</module> <module>spring-boot-property-exp</module>
|
||||
<module>testing-modules/mockserver</module> <module>testing-modules/test-containers</module>
|
||||
<module>undertow</module> <module>vertx-and-rxjava</module> <module>saas</module>
|
||||
<module>deeplearning4j</module> <module>lucene</module> <module>vraptor</module>
|
||||
<module>persistence-modules/java-cockroachdb</module> <module>spring-security-thymeleaf</module>
|
||||
<module>persistence-modules/java-jdbi</module> <module>jersey</module> <module>java-spi</module>
|
||||
<module>performance-tests</module> <module>twilio</module> <module>spring-boot-ctx-fluent</module>
|
||||
<module>java-ee-8-security-api</module> <module>spring-webflux-amqp</module>
|
||||
<!-- <module>spring-security-acl</module> <module>spring-security-cache-control</module>
|
||||
<module>spring-security-client/spring-security-jsp-authentication</module>
|
||||
<module>spring-security-client/spring-security-jsp-authorize</module> <module>spring-security-client/spring-security-jsp-config</module>
|
||||
<module>spring-security-client/spring-security-mvc</module> <module>spring-security-client/spring-security-thymeleaf-authentication</module>
|
||||
<module>spring-security-client/spring-security-thymeleaf-authorize</module>
|
||||
<module>spring-security-client/spring-security-thymeleaf-config</module>
|
||||
<module>spring-security-core</module> <module>spring-security-mvc-boot</module>
|
||||
<module>spring-security-mvc-custom</module> <module>spring-security-mvc-digest-auth</module>
|
||||
<module>spring-security-mvc-ldap</module> <module>spring-security-mvc-login</module>
|
||||
<module>spring-security-mvc-persisted-remember-me</module> <module>spring-security-mvc-session</module>
|
||||
<module>spring-security-mvc-socket</module> <module>spring-security-openid</module>
|
||||
<module>spring-security-react</module> <module>spring-security-rest-basic-auth</module>
|
||||
<module>spring-security-rest-custom</module> <module>spring-security-rest</module>
|
||||
<module>spring-security-sso</module> <module>spring-security-x509</module>
|
||||
<module>spring-session</module> <module>spring-sleuth</module> <module>spring-social-login</module>
|
||||
<module>spring-spel</module> <module>spring-state-machine</module> <module>spring-thymeleaf</module>
|
||||
<module>spring-userservice</module> <module>spring-zuul</module> <module>spring-reactor</module>
|
||||
<module>spring-vertx</module> <module>spring-jinq</module> <module>spring-rest-embedded-tomcat</module>
|
||||
<module>testing-modules/testing</module> <module>testing-modules/testng</module>
|
||||
<module>video-tutorials</module> <module>xml</module> <module>xmlunit-2</module>
|
||||
<module>struts-2</module> <module>apache-velocity</module> <module>apache-solrj</module>
|
||||
<module>rabbitmq</module> <module>vertx</module> <module>persistence-modules/spring-data-gemfire</module>
|
||||
<module>mybatis</module> <module>spring-drools</module> <module>drools</module>
|
||||
<module>persistence-modules/liquibase</module> <module>spring-boot-property-exp</module>
|
||||
<module>testing-modules/mockserver</module> <module>testing-modules/test-containers</module>
|
||||
<module>undertow</module> <module>vertx-and-rxjava</module> <module>saas</module>
|
||||
<module>deeplearning4j</module> <module>lucene</module> <module>vraptor</module>
|
||||
<module>persistence-modules/java-cockroachdb</module> <module>spring-security-thymeleaf</module>
|
||||
<module>persistence-modules/java-jdbi</module> <module>jersey</module> <module>java-spi</module>
|
||||
<module>performance-tests</module> <module>twilio</module> <module>spring-boot-ctx-fluent</module>
|
||||
<module>java-ee-8-security-api</module> <module>spring-webflux-amqp</module>
|
||||
<module>antlr</module> <module>maven-archetype</module> <module>apache-meecrowave</module> -->
|
||||
|
||||
<!-- group 4 - OK, 12 min, 3,961 KB log, 12 failed tests -->
|
||||
@ -794,7 +796,7 @@
|
||||
|
||||
<profile>
|
||||
<id>integration-lite</id>
|
||||
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
@ -833,7 +835,7 @@
|
||||
<module>parent-spring-4</module>
|
||||
<module>parent-spring-5</module>
|
||||
<module>parent-java</module>
|
||||
|
||||
|
||||
<module>asm</module>
|
||||
<module>atomix</module>
|
||||
<module>apache-cayenne</module>
|
||||
@ -860,7 +862,7 @@
|
||||
<module>core-java-io</module>
|
||||
<module>core-java-8</module>
|
||||
<module>core-groovy</module>
|
||||
|
||||
|
||||
<module>couchbase</module>
|
||||
<module>deltaspike</module>
|
||||
<module>dozer</module>
|
||||
@ -1077,16 +1079,16 @@
|
||||
<module>antlr</module>
|
||||
<module>maven-archetype</module>
|
||||
<module>apache-meecrowave</module>
|
||||
<module>testing-modules/junit-abstract</module>
|
||||
|
||||
<module>testing-modules/junit-abstract</module>
|
||||
|
||||
<module>spring-hibernate4</module>
|
||||
<module>xml</module>
|
||||
<module>vertx</module>
|
||||
<module>metrics</module>
|
||||
<module>httpclient</module>
|
||||
|
||||
|
||||
<!-- problematic -->
|
||||
<!--
|
||||
<!--
|
||||
<module>ejb</module>
|
||||
<module>persistence-modules/java-cassandra</module>
|
||||
<module>persistence-modules/spring-data-cassandra</module>
|
||||
@ -1096,9 +1098,9 @@
|
||||
|
||||
<module>jmeter</module>
|
||||
-->
|
||||
|
||||
|
||||
<!-- heavy -->
|
||||
<!--
|
||||
<!--
|
||||
<module>libraries</module>
|
||||
<module>geotools</module>
|
||||
<module>jhipster/jhipster-monolithic</module>
|
||||
@ -1112,7 +1114,7 @@
|
||||
<module>spring-security-mvc-custom</module>
|
||||
<module>core-java-concurrency</module>
|
||||
-->
|
||||
|
||||
|
||||
<!-- 30:32 min -->
|
||||
</modules>
|
||||
|
||||
@ -1120,7 +1122,7 @@
|
||||
|
||||
<profile>
|
||||
<id>integration-heavy</id>
|
||||
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
@ -1159,7 +1161,7 @@
|
||||
<module>parent-spring-4</module>
|
||||
<module>parent-spring-5</module>
|
||||
<module>parent-java</module>
|
||||
|
||||
|
||||
<module>libraries</module>
|
||||
<module>geotools</module>
|
||||
<module>jhipster/jhipster-monolithic</module>
|
||||
@ -1237,4 +1239,4 @@
|
||||
<!-- <maven-pmd-plugin.version>3.9.0</maven-pmd-plugin.version> -->
|
||||
<maven-pmd-plugin.version>3.8</maven-pmd-plugin.version>
|
||||
</properties>
|
||||
</project>
|
||||
</project>
|
||||
|
@ -1,2 +1,3 @@
|
||||
### Relevant Articles:
|
||||
- [Spring Boot and Kotlin](http://www.baeldung.com/spring-boot-kotlin)
|
||||
- [Spring MVC Streaming and SSE Request Processing](http://www.baeldung.com/spring-mvc-sse-streams)
|
||||
|
@ -10,7 +10,7 @@ import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
@Controller
|
||||
public class SseEmitterController {
|
||||
private ExecutorService nonBlockingService = Executors.newSingleThreadExecutor();
|
||||
private ExecutorService nonBlockingService = Executors.newCachedThreadPool();
|
||||
|
||||
@GetMapping(Constants.API_SSE)
|
||||
public SseEmitter handleSse() {
|
||||
@ -29,4 +29,4 @@ public class SseEmitterController {
|
||||
return emitter;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -1,7 +1,9 @@
|
||||
package com.baeldung.oauth2extractors;
|
||||
|
||||
import org.apache.logging.log4j.util.Strings;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.core.env.AbstractEnvironment;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
@ -9,6 +11,13 @@ import org.springframework.web.bind.annotation.RequestMapping;
|
||||
@Controller
|
||||
public class ExtractorsApplication {
|
||||
public static void main(String[] args) {
|
||||
if (Strings.isEmpty(System.getProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME))) {
|
||||
/*System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME,
|
||||
"oauth2-extractors-baeldung");*/
|
||||
System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME,
|
||||
"oauth2-extractors-github");
|
||||
}
|
||||
|
||||
SpringApplication.run(ExtractorsApplication.class, args);
|
||||
}
|
||||
|
||||
|
@ -1,18 +1,19 @@
|
||||
package com.baeldung.oauth2extractors.configuration;
|
||||
|
||||
import com.baeldung.oauth2extractors.extractor.CustomAuthoritiesExtractor;
|
||||
import com.baeldung.oauth2extractors.extractor.CustomPrincipalExtractor;
|
||||
import com.baeldung.oauth2extractors.extractor.custom.BaeldungAuthoritiesExtractor;
|
||||
import com.baeldung.oauth2extractors.extractor.custom.BaeldungPrincipalExtractor;
|
||||
import com.baeldung.oauth2extractors.extractor.github.GithubAuthoritiesExtractor;
|
||||
import com.baeldung.oauth2extractors.extractor.github.GithubPrincipalExtractor;
|
||||
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
|
||||
import org.springframework.boot.autoconfigure.security.oauth2.resource.AuthoritiesExtractor;
|
||||
import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
|
||||
@Configuration
|
||||
@PropertySource("application-oauth2-extractors.properties")
|
||||
@EnableOAuth2Sso
|
||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@ -29,12 +30,26 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PrincipalExtractor principalExtractor() {
|
||||
return new CustomPrincipalExtractor();
|
||||
@Profile("oauth2-extractors-baeldung")
|
||||
public PrincipalExtractor baeldungPrincipalExtractor() {
|
||||
return new BaeldungPrincipalExtractor();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthoritiesExtractor authoritiesExtractor() {
|
||||
return new CustomAuthoritiesExtractor();
|
||||
@Profile("oauth2-extractors-baeldung")
|
||||
public AuthoritiesExtractor baeldungAuthoritiesExtractor() {
|
||||
return new BaeldungAuthoritiesExtractor();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Profile("oauth2-extractors-github")
|
||||
public PrincipalExtractor githubPrincipalExtractor() {
|
||||
return new GithubPrincipalExtractor();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Profile("oauth2-extractors-github")
|
||||
public AuthoritiesExtractor githubAuthoritiesExtractor() {
|
||||
return new GithubAuthoritiesExtractor();
|
||||
}
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
package com.baeldung.oauth2extractors.extractor.custom;
|
||||
|
||||
import org.springframework.boot.autoconfigure.security.oauth2.resource.AuthoritiesExtractor;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.AuthorityUtils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class BaeldungAuthoritiesExtractor implements AuthoritiesExtractor {
|
||||
|
||||
@Override
|
||||
public List<GrantedAuthority> extractAuthorities(Map<String, Object> map) {
|
||||
return AuthorityUtils
|
||||
.commaSeparatedStringToAuthorityList(asAuthorities(map));
|
||||
}
|
||||
|
||||
private String asAuthorities(Map<String, Object> map) {
|
||||
List<String> authorities = new ArrayList<>();
|
||||
authorities.add("BAELDUNG_USER");
|
||||
List<LinkedHashMap<String, String>> authz = (List<LinkedHashMap<String, String>>) map.get("authorities");
|
||||
for (LinkedHashMap<String, String> entry : authz) {
|
||||
authorities.add(entry.get("authority"));
|
||||
}
|
||||
return String.join(",", authorities);
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.oauth2extractors.extractor.custom;
|
||||
|
||||
import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class BaeldungPrincipalExtractor implements PrincipalExtractor {
|
||||
|
||||
@Override
|
||||
public Object extractPrincipal(Map<String, Object> map) {
|
||||
return map.get("name");
|
||||
}
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.oauth2extractors.extractor;
|
||||
package com.baeldung.oauth2extractors.extractor.github;
|
||||
|
||||
import org.springframework.boot.autoconfigure.security.oauth2.resource.AuthoritiesExtractor;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
@ -9,7 +9,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
public class CustomAuthoritiesExtractor implements AuthoritiesExtractor {
|
||||
public class GithubAuthoritiesExtractor implements AuthoritiesExtractor {
|
||||
private List<GrantedAuthority> GITHUB_FREE_AUTHORITIES = AuthorityUtils
|
||||
.commaSeparatedStringToAuthorityList("GITHUB_USER,GITHUB_USER_FREE");
|
||||
private List<GrantedAuthority> GITHUB_SUBSCRIBED_AUTHORITIES = AuthorityUtils
|
@ -1,10 +1,10 @@
|
||||
package com.baeldung.oauth2extractors.extractor;
|
||||
package com.baeldung.oauth2extractors.extractor.github;
|
||||
|
||||
import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class CustomPrincipalExtractor implements PrincipalExtractor {
|
||||
public class GithubPrincipalExtractor implements PrincipalExtractor {
|
||||
|
||||
@Override
|
||||
public Object extractPrincipal(Map<String, Object> map) {
|
@ -0,0 +1,6 @@
|
||||
server.port=8082
|
||||
security.oauth2.client.client-id=SampleClientId
|
||||
security.oauth2.client.client-secret=secret
|
||||
security.oauth2.client.access-token-uri=http://localhost:8081/auth/oauth/token
|
||||
security.oauth2.client.user-authorization-uri=http://localhost:8081/auth/oauth/authorize
|
||||
security.oauth2.resource.user-info-uri=http://localhost:8081/auth/user/me
|
@ -1,3 +1,4 @@
|
||||
server.port=8082
|
||||
security.oauth2.client.client-id=89a7c4facbb3434d599d
|
||||
security.oauth2.client.client-secret=9b3b08e4a340bd20e866787e4645b54f73d74b6a
|
||||
security.oauth2.client.access-token-uri=https://github.com/login/oauth/access_token
|
@ -6,6 +6,7 @@ import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
@ -21,6 +22,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = ExtractorsApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
@ContextConfiguration(classes = {SecurityConfig.class})
|
||||
@ActiveProfiles("oauth2-extractors-github")
|
||||
public class ExtractorsUnitTest {
|
||||
|
||||
@Autowired
|
||||
|
2
spring-boot-angular-ecommerce/README.md
Normal file
2
spring-boot-angular-ecommerce/README.md
Normal file
@ -0,0 +1,2 @@
|
||||
### Relevant Articles:
|
||||
- [A Simple E-Commerce Implementation with Spring]()
|
84
spring-boot-angular-ecommerce/pom.xml
Normal file
84
spring-boot-angular-ecommerce/pom.xml
Normal file
@ -0,0 +1,84 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>spring-boot-angular-ecommerce</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>spring-boot-angular-ecommerce</name>
|
||||
<description>Spring Boot Angular E-commerce Appliciation</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-dependencies</artifactId>
|
||||
<version>${spring.boot.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
<version>${spring.boot.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
<version>${spring.boot.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-devtools</artifactId>
|
||||
<version>${spring.boot.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>1.4.197</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||
<version>2.9.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<version>${spring.boot.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot-maven-plugin.version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
<spring.boot.version>2.0.3.RELEASE</spring.boot.version>
|
||||
<spring-boot-maven-plugin.version>2.0.4.RELEASE</spring-boot-maven-plugin.version>
|
||||
</properties>
|
||||
</project>
|
@ -0,0 +1,13 @@
|
||||
# Editor configuration, see http://editorconfig.org
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.md]
|
||||
max_line_length = off
|
||||
trim_trailing_whitespace = false
|
27
spring-boot-angular-ecommerce/src/main/frontend/README.md
Normal file
27
spring-boot-angular-ecommerce/src/main/frontend/README.md
Normal file
@ -0,0 +1,27 @@
|
||||
# Frontend
|
||||
|
||||
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 6.0.8.
|
||||
|
||||
## Development server
|
||||
|
||||
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
|
||||
|
||||
## Code scaffolding
|
||||
|
||||
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
|
||||
|
||||
## Build
|
||||
|
||||
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build.
|
||||
|
||||
## Running unit tests
|
||||
|
||||
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
|
||||
|
||||
## Running end-to-end tests
|
||||
|
||||
Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
|
||||
|
||||
## Further help
|
||||
|
||||
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
|
128
spring-boot-angular-ecommerce/src/main/frontend/angular.json
Normal file
128
spring-boot-angular-ecommerce/src/main/frontend/angular.json
Normal file
@ -0,0 +1,128 @@
|
||||
{
|
||||
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
|
||||
"version": 1,
|
||||
"newProjectRoot": "projects",
|
||||
"projects": {
|
||||
"frontend": {
|
||||
"root": "",
|
||||
"sourceRoot": "src",
|
||||
"projectType": "application",
|
||||
"prefix": "app",
|
||||
"schematics": {},
|
||||
"architect": {
|
||||
"build": {
|
||||
"builder": "@angular-devkit/build-angular:browser",
|
||||
"options": {
|
||||
"outputPath": "dist/frontend",
|
||||
"index": "src/index.html",
|
||||
"main": "src/main.ts",
|
||||
"polyfills": "src/polyfills.ts",
|
||||
"tsConfig": "src/tsconfig.app.json",
|
||||
"assets": [
|
||||
"src/favicon.ico",
|
||||
"src/assets"
|
||||
],
|
||||
"styles": [
|
||||
"node_modules/bootstrap/dist/css/bootstrap.min.css",
|
||||
"src/styles.css"
|
||||
],
|
||||
"scripts": []
|
||||
},
|
||||
"configurations": {
|
||||
"production": {
|
||||
"fileReplacements": [
|
||||
{
|
||||
"replace": "src/environments/environment.ts",
|
||||
"with": "src/environments/environment.prod.ts"
|
||||
}
|
||||
],
|
||||
"optimization": true,
|
||||
"outputHashing": "all",
|
||||
"sourceMap": false,
|
||||
"extractCss": true,
|
||||
"namedChunks": false,
|
||||
"aot": true,
|
||||
"extractLicenses": true,
|
||||
"vendorChunk": false,
|
||||
"buildOptimizer": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"serve": {
|
||||
"builder": "@angular-devkit/build-angular:dev-server",
|
||||
"options": {
|
||||
"browserTarget": "frontend:build"
|
||||
},
|
||||
"configurations": {
|
||||
"production": {
|
||||
"browserTarget": "frontend:build:production"
|
||||
}
|
||||
}
|
||||
},
|
||||
"extract-i18n": {
|
||||
"builder": "@angular-devkit/build-angular:extract-i18n",
|
||||
"options": {
|
||||
"browserTarget": "frontend:build"
|
||||
}
|
||||
},
|
||||
"test": {
|
||||
"builder": "@angular-devkit/build-angular:karma",
|
||||
"options": {
|
||||
"main": "src/test.ts",
|
||||
"polyfills": "src/polyfills.ts",
|
||||
"tsConfig": "src/tsconfig.spec.json",
|
||||
"karmaConfig": "src/karma.conf.js",
|
||||
"styles": [
|
||||
"src/styles.css"
|
||||
],
|
||||
"scripts": [],
|
||||
"assets": [
|
||||
"src/favicon.ico",
|
||||
"src/assets"
|
||||
]
|
||||
}
|
||||
},
|
||||
"lint": {
|
||||
"builder": "@angular-devkit/build-angular:tslint",
|
||||
"options": {
|
||||
"tsConfig": [
|
||||
"src/tsconfig.app.json",
|
||||
"src/tsconfig.spec.json"
|
||||
],
|
||||
"exclude": [
|
||||
"**/node_modules/**"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"frontend-e2e": {
|
||||
"root": "e2e/",
|
||||
"projectType": "application",
|
||||
"architect": {
|
||||
"e2e": {
|
||||
"builder": "@angular-devkit/build-angular:protractor",
|
||||
"options": {
|
||||
"protractorConfig": "e2e/protractor.conf.js",
|
||||
"devServerTarget": "frontend:serve"
|
||||
},
|
||||
"configurations": {
|
||||
"production": {
|
||||
"devServerTarget": "frontend:serve:production"
|
||||
}
|
||||
}
|
||||
},
|
||||
"lint": {
|
||||
"builder": "@angular-devkit/build-angular:tslint",
|
||||
"options": {
|
||||
"tsConfig": "e2e/tsconfig.e2e.json",
|
||||
"exclude": [
|
||||
"**/node_modules/**"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"defaultProject": "frontend"
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
// Protractor configuration file, see link for more information
|
||||
// https://github.com/angular/protractor/blob/master/lib/config.ts
|
||||
|
||||
const { SpecReporter } = require('jasmine-spec-reporter');
|
||||
|
||||
exports.config = {
|
||||
allScriptsTimeout: 11000,
|
||||
specs: [
|
||||
'./src/**/*.e2e-spec.ts'
|
||||
],
|
||||
capabilities: {
|
||||
'browserName': 'chrome'
|
||||
},
|
||||
directConnect: true,
|
||||
baseUrl: 'http://localhost:4200/',
|
||||
framework: 'jasmine',
|
||||
jasmineNodeOpts: {
|
||||
showColors: true,
|
||||
defaultTimeoutInterval: 30000,
|
||||
print: function() {}
|
||||
},
|
||||
onPrepare() {
|
||||
require('ts-node').register({
|
||||
project: require('path').join(__dirname, './tsconfig.e2e.json')
|
||||
});
|
||||
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
|
||||
}
|
||||
};
|
@ -0,0 +1,14 @@
|
||||
import { AppPage } from './app.po';
|
||||
|
||||
describe('workspace-project App', () => {
|
||||
let page: AppPage;
|
||||
|
||||
beforeEach(() => {
|
||||
page = new AppPage();
|
||||
});
|
||||
|
||||
it('should display welcome message', () => {
|
||||
page.navigateTo();
|
||||
expect(page.getParagraphText()).toEqual('Welcome to frontend!');
|
||||
});
|
||||
});
|
@ -0,0 +1,11 @@
|
||||
import { browser, by, element } from 'protractor';
|
||||
|
||||
export class AppPage {
|
||||
navigateTo() {
|
||||
return browser.get('/');
|
||||
}
|
||||
|
||||
getParagraphText() {
|
||||
return element(by.css('app-root h1')).getText();
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
{
|
||||
"extends": "../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../out-tsc/app",
|
||||
"module": "commonjs",
|
||||
"target": "es5",
|
||||
"types": [
|
||||
"jasmine",
|
||||
"jasminewd2",
|
||||
"node"
|
||||
]
|
||||
}
|
||||
}
|
10591
spring-boot-angular-ecommerce/src/main/frontend/package-lock.json
generated
Normal file
10591
spring-boot-angular-ecommerce/src/main/frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
49
spring-boot-angular-ecommerce/src/main/frontend/package.json
Normal file
49
spring-boot-angular-ecommerce/src/main/frontend/package.json
Normal file
@ -0,0 +1,49 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"version": "0.0.0",
|
||||
"scripts": {
|
||||
"ng": "ng",
|
||||
"start": "ng serve --proxy-config proxy-conf.json",
|
||||
"build": "ng build",
|
||||
"test": "ng test",
|
||||
"lint": "ng lint",
|
||||
"e2e": "ng e2e"
|
||||
},
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@angular/animations": "^6.0.3",
|
||||
"@angular/common": "^6.0.3",
|
||||
"@angular/compiler": "^6.0.3",
|
||||
"@angular/core": "^6.0.3",
|
||||
"@angular/forms": "^6.0.3",
|
||||
"@angular/http": "^6.0.3",
|
||||
"@angular/platform-browser": "^6.0.3",
|
||||
"@angular/platform-browser-dynamic": "^6.0.3",
|
||||
"@angular/router": "^6.0.3",
|
||||
"bootstrap": "^4.1.2",
|
||||
"core-js": "^2.5.4",
|
||||
"rxjs": "^6.0.0",
|
||||
"zone.js": "^0.8.26"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@angular/compiler-cli": "^6.0.3",
|
||||
"@angular-devkit/build-angular": "~0.6.8",
|
||||
"typescript": "~2.7.2",
|
||||
"@angular/cli": "~6.0.8",
|
||||
"@angular/language-service": "^6.0.3",
|
||||
"@types/jasmine": "~2.8.6",
|
||||
"@types/jasminewd2": "~2.0.3",
|
||||
"@types/node": "~8.9.4",
|
||||
"codelyzer": "~4.2.1",
|
||||
"jasmine-core": "~2.99.1",
|
||||
"jasmine-spec-reporter": "~4.2.1",
|
||||
"karma": "~1.7.1",
|
||||
"karma-chrome-launcher": "~2.2.0",
|
||||
"karma-coverage-istanbul-reporter": "~2.0.0",
|
||||
"karma-jasmine": "~1.1.1",
|
||||
"karma-jasmine-html-reporter": "^0.2.2",
|
||||
"protractor": "~5.3.0",
|
||||
"ts-node": "~5.0.1",
|
||||
"tslint": "~5.9.1"
|
||||
}
|
||||
}
|
@ -0,0 +1,6 @@
|
||||
{
|
||||
"/api": {
|
||||
"target": "http://localhost:8080",
|
||||
"secure": false
|
||||
}
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
.container {
|
||||
padding-top: 65px;
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
<div class="container">
|
||||
<app-ecommerce></app-ecommerce>
|
||||
</div>
|
@ -0,0 +1,27 @@
|
||||
import { TestBed, async } from '@angular/core/testing';
|
||||
import { AppComponent } from './app.component';
|
||||
describe('AppComponent', () => {
|
||||
beforeEach(async(() => {
|
||||
TestBed.configureTestingModule({
|
||||
declarations: [
|
||||
AppComponent
|
||||
],
|
||||
}).compileComponents();
|
||||
}));
|
||||
it('should create the app', async(() => {
|
||||
const fixture = TestBed.createComponent(AppComponent);
|
||||
const app = fixture.debugElement.componentInstance;
|
||||
expect(app).toBeTruthy();
|
||||
}));
|
||||
it(`should have as title 'app'`, async(() => {
|
||||
const fixture = TestBed.createComponent(AppComponent);
|
||||
const app = fixture.debugElement.componentInstance;
|
||||
expect(app.title).toEqual('app');
|
||||
}));
|
||||
it('should render title in a h1 tag', async(() => {
|
||||
const fixture = TestBed.createComponent(AppComponent);
|
||||
fixture.detectChanges();
|
||||
const compiled = fixture.debugElement.nativeElement;
|
||||
expect(compiled.querySelector('h1').textContent).toContain('Welcome to frontend!');
|
||||
}));
|
||||
});
|
@ -0,0 +1,12 @@
|
||||
import {Component} from '@angular/core';
|
||||
import {EcommerceService} from "./ecommerce/services/EcommerceService";
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
templateUrl: './app.component.html',
|
||||
styleUrls: ['./app.component.css'],
|
||||
providers: [EcommerceService]
|
||||
})
|
||||
export class AppComponent {
|
||||
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
import {BrowserModule} from '@angular/platform-browser';
|
||||
import {NgModule} from '@angular/core';
|
||||
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
|
||||
import {HttpClientModule} from '@angular/common/http';
|
||||
|
||||
import {AppComponent} from './app.component';
|
||||
import {EcommerceComponent} from './ecommerce/ecommerce.component';
|
||||
import {ProductsComponent} from './ecommerce/products/products.component';
|
||||
import {ShoppingCartComponent} from './ecommerce/shopping-cart/shopping-cart.component';
|
||||
import {OrdersComponent} from './ecommerce/orders/orders.component';
|
||||
import {EcommerceService} from "./ecommerce/services/EcommerceService";
|
||||
|
||||
@NgModule({
|
||||
declarations: [
|
||||
AppComponent,
|
||||
EcommerceComponent,
|
||||
ProductsComponent,
|
||||
ShoppingCartComponent,
|
||||
OrdersComponent
|
||||
],
|
||||
imports: [
|
||||
BrowserModule,
|
||||
HttpClientModule,
|
||||
FormsModule,
|
||||
ReactiveFormsModule
|
||||
],
|
||||
providers: [EcommerceService],
|
||||
bootstrap: [AppComponent]
|
||||
})
|
||||
export class AppModule {
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
|
||||
<div class="container">
|
||||
<a class="navbar-brand" href="#">Baeldung Ecommerce</a>
|
||||
<button class="navbar-toggler" type="button" data-toggle="collapse"
|
||||
data-target="#navbarResponsive" aria-controls="navbarResponsive"
|
||||
aria-expanded="false" aria-label="Toggle navigation" (click)="toggleCollapsed()">
|
||||
<span class="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
<div id="navbarResponsive" [ngClass]="{'collapse': collapsed, 'navbar-collapse': true}">
|
||||
<ul class="navbar-nav ml-auto">
|
||||
<li class="nav-item active">
|
||||
<a class="nav-link" href="#" (click)="reset()">Home
|
||||
<span class="sr-only">(current)</span>
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
<div class="row">
|
||||
<div class="col-md-9">
|
||||
<app-products #productsC [hidden]="orderFinished"></app-products>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<app-shopping-cart (onOrderFinished)=finishOrder($event) #shoppingCartC
|
||||
[hidden]="orderFinished"></app-shopping-cart>
|
||||
</div>
|
||||
<div class="col-md-6 offset-3">
|
||||
<app-orders #ordersC [hidden]="!orderFinished"></app-orders>
|
||||
</div>
|
||||
</div>
|
@ -0,0 +1,25 @@
|
||||
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
|
||||
import { EcommerceComponent } from './ecommerce.component';
|
||||
|
||||
describe('EcommerceComponent', () => {
|
||||
let component: EcommerceComponent;
|
||||
let fixture: ComponentFixture<EcommerceComponent>;
|
||||
|
||||
beforeEach(async(() => {
|
||||
TestBed.configureTestingModule({
|
||||
declarations: [ EcommerceComponent ]
|
||||
})
|
||||
.compileComponents();
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = TestBed.createComponent(EcommerceComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
});
|
@ -0,0 +1,44 @@
|
||||
import {Component, OnInit, ViewChild} from '@angular/core';
|
||||
import {ProductsComponent} from "./products/products.component";
|
||||
import {ShoppingCartComponent} from "./shopping-cart/shopping-cart.component";
|
||||
import {OrdersComponent} from "./orders/orders.component";
|
||||
|
||||
@Component({
|
||||
selector: 'app-ecommerce',
|
||||
templateUrl: './ecommerce.component.html',
|
||||
styleUrls: ['./ecommerce.component.css']
|
||||
})
|
||||
export class EcommerceComponent implements OnInit {
|
||||
private collapsed = true;
|
||||
orderFinished = false;
|
||||
|
||||
@ViewChild('productsC')
|
||||
productsC: ProductsComponent;
|
||||
|
||||
@ViewChild('shoppingCartC')
|
||||
shoppingCartC: ShoppingCartComponent;
|
||||
|
||||
@ViewChild('ordersC')
|
||||
ordersC: OrdersComponent;
|
||||
|
||||
constructor() {
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
}
|
||||
|
||||
toggleCollapsed(): void {
|
||||
this.collapsed = !this.collapsed;
|
||||
}
|
||||
|
||||
finishOrder(orderFinished: boolean) {
|
||||
this.orderFinished = orderFinished;
|
||||
}
|
||||
|
||||
reset() {
|
||||
this.orderFinished = false;
|
||||
this.productsC.reset();
|
||||
this.shoppingCartC.reset();
|
||||
this.ordersC.paid = false;
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
import {Product} from "./product.model";
|
||||
|
||||
export class ProductOrder {
|
||||
product: Product;
|
||||
quantity: number;
|
||||
|
||||
constructor(product: Product, quantity: number) {
|
||||
this.product = product;
|
||||
this.quantity = quantity;
|
||||
}
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
import {ProductOrder} from "./product-order.model";
|
||||
|
||||
export class ProductOrders {
|
||||
productOrders: ProductOrder[] = [];
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
export class Product {
|
||||
id: number;
|
||||
name: string;
|
||||
price: number;
|
||||
pictureUrl: string;
|
||||
|
||||
constructor(id: number, name: string, price: number, pictureUrl: string) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.price = price;
|
||||
this.pictureUrl = pictureUrl;
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
<h2 class="text-center">ORDER</h2>
|
||||
<ul>
|
||||
<li *ngFor="let order of orders.productOrders">
|
||||
{{ order.product.name }} - ${{ order.product.price }} x {{ order.quantity}} pcs.
|
||||
</li>
|
||||
</ul>
|
||||
<h3 class="text-right">Total amount: ${{ total }}</h3>
|
||||
|
||||
<button class="btn btn-primary btn-block" (click)="pay()" *ngIf="!paid">Pay</button>
|
||||
|
||||
<div class="alert alert-success" role="alert" *ngIf="paid">
|
||||
<strong>Congratulation!</strong> You successfully made the order.
|
||||
</div>
|
@ -0,0 +1,25 @@
|
||||
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
|
||||
import { OrdersComponent } from './orders.component';
|
||||
|
||||
describe('OrdersComponent', () => {
|
||||
let component: OrdersComponent;
|
||||
let fixture: ComponentFixture<OrdersComponent>;
|
||||
|
||||
beforeEach(async(() => {
|
||||
TestBed.configureTestingModule({
|
||||
declarations: [ OrdersComponent ]
|
||||
})
|
||||
.compileComponents();
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = TestBed.createComponent(OrdersComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
});
|
@ -0,0 +1,39 @@
|
||||
import {Component, OnInit} from '@angular/core';
|
||||
import {ProductOrders} from "../models/product-orders.model";
|
||||
import {Subscription} from "rxjs/internal/Subscription";
|
||||
import {EcommerceService} from "../services/EcommerceService";
|
||||
|
||||
@Component({
|
||||
selector: 'app-orders',
|
||||
templateUrl: './orders.component.html',
|
||||
styleUrls: ['./orders.component.css']
|
||||
})
|
||||
export class OrdersComponent implements OnInit {
|
||||
orders: ProductOrders;
|
||||
total: number;
|
||||
paid: boolean;
|
||||
sub: Subscription;
|
||||
|
||||
constructor(private ecommerceService: EcommerceService) {
|
||||
this.orders = this.ecommerceService.ProductOrders;
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
this.paid = false;
|
||||
this.sub = this.ecommerceService.OrdersChanged.subscribe(() => {
|
||||
this.orders = this.ecommerceService.ProductOrders;
|
||||
});
|
||||
this.loadTotal();
|
||||
}
|
||||
|
||||
pay() {
|
||||
this.paid = true;
|
||||
this.ecommerceService.saveOrder(this.orders).subscribe();
|
||||
}
|
||||
|
||||
loadTotal() {
|
||||
this.sub = this.ecommerceService.TotalChanged.subscribe(() => {
|
||||
this.total = this.ecommerceService.Total;
|
||||
});
|
||||
}
|
||||
}
|
@ -0,0 +1,4 @@
|
||||
.padding-0 {
|
||||
padding-right: 0;
|
||||
padding-left: 1;
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
<div class="row card-deck">
|
||||
<div class="col-lg-4 col-md-6 mb-4" *ngFor="let order of productOrders">
|
||||
<div class="card text-center">
|
||||
<div class="card-header">
|
||||
<h4>{{order.product.name}}</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<a href="#"><img class="card-img-top" src={{order.product.pictureUrl}} alt=""></a>
|
||||
<h5 class="card-title">${{order.product.price}}</h5>
|
||||
<div class="row">
|
||||
<div class="col-4 padding-0" *ngIf="!isProductSelected(order.product)">
|
||||
<input type="number" min="0" class="form-control" [(ngModel)]=order.quantity>
|
||||
</div>
|
||||
<div class="col-4 padding-0" *ngIf="!isProductSelected(order.product)">
|
||||
<button class="btn btn-primary" (click)="addToCart(order)"
|
||||
[disabled]="order.quantity <= 0">Add To Cart
|
||||
</button>
|
||||
</div>
|
||||
<div class="col-12" *ngIf="isProductSelected(order.product)">
|
||||
<button class="btn btn-primary btn-block"
|
||||
(click)="removeFromCart(order)">Remove From Cart
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
@ -0,0 +1,25 @@
|
||||
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
|
||||
import { ProductsComponent } from './products.component';
|
||||
|
||||
describe('ProductsComponent', () => {
|
||||
let component: ProductsComponent;
|
||||
let fixture: ComponentFixture<ProductsComponent>;
|
||||
|
||||
beforeEach(async(() => {
|
||||
TestBed.configureTestingModule({
|
||||
declarations: [ ProductsComponent ]
|
||||
})
|
||||
.compileComponents();
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = TestBed.createComponent(ProductsComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
});
|
@ -0,0 +1,82 @@
|
||||
import {Component, OnInit} from '@angular/core';
|
||||
import {ProductOrder} from "../models/product-order.model";
|
||||
import {EcommerceService} from "../services/EcommerceService";
|
||||
import {Subscription} from "rxjs/internal/Subscription";
|
||||
import {ProductOrders} from "../models/product-orders.model";
|
||||
import {Product} from "../models/product.model";
|
||||
|
||||
@Component({
|
||||
selector: 'app-products',
|
||||
templateUrl: './products.component.html',
|
||||
styleUrls: ['./products.component.css']
|
||||
})
|
||||
export class ProductsComponent implements OnInit {
|
||||
productOrders: ProductOrder[] = [];
|
||||
products: Product[] = [];
|
||||
selectedProductOrder: ProductOrder;
|
||||
private shoppingCartOrders: ProductOrders;
|
||||
sub: Subscription;
|
||||
productSelected: boolean = false;
|
||||
|
||||
constructor(private ecommerceService: EcommerceService) {
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
this.productOrders = [];
|
||||
this.loadProducts();
|
||||
this.loadOrders();
|
||||
}
|
||||
|
||||
addToCart(order: ProductOrder) {
|
||||
this.ecommerceService.SelectedProductOrder = order;
|
||||
this.selectedProductOrder = this.ecommerceService.SelectedProductOrder;
|
||||
this.productSelected = true;
|
||||
}
|
||||
|
||||
removeFromCart(productOrder: ProductOrder) {
|
||||
let index = this.getProductIndex(productOrder.product);
|
||||
if (index > -1) {
|
||||
this.shoppingCartOrders.productOrders.splice(
|
||||
this.getProductIndex(productOrder.product), 1);
|
||||
}
|
||||
this.ecommerceService.ProductOrders = this.shoppingCartOrders;
|
||||
this.shoppingCartOrders = this.ecommerceService.ProductOrders;
|
||||
this.productSelected = false;
|
||||
}
|
||||
|
||||
getProductIndex(product: Product): number {
|
||||
return this.ecommerceService.ProductOrders.productOrders.findIndex(
|
||||
value => value.product === product);
|
||||
}
|
||||
|
||||
isProductSelected(product: Product): boolean {
|
||||
return this.getProductIndex(product) > -1;
|
||||
}
|
||||
|
||||
loadProducts() {
|
||||
this.ecommerceService.getAllProducts()
|
||||
.subscribe(
|
||||
(products: any[]) => {
|
||||
this.products = products;
|
||||
this.products.forEach(product => {
|
||||
this.productOrders.push(new ProductOrder(product, 0));
|
||||
})
|
||||
},
|
||||
(error) => console.log(error)
|
||||
);
|
||||
}
|
||||
|
||||
loadOrders() {
|
||||
this.sub = this.ecommerceService.OrdersChanged.subscribe(() => {
|
||||
this.shoppingCartOrders = this.ecommerceService.ProductOrders;
|
||||
});
|
||||
}
|
||||
|
||||
reset() {
|
||||
this.productOrders = [];
|
||||
this.loadProducts();
|
||||
this.ecommerceService.ProductOrders.productOrders = [];
|
||||
this.loadOrders();
|
||||
this.productSelected = false;
|
||||
}
|
||||
}
|
@ -0,0 +1,62 @@
|
||||
import {ProductOrder} from "../models/product-order.model";
|
||||
import {Subject} from "rxjs/internal/Subject";
|
||||
import {ProductOrders} from "../models/product-orders.model";
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Injectable} from "@angular/core";
|
||||
|
||||
@Injectable()
|
||||
export class EcommerceService {
|
||||
private productsUrl = "/api/products";
|
||||
private ordersUrl = "/api/orders";
|
||||
|
||||
private productOrder: ProductOrder;
|
||||
private orders: ProductOrders = new ProductOrders();
|
||||
|
||||
private productOrderSubject = new Subject();
|
||||
private ordersSubject = new Subject();
|
||||
private totalSubject = new Subject();
|
||||
|
||||
private total: number;
|
||||
|
||||
ProductOrderChanged = this.productOrderSubject.asObservable();
|
||||
OrdersChanged = this.ordersSubject.asObservable();
|
||||
TotalChanged = this.totalSubject.asObservable();
|
||||
|
||||
constructor(private http: HttpClient) {
|
||||
}
|
||||
|
||||
getAllProducts() {
|
||||
return this.http.get(this.productsUrl);
|
||||
}
|
||||
|
||||
saveOrder(order: ProductOrders) {
|
||||
return this.http.post(this.ordersUrl, order);
|
||||
}
|
||||
|
||||
set SelectedProductOrder(value: ProductOrder) {
|
||||
this.productOrder = value;
|
||||
this.productOrderSubject.next();
|
||||
}
|
||||
|
||||
get SelectedProductOrder() {
|
||||
return this.productOrder;
|
||||
}
|
||||
|
||||
set ProductOrders(value: ProductOrders) {
|
||||
this.orders = value;
|
||||
this.ordersSubject.next();
|
||||
}
|
||||
|
||||
get ProductOrders() {
|
||||
return this.orders;
|
||||
}
|
||||
|
||||
get Total() {
|
||||
return this.total;
|
||||
}
|
||||
|
||||
set Total(value: number) {
|
||||
this.total = value;
|
||||
this.totalSubject.next();
|
||||
}
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
<div class="card text-white bg-danger mb-3" style="max-width: 18rem;">
|
||||
<div class="card-header text-center">Shopping Cart</div>
|
||||
<div class="card-body">
|
||||
<h5 class="card-title">Total: ${{total}}</h5>
|
||||
<hr>
|
||||
<h6 class="card-title">Items bought:</h6>
|
||||
|
||||
<ul>
|
||||
<li *ngFor="let order of orders.productOrders">
|
||||
{{ order.product.name }} - {{ order.quantity}} pcs.
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<button class="btn btn-light btn-block" (click)="finishOrder()"
|
||||
[disabled]="orders.productOrders.length == 0">Checkout
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
@ -0,0 +1,25 @@
|
||||
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
|
||||
import { ShoppingCartComponent } from './shopping-cart.component';
|
||||
|
||||
describe('ShoppingCartComponent', () => {
|
||||
let component: ShoppingCartComponent;
|
||||
let fixture: ComponentFixture<ShoppingCartComponent>;
|
||||
|
||||
beforeEach(async(() => {
|
||||
TestBed.configureTestingModule({
|
||||
declarations: [ ShoppingCartComponent ]
|
||||
})
|
||||
.compileComponents();
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = TestBed.createComponent(ShoppingCartComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
});
|
@ -0,0 +1,76 @@
|
||||
import {Component, EventEmitter, OnDestroy, OnInit, Output} from '@angular/core';
|
||||
import {ProductOrders} from "../models/product-orders.model";
|
||||
import {ProductOrder} from "../models/product-order.model";
|
||||
import {EcommerceService} from "../services/EcommerceService";
|
||||
import {Subscription} from "rxjs/internal/Subscription";
|
||||
|
||||
@Component({
|
||||
selector: 'app-shopping-cart',
|
||||
templateUrl: './shopping-cart.component.html',
|
||||
styleUrls: ['./shopping-cart.component.css']
|
||||
})
|
||||
export class ShoppingCartComponent implements OnInit, OnDestroy {
|
||||
orderFinished: boolean;
|
||||
orders: ProductOrders;
|
||||
total: number;
|
||||
sub: Subscription;
|
||||
|
||||
@Output() onOrderFinished: EventEmitter<boolean>;
|
||||
|
||||
constructor(private ecommerceService: EcommerceService) {
|
||||
this.total = 0;
|
||||
this.orderFinished = false;
|
||||
this.onOrderFinished = new EventEmitter<boolean>();
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
this.orders = new ProductOrders();
|
||||
this.loadCart();
|
||||
this.loadTotal();
|
||||
}
|
||||
|
||||
private calculateTotal(products: ProductOrder[]): number {
|
||||
let sum = 0;
|
||||
products.forEach(value => {
|
||||
sum += (value.product.price * value.quantity);
|
||||
});
|
||||
return sum;
|
||||
}
|
||||
|
||||
ngOnDestroy() {
|
||||
this.sub.unsubscribe();
|
||||
}
|
||||
|
||||
finishOrder() {
|
||||
this.orderFinished = true;
|
||||
this.ecommerceService.Total = this.total;
|
||||
this.onOrderFinished.emit(this.orderFinished);
|
||||
}
|
||||
|
||||
loadTotal() {
|
||||
this.sub = this.ecommerceService.OrdersChanged.subscribe(() => {
|
||||
this.total = this.calculateTotal(this.orders.productOrders);
|
||||
});
|
||||
}
|
||||
|
||||
loadCart() {
|
||||
this.sub = this.ecommerceService.ProductOrderChanged.subscribe(() => {
|
||||
let productOrder = this.ecommerceService.SelectedProductOrder;
|
||||
if (productOrder) {
|
||||
this.orders.productOrders.push(new ProductOrder(
|
||||
productOrder.product, productOrder.quantity));
|
||||
}
|
||||
this.ecommerceService.ProductOrders = this.orders;
|
||||
this.orders = this.ecommerceService.ProductOrders;
|
||||
this.total = this.calculateTotal(this.orders.productOrders);
|
||||
});
|
||||
}
|
||||
|
||||
reset() {
|
||||
this.orderFinished = false;
|
||||
this.orders = new ProductOrders();
|
||||
this.orders.productOrders = []
|
||||
this.loadTotal();
|
||||
this.total = 0;
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
# This file is currently used by autoprefixer to adjust CSS to support the below specified browsers
|
||||
# For additional information regarding the format and rule options, please see:
|
||||
# https://github.com/browserslist/browserslist#queries
|
||||
# For IE 9-11 support, please uncomment the last line of the file and adjust as needed
|
||||
> 0.5%
|
||||
last 2 versions
|
||||
Firefox ESR
|
||||
not dead
|
||||
# IE 9-11
|
@ -0,0 +1,3 @@
|
||||
export const environment = {
|
||||
production: true
|
||||
};
|
@ -0,0 +1,15 @@
|
||||
// This file can be replaced during build by using the `fileReplacements` array.
|
||||
// `ng build ---prod` replaces `environment.ts` with `environment.prod.ts`.
|
||||
// The list of file replacements can be found in `angular.json`.
|
||||
|
||||
export const environment = {
|
||||
production: false
|
||||
};
|
||||
|
||||
/*
|
||||
* In development mode, to ignore zone related error stack frames such as
|
||||
* `zone.run`, `zoneDelegate.invokeTask` for easier debugging, you can
|
||||
* import the following file, but please comment it out in production mode
|
||||
* because it will have performance impact when throw error
|
||||
*/
|
||||
// import 'zone.js/dist/zone-error'; // Included with Angular CLI.
|
BIN
spring-boot-angular-ecommerce/src/main/frontend/src/favicon.ico
Normal file
BIN
spring-boot-angular-ecommerce/src/main/frontend/src/favicon.ico
Normal file
Binary file not shown.
After Width: | Height: | Size: 5.3 KiB |
@ -0,0 +1,14 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Frontend</title>
|
||||
<base href="/">
|
||||
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="icon" type="image/x-icon" href="favicon.ico">
|
||||
</head>
|
||||
<body>
|
||||
<app-root></app-root>
|
||||
</body>
|
||||
</html>
|
@ -0,0 +1,31 @@
|
||||
// Karma configuration file, see link for more information
|
||||
// https://karma-runner.github.io/1.0/config/configuration-file.html
|
||||
|
||||
module.exports = function (config) {
|
||||
config.set({
|
||||
basePath: '',
|
||||
frameworks: ['jasmine', '@angular-devkit/build-angular'],
|
||||
plugins: [
|
||||
require('karma-jasmine'),
|
||||
require('karma-chrome-launcher'),
|
||||
require('karma-jasmine-html-reporter'),
|
||||
require('karma-coverage-istanbul-reporter'),
|
||||
require('@angular-devkit/build-angular/plugins/karma')
|
||||
],
|
||||
client: {
|
||||
clearContext: false // leave Jasmine Spec Runner output visible in browser
|
||||
},
|
||||
coverageIstanbulReporter: {
|
||||
dir: require('path').join(__dirname, '../coverage'),
|
||||
reports: ['html', 'lcovonly'],
|
||||
fixWebpackSourcePaths: true
|
||||
},
|
||||
reporters: ['progress', 'kjhtml'],
|
||||
port: 9876,
|
||||
colors: true,
|
||||
logLevel: config.LOG_INFO,
|
||||
autoWatch: true,
|
||||
browsers: ['Chrome'],
|
||||
singleRun: false
|
||||
});
|
||||
};
|
12
spring-boot-angular-ecommerce/src/main/frontend/src/main.ts
Normal file
12
spring-boot-angular-ecommerce/src/main/frontend/src/main.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { enableProdMode } from '@angular/core';
|
||||
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
|
||||
|
||||
import { AppModule } from './app/app.module';
|
||||
import { environment } from './environments/environment';
|
||||
|
||||
if (environment.production) {
|
||||
enableProdMode();
|
||||
}
|
||||
|
||||
platformBrowserDynamic().bootstrapModule(AppModule)
|
||||
.catch(err => console.log(err));
|
@ -0,0 +1,80 @@
|
||||
/**
|
||||
* This file includes polyfills needed by Angular and is loaded before the app.
|
||||
* You can add your own extra polyfills to this file.
|
||||
*
|
||||
* This file is divided into 2 sections:
|
||||
* 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
|
||||
* 2. Application imports. Files imported after ZoneJS that should be loaded before your main
|
||||
* file.
|
||||
*
|
||||
* The current setup is for so-called "evergreen" browsers; the last versions of browsers that
|
||||
* automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
|
||||
* Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
|
||||
*
|
||||
* Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html
|
||||
*/
|
||||
|
||||
/***************************************************************************************************
|
||||
* BROWSER POLYFILLS
|
||||
*/
|
||||
|
||||
/** IE9, IE10 and IE11 requires all of the following polyfills. **/
|
||||
// import 'core-js/es6/symbol';
|
||||
// import 'core-js/es6/object';
|
||||
// import 'core-js/es6/function';
|
||||
// import 'core-js/es6/parse-int';
|
||||
// import 'core-js/es6/parse-float';
|
||||
// import 'core-js/es6/number';
|
||||
// import 'core-js/es6/math';
|
||||
// import 'core-js/es6/string';
|
||||
// import 'core-js/es6/date';
|
||||
// import 'core-js/es6/array';
|
||||
// import 'core-js/es6/regexp';
|
||||
// import 'core-js/es6/map';
|
||||
// import 'core-js/es6/weak-map';
|
||||
// import 'core-js/es6/set';
|
||||
|
||||
/** IE10 and IE11 requires the following for NgClass support on SVG elements */
|
||||
// import 'classlist.js'; // Run `npm install --save classlist.js`.
|
||||
|
||||
/** IE10 and IE11 requires the following for the Reflect API. */
|
||||
// import 'core-js/es6/reflect';
|
||||
|
||||
|
||||
/** Evergreen browsers require these. **/
|
||||
// Used for reflect-metadata in JIT. If you use AOT (and only Angular decorators), you can remove.
|
||||
import 'core-js/es7/reflect';
|
||||
|
||||
|
||||
/**
|
||||
* Web Animations `@angular/platform-browser/animations`
|
||||
* Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
|
||||
* Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
|
||||
**/
|
||||
// import 'web-animations-js'; // Run `npm install --save web-animations-js`.
|
||||
|
||||
/**
|
||||
* By default, zone.js will patch all possible macroTask and DomEvents
|
||||
* user can disable parts of macroTask/DomEvents patch by setting following flags
|
||||
*/
|
||||
|
||||
// (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
|
||||
// (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
|
||||
// (window as any).__zone_symbol__BLACK_LISTED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
|
||||
|
||||
/*
|
||||
* in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
|
||||
* with the following flag, it will bypass `zone.js` patch for IE/Edge
|
||||
*/
|
||||
// (window as any).__Zone_enable_cross_context_check = true;
|
||||
|
||||
/***************************************************************************************************
|
||||
* Zone JS is required by default for Angular itself.
|
||||
*/
|
||||
import 'zone.js/dist/zone'; // Included with Angular CLI.
|
||||
|
||||
|
||||
|
||||
/***************************************************************************************************
|
||||
* APPLICATION IMPORTS
|
||||
*/
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user