Merge branch 'master' of https://github.com/sandy03934/tutorials into sandy03934-master
This commit is contained in:
+19
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
+21
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+20
@@ -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();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
+41
@@ -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();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+53
@@ -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 <[email protected]>
|
||||||
|
*/
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+45
@@ -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 <[email protected]>
|
||||||
|
*/
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package com.baeldung.java9.maps.initialize;
|
||||||
|
|
||||||
|
import java.util.AbstractMap;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class MapsInitializer {
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public void createMapWithMapOf() {
|
||||||
|
Map<String, String> emptyMap = Map.of();
|
||||||
|
Map<String, String> singletonMap = Map.of("key1", "value");
|
||||||
|
Map<String, String> map = Map.of("key1","value1", "key2", "value2");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void createMapWithMapEntries() {
|
||||||
|
Map<String, String> map = Map.ofEntries(
|
||||||
|
new AbstractMap.SimpleEntry<String, String>("name", "John"),
|
||||||
|
new AbstractMap.SimpleEntry<String, String>("city", "budapest"),
|
||||||
|
new AbstractMap.SimpleEntry<String, String>("zip", "000000"),
|
||||||
|
new AbstractMap.SimpleEntry<String, String>("home", "1231231231")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public void createMutableMaps() {
|
||||||
|
Map<String, String> map = new HashMap<String, String> (Map.of("key1","value1", "key2", "value2"));
|
||||||
|
Map<String, String> map2 = new HashMap<String, String> ( Map.ofEntries(
|
||||||
|
new AbstractMap.SimpleEntry<String, String>("name", "John"),
|
||||||
|
new AbstractMap.SimpleEntry<String, String>("city", "budapest")));
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package com.baeldung.java.list;
|
||||||
|
|
||||||
|
public class Flower {
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
private int petals;
|
||||||
|
|
||||||
|
public Flower(String name, int petals) {
|
||||||
|
this.name = name;
|
||||||
|
this.petals = petals;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getPetals() {
|
||||||
|
return petals;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPetals(int petals) {
|
||||||
|
this.petals = petals;
|
||||||
|
}
|
||||||
|
}
|
||||||
+80
@@ -0,0 +1,80 @@
|
|||||||
|
package com.baeldung.java.map.initialize;
|
||||||
|
|
||||||
|
import java.util.AbstractMap;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
public class MapInitializer {
|
||||||
|
|
||||||
|
public static Map<String, String> articleMapOne;
|
||||||
|
static {
|
||||||
|
articleMapOne = new HashMap<>();
|
||||||
|
articleMapOne.put("ar01", "Intro to Map");
|
||||||
|
articleMapOne.put("ar02", "Some article");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Map<String, String> createSingletonMap() {
|
||||||
|
Map<String, String> passwordMap = Collections.singletonMap("username1", "password1");
|
||||||
|
return passwordMap;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, String> createEmptyMap() {
|
||||||
|
Map<String, String> emptyMap = Collections.emptyMap();
|
||||||
|
return emptyMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, String> createUsingDoubleBrace() {
|
||||||
|
Map<String, String> doubleBraceMap = new HashMap<String, String>() {
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
{
|
||||||
|
put("key1", "value1");
|
||||||
|
put("key2", "value2");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
return doubleBraceMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, String> createMapUsingStreamStringArray() {
|
||||||
|
Map<String, String> map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, })
|
||||||
|
.collect(Collectors.toMap(data -> data[0], data -> data[1]));
|
||||||
|
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Integer> createMapUsingStreamObjectArray() {
|
||||||
|
Map<String, Integer> map = Stream.of(new Object[][] { { "data1", 1 }, { "data2", 2 }, })
|
||||||
|
.collect(Collectors.toMap(data -> (String) data[0], data -> (Integer) data[1]));
|
||||||
|
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Integer> createMapUsingStreamSimpleEntry() {
|
||||||
|
Map<String, Integer> map = Stream.of(new AbstractMap.SimpleEntry<>("idea", 1), new AbstractMap.SimpleEntry<>("mobile", 2))
|
||||||
|
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||||
|
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Integer> createMapUsingStreamSimpleImmutableEntry() {
|
||||||
|
Map<String, Integer> map = Stream.of(new AbstractMap.SimpleImmutableEntry<>("idea", 1), new AbstractMap.SimpleImmutableEntry<>("mobile", 2))
|
||||||
|
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||||
|
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, String> createImmutableMapWithStreams() {
|
||||||
|
Map<String, String> map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, })
|
||||||
|
.collect(Collectors.collectingAndThen(Collectors.toMap(data -> data[0], data -> data[1]), Collections::<String, String> unmodifiableMap));
|
||||||
|
return map;
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
+27
@@ -0,0 +1,27 @@
|
|||||||
|
package com.baeldung.java.map.initialize;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class MapInitializerUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStaticMap_whenUpdated_thenCorrect() {
|
||||||
|
|
||||||
|
MapInitializer.articleMapOne.put("NewArticle1", "Convert array to List");
|
||||||
|
|
||||||
|
assertEquals(MapInitializer.articleMapOne.get("NewArticle1"), "Convert array to List");
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected=UnsupportedOperationException.class)
|
||||||
|
public void givenSingleTonMap_whenEntriesAdded_throwsException() {
|
||||||
|
|
||||||
|
Map<String, String> map = MapInitializer.createSingletonMap();
|
||||||
|
map.put("username2", "password2");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+69
@@ -0,0 +1,69 @@
|
|||||||
|
package com.baeldung.list.listoflist;
|
||||||
|
|
||||||
|
import com.baeldung.java.list.Flower;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import java.util.*;
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
public class AddElementsToListUnitTest {
|
||||||
|
|
||||||
|
List<Flower> flowers;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void init() {
|
||||||
|
this.flowers = new ArrayList<>(Arrays.asList(
|
||||||
|
new Flower("Poppy", 12),
|
||||||
|
new Flower("Anemone", 8),
|
||||||
|
new Flower("Catmint", 12)));
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithNewItems() {
|
||||||
|
List<Flower> anotherList = new ArrayList<>();
|
||||||
|
anotherList.addAll(flowers);
|
||||||
|
assertEquals(anotherList.size(), flowers.size());
|
||||||
|
Assert.assertTrue(anotherList.containsAll(flowers));
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithOneModifiedElementByConstructor() {
|
||||||
|
List<Flower> anotherList = new ArrayList<>();
|
||||||
|
anotherList.addAll(flowers);
|
||||||
|
Flower flower = anotherList.get(0);
|
||||||
|
flower.setPetals(flowers.get(0).getPetals() * 3);
|
||||||
|
assertEquals(anotherList.size(), flowers.size());
|
||||||
|
Assert.assertTrue(anotherList.containsAll(flowers));
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void givenAListAndElements_whenUseCollectionsAddAll_thenAddElementsToTargetList() {
|
||||||
|
List<Flower> target = new ArrayList<>();
|
||||||
|
Collections.addAll(target, flowers.get(0), flowers.get(1), flowers.get(2), flowers.get(0));
|
||||||
|
assertEquals(target.size(), 4);
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListSkipFirstElementByStreamProcess() {
|
||||||
|
List<Flower> flowerVase = new ArrayList<>();
|
||||||
|
flowers.stream()
|
||||||
|
.skip(1)
|
||||||
|
.forEachOrdered(flowerVase::add);
|
||||||
|
assertEquals(flowerVase.size() + 1, flowers.size());
|
||||||
|
assertFalse(flowerVase.containsAll(flowers));
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListFilteringElementsByStreamProcess() {
|
||||||
|
List<Flower> flowerVase = new ArrayList<>();
|
||||||
|
flowers.stream()
|
||||||
|
.filter(f -> f.getPetals() > 10)
|
||||||
|
.forEachOrdered(flowerVase::add);
|
||||||
|
assertEquals(flowerVase.size() + 1, flowers.size());
|
||||||
|
assertFalse(flowerVase.containsAll(flowers));
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void givenAList_whenListIsNotNull_thenAddElementsToListByStreamProcessWihtOptional() {
|
||||||
|
List<Flower> target = new ArrayList<>();
|
||||||
|
Optional.ofNullable(flowers)
|
||||||
|
.ifPresent(target::addAll);
|
||||||
|
assertNotNull(target);
|
||||||
|
assertEquals(target.size(), 3);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>com.baeldung.core-java-persistence</groupId>
|
||||||
|
<artifactId>core-java-persistence</artifactId>
|
||||||
|
<version>0.1.0-SNAPSHOT</version>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
<name>core-java-persistence</name>
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-java</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../parent-java</relativePath>
|
||||||
|
</parent>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>${assertj-core.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.h2database</groupId>
|
||||||
|
<artifactId>h2</artifactId>
|
||||||
|
<version>${h2database.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-dbcp2</artifactId>
|
||||||
|
<version>${commons-dbcp2.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.zaxxer</groupId>
|
||||||
|
<artifactId>HikariCP</artifactId>
|
||||||
|
<version>${HikariCP.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.mchange</groupId>
|
||||||
|
<artifactId>c3p0</artifactId>
|
||||||
|
<version>${c3p0.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<build>
|
||||||
|
<finalName>core-java-persistence</finalName>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources</directory>
|
||||||
|
<filtering>true</filtering>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
</build>
|
||||||
|
<properties>
|
||||||
|
<assertj-core.version>3.10.0</assertj-core.version>
|
||||||
|
<h2database.version>1.4.197</h2database.version>
|
||||||
|
<commons-dbcp2.version>2.4.0</commons-dbcp2.version>
|
||||||
|
<HikariCP.version>3.2.0</HikariCP.version>
|
||||||
|
<c3p0.version>0.9.5.2</c3p0.version>
|
||||||
|
</properties>
|
||||||
|
</project>
|
||||||
+92
-85
@@ -1,85 +1,92 @@
|
|||||||
package com.baeldung.connectionpool.connectionpools;
|
package com.baeldung.connectionpool;
|
||||||
|
|
||||||
import java.sql.Connection;
|
import java.sql.Connection;
|
||||||
import java.sql.DriverManager;
|
import java.sql.DriverManager;
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public class BasicConnectionPool implements ConnectionPool {
|
public class BasicConnectionPool implements ConnectionPool {
|
||||||
|
|
||||||
private final String url;
|
private final String url;
|
||||||
private final String user;
|
private final String user;
|
||||||
private final String password;
|
private final String password;
|
||||||
private final List<Connection> connectionPool;
|
private final List<Connection> connectionPool;
|
||||||
private final List<Connection> usedConnections = new ArrayList<>();
|
private final List<Connection> usedConnections = new ArrayList<>();
|
||||||
private static final int INITIAL_POOL_SIZE = 10;
|
private static final int INITIAL_POOL_SIZE = 10;
|
||||||
private final int MAX_POOL_SIZE = 20;
|
private final int MAX_POOL_SIZE = 20;
|
||||||
|
|
||||||
public static BasicConnectionPool create(String url, String user, String password) throws SQLException {
|
public static BasicConnectionPool create(String url, String user, String password) throws SQLException {
|
||||||
List<Connection> pool = new ArrayList<>(INITIAL_POOL_SIZE);
|
List<Connection> pool = new ArrayList<>(INITIAL_POOL_SIZE);
|
||||||
for (int i = 0; i < INITIAL_POOL_SIZE; i++) {
|
for (int i = 0; i < INITIAL_POOL_SIZE; i++) {
|
||||||
pool.add(createConnection(url, user, password));
|
pool.add(createConnection(url, user, password));
|
||||||
}
|
}
|
||||||
return new BasicConnectionPool(url, user, password, pool);
|
return new BasicConnectionPool(url, user, password, pool);
|
||||||
}
|
}
|
||||||
|
|
||||||
private BasicConnectionPool(String url, String user, String password, List<Connection> connectionPool) {
|
private BasicConnectionPool(String url, String user, String password, List<Connection> connectionPool) {
|
||||||
this.url = url;
|
this.url = url;
|
||||||
this.user = user;
|
this.user = user;
|
||||||
this.password = password;
|
this.password = password;
|
||||||
this.connectionPool = connectionPool;
|
this.connectionPool = connectionPool;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Connection getConnection() throws SQLException {
|
public Connection getConnection() throws SQLException {
|
||||||
if (connectionPool.isEmpty()) {
|
if (connectionPool.isEmpty()) {
|
||||||
if (usedConnections.size() < MAX_POOL_SIZE) {
|
if (usedConnections.size() < MAX_POOL_SIZE) {
|
||||||
connectionPool.add(createConnection(url, user, password));
|
connectionPool.add(createConnection(url, user, password));
|
||||||
} else {
|
} else {
|
||||||
throw new RuntimeException("Maximum pool size reached, no available connections!");
|
throw new RuntimeException("Maximum pool size reached, no available connections!");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Connection connection = connectionPool.remove(connectionPool.size() - 1);
|
Connection connection = connectionPool.remove(connectionPool.size() - 1);
|
||||||
usedConnections.add(connection);
|
usedConnections.add(connection);
|
||||||
return connection;
|
return connection;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean releaseConnection(Connection connection) {
|
public boolean releaseConnection(Connection connection) {
|
||||||
connectionPool.add(connection);
|
connectionPool.add(connection);
|
||||||
return usedConnections.remove(connection);
|
return usedConnections.remove(connection);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Connection createConnection(String url, String user, String password) throws SQLException {
|
private static Connection createConnection(String url, String user, String password) throws SQLException {
|
||||||
return DriverManager.getConnection(url, user, password);
|
return DriverManager.getConnection(url, user, password);
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getSize() {
|
@Override
|
||||||
return connectionPool.size() + usedConnections.size();
|
public int getSize() {
|
||||||
}
|
return connectionPool.size() + usedConnections.size();
|
||||||
|
}
|
||||||
@Override
|
|
||||||
public String getUrl() {
|
@Override
|
||||||
return url;
|
public List<Connection> getConnectionPool() {
|
||||||
}
|
return connectionPool;
|
||||||
|
}
|
||||||
@Override
|
|
||||||
public String getUser() {
|
@Override
|
||||||
return user;
|
public String getUrl() {
|
||||||
}
|
return url;
|
||||||
|
}
|
||||||
@Override
|
|
||||||
public String getPassword() {
|
@Override
|
||||||
return password;
|
public String getUser() {
|
||||||
}
|
return user;
|
||||||
|
}
|
||||||
public void shutdown() throws SQLException {
|
|
||||||
usedConnections.forEach(this::releaseConnection);
|
@Override
|
||||||
for (Connection c : connectionPool) {
|
public String getPassword() {
|
||||||
c.close();
|
return password;
|
||||||
}
|
}
|
||||||
connectionPool.clear();
|
|
||||||
}
|
@Override
|
||||||
}
|
public void shutdown() throws SQLException {
|
||||||
|
usedConnections.forEach(this::releaseConnection);
|
||||||
|
for (Connection c : connectionPool) {
|
||||||
|
c.close();
|
||||||
|
}
|
||||||
|
connectionPool.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
+27
-27
@@ -1,28 +1,28 @@
|
|||||||
package com.baeldung.connectionpool.connectionpools;
|
package com.baeldung.connectionpool;
|
||||||
|
|
||||||
import com.mchange.v2.c3p0.ComboPooledDataSource;
|
import com.mchange.v2.c3p0.ComboPooledDataSource;
|
||||||
import java.beans.PropertyVetoException;
|
import java.beans.PropertyVetoException;
|
||||||
import java.sql.Connection;
|
import java.sql.Connection;
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
|
|
||||||
public class C3poDataSource {
|
public class C3poDataSource {
|
||||||
|
|
||||||
private static final ComboPooledDataSource cpds = new ComboPooledDataSource();
|
private static final ComboPooledDataSource cpds = new ComboPooledDataSource();
|
||||||
|
|
||||||
static {
|
static {
|
||||||
try {
|
try {
|
||||||
cpds.setDriverClass("org.h2.Driver");
|
cpds.setDriverClass("org.h2.Driver");
|
||||||
cpds.setJdbcUrl("jdbc:h2:mem:test");
|
cpds.setJdbcUrl("jdbc:h2:mem:test");
|
||||||
cpds.setUser("user");
|
cpds.setUser("user");
|
||||||
cpds.setPassword("password");
|
cpds.setPassword("password");
|
||||||
} catch (PropertyVetoException e) {
|
} catch (PropertyVetoException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Connection getConnection() throws SQLException {
|
public static Connection getConnection() throws SQLException {
|
||||||
return cpds.getConnection();
|
return cpds.getConnection();
|
||||||
}
|
}
|
||||||
|
|
||||||
private C3poDataSource(){}
|
private C3poDataSource(){}
|
||||||
}
|
}
|
||||||
+23
-17
@@ -1,18 +1,24 @@
|
|||||||
package com.baeldung.connectionpool.connectionpools;
|
package com.baeldung.connectionpool;
|
||||||
|
|
||||||
import java.sql.Connection;
|
import java.sql.Connection;
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public interface ConnectionPool {
|
public interface ConnectionPool {
|
||||||
|
|
||||||
Connection getConnection() throws SQLException;
|
Connection getConnection() throws SQLException;
|
||||||
|
|
||||||
boolean releaseConnection(Connection connection);
|
boolean releaseConnection(Connection connection);
|
||||||
|
|
||||||
String getUrl();
|
List<Connection> getConnectionPool();
|
||||||
|
|
||||||
String getUser();
|
int getSize();
|
||||||
|
|
||||||
String getPassword();
|
String getUrl();
|
||||||
|
|
||||||
|
String getUser();
|
||||||
|
|
||||||
|
String getPassword();
|
||||||
|
|
||||||
|
void shutdown() throws SQLException;;
|
||||||
}
|
}
|
||||||
+25
-25
@@ -1,25 +1,25 @@
|
|||||||
package com.baeldung.connectionpool.connectionpools;
|
package com.baeldung.connectionpool;
|
||||||
|
|
||||||
import java.sql.Connection;
|
import java.sql.Connection;
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
import org.apache.commons.dbcp2.BasicDataSource;
|
import org.apache.commons.dbcp2.BasicDataSource;
|
||||||
|
|
||||||
public class DBCPDataSource {
|
public class DBCPDataSource {
|
||||||
|
|
||||||
private static final BasicDataSource ds = new BasicDataSource();
|
private static final BasicDataSource ds = new BasicDataSource();
|
||||||
|
|
||||||
static {
|
static {
|
||||||
ds.setUrl("jdbc:h2:mem:test");
|
ds.setUrl("jdbc:h2:mem:test");
|
||||||
ds.setUsername("user");
|
ds.setUsername("user");
|
||||||
ds.setPassword("password");
|
ds.setPassword("password");
|
||||||
ds.setMinIdle(5);
|
ds.setMinIdle(5);
|
||||||
ds.setMaxIdle(10);
|
ds.setMaxIdle(10);
|
||||||
ds.setMaxOpenPreparedStatements(100);
|
ds.setMaxOpenPreparedStatements(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Connection getConnection() throws SQLException {
|
public static Connection getConnection() throws SQLException {
|
||||||
return ds.getConnection();
|
return ds.getConnection();
|
||||||
}
|
}
|
||||||
|
|
||||||
private DBCPDataSource(){}
|
private DBCPDataSource(){}
|
||||||
}
|
}
|
||||||
+28
-28
@@ -1,28 +1,28 @@
|
|||||||
package com.baeldung.connectionpool.connectionpools;
|
package com.baeldung.connectionpool;
|
||||||
|
|
||||||
import com.zaxxer.hikari.HikariConfig;
|
import com.zaxxer.hikari.HikariConfig;
|
||||||
import com.zaxxer.hikari.HikariDataSource;
|
import com.zaxxer.hikari.HikariDataSource;
|
||||||
import java.sql.Connection;
|
import java.sql.Connection;
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
|
|
||||||
public class HikariCPDataSource {
|
public class HikariCPDataSource {
|
||||||
|
|
||||||
private static final HikariConfig config = new HikariConfig();
|
private static final HikariConfig config = new HikariConfig();
|
||||||
private static final HikariDataSource ds;
|
private static final HikariDataSource ds;
|
||||||
|
|
||||||
static {
|
static {
|
||||||
config.setJdbcUrl("jdbc:h2:mem:test");
|
config.setJdbcUrl("jdbc:h2:mem:test");
|
||||||
config.setUsername("user");
|
config.setUsername("user");
|
||||||
config.setPassword("password");
|
config.setPassword("password");
|
||||||
config.addDataSourceProperty("cachePrepStmts", "true");
|
config.addDataSourceProperty("cachePrepStmts", "true");
|
||||||
config.addDataSourceProperty("prepStmtCacheSize", "250");
|
config.addDataSourceProperty("prepStmtCacheSize", "250");
|
||||||
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
|
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
|
||||||
ds = new HikariDataSource(config);
|
ds = new HikariDataSource(config);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Connection getConnection() throws SQLException {
|
public static Connection getConnection() throws SQLException {
|
||||||
return ds.getConnection();
|
return ds.getConnection();
|
||||||
}
|
}
|
||||||
|
|
||||||
private HikariCPDataSource(){}
|
private HikariCPDataSource(){}
|
||||||
}
|
}
|
||||||
+1
-3
@@ -1,10 +1,8 @@
|
|||||||
package com.baeldung.connectionpool;
|
package com.baeldung.connectionpool;
|
||||||
|
|
||||||
import com.baeldung.connectionpool.connectionpools.BasicConnectionPool;
|
|
||||||
import com.baeldung.connectionpool.connectionpools.ConnectionPool;
|
|
||||||
import java.sql.Connection;
|
import java.sql.Connection;
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
import java.util.List;
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
import static org.junit.Assert.fail;
|
import static org.junit.Assert.fail;
|
||||||
-1
@@ -1,6 +1,5 @@
|
|||||||
package com.baeldung.connectionpool;
|
package com.baeldung.connectionpool;
|
||||||
|
|
||||||
import com.baeldung.connectionpool.connectionpools.C3poDataSource;
|
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
-1
@@ -1,6 +1,5 @@
|
|||||||
package com.baeldung.connectionpool;
|
package com.baeldung.connectionpool;
|
||||||
|
|
||||||
import com.baeldung.connectionpool.connectionpools.DBCPDataSource;
|
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
-1
@@ -1,6 +1,5 @@
|
|||||||
package com.baeldung.connectionpool;
|
package com.baeldung.connectionpool;
|
||||||
|
|
||||||
import com.baeldung.connectionpool.connectionpools.HikariCPDataSource;
|
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
@@ -158,21 +158,6 @@
|
|||||||
<artifactId>jmimemagic</artifactId>
|
<artifactId>jmimemagic</artifactId>
|
||||||
<version>${jmime-magic.version}</version>
|
<version>${jmime-magic.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.commons</groupId>
|
|
||||||
<artifactId>commons-dbcp2</artifactId>
|
|
||||||
<version>${commons-dbcp2.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.zaxxer</groupId>
|
|
||||||
<artifactId>HikariCP</artifactId>
|
|
||||||
<version>${HikariCP.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.mchange</groupId>
|
|
||||||
<artifactId>c3p0</artifactId>
|
|
||||||
<version>${c3p0.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<!-- instrumentation -->
|
<!-- instrumentation -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.javassist</groupId>
|
<groupId>org.javassist</groupId>
|
||||||
@@ -544,11 +529,6 @@
|
|||||||
<!-- testing -->
|
<!-- testing -->
|
||||||
<assertj-core.version>3.10.0</assertj-core.version>
|
<assertj-core.version>3.10.0</assertj-core.version>
|
||||||
|
|
||||||
<!-- JDBC pooling frameworks -->
|
|
||||||
<commons-dbcp2.version>2.4.0</commons-dbcp2.version>
|
|
||||||
<HikariCP.version>3.2.0</HikariCP.version>
|
|
||||||
<c3p0.version>0.9.5.2</c3p0.version>
|
|
||||||
|
|
||||||
<!-- maven plugins -->
|
<!-- maven plugins -->
|
||||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||||
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
|
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
|
||||||
|
|||||||
+10
-3
@@ -771,12 +771,19 @@
|
|||||||
<version>${hamcrest-all.version}</version>
|
<version>${hamcrest-all.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.yaml</groupId>
|
<groupId>org.yaml</groupId>
|
||||||
<artifactId>snakeyaml</artifactId>
|
<artifactId>snakeyaml</artifactId>
|
||||||
<version>${snakeyaml.version}</version>
|
<version>${snakeyaml.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.eclipse.paho</groupId>
|
||||||
|
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
|
||||||
|
<version>1.2.0</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
@@ -1026,4 +1033,4 @@
|
|||||||
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
|
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package com.baeldung.mqtt;
|
||||||
|
|
||||||
|
import java.util.Random;
|
||||||
|
import java.util.concurrent.Callable;
|
||||||
|
|
||||||
|
import org.eclipse.paho.client.mqttv3.IMqttClient;
|
||||||
|
import org.eclipse.paho.client.mqttv3.MqttMessage;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
public class EngineTemperatureSensor implements Callable<Void> {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(EngineTemperatureSensor.class);
|
||||||
|
public static final String TOPIC = "engine/temperature";
|
||||||
|
|
||||||
|
private IMqttClient client;
|
||||||
|
private Random rnd = new Random();
|
||||||
|
|
||||||
|
public EngineTemperatureSensor(IMqttClient client) {
|
||||||
|
this.client = client;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Void call() throws Exception {
|
||||||
|
|
||||||
|
if ( !client.isConnected()) {
|
||||||
|
log.info("[I31] Client not connected.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
MqttMessage msg = readEngineTemp();
|
||||||
|
msg.setQos(0);
|
||||||
|
msg.setRetained(true);
|
||||||
|
client.publish(TOPIC,msg);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method simulates reading the engine temperature
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
private MqttMessage readEngineTemp() {
|
||||||
|
double temp = 80 + rnd.nextDouble() * 20.0;
|
||||||
|
byte[] payload = String.format("T:%04.2f",temp).getBytes();
|
||||||
|
MqttMessage msg = new MqttMessage(payload);
|
||||||
|
return msg;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,8 @@ public class Contact {
|
|||||||
|
|
||||||
private String type;
|
private String type;
|
||||||
|
|
||||||
private Integer number;
|
private int number;
|
||||||
|
|
||||||
|
|
||||||
public String getType() {
|
public String getType() {
|
||||||
return type;
|
return type;
|
||||||
@@ -14,11 +15,11 @@ public class Contact {
|
|||||||
this.type = type;
|
this.type = type;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Integer getNumber() {
|
public int getNumber() {
|
||||||
return number;
|
return number;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setNumber(Integer number) {
|
public void setNumber(int number) {
|
||||||
this.number = number;
|
this.number = number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ public class Customer {
|
|||||||
|
|
||||||
private String firstName;
|
private String firstName;
|
||||||
private String lastName;
|
private String lastName;
|
||||||
private Integer age;
|
private int age;
|
||||||
private List<Contact> contactDetails;
|
private List<Contact> contactDetails;
|
||||||
private Address homeAddress;
|
private Address homeAddress;
|
||||||
|
|
||||||
@@ -26,11 +26,11 @@ public class Customer {
|
|||||||
this.lastName = lastName;
|
this.lastName = lastName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Integer getAge() {
|
public int getAge() {
|
||||||
return age;
|
return age;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setAge(Integer age) {
|
public void setAge(int age) {
|
||||||
this.age = age;
|
this.age = age;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
package com.baeldung.mqtt;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.concurrent.Callable;
|
||||||
|
import java.util.concurrent.CountDownLatch;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import org.eclipse.paho.client.mqttv3.MqttClient;
|
||||||
|
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
public class EngineTemperatureSensorLiveTest {
|
||||||
|
|
||||||
|
private static Logger log = LoggerFactory.getLogger(EngineTemperatureSensorLiveTest.class);
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenSendSingleMessage_thenSuccess() throws Exception {
|
||||||
|
|
||||||
|
String publisherId = UUID.randomUUID().toString();
|
||||||
|
MqttClient publisher = new MqttClient("tcp://iot.eclipse.org:1883",publisherId);
|
||||||
|
|
||||||
|
String subscriberId = UUID.randomUUID().toString();
|
||||||
|
MqttClient subscriber = new MqttClient("tcp://iot.eclipse.org:1883",subscriberId);
|
||||||
|
|
||||||
|
MqttConnectOptions options = new MqttConnectOptions();
|
||||||
|
options.setAutomaticReconnect(true);
|
||||||
|
options.setCleanSession(true);
|
||||||
|
options.setConnectionTimeout(10);
|
||||||
|
|
||||||
|
|
||||||
|
subscriber.connect(options);
|
||||||
|
publisher.connect(options);
|
||||||
|
|
||||||
|
CountDownLatch receivedSignal = new CountDownLatch(1);
|
||||||
|
|
||||||
|
subscriber.subscribe(EngineTemperatureSensor.TOPIC, (topic, msg) -> {
|
||||||
|
byte[] payload = msg.getPayload();
|
||||||
|
log.info("[I46] Message received: topic={}, payload={}", topic, new String(payload));
|
||||||
|
receivedSignal.countDown();
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
Callable<Void> target = new EngineTemperatureSensor(publisher);
|
||||||
|
target.call();
|
||||||
|
|
||||||
|
receivedSignal.await(1, TimeUnit.MINUTES);
|
||||||
|
|
||||||
|
log.info("[I56] Success !");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenSendMultipleMessages_thenSuccess() throws Exception {
|
||||||
|
|
||||||
|
String publisherId = UUID.randomUUID().toString();
|
||||||
|
MqttClient publisher = new MqttClient("tcp://iot.eclipse.org:1883",publisherId);
|
||||||
|
|
||||||
|
String subscriberId = UUID.randomUUID().toString();
|
||||||
|
MqttClient subscriber = new MqttClient("tcp://iot.eclipse.org:1883",subscriberId);
|
||||||
|
|
||||||
|
|
||||||
|
MqttConnectOptions options = new MqttConnectOptions();
|
||||||
|
options.setAutomaticReconnect(true);
|
||||||
|
options.setCleanSession(true);
|
||||||
|
options.setConnectionTimeout(10);
|
||||||
|
|
||||||
|
|
||||||
|
publisher.connect(options);
|
||||||
|
subscriber.connect(options);
|
||||||
|
|
||||||
|
CountDownLatch receivedSignal = new CountDownLatch(10);
|
||||||
|
|
||||||
|
subscriber.subscribe(EngineTemperatureSensor.TOPIC, (topic, msg) -> {
|
||||||
|
byte[] payload = msg.getPayload();
|
||||||
|
log.info("[I82] Message received: topic={}, payload={}", topic, new String(payload));
|
||||||
|
receivedSignal.countDown();
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
Callable<Void> target = new EngineTemperatureSensor(publisher);
|
||||||
|
|
||||||
|
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
|
||||||
|
executor.scheduleAtFixedRate(() -> {
|
||||||
|
try {
|
||||||
|
target.call();
|
||||||
|
}
|
||||||
|
catch(Exception ex) {
|
||||||
|
throw new RuntimeException(ex);
|
||||||
|
}
|
||||||
|
}, 1, 1, TimeUnit.SECONDS);
|
||||||
|
|
||||||
|
|
||||||
|
receivedSignal.await(1, TimeUnit.MINUTES);
|
||||||
|
executor.shutdown();
|
||||||
|
|
||||||
|
assertTrue(receivedSignal.getCount() == 0 , "Countdown should be zero");
|
||||||
|
|
||||||
|
log.info("[I105] Success !");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@@ -23,7 +23,6 @@ public class JavaToYAMLSerializationUnitTest {
|
|||||||
Yaml yaml = new Yaml();
|
Yaml yaml = new Yaml();
|
||||||
StringWriter writer = new StringWriter();
|
StringWriter writer = new StringWriter();
|
||||||
yaml.dump(data, writer);
|
yaml.dump(data, writer);
|
||||||
System.out.println(writer.toString());
|
|
||||||
String expectedYaml = "name: Silenthand Olleander\nrace: Human\ntraits: [ONE_HAND, ONE_EYE]\n";
|
String expectedYaml = "name: Silenthand Olleander\nrace: Human\ntraits: [ONE_HAND, ONE_EYE]\n";
|
||||||
assertEquals(expectedYaml, writer.toString());
|
assertEquals(expectedYaml, writer.toString());
|
||||||
}
|
}
|
||||||
@@ -48,7 +47,6 @@ public class JavaToYAMLSerializationUnitTest {
|
|||||||
customer.setFirstName("Greg");
|
customer.setFirstName("Greg");
|
||||||
customer.setLastName("McDowell");
|
customer.setLastName("McDowell");
|
||||||
Yaml yaml = new Yaml();
|
Yaml yaml = new Yaml();
|
||||||
System.out.println(yaml.dumpAs(customer, Tag.MAP, null));
|
|
||||||
String expectedYaml = "{age: 45, contactDetails: null, firstName: Greg, homeAddress: null, lastName: McDowell}\n";
|
String expectedYaml = "{age: 45, contactDetails: null, firstName: Greg, homeAddress: null, lastName: McDowell}\n";
|
||||||
assertEquals(expectedYaml, yaml.dumpAs(customer, Tag.MAP, null));
|
assertEquals(expectedYaml, yaml.dumpAs(customer, Tag.MAP, null));
|
||||||
}
|
}
|
||||||
|
|||||||
+26
-24
@@ -1,20 +1,15 @@
|
|||||||
package com.baeldung.snakeyaml;
|
package com.baeldung.snakeyaml;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertNotNull;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
import java.io.InputStream;
|
|
||||||
import java.util.Date;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.yaml.snakeyaml.TypeDescription;
|
import org.yaml.snakeyaml.TypeDescription;
|
||||||
import org.yaml.snakeyaml.Yaml;
|
import org.yaml.snakeyaml.Yaml;
|
||||||
import org.yaml.snakeyaml.constructor.Constructor;
|
import org.yaml.snakeyaml.constructor.Constructor;
|
||||||
|
|
||||||
import com.baeldung.snakeyaml.Contact;
|
import java.io.InputStream;
|
||||||
import com.baeldung.snakeyaml.Customer;
|
import java.util.Date;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
public class YAMLToJavaDeserialisationUnitTest {
|
public class YAMLToJavaDeserialisationUnitTest {
|
||||||
|
|
||||||
@@ -25,6 +20,9 @@ public class YAMLToJavaDeserialisationUnitTest {
|
|||||||
.getClassLoader()
|
.getClassLoader()
|
||||||
.getResourceAsStream("yaml/customer.yaml");
|
.getResourceAsStream("yaml/customer.yaml");
|
||||||
Map<String, Object> obj = yaml.load(inputStream);
|
Map<String, Object> obj = yaml.load(inputStream);
|
||||||
|
assertEquals("John", obj.get("firstName"));
|
||||||
|
assertEquals("Doe", obj.get("lastName"));
|
||||||
|
assertEquals(20, obj.get("age"));
|
||||||
System.out.println(obj);
|
System.out.println(obj);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,6 +33,9 @@ public class YAMLToJavaDeserialisationUnitTest {
|
|||||||
.getClassLoader()
|
.getClassLoader()
|
||||||
.getResourceAsStream("yaml/customer.yaml");
|
.getResourceAsStream("yaml/customer.yaml");
|
||||||
Customer customer = yaml.load(inputStream);
|
Customer customer = yaml.load(inputStream);
|
||||||
|
assertEquals("John", customer.getFirstName());
|
||||||
|
assertEquals("Doe", customer.getLastName());
|
||||||
|
assertEquals(20, customer.getAge());
|
||||||
System.out.println(customer);
|
System.out.println(customer);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,6 +46,9 @@ public class YAMLToJavaDeserialisationUnitTest {
|
|||||||
.getClassLoader()
|
.getClassLoader()
|
||||||
.getResourceAsStream("yaml/customer_with_type.yaml");
|
.getResourceAsStream("yaml/customer_with_type.yaml");
|
||||||
Customer customer = yaml.load(inputStream);
|
Customer customer = yaml.load(inputStream);
|
||||||
|
assertEquals("John", customer.getFirstName());
|
||||||
|
assertEquals("Doe", customer.getLastName());
|
||||||
|
assertEquals(20, customer.getAge());
|
||||||
System.out.println(customer);
|
System.out.println(customer);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,9 +57,9 @@ public class YAMLToJavaDeserialisationUnitTest {
|
|||||||
Yaml yaml = new Yaml();
|
Yaml yaml = new Yaml();
|
||||||
Map<Object, Object> document = yaml.load("3.0: 2018-07-22");
|
Map<Object, Object> document = yaml.load("3.0: 2018-07-22");
|
||||||
assertNotNull(document);
|
assertNotNull(document);
|
||||||
assertTrue(document.size() == 1);
|
assertEquals(1, document.size());
|
||||||
assertTrue(document.containsKey(Double.valueOf(3.0)));
|
assertTrue(document.containsKey(3.0d));
|
||||||
assertTrue(document.get(Double.valueOf(3.0)) instanceof Date);
|
assertTrue(document.get(3.0d) instanceof Date);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -68,22 +72,21 @@ public class YAMLToJavaDeserialisationUnitTest {
|
|||||||
assertNotNull(customer);
|
assertNotNull(customer);
|
||||||
assertEquals("John", customer.getFirstName());
|
assertEquals("John", customer.getFirstName());
|
||||||
assertEquals("Doe", customer.getLastName());
|
assertEquals("Doe", customer.getLastName());
|
||||||
assertTrue(customer.getAge() == 31);
|
assertEquals(31, customer.getAge());
|
||||||
assertNotNull(customer.getContactDetails());
|
assertNotNull(customer.getContactDetails());
|
||||||
assertTrue(customer.getContactDetails()
|
assertEquals(2, customer.getContactDetails().size());
|
||||||
.size() == 2);
|
|
||||||
assertEquals("mobile", customer.getContactDetails()
|
assertEquals("mobile", customer.getContactDetails()
|
||||||
.get(0)
|
.get(0)
|
||||||
.getType());
|
.getType());
|
||||||
assertTrue(customer.getContactDetails()
|
assertEquals(123456789,customer.getContactDetails()
|
||||||
.get(0)
|
.get(0)
|
||||||
.getNumber() == 123456789);
|
.getNumber());
|
||||||
assertEquals("landline", customer.getContactDetails()
|
assertEquals("landline", customer.getContactDetails()
|
||||||
.get(1)
|
.get(1)
|
||||||
.getType());
|
.getType());
|
||||||
assertTrue(customer.getContactDetails()
|
assertEquals(456786868, customer.getContactDetails()
|
||||||
.get(1)
|
.get(1)
|
||||||
.getNumber() == 456786868);
|
.getNumber());
|
||||||
assertNotNull(customer.getHomeAddress());
|
assertNotNull(customer.getHomeAddress());
|
||||||
assertEquals("Xyz, DEF Street", customer.getHomeAddress()
|
assertEquals("Xyz, DEF Street", customer.getHomeAddress()
|
||||||
.getLine());
|
.getLine());
|
||||||
@@ -103,10 +106,9 @@ public class YAMLToJavaDeserialisationUnitTest {
|
|||||||
assertNotNull(customer);
|
assertNotNull(customer);
|
||||||
assertEquals("John", customer.getFirstName());
|
assertEquals("John", customer.getFirstName());
|
||||||
assertEquals("Doe", customer.getLastName());
|
assertEquals("Doe", customer.getLastName());
|
||||||
assertTrue(customer.getAge() == 31);
|
assertEquals(31, customer.getAge());
|
||||||
assertNotNull(customer.getContactDetails());
|
assertNotNull(customer.getContactDetails());
|
||||||
assertTrue(customer.getContactDetails()
|
assertEquals(2, customer.getContactDetails().size());
|
||||||
.size() == 2);
|
|
||||||
assertEquals("mobile", customer.getContactDetails()
|
assertEquals("mobile", customer.getContactDetails()
|
||||||
.get(0)
|
.get(0)
|
||||||
.getType());
|
.getType());
|
||||||
@@ -126,7 +128,7 @@ public class YAMLToJavaDeserialisationUnitTest {
|
|||||||
count++;
|
count++;
|
||||||
assertTrue(object instanceof Customer);
|
assertTrue(object instanceof Customer);
|
||||||
}
|
}
|
||||||
assertTrue(count == 2);
|
assertEquals(2, count);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -312,6 +312,7 @@
|
|||||||
<module>core-java-collections</module>
|
<module>core-java-collections</module>
|
||||||
<module>core-java-io</module>
|
<module>core-java-io</module>
|
||||||
<module>core-java-8</module>
|
<module>core-java-8</module>
|
||||||
|
<module>core-java-persistence</module>
|
||||||
<module>core-kotlin</module>
|
<module>core-kotlin</module>
|
||||||
<module>core-groovy</module>
|
<module>core-groovy</module>
|
||||||
<module>core-java-concurrency</module>
|
<module>core-java-concurrency</module>
|
||||||
@@ -858,7 +859,7 @@
|
|||||||
<module>core-java-io</module>
|
<module>core-java-io</module>
|
||||||
<module>core-java-8</module>
|
<module>core-java-8</module>
|
||||||
<module>core-groovy</module>
|
<module>core-groovy</module>
|
||||||
<module>core-java-concurrency</module>
|
|
||||||
<module>couchbase</module>
|
<module>couchbase</module>
|
||||||
<module>deltaspike</module>
|
<module>deltaspike</module>
|
||||||
<module>dozer</module>
|
<module>dozer</module>
|
||||||
@@ -877,7 +878,7 @@
|
|||||||
<module>spring-static-resources</module>
|
<module>spring-static-resources</module>
|
||||||
<module>hazelcast</module>
|
<module>hazelcast</module>
|
||||||
<module>hbase</module>
|
<module>hbase</module>
|
||||||
|
|
||||||
<module>hystrix</module>
|
<module>hystrix</module>
|
||||||
<module>image-processing</module>
|
<module>image-processing</module>
|
||||||
<module>immutables</module>
|
<module>immutables</module>
|
||||||
@@ -906,11 +907,11 @@
|
|||||||
<module>linkrest</module>
|
<module>linkrest</module>
|
||||||
<module>logging-modules/log-mdc</module>
|
<module>logging-modules/log-mdc</module>
|
||||||
<module>logging-modules/log4j</module>
|
<module>logging-modules/log4j</module>
|
||||||
|
|
||||||
<module>logging-modules/logback</module>
|
<module>logging-modules/logback</module>
|
||||||
<module>lombok</module>
|
<module>lombok</module>
|
||||||
<module>mapstruct</module>
|
<module>mapstruct</module>
|
||||||
|
|
||||||
<module>maven</module>
|
<module>maven</module>
|
||||||
<module>mesos-marathon</module>
|
<module>mesos-marathon</module>
|
||||||
<module>msf4j</module>
|
<module>msf4j</module>
|
||||||
@@ -962,25 +963,25 @@
|
|||||||
<module>spring-cucumber</module>
|
<module>spring-cucumber</module>
|
||||||
<module>spring-ejb</module>
|
<module>spring-ejb</module>
|
||||||
<module>spring-aop</module>
|
<module>spring-aop</module>
|
||||||
|
|
||||||
<module>persistence-modules/spring-data-dynamodb</module>
|
<module>persistence-modules/spring-data-dynamodb</module>
|
||||||
<module>spring-data-keyvalue</module>
|
<module>spring-data-keyvalue</module>
|
||||||
<module>spring-data-mongodb</module>
|
<module>spring-data-mongodb</module>
|
||||||
<module>persistence-modules/spring-data-neo4j</module>
|
<module>persistence-modules/spring-data-neo4j</module>
|
||||||
|
|
||||||
<module>spring-data-rest</module>
|
<module>spring-data-rest</module>
|
||||||
<module>persistence-modules/spring-data-solr</module>
|
<module>persistence-modules/spring-data-solr</module>
|
||||||
<module>spring-dispatcher-servlet</module>
|
<module>spring-dispatcher-servlet</module>
|
||||||
<module>spring-exceptions</module>
|
<module>spring-exceptions</module>
|
||||||
<module>spring-freemarker</module>
|
<module>spring-freemarker</module>
|
||||||
<module>persistence-modules/spring-hibernate-3</module>
|
<module>persistence-modules/spring-hibernate-3</module>
|
||||||
|
|
||||||
<module>persistence-modules/spring-hibernate-5</module>
|
<module>persistence-modules/spring-hibernate-5</module>
|
||||||
<module>persistence-modules/spring-data-eclipselink</module>
|
<module>persistence-modules/spring-data-eclipselink</module>
|
||||||
<module>spring-integration</module>
|
<module>spring-integration</module>
|
||||||
<module>spring-jenkins-pipeline</module>
|
<module>spring-jenkins-pipeline</module>
|
||||||
<module>spring-jersey</module>
|
<module>spring-jersey</module>
|
||||||
|
|
||||||
<module>spring-jms</module>
|
<module>spring-jms</module>
|
||||||
<module>spring-jooq</module>
|
<module>spring-jooq</module>
|
||||||
<module>persistence-modules/spring-jpa</module>
|
<module>persistence-modules/spring-jpa</module>
|
||||||
@@ -1041,13 +1042,13 @@
|
|||||||
<module>testing-modules/testing</module>
|
<module>testing-modules/testing</module>
|
||||||
<module>testing-modules/testng</module>
|
<module>testing-modules/testng</module>
|
||||||
<module>video-tutorials</module>
|
<module>video-tutorials</module>
|
||||||
|
|
||||||
<module>xmlunit-2</module>
|
<module>xmlunit-2</module>
|
||||||
<module>struts-2</module>
|
<module>struts-2</module>
|
||||||
<module>apache-velocity</module>
|
<module>apache-velocity</module>
|
||||||
<module>apache-solrj</module>
|
<module>apache-solrj</module>
|
||||||
<module>rabbitmq</module>
|
<module>rabbitmq</module>
|
||||||
|
|
||||||
<module>persistence-modules/spring-data-gemfire</module>
|
<module>persistence-modules/spring-data-gemfire</module>
|
||||||
<module>mybatis</module>
|
<module>mybatis</module>
|
||||||
<module>spring-drools</module>
|
<module>spring-drools</module>
|
||||||
@@ -1077,6 +1078,12 @@
|
|||||||
<module>apache-meecrowave</module>
|
<module>apache-meecrowave</module>
|
||||||
<module>testing-modules/junit-abstract</module>
|
<module>testing-modules/junit-abstract</module>
|
||||||
|
|
||||||
|
<module>spring-hibernate4</module>
|
||||||
|
<module>xml</module>
|
||||||
|
<module>vertx</module>
|
||||||
|
<module>metrics</module>
|
||||||
|
<module>httpclient</module>
|
||||||
|
|
||||||
<!-- problematic -->
|
<!-- problematic -->
|
||||||
<!--
|
<!--
|
||||||
<module>ejb</module>
|
<module>ejb</module>
|
||||||
@@ -1085,12 +1092,7 @@
|
|||||||
<module>logging-modules/log4j2</module>
|
<module>logging-modules/log4j2</module>
|
||||||
<module>spring-data-couchbase-2</module>
|
<module>spring-data-couchbase-2</module>
|
||||||
<module>persistence-modules/spring-data-redis</module>
|
<module>persistence-modules/spring-data-redis</module>
|
||||||
<module>spring-hibernate4</module>
|
|
||||||
<module>xml</module>
|
|
||||||
<module>vertx</module>
|
|
||||||
<module>metrics</module>
|
|
||||||
<module>httpclient</module>
|
|
||||||
|
|
||||||
<module>jmeter</module>
|
<module>jmeter</module>
|
||||||
-->
|
-->
|
||||||
|
|
||||||
@@ -1107,6 +1109,7 @@
|
|||||||
<module>core-java</module>
|
<module>core-java</module>
|
||||||
<module>google-web-toolkit</module>
|
<module>google-web-toolkit</module>
|
||||||
<module>spring-security-mvc-custom</module>
|
<module>spring-security-mvc-custom</module>
|
||||||
|
<module>core-java-concurrency</module>
|
||||||
-->
|
-->
|
||||||
|
|
||||||
<!-- 30:32 min -->
|
<!-- 30:32 min -->
|
||||||
@@ -1169,7 +1172,7 @@
|
|||||||
<module>spring-security-mvc-custom</module>
|
<module>spring-security-mvc-custom</module>
|
||||||
<module>hibernate5</module>
|
<module>hibernate5</module>
|
||||||
<module>spring-data-elasticsearch</module>
|
<module>spring-data-elasticsearch</module>
|
||||||
|
<module>core-java-concurrency</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
</profile>
|
</profile>
|
||||||
@@ -1233,6 +1236,4 @@
|
|||||||
<!-- <maven-pmd-plugin.version>3.9.0</maven-pmd-plugin.version> -->
|
<!-- <maven-pmd-plugin.version>3.9.0</maven-pmd-plugin.version> -->
|
||||||
<maven-pmd-plugin.version>3.8</maven-pmd-plugin.version>
|
<maven-pmd-plugin.version>3.8</maven-pmd-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
</project>
|
||||||
</project>
|
|
||||||
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user