commit
c1d6c92857
|
@ -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)
|
||||
|
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.nullsafecollectionstreams;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.stream.Stream;
|
||||
import static org.apache.commons.collections4.CollectionUtils.emptyIfNull;
|
||||
|
||||
public class NullSafeCollectionStreamsUsingCommonsEmptyIfNull {
|
||||
|
||||
/**
|
||||
* This method shows how to make a null safe stream from a collection through the use of
|
||||
* emptyIfNull() method from Apache Commons CollectionUtils library
|
||||
*
|
||||
* @param collection The collection that is to be converted into a stream
|
||||
* @return The stream that has been created from the collection or an empty stream if the collection is null
|
||||
*/
|
||||
public Stream<String> collectionAsStream(Collection<String> collection) {
|
||||
return emptyIfNull(collection).stream();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.nullsafecollectionstreams;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class NullSafeCollectionStreamsUsingJava8OptionalContainer {
|
||||
|
||||
/**
|
||||
* This method shows how to make a null safe stream from a collection through the use of
|
||||
* Java SE 8’s Optional Container
|
||||
*
|
||||
* @param collection The collection that is to be converted into a stream
|
||||
* @return The stream that has been created from the collection or an empty stream if the collection is null
|
||||
*/
|
||||
public Stream<String> collectionAsStream(Collection<String> collection) {
|
||||
return Optional.ofNullable(collection)
|
||||
.map(Collection::stream)
|
||||
.orElseGet(Stream::empty);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.nullsafecollectionstreams;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class NullSafeCollectionStreamsUsingNullDereferenceCheck {
|
||||
|
||||
/**
|
||||
* This method shows how to make a null safe stream from a collection through the use of a check
|
||||
* to prevent null dereferences
|
||||
*
|
||||
* @param collection The collection that is to be converted into a stream
|
||||
* @return The stream that has been created from the collection or an empty stream if the collection is null
|
||||
*/
|
||||
public Stream<String> collectionAsStream(Collection<String> collection) {
|
||||
return collection == null ? Stream.empty() : collection.stream();
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.nullsafecollectionstreams;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
|
||||
public class NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest {
|
||||
|
||||
private final NullSafeCollectionStreamsUsingCommonsEmptyIfNull instance =
|
||||
new NullSafeCollectionStreamsUsingCommonsEmptyIfNull();
|
||||
|
||||
@Test
|
||||
public void whenCollectionIsNull_thenExpectAnEmptyStream() {
|
||||
Collection<String> collection = null;
|
||||
Stream<String> expResult = Stream.empty();
|
||||
Stream<String> result = instance.collectionAsStream(collection);
|
||||
assertStreamEquals(expResult, result);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
|
||||
|
||||
Collection<String> collection = Arrays.asList("a", "b", "c");
|
||||
Stream<String> expResult = Arrays.stream(new String[] { "a", "b", "c" });
|
||||
Stream<String> result = instance.collectionAsStream(collection);
|
||||
assertStreamEquals(expResult, result);
|
||||
}
|
||||
|
||||
private static void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
|
||||
Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator();
|
||||
while (iter1.hasNext() && iter2.hasNext())
|
||||
assertEquals(iter1.next(), iter2.next());
|
||||
assert !iter1.hasNext() && !iter2.hasNext();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,53 @@
|
|||
/*
|
||||
* To change this license header, choose License Headers in Project Properties.
|
||||
* To change this template file, choose Tools | Templates
|
||||
* and open the template in the editor.
|
||||
*/
|
||||
package com.baeldung.nullsafecollectionstreams;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Kwaje Anthony <kwajeanthony@gmail.com>
|
||||
*/
|
||||
public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest {
|
||||
|
||||
private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance =
|
||||
new NullSafeCollectionStreamsUsingJava8OptionalContainer();
|
||||
|
||||
@Test
|
||||
public void whenCollectionIsNull_thenExpectAnEmptyStream() {
|
||||
Collection<String> collection = null;
|
||||
Stream<String> expResult = Stream.empty();
|
||||
Stream<String> result = instance.collectionAsStream(collection);
|
||||
assertStreamEquals(expResult, result);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
|
||||
|
||||
Collection<String> collection = Arrays.asList("a", "b", "c");
|
||||
Stream<String> expResult = Arrays.stream(new String[] { "a", "b", "c" });
|
||||
Stream<String> result = instance.collectionAsStream(collection);
|
||||
assertStreamEquals(expResult, result);
|
||||
}
|
||||
|
||||
private static void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
|
||||
Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator();
|
||||
while (iter1.hasNext() && iter2.hasNext())
|
||||
assertEquals(iter1.next(), iter2.next());
|
||||
assert !iter1.hasNext() && !iter2.hasNext();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
|
||||
package com.baeldung.nullsafecollectionstreams;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Kwaje Anthony <kwajeanthony@gmail.com>
|
||||
*/
|
||||
public class NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest {
|
||||
|
||||
private final NullSafeCollectionStreamsUsingNullDereferenceCheck instance =
|
||||
new NullSafeCollectionStreamsUsingNullDereferenceCheck();
|
||||
|
||||
@Test
|
||||
public void whenCollectionIsNull_thenExpectAnEmptyStream() {
|
||||
Collection<String> collection = null;
|
||||
Stream<String> expResult = Stream.empty();
|
||||
Stream<String> result = instance.collectionAsStream(collection);
|
||||
assertStreamEquals(expResult, result);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
|
||||
|
||||
Collection<String> collection = Arrays.asList("a", "b", "c");
|
||||
Stream<String> expResult = Arrays.stream(new String[] { "a", "b", "c" });
|
||||
Stream<String> result = instance.collectionAsStream(collection);
|
||||
assertStreamEquals(expResult, result);
|
||||
}
|
||||
|
||||
private static void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
|
||||
Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator();
|
||||
while (iter1.hasNext() && iter2.hasNext())
|
||||
assertEquals(iter1.next(), iter2.next());
|
||||
assert !iter1.hasNext() && !iter2.hasNext();
|
||||
}
|
||||
|
||||
}
|
|
@ -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>
|
||||
|
|
|
@ -0,0 +1,111 @@
|
|||
package com.baeldung.list.removeall;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class RemoveAll {
|
||||
|
||||
static void removeWithWhileLoopPrimitiveElement(List<Integer> list, int element) {
|
||||
while (list.contains(element)) {
|
||||
list.remove(element);
|
||||
}
|
||||
}
|
||||
|
||||
static void removeWithWhileLoopNonPrimitiveElement(List<Integer> list, Integer element) {
|
||||
while (list.contains(element)) {
|
||||
list.remove(element);
|
||||
}
|
||||
}
|
||||
|
||||
static void removeWithWhileLoopStoringFirstOccurrenceIndex(List<Integer> list, Integer element) {
|
||||
int index;
|
||||
while ((index = list.indexOf(element)) >= 0) {
|
||||
list.remove(index);
|
||||
}
|
||||
}
|
||||
|
||||
static void removeWithCallingRemoveUntilModifies(List<Integer> list, Integer element) {
|
||||
while (list.remove(element))
|
||||
;
|
||||
}
|
||||
|
||||
static void removeWithStandardForLoopUsingIndex(List<Integer> list, int element) {
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
if (Objects.equals(element, list.get(i))) {
|
||||
list.remove(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void removeWithForLoopDecrementOnRemove(List<Integer> list, int element) {
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
if (Objects.equals(element, list.get(i))) {
|
||||
list.remove(i);
|
||||
i--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void removeWithForLoopIncrementIfRemains(List<Integer> list, int element) {
|
||||
for (int i = 0; i < list.size();) {
|
||||
if (Objects.equals(element, list.get(i))) {
|
||||
list.remove(i);
|
||||
} else {
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void removeWithForEachLoop(List<Integer> list, int element) {
|
||||
for (Integer number : list) {
|
||||
if (Objects.equals(number, element)) {
|
||||
list.remove(number);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void removeWithIterator(List<Integer> list, int element) {
|
||||
for (Iterator<Integer> i = list.iterator(); i.hasNext();) {
|
||||
Integer number = i.next();
|
||||
if (Objects.equals(number, element)) {
|
||||
i.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static List<Integer> removeWithCollectingAndReturningRemainingElements(List<Integer> list, int element) {
|
||||
List<Integer> remainingElements = new ArrayList<>();
|
||||
for (Integer number : list) {
|
||||
if (!Objects.equals(number, element)) {
|
||||
remainingElements.add(number);
|
||||
}
|
||||
}
|
||||
return remainingElements;
|
||||
}
|
||||
|
||||
static void removeWithCollectingRemainingElementsAndAddingToOriginalList(List<Integer> list, int element) {
|
||||
List<Integer> remainingElements = new ArrayList<>();
|
||||
for (Integer number : list) {
|
||||
if (!Objects.equals(number, element)) {
|
||||
remainingElements.add(number);
|
||||
}
|
||||
}
|
||||
|
||||
list.clear();
|
||||
list.addAll(remainingElements);
|
||||
}
|
||||
|
||||
static List<Integer> removeWithStreamFilter(List<Integer> list, Integer element) {
|
||||
return list.stream()
|
||||
.filter(e -> !Objects.equals(e, element))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
static void removeWithRemoveIf(List<Integer> list, Integer element) {
|
||||
list.removeIf(n -> Objects.equals(n, element));
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
{}
|
|
@ -0,0 +1 @@
|
|||
{}
|
|
@ -0,0 +1 @@
|
|||
<xml></xml>
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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"));
|
||||
}
|
||||
}
|
|
@ -36,3 +36,4 @@
|
|||
- [Working with Enums in Kotlin](http://www.baeldung.com/kotlin-enum)
|
||||
- [Create a Java and Kotlin Project with Maven](http://www.baeldung.com/kotlin-maven-java-project)
|
||||
- [Reflection with Kotlin](http://www.baeldung.com/kotlin-reflection)
|
||||
- [Get a Random Number in Kotlin](http://www.baeldung.com/kotlin-random-number)
|
||||
|
|
|
@ -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)
|
||||
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
*.class
|
||||
|
||||
# Folders #
|
||||
/gensrc
|
||||
/target
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
/bin/
|
|
@ -1,23 +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>org.baeldung</groupId>
|
||||
<artifactId>mqtt</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>libraries-server</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.paho</groupId>
|
||||
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
|
||||
<version>1.2.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
</project>
|
||||
</project>
|
|
@ -6,3 +6,4 @@
|
|||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
/bin/
|
||||
|
|
|
@ -772,6 +772,12 @@
|
|||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.yaml</groupId>
|
||||
<artifactId>snakeyaml</artifactId>
|
||||
<version>${snakeyaml.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<repositories>
|
||||
|
@ -909,6 +915,7 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<snakeyaml.version>1.21</snakeyaml.version>
|
||||
<googleclient.version>1.23.0</googleclient.version>
|
||||
<crdt.version>0.1.0</crdt.version>
|
||||
<multiverse.version>0.7.0</multiverse.version>
|
||||
|
@ -1019,4 +1026,4 @@
|
|||
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.snakeyaml;
|
||||
|
||||
public class Address {
|
||||
private String line;
|
||||
private String city;
|
||||
private String state;
|
||||
private Integer zip;
|
||||
|
||||
public String getLine() {
|
||||
return line;
|
||||
}
|
||||
|
||||
public void setLine(String line) {
|
||||
this.line = line;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public String getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
public void setState(String state) {
|
||||
this.state = state;
|
||||
}
|
||||
|
||||
public Integer getZip() {
|
||||
return zip;
|
||||
}
|
||||
|
||||
public void setZip(Integer zip) {
|
||||
this.zip = zip;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.snakeyaml;
|
||||
|
||||
public class Contact {
|
||||
|
||||
private String type;
|
||||
|
||||
private int number;
|
||||
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public int getNumber() {
|
||||
return number;
|
||||
}
|
||||
|
||||
public void setNumber(int number) {
|
||||
this.number = number;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,53 @@
|
|||
package com.baeldung.snakeyaml;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class Customer {
|
||||
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private int age;
|
||||
private List<Contact> contactDetails;
|
||||
private Address homeAddress;
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public List<Contact> getContactDetails() {
|
||||
return contactDetails;
|
||||
}
|
||||
|
||||
public void setContactDetails(List<Contact> contactDetails) {
|
||||
this.contactDetails = contactDetails;
|
||||
}
|
||||
|
||||
public Address getHomeAddress() {
|
||||
return homeAddress;
|
||||
}
|
||||
|
||||
public void setHomeAddress(Address homeAddress) {
|
||||
this.homeAddress = homeAddress;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
package com.baeldung.snakeyaml;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.StringWriter;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
import org.yaml.snakeyaml.nodes.Tag;
|
||||
|
||||
import com.baeldung.snakeyaml.Customer;
|
||||
|
||||
public class JavaToYAMLSerializationUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenDumpMap_thenGenerateCorrectYAML() {
|
||||
Map<String, Object> data = new LinkedHashMap<String, Object>();
|
||||
data.put("name", "Silenthand Olleander");
|
||||
data.put("race", "Human");
|
||||
data.put("traits", new String[] { "ONE_HAND", "ONE_EYE" });
|
||||
Yaml yaml = new Yaml();
|
||||
StringWriter writer = new StringWriter();
|
||||
yaml.dump(data, writer);
|
||||
String expectedYaml = "name: Silenthand Olleander\nrace: Human\ntraits: [ONE_HAND, ONE_EYE]\n";
|
||||
assertEquals(expectedYaml, writer.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDumpACustomType_thenGenerateCorrectYAML() {
|
||||
Customer customer = new Customer();
|
||||
customer.setAge(45);
|
||||
customer.setFirstName("Greg");
|
||||
customer.setLastName("McDowell");
|
||||
Yaml yaml = new Yaml();
|
||||
StringWriter writer = new StringWriter();
|
||||
yaml.dump(customer, writer);
|
||||
String expectedYaml = "!!com.baeldung.snakeyaml.Customer {age: 45, contactDetails: null, firstName: Greg,\n homeAddress: null, lastName: McDowell}\n";
|
||||
assertEquals(expectedYaml, writer.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDumpAsCustomType_thenGenerateCorrectYAML() {
|
||||
Customer customer = new Customer();
|
||||
customer.setAge(45);
|
||||
customer.setFirstName("Greg");
|
||||
customer.setLastName("McDowell");
|
||||
Yaml yaml = new Yaml();
|
||||
String expectedYaml = "{age: 45, contactDetails: null, firstName: Greg, homeAddress: null, lastName: McDowell}\n";
|
||||
assertEquals(expectedYaml, yaml.dumpAs(customer, Tag.MAP, null));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,131 @@
|
|||
package com.baeldung.snakeyaml;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.yaml.snakeyaml.TypeDescription;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
import org.yaml.snakeyaml.constructor.Constructor;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class YAMLToJavaDeserialisationUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenLoadYAMLDocument_thenLoadCorrectMap() {
|
||||
Yaml yaml = new Yaml();
|
||||
InputStream inputStream = this.getClass()
|
||||
.getClassLoader()
|
||||
.getResourceAsStream("yaml/customer.yaml");
|
||||
Map<String, Object> obj = yaml.load(inputStream);
|
||||
assertEquals("John", obj.get("firstName"));
|
||||
assertEquals("Doe", obj.get("lastName"));
|
||||
assertEquals(20, obj.get("age"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLoadYAMLDocumentWithTopLevelClass_thenLoadCorrectJavaObject() {
|
||||
Yaml yaml = new Yaml(new Constructor(Customer.class));
|
||||
InputStream inputStream = this.getClass()
|
||||
.getClassLoader()
|
||||
.getResourceAsStream("yaml/customer.yaml");
|
||||
Customer customer = yaml.load(inputStream);
|
||||
assertEquals("John", customer.getFirstName());
|
||||
assertEquals("Doe", customer.getLastName());
|
||||
assertEquals(20, customer.getAge());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLoadYAMLDocumentWithAssumedClass_thenLoadCorrectJavaObject() {
|
||||
Yaml yaml = new Yaml();
|
||||
InputStream inputStream = this.getClass()
|
||||
.getClassLoader()
|
||||
.getResourceAsStream("yaml/customer_with_type.yaml");
|
||||
Customer customer = yaml.load(inputStream);
|
||||
assertEquals("John", customer.getFirstName());
|
||||
assertEquals("Doe", customer.getLastName());
|
||||
assertEquals(20, customer.getAge());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLoadYAML_thenLoadCorrectImplicitTypes() {
|
||||
Yaml yaml = new Yaml();
|
||||
Map<Object, Object> document = yaml.load("3.0: 2018-07-22");
|
||||
assertNotNull(document);
|
||||
assertEquals(1, document.size());
|
||||
assertTrue(document.containsKey(3.0d));
|
||||
assertTrue(document.get(3.0d) instanceof Date);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLoadYAMLDocumentWithTopLevelClass_thenLoadCorrectJavaObjectWithNestedObjects() {
|
||||
Yaml yaml = new Yaml(new Constructor(Customer.class));
|
||||
InputStream inputStream = this.getClass()
|
||||
.getClassLoader()
|
||||
.getResourceAsStream("yaml/customer_with_contact_details_and_address.yaml");
|
||||
Customer customer = yaml.load(inputStream);
|
||||
assertNotNull(customer);
|
||||
assertEquals("John", customer.getFirstName());
|
||||
assertEquals("Doe", customer.getLastName());
|
||||
assertEquals(31, customer.getAge());
|
||||
assertNotNull(customer.getContactDetails());
|
||||
assertEquals(2, customer.getContactDetails().size());
|
||||
assertEquals("mobile", customer.getContactDetails()
|
||||
.get(0)
|
||||
.getType());
|
||||
assertEquals(123456789,customer.getContactDetails()
|
||||
.get(0)
|
||||
.getNumber());
|
||||
assertEquals("landline", customer.getContactDetails()
|
||||
.get(1)
|
||||
.getType());
|
||||
assertEquals(456786868, customer.getContactDetails()
|
||||
.get(1)
|
||||
.getNumber());
|
||||
assertNotNull(customer.getHomeAddress());
|
||||
assertEquals("Xyz, DEF Street", customer.getHomeAddress()
|
||||
.getLine());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLoadYAMLDocumentWithTypeDescription_thenLoadCorrectJavaObjectWithCorrectGenericType() {
|
||||
Constructor constructor = new Constructor(Customer.class);
|
||||
TypeDescription customTypeDescription = new TypeDescription(Customer.class);
|
||||
customTypeDescription.addPropertyParameters("contactDetails", Contact.class);
|
||||
constructor.addTypeDescription(customTypeDescription);
|
||||
Yaml yaml = new Yaml(constructor);
|
||||
InputStream inputStream = this.getClass()
|
||||
.getClassLoader()
|
||||
.getResourceAsStream("yaml/customer_with_contact_details.yaml");
|
||||
Customer customer = yaml.load(inputStream);
|
||||
assertNotNull(customer);
|
||||
assertEquals("John", customer.getFirstName());
|
||||
assertEquals("Doe", customer.getLastName());
|
||||
assertEquals(31, customer.getAge());
|
||||
assertNotNull(customer.getContactDetails());
|
||||
assertEquals(2, customer.getContactDetails().size());
|
||||
assertEquals("mobile", customer.getContactDetails()
|
||||
.get(0)
|
||||
.getType());
|
||||
assertEquals("landline", customer.getContactDetails()
|
||||
.get(1)
|
||||
.getType());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLoadMultipleYAMLDocuments_thenLoadCorrectJavaObjects() {
|
||||
Yaml yaml = new Yaml(new Constructor(Customer.class));
|
||||
InputStream inputStream = this.getClass()
|
||||
.getClassLoader()
|
||||
.getResourceAsStream("yaml/customers.yaml");
|
||||
int count = 0;
|
||||
for (Object object : yaml.loadAll(inputStream)) {
|
||||
count++;
|
||||
assertTrue(object instanceof Customer);
|
||||
}
|
||||
assertEquals(2, count);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
firstName: "John"
|
||||
lastName: "Doe"
|
||||
age: 20
|
|
@ -0,0 +1,7 @@
|
|||
firstName: "John"
|
||||
lastName: "Doe"
|
||||
age: 31
|
||||
contactDetails:
|
||||
- { type: "mobile", number: 123456789}
|
||||
- { type: "landline", number: 456786868}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
firstName: "John"
|
||||
lastName: "Doe"
|
||||
age: 31
|
||||
contactDetails:
|
||||
- type: "mobile"
|
||||
number: 123456789
|
||||
- type: "landline"
|
||||
number: 456786868
|
||||
homeAddress:
|
||||
line: "Xyz, DEF Street"
|
||||
city: "City Y"
|
||||
state: "State Y"
|
||||
zip: 345657
|
|
@ -0,0 +1,6 @@
|
|||
firstName: "John"
|
||||
lastName: "Doe"
|
||||
age: 31
|
||||
contactDetails:
|
||||
- !contact { type: "mobile", number: 123456789}
|
||||
- !contact { type: "landline", number: 456786868}
|
|
@ -0,0 +1,4 @@
|
|||
!!com.baeldung.snakeyaml.Customer
|
||||
firstName: "John"
|
||||
lastName: "Doe"
|
||||
age: 20
|
|
@ -0,0 +1,8 @@
|
|||
---
|
||||
firstName: "John"
|
||||
lastName: "Doe"
|
||||
age: 20
|
||||
---
|
||||
firstName: "Jack"
|
||||
lastName: "Jones"
|
||||
age: 25
|
|
@ -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"));
|
||||
}
|
||||
|
||||
}
|
|
@ -1,4 +0,0 @@
|
|||
### Relevant Articles:
|
||||
================================
|
||||
|
||||
- [MQTT Client in Java](http://www.baeldung.com/mqtt-client)
|
|
@ -0,0 +1,3 @@
|
|||
# Relevant Articles
|
||||
|
||||
* [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping)
|
153
pom.xml
153
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>
|
||||
|
@ -368,6 +368,7 @@
|
|||
<module>jws</module>
|
||||
<module>libraries</module>
|
||||
<module>libraries-data</module>
|
||||
<module>libraries-server</module>
|
||||
<module>linkrest</module>
|
||||
<module>logging-modules/log-mdc</module>
|
||||
<module>logging-modules/log4j</module>
|
||||
|
@ -551,6 +552,8 @@
|
|||
<module>spring-reactive-kotlin</module>
|
||||
<module>jnosql</module>
|
||||
<module>testing-modules/junit-abstract</module>
|
||||
<module>sse-jaxrs</module>
|
||||
<module>spring-boot-angular-ecommerce</module>
|
||||
</modules>
|
||||
|
||||
</profile>
|
||||
|
@ -599,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 -->
|
||||
|
@ -670,8 +673,8 @@
|
|||
<module>spring-amqp-simple</module>
|
||||
<module>spring-apache-camel</module>
|
||||
<module>spring-batch</module>
|
||||
<module>testing-modules/junit-abstract</module>
|
||||
|
||||
<module>testing-modules/junit-abstract</module>
|
||||
<module>jmh</module>
|
||||
|
||||
<!-- group 2 - Pass, 11-16 min, 42 test failures, 4,020 KB -->
|
||||
|
||||
|
@ -750,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 -->
|
||||
|
@ -793,7 +796,7 @@
|
|||
|
||||
<profile>
|
||||
<id>integration-lite</id>
|
||||
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
@ -832,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>
|
||||
|
@ -859,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,15 +1080,15 @@
|
|||
<module>maven-archetype</module>
|
||||
<module>apache-meecrowave</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>
|
||||
|
@ -1095,9 +1098,9 @@
|
|||
|
||||
<module>jmeter</module>
|
||||
-->
|
||||
|
||||
|
||||
<!-- heavy -->
|
||||
<!--
|
||||
<!--
|
||||
<module>libraries</module>
|
||||
<module>geotools</module>
|
||||
<module>jhipster/jhipster-monolithic</module>
|
||||
|
@ -1111,7 +1114,7 @@
|
|||
<module>spring-security-mvc-custom</module>
|
||||
<module>core-java-concurrency</module>
|
||||
-->
|
||||
|
||||
|
||||
<!-- 30:32 min -->
|
||||
</modules>
|
||||
|
||||
|
@ -1119,7 +1122,7 @@
|
|||
|
||||
<profile>
|
||||
<id>integration-heavy</id>
|
||||
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
@ -1158,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>
|
||||
|
@ -1236,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)
|
||||
|
|
|
@ -13,11 +13,11 @@ import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter
|
|||
|
||||
@Controller
|
||||
public class ResponseBodyEmitterController {
|
||||
private ExecutorService nonBlockingService = Executors.newSingleThreadExecutor();
|
||||
|
||||
@GetMapping(Constants.API_RBE)
|
||||
public ResponseEntity<ResponseBodyEmitter> handleRbe() {
|
||||
ResponseBodyEmitter emitter = new ResponseBodyEmitter();
|
||||
ExecutorService nonBlockingService = Executors.newSingleThreadExecutor();
|
||||
|
||||
nonBlockingService.execute(() -> {
|
||||
try {
|
||||
|
|
|
@ -10,12 +10,12 @@ import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
|||
|
||||
@Controller
|
||||
public class SseEmitterController {
|
||||
private ExecutorService nonBlockingService = Executors.newCachedThreadPool();
|
||||
|
||||
@GetMapping(Constants.API_SSE)
|
||||
public SseEmitter handleSse() {
|
||||
SseEmitter emitter = new SseEmitter();
|
||||
|
||||
ExecutorService nonBlockingService = Executors.newSingleThreadExecutor();
|
||||
nonBlockingService.execute(() -> {
|
||||
try {
|
||||
emitter.send(Constants.API_SSE_MSG + " @ " + new Date());
|
||||
|
@ -29,4 +29,4 @@ public class SseEmitterController {
|
|||
return emitter;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
@ -34,8 +34,7 @@ public class FormHandler {
|
|||
|
||||
private AtomicLong extractData(List<DataBuffer> dataBuffers) {
|
||||
AtomicLong atomicLong = new AtomicLong(0);
|
||||
dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer()
|
||||
.array().length));
|
||||
dataBuffers.forEach(d -> atomicLong.addAndGet(d.readableByteCount()));
|
||||
return atomicLong;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -13,6 +13,7 @@ import java.util.List;
|
|||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import org.apache.catalina.Context;
|
||||
import org.apache.catalina.Wrapper;
|
||||
import org.apache.catalina.startup.Tomcat;
|
||||
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
|
||||
import org.springframework.boot.web.server.WebServer;
|
||||
|
@ -61,7 +62,8 @@ public class FunctionalWebApplication {
|
|||
tomcat.setPort(9090);
|
||||
Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
|
||||
ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler);
|
||||
Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet);
|
||||
Wrapper servletWrapper = Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet);
|
||||
servletWrapper.setAsyncSupported(true);
|
||||
rootContext.addServletMappingDecoded("/", "httpHandlerServlet");
|
||||
|
||||
TomcatWebServer server = new TomcatWebServer(tomcat);
|
||||
|
|
|
@ -11,7 +11,7 @@ import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
|
|||
import reactor.ipc.netty.NettyContext;
|
||||
import reactor.ipc.netty.http.server.HttpServer;
|
||||
|
||||
@ComponentScan(basePackages = {"com.baeldung.security"})
|
||||
@ComponentScan(basePackages = {"com.baeldung.reactive.security"})
|
||||
@EnableWebFlux
|
||||
public class SpringSecurity5Application {
|
||||
|
||||
|
|
|
@ -8,7 +8,7 @@ import org.springframework.web.bind.annotation.RestController;
|
|||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@RestController
|
||||
@RestController("FurtherCorsConfigsController-cors-on-global-config-and-more")
|
||||
@RequestMapping("/cors-on-global-config-and-more")
|
||||
public class FurtherCorsConfigsController {
|
||||
|
||||
|
|
|
@ -7,7 +7,7 @@ import org.springframework.web.bind.annotation.RestController;
|
|||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@RestController
|
||||
@RestController("RegularRestController-cors-on-global-config")
|
||||
@RequestMapping("/cors-on-global-config")
|
||||
public class RegularRestController {
|
||||
|
||||
|
|
|
@ -19,7 +19,7 @@ public class SecurityConfig {
|
|||
@Bean
|
||||
public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) {
|
||||
return http.authorizeExchange()
|
||||
.pathMatchers("/admin")
|
||||
.pathMatchers("/", "/admin")
|
||||
.hasAuthority("ROLE_ADMIN")
|
||||
.matchers(EndpointRequest.to(FeaturesEndpoint.class))
|
||||
.permitAll()
|
||||
|
|
|
@ -7,6 +7,7 @@ import static org.springframework.web.reactive.function.server.RouterFunctions.t
|
|||
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
|
||||
|
||||
import org.apache.catalina.Context;
|
||||
import org.apache.catalina.Wrapper;
|
||||
import org.apache.catalina.startup.Tomcat;
|
||||
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
|
||||
import org.springframework.boot.web.server.WebServer;
|
||||
|
@ -41,7 +42,8 @@ public class ExploreSpring5URLPatternUsingRouterFunctions {
|
|||
tomcat.setPort(9090);
|
||||
Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
|
||||
ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler);
|
||||
Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet);
|
||||
Wrapper servletWrapper = Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet);
|
||||
servletWrapper.setAsyncSupported(true);
|
||||
rootContext.addServletMappingDecoded("/", "httpHandlerServlet");
|
||||
|
||||
TomcatWebServer server = new TomcatWebServer(tomcat);
|
||||
|
|
|
@ -4,8 +4,12 @@ import lombok.AllArgsConstructor;
|
|||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class EmployeeCreationEvent {
|
||||
private String employeeId;
|
||||
private String creationTime;
|
||||
public EmployeeCreationEvent(String employeeId, String creationTime) {
|
||||
super();
|
||||
this.employeeId = employeeId;
|
||||
this.creationTime = creationTime;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -15,7 +15,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
|||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Component
|
||||
@Component("EmployeeWebSocketHandler")
|
||||
public class EmployeeWebSocketHandler implements WebSocketHandler {
|
||||
|
||||
ObjectMapper om = new ObjectMapper();
|
||||
|
|
|
@ -1,19 +1,22 @@
|
|||
package com.baeldung.websocket;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.reactive.HandlerMapping;
|
||||
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
|
||||
import org.springframework.web.reactive.socket.WebSocketHandler;
|
||||
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Configuration
|
||||
public class ReactiveWebSocketConfiguration {
|
||||
|
||||
@Autowired
|
||||
@Qualifier("ReactiveWebSocketHandler")
|
||||
private WebSocketHandler webSocketHandler;
|
||||
|
||||
@Bean
|
||||
|
|
|
@ -14,7 +14,7 @@ import java.time.Duration;
|
|||
import static java.time.LocalDateTime.now;
|
||||
import static java.util.UUID.randomUUID;
|
||||
|
||||
@Component
|
||||
@Component("ReactiveWebSocketHandler")
|
||||
public class ReactiveWebSocketHandler implements WebSocketHandler {
|
||||
|
||||
private static final ObjectMapper json = new ObjectMapper();
|
||||
|
|
|
@ -1,5 +1,8 @@
|
|||
package com.baeldung.functional;
|
||||
|
||||
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
|
||||
import static org.springframework.web.reactive.function.BodyInserters.fromResource;
|
||||
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
@ -12,9 +15,6 @@ import org.springframework.util.LinkedMultiValueMap;
|
|||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.reactive.function.BodyInserters;
|
||||
|
||||
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
|
||||
import static org.springframework.web.reactive.function.BodyInserters.fromResource;
|
||||
|
||||
public class FunctionalWebApplicationIntegrationTest {
|
||||
|
||||
private static WebTestClient client;
|
||||
|
|
|
@ -6,8 +6,6 @@ import org.junit.Test;
|
|||
import org.springframework.boot.web.server.WebServer;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
|
||||
import com.baeldung.reactive.urlmatch.ExploreSpring5URLPatternUsingRouterFunctions;
|
||||
|
||||
public class ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest {
|
||||
|
||||
private static WebTestClient client;
|
||||
|
|
|
@ -53,7 +53,7 @@ public class WebTestClientIntegrationTest {
|
|||
.uri("/resource")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.is3xxRedirection()
|
||||
.isOk()
|
||||
.expectBody();
|
||||
}
|
||||
|
||||
|
|
Binary file not shown.
After Width: | Height: | Size: 27 KiB |
|
@ -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
|
||||
|
|
|
@ -0,0 +1,2 @@
|
|||
### Relevant Articles:
|
||||
- [A Simple E-Commerce Implementation with Spring]()
|
|
@ -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
|
|
@ -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).
|
|
@ -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"
|
||||
]
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -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"
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue