Merge branch 'master' of https://github.com/sandy03934/tutorials into sandy03934-master
This commit is contained in:
commit
7db1da7cb3
@ -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();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
@ -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;
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@ -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");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
59
core-java-persistence/pom.xml
Normal file
59
core-java-persistence/pom.xml
Normal file
@ -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>
|
@ -1,4 +1,4 @@
|
|||||||
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;
|
||||||
@ -56,10 +56,16 @@ public class BasicConnectionPool implements ConnectionPool {
|
|||||||
return DriverManager.getConnection(url, user, password);
|
return DriverManager.getConnection(url, user, password);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
public int getSize() {
|
public int getSize() {
|
||||||
return connectionPool.size() + usedConnections.size();
|
return connectionPool.size() + usedConnections.size();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Connection> getConnectionPool() {
|
||||||
|
return connectionPool;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getUrl() {
|
public String getUrl() {
|
||||||
return url;
|
return url;
|
||||||
@ -75,6 +81,7 @@ public class BasicConnectionPool implements ConnectionPool {
|
|||||||
return password;
|
return password;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
public void shutdown() throws SQLException {
|
public void shutdown() throws SQLException {
|
||||||
usedConnections.forEach(this::releaseConnection);
|
usedConnections.forEach(this::releaseConnection);
|
||||||
for (Connection c : connectionPool) {
|
for (Connection c : connectionPool) {
|
@ -1,4 +1,4 @@
|
|||||||
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;
|
@ -1,4 +1,4 @@
|
|||||||
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;
|
||||||
@ -10,9 +10,15 @@ public interface ConnectionPool {
|
|||||||
|
|
||||||
boolean releaseConnection(Connection connection);
|
boolean releaseConnection(Connection connection);
|
||||||
|
|
||||||
|
List<Connection> getConnectionPool();
|
||||||
|
|
||||||
|
int getSize();
|
||||||
|
|
||||||
String getUrl();
|
String getUrl();
|
||||||
|
|
||||||
String getUser();
|
String getUser();
|
||||||
|
|
||||||
String getPassword();
|
String getPassword();
|
||||||
|
|
||||||
|
void shutdown() throws SQLException;;
|
||||||
}
|
}
|
@ -1,4 +1,4 @@
|
|||||||
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;
|
@ -1,4 +1,4 @@
|
|||||||
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;
|
@ -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,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,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,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>
|
||||||
|
@ -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>
|
||||||
|
|
||||||
|
@ -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));
|
||||||
}
|
}
|
||||||
|
@ -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);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
19
pom.xml
19
pom.xml
@ -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>
|
||||||
@ -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,11 +1092,6 @@
|
|||||||
<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>
|
||||||
|
|
||||||
|
@ -34,8 +34,7 @@ public class FormHandler {
|
|||||||
|
|
||||||
private AtomicLong extractData(List<DataBuffer> dataBuffers) {
|
private AtomicLong extractData(List<DataBuffer> dataBuffers) {
|
||||||
AtomicLong atomicLong = new AtomicLong(0);
|
AtomicLong atomicLong = new AtomicLong(0);
|
||||||
dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer()
|
dataBuffers.forEach(d -> atomicLong.addAndGet(d.readableByteCount()));
|
||||||
.array().length));
|
|
||||||
return atomicLong;
|
return atomicLong;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -13,6 +13,7 @@ import java.util.List;
|
|||||||
import java.util.concurrent.CopyOnWriteArrayList;
|
import java.util.concurrent.CopyOnWriteArrayList;
|
||||||
|
|
||||||
import org.apache.catalina.Context;
|
import org.apache.catalina.Context;
|
||||||
|
import org.apache.catalina.Wrapper;
|
||||||
import org.apache.catalina.startup.Tomcat;
|
import org.apache.catalina.startup.Tomcat;
|
||||||
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
|
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
|
||||||
import org.springframework.boot.web.server.WebServer;
|
import org.springframework.boot.web.server.WebServer;
|
||||||
@ -61,7 +62,8 @@ public class FunctionalWebApplication {
|
|||||||
tomcat.setPort(9090);
|
tomcat.setPort(9090);
|
||||||
Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
|
Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
|
||||||
ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler);
|
ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler);
|
||||||
Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet);
|
Wrapper servletWrapper = Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet);
|
||||||
|
servletWrapper.setAsyncSupported(true);
|
||||||
rootContext.addServletMappingDecoded("/", "httpHandlerServlet");
|
rootContext.addServletMappingDecoded("/", "httpHandlerServlet");
|
||||||
|
|
||||||
TomcatWebServer server = new TomcatWebServer(tomcat);
|
TomcatWebServer server = new TomcatWebServer(tomcat);
|
||||||
|
@ -8,7 +8,7 @@ import org.springframework.web.bind.annotation.RestController;
|
|||||||
|
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
@RestController
|
@RestController("FurtherCorsConfigsController-cors-on-global-config-and-more")
|
||||||
@RequestMapping("/cors-on-global-config-and-more")
|
@RequestMapping("/cors-on-global-config-and-more")
|
||||||
public class FurtherCorsConfigsController {
|
public class FurtherCorsConfigsController {
|
||||||
|
|
||||||
|
@ -7,7 +7,7 @@ import org.springframework.web.bind.annotation.RestController;
|
|||||||
|
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
@RestController
|
@RestController("RegularRestController-cors-on-global-config")
|
||||||
@RequestMapping("/cors-on-global-config")
|
@RequestMapping("/cors-on-global-config")
|
||||||
public class RegularRestController {
|
public class RegularRestController {
|
||||||
|
|
||||||
|
@ -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 static org.springframework.web.reactive.function.server.ServerResponse.ok;
|
||||||
|
|
||||||
import org.apache.catalina.Context;
|
import org.apache.catalina.Context;
|
||||||
|
import org.apache.catalina.Wrapper;
|
||||||
import org.apache.catalina.startup.Tomcat;
|
import org.apache.catalina.startup.Tomcat;
|
||||||
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
|
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
|
||||||
import org.springframework.boot.web.server.WebServer;
|
import org.springframework.boot.web.server.WebServer;
|
||||||
@ -41,7 +42,8 @@ public class ExploreSpring5URLPatternUsingRouterFunctions {
|
|||||||
tomcat.setPort(9090);
|
tomcat.setPort(9090);
|
||||||
Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
|
Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
|
||||||
ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler);
|
ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler);
|
||||||
Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet);
|
Wrapper servletWrapper = Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet);
|
||||||
|
servletWrapper.setAsyncSupported(true);
|
||||||
rootContext.addServletMappingDecoded("/", "httpHandlerServlet");
|
rootContext.addServletMappingDecoded("/", "httpHandlerServlet");
|
||||||
|
|
||||||
TomcatWebServer server = new TomcatWebServer(tomcat);
|
TomcatWebServer server = new TomcatWebServer(tomcat);
|
||||||
|
@ -4,8 +4,12 @@ import lombok.AllArgsConstructor;
|
|||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
@AllArgsConstructor
|
|
||||||
public class EmployeeCreationEvent {
|
public class EmployeeCreationEvent {
|
||||||
private String employeeId;
|
private String employeeId;
|
||||||
private String creationTime;
|
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.Flux;
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
@Component
|
@Component("EmployeeWebSocketHandler")
|
||||||
public class EmployeeWebSocketHandler implements WebSocketHandler {
|
public class EmployeeWebSocketHandler implements WebSocketHandler {
|
||||||
|
|
||||||
ObjectMapper om = new ObjectMapper();
|
ObjectMapper om = new ObjectMapper();
|
||||||
|
@ -1,19 +1,22 @@
|
|||||||
package com.baeldung.websocket;
|
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.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.web.reactive.HandlerMapping;
|
import org.springframework.web.reactive.HandlerMapping;
|
||||||
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
|
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
|
||||||
import org.springframework.web.reactive.socket.WebSocketHandler;
|
import org.springframework.web.reactive.socket.WebSocketHandler;
|
||||||
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;
|
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
public class ReactiveWebSocketConfiguration {
|
public class ReactiveWebSocketConfiguration {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
|
@Qualifier("ReactiveWebSocketHandler")
|
||||||
private WebSocketHandler webSocketHandler;
|
private WebSocketHandler webSocketHandler;
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
|
@ -14,7 +14,7 @@ import java.time.Duration;
|
|||||||
import static java.time.LocalDateTime.now;
|
import static java.time.LocalDateTime.now;
|
||||||
import static java.util.UUID.randomUUID;
|
import static java.util.UUID.randomUUID;
|
||||||
|
|
||||||
@Component
|
@Component("ReactiveWebSocketHandler")
|
||||||
public class ReactiveWebSocketHandler implements WebSocketHandler {
|
public class ReactiveWebSocketHandler implements WebSocketHandler {
|
||||||
|
|
||||||
private static final ObjectMapper json = new ObjectMapper();
|
private static final ObjectMapper json = new ObjectMapper();
|
||||||
|
@ -1,5 +1,8 @@
|
|||||||
package com.baeldung.functional;
|
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.AfterClass;
|
||||||
import org.junit.BeforeClass;
|
import org.junit.BeforeClass;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
@ -12,9 +15,6 @@ import org.springframework.util.LinkedMultiValueMap;
|
|||||||
import org.springframework.util.MultiValueMap;
|
import org.springframework.util.MultiValueMap;
|
||||||
import org.springframework.web.reactive.function.BodyInserters;
|
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 {
|
public class FunctionalWebApplicationIntegrationTest {
|
||||||
|
|
||||||
private static WebTestClient client;
|
private static WebTestClient client;
|
||||||
|
@ -6,8 +6,6 @@ import org.junit.Test;
|
|||||||
import org.springframework.boot.web.server.WebServer;
|
import org.springframework.boot.web.server.WebServer;
|
||||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||||
|
|
||||||
import com.baeldung.reactive.urlmatch.ExploreSpring5URLPatternUsingRouterFunctions;
|
|
||||||
|
|
||||||
public class ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest {
|
public class ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest {
|
||||||
|
|
||||||
private static WebTestClient client;
|
private static WebTestClient client;
|
||||||
|
@ -28,7 +28,7 @@ public class SecurityIntegrationTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenNoCredentials_thenRedirectToLogin() {
|
public void whenNoCredentials_thenRedirectToLogin() {
|
||||||
this.rest.get().uri("/").exchange().expectStatus().is3xxRedirection();
|
this.rest.get().uri("/").exchange().expectStatus().is4xxClientError();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -53,7 +53,7 @@ public class WebTestClientIntegrationTest {
|
|||||||
.uri("/resource")
|
.uri("/resource")
|
||||||
.exchange()
|
.exchange()
|
||||||
.expectStatus()
|
.expectStatus()
|
||||||
.is3xxRedirection()
|
.isOk()
|
||||||
.expectBody();
|
.expectBody();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
BIN
spring-5-reactive/src/test/resources/baeldung-weekly.png
Normal file
BIN
spring-5-reactive/src/test/resources/baeldung-weekly.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 27 KiB |
@ -58,6 +58,12 @@
|
|||||||
<artifactId>spring-security-test</artifactId>
|
<artifactId>spring-security-test</artifactId>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.security.oauth.boot</groupId>
|
||||||
|
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
|
||||||
|
<version>2.0.1.RELEASE</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
@ -0,0 +1,20 @@
|
|||||||
|
package com.baeldung.oauth2extractors;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.stereotype.Controller;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
@Controller
|
||||||
|
public class ExtractorsApplication {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(ExtractorsApplication.class, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
@RequestMapping("/")
|
||||||
|
public String index() {
|
||||||
|
return "oauth2_extractors";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,40 @@
|
|||||||
|
package com.baeldung.oauth2extractors.configuration;
|
||||||
|
|
||||||
|
import com.baeldung.oauth2extractors.extractor.CustomAuthoritiesExtractor;
|
||||||
|
import com.baeldung.oauth2extractors.extractor.CustomPrincipalExtractor;
|
||||||
|
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.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 {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
|
http.antMatcher("/**")
|
||||||
|
.authorizeRequests()
|
||||||
|
.antMatchers("/login**")
|
||||||
|
.permitAll()
|
||||||
|
.anyRequest()
|
||||||
|
.authenticated()
|
||||||
|
.and()
|
||||||
|
.formLogin().disable();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public PrincipalExtractor principalExtractor() {
|
||||||
|
return new CustomPrincipalExtractor();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public AuthoritiesExtractor authoritiesExtractor() {
|
||||||
|
return new CustomAuthoritiesExtractor();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,29 @@
|
|||||||
|
package com.baeldung.oauth2extractors.extractor;
|
||||||
|
|
||||||
|
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.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public class CustomAuthoritiesExtractor implements AuthoritiesExtractor {
|
||||||
|
private List<GrantedAuthority> GITHUB_FREE_AUTHORITIES = AuthorityUtils
|
||||||
|
.commaSeparatedStringToAuthorityList("GITHUB_USER,GITHUB_USER_FREE");
|
||||||
|
private List<GrantedAuthority> GITHUB_SUBSCRIBED_AUTHORITIES = AuthorityUtils
|
||||||
|
.commaSeparatedStringToAuthorityList("GITHUB_USER,GITHUB_USER_SUBSCRIBED");
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<GrantedAuthority> extractAuthorities(Map<String, Object> map) {
|
||||||
|
if (Objects.nonNull(map.get("plan"))) {
|
||||||
|
if (!((LinkedHashMap) map.get("plan"))
|
||||||
|
.get("name")
|
||||||
|
.equals("free")) {
|
||||||
|
return GITHUB_SUBSCRIBED_AUTHORITIES;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return GITHUB_FREE_AUTHORITIES;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.oauth2extractors.extractor;
|
||||||
|
|
||||||
|
import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class CustomPrincipalExtractor implements PrincipalExtractor {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object extractPrincipal(Map<String, Object> map) {
|
||||||
|
return map.get("login");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,6 @@
|
|||||||
|
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
|
||||||
|
security.oauth2.client.user-authorization-uri=https://github.com/login/oauth/authorize
|
||||||
|
security.oauth2.client.scope=read:user,user:email
|
||||||
|
security.oauth2.resource.user-info-uri=https://api.github.com/user
|
@ -0,0 +1,21 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
|
||||||
|
<title>Spring Security Principal and Authorities extractor</title>
|
||||||
|
<link rel="stylesheet"
|
||||||
|
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"/>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<div class="container">
|
||||||
|
<div class="col-sm-12">
|
||||||
|
<h1>Secured Page</h1>
|
||||||
|
Authenticated username:
|
||||||
|
<div th:text="${#authentication.name}"></div>
|
||||||
|
Authorities:
|
||||||
|
<div th:text="${#authentication.authorities}"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
@ -0,0 +1,54 @@
|
|||||||
|
package com.baeldung.oauth2extractors;
|
||||||
|
|
||||||
|
import com.baeldung.oauth2extractors.configuration.SecurityConfig;
|
||||||
|
import org.junit.Before;
|
||||||
|
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.ContextConfiguration;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
|
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||||
|
import org.springframework.web.context.WebApplicationContext;
|
||||||
|
|
||||||
|
import javax.servlet.Filter;
|
||||||
|
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||||
|
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest(classes = ExtractorsApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||||
|
@ContextConfiguration(classes = {SecurityConfig.class})
|
||||||
|
public class ExtractorsUnitTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private WebApplicationContext context;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private Filter springSecurityFilterChain;
|
||||||
|
|
||||||
|
private MockMvc mvc;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setup() {
|
||||||
|
mvc = MockMvcBuilders
|
||||||
|
.webAppContextSetup(context)
|
||||||
|
.addFilters(springSecurityFilterChain)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void contextLoads() throws Exception {
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidRequestWithoutAuthentication_shouldFailWith302() throws Exception {
|
||||||
|
mvc
|
||||||
|
.perform(get("/"))
|
||||||
|
.andExpect(status().isFound())
|
||||||
|
.andReturn();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -3,6 +3,7 @@ package com.baeldung.displayallbeans.controller;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.stereotype.Controller;
|
import org.springframework.stereotype.Controller;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
|
||||||
@ -14,9 +15,9 @@ public class FooController {
|
|||||||
private FooService fooService;
|
private FooService fooService;
|
||||||
|
|
||||||
@GetMapping(value = "/displayallbeans")
|
@GetMapping(value = "/displayallbeans")
|
||||||
public String getHeaderAndBody(Map<String, Object> model) {
|
public ResponseEntity<String> getHeaderAndBody(Map<String, Object> model) {
|
||||||
model.put("header", fooService.getHeader());
|
model.put("header", fooService.getHeader());
|
||||||
model.put("message", fooService.getBody());
|
model.put("message", fooService.getBody());
|
||||||
return "displayallbeans";
|
return ResponseEntity.ok("displayallbeans");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,15 @@
|
|||||||
|
package org.baeldung.boot.config;
|
||||||
|
|
||||||
|
import org.baeldung.boot.converter.StringToEmployeeConverter;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.format.FormatterRegistry;
|
||||||
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class WebConfig implements WebMvcConfigurer {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addFormatters(FormatterRegistry registry) {
|
||||||
|
registry.addConverter(new StringToEmployeeConverter());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package org.baeldung.boot.converter;
|
||||||
|
|
||||||
|
import org.springframework.core.convert.converter.Converter;
|
||||||
|
|
||||||
|
import com.baeldung.toggle.Employee;
|
||||||
|
|
||||||
|
public class StringToEmployeeConverter implements Converter<String, Employee> {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Employee convert(String from) {
|
||||||
|
String[] data = from.split(",");
|
||||||
|
return new Employee(
|
||||||
|
Long.parseLong(data[0]),
|
||||||
|
Double.parseDouble(data[1]));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,17 @@
|
|||||||
|
package org.baeldung.boot.converter.controller;
|
||||||
|
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import com.baeldung.toggle.Employee;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
public class StringToEmployeeConverterController {
|
||||||
|
|
||||||
|
@GetMapping("/string-to-employee")
|
||||||
|
public ResponseEntity<Object> getStringToEmployee(@RequestParam("employee") Employee employee) {
|
||||||
|
return ResponseEntity.ok(employee);
|
||||||
|
}
|
||||||
|
}
|
@ -4,17 +4,15 @@ import static org.hamcrest.CoreMatchers.is;
|
|||||||
import static org.hamcrest.CoreMatchers.notNullValue;
|
import static org.hamcrest.CoreMatchers.notNullValue;
|
||||||
import static org.junit.Assert.assertThat;
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
import org.baeldung.boot.ApplicationIntegrationTest;
|
import org.baeldung.boot.DemoApplicationIntegrationTest;
|
||||||
import org.baeldung.demo.model.Foo;
|
import org.baeldung.demo.model.Foo;
|
||||||
import org.baeldung.session.exception.repository.FooRepository;
|
import org.baeldung.demo.repository.FooRepository;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.test.context.TestPropertySource;
|
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
@TestPropertySource("classpath:exception-hibernate.properties")
|
public class HibernateSessionIntegrationTest extends DemoApplicationIntegrationTest {
|
||||||
public class HibernateSessionIntegrationTest extends ApplicationIntegrationTest {
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private FooRepository fooRepository;
|
private FooRepository fooRepository;
|
||||||
|
|
||||||
@ -23,7 +21,7 @@ public class HibernateSessionIntegrationTest extends ApplicationIntegrationTest
|
|||||||
Foo foo = new Foo("Exception Solved");
|
Foo foo = new Foo("Exception Solved");
|
||||||
fooRepository.save(foo);
|
fooRepository.save(foo);
|
||||||
foo = null;
|
foo = null;
|
||||||
foo = fooRepository.get(1);
|
foo = fooRepository.findByName("Exception Solved");
|
||||||
|
|
||||||
assertThat(foo, notNullValue());
|
assertThat(foo, notNullValue());
|
||||||
assertThat(foo.getId(), is(1));
|
assertThat(foo.getId(), is(1));
|
||||||
|
@ -6,9 +6,11 @@ import org.baeldung.session.exception.repository.FooRepository;
|
|||||||
import org.hibernate.HibernateException;
|
import org.hibernate.HibernateException;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.test.context.TestPropertySource;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
|
@TestPropertySource("classpath:exception-hibernate.properties")
|
||||||
public class NoHibernateSessionIntegrationTest extends ApplicationIntegrationTest {
|
public class NoHibernateSessionIntegrationTest extends ApplicationIntegrationTest {
|
||||||
@Autowired
|
@Autowired
|
||||||
private FooRepository fooRepository;
|
private FooRepository fooRepository;
|
||||||
|
@ -43,7 +43,7 @@ public class CustomConverterIntegrationTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenConvertingToBigDecimalUsingGenericConverter_thenSuccess() {
|
public void whenConvertingToBigDecimalUsingGenericConverter_thenSuccess() {
|
||||||
assertThat(conversionService.convert(Integer.valueOf(11), BigDecimal.class)).isEqualTo(BigDecimal.valueOf(11.00).setScale(2, BigDecimal.ROUND_HALF_EVEN));
|
assertThat(conversionService.convert(Integer.valueOf(11), BigDecimal.class)).isEqualTo(BigDecimal.valueOf(11.00).setScale(0, BigDecimal.ROUND_HALF_EVEN));
|
||||||
assertThat(conversionService.convert(Double.valueOf(25.23), BigDecimal.class)).isEqualByComparingTo(BigDecimal.valueOf(Double.valueOf(25.23)));
|
assertThat(conversionService.convert(Double.valueOf(25.23), BigDecimal.class)).isEqualByComparingTo(BigDecimal.valueOf(Double.valueOf(25.23)));
|
||||||
assertThat(conversionService.convert("2.32", BigDecimal.class)).isEqualTo(BigDecimal.valueOf(2.32));
|
assertThat(conversionService.convert("2.32", BigDecimal.class)).isEqualTo(BigDecimal.valueOf(2.32));
|
||||||
}
|
}
|
||||||
|
@ -1,9 +1,11 @@
|
|||||||
package org.baeldung.demo.boottest;
|
package org.baeldung.demo.boottest;
|
||||||
|
|
||||||
import org.baeldung.demo.boottest.Employee;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import org.baeldung.demo.boottest.EmployeeRepository;
|
|
||||||
import org.baeldung.demo.boottest.EmployeeService;
|
import java.util.Arrays;
|
||||||
import org.baeldung.demo.boottest.EmployeeServiceImpl;
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
@ -15,11 +17,6 @@ import org.springframework.boot.test.mock.mockito.MockBean;
|
|||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.test.context.junit4.SpringRunner;
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
|
||||||
|
|
||||||
@RunWith(SpringRunner.class)
|
@RunWith(SpringRunner.class)
|
||||||
public class EmployeeServiceImplIntegrationTest {
|
public class EmployeeServiceImplIntegrationTest {
|
||||||
|
|
||||||
@ -50,9 +47,9 @@ public class EmployeeServiceImplIntegrationTest {
|
|||||||
Mockito.when(employeeRepository.findByName(john.getName())).thenReturn(john);
|
Mockito.when(employeeRepository.findByName(john.getName())).thenReturn(john);
|
||||||
Mockito.when(employeeRepository.findByName(alex.getName())).thenReturn(alex);
|
Mockito.when(employeeRepository.findByName(alex.getName())).thenReturn(alex);
|
||||||
Mockito.when(employeeRepository.findByName("wrong_name")).thenReturn(null);
|
Mockito.when(employeeRepository.findByName("wrong_name")).thenReturn(null);
|
||||||
Mockito.when(employeeRepository.findById(john.getId()).orElse(null)).thenReturn(john);
|
Mockito.when(employeeRepository.findById(john.getId())).thenReturn(Optional.of(john));
|
||||||
Mockito.when(employeeRepository.findAll()).thenReturn(allEmployees);
|
Mockito.when(employeeRepository.findAll()).thenReturn(allEmployees);
|
||||||
Mockito.when(employeeRepository.findById(-99L).orElse(null)).thenReturn(null);
|
Mockito.when(employeeRepository.findById(-99L)).thenReturn(Optional.empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -0,0 +1,31 @@
|
|||||||
|
package com.baeldung.config.scope;
|
||||||
|
|
||||||
|
import java.util.function.Function;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.context.annotation.Scope;
|
||||||
|
|
||||||
|
import com.baeldung.scope.prototype.PrototypeBean;
|
||||||
|
import com.baeldung.scope.singletone.SingletonFunctionBean;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class AppConfigFunctionBean {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public Function<String, PrototypeBean> beanFactory() {
|
||||||
|
return name -> prototypeBeanWithParam(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@Scope(value = "prototype")
|
||||||
|
public PrototypeBean prototypeBeanWithParam(String name) {
|
||||||
|
return new PrototypeBean(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public SingletonFunctionBean singletonFunctionBean() {
|
||||||
|
return new SingletonFunctionBean();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -40,4 +40,5 @@ public class AppConfig {
|
|||||||
public SingletonObjectFactoryBean singletonObjectFactoryBean() {
|
public SingletonObjectFactoryBean singletonObjectFactoryBean() {
|
||||||
return new SingletonObjectFactoryBean();
|
return new SingletonObjectFactoryBean();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -2,6 +2,7 @@ package com.baeldung.scope;
|
|||||||
|
|
||||||
import com.baeldung.scope.prototype.PrototypeBean;
|
import com.baeldung.scope.prototype.PrototypeBean;
|
||||||
import com.baeldung.scope.singletone.SingletonBean;
|
import com.baeldung.scope.singletone.SingletonBean;
|
||||||
|
|
||||||
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
|
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
|
||||||
import org.springframework.context.annotation.*;
|
import org.springframework.context.annotation.*;
|
||||||
|
|
||||||
@ -19,4 +20,5 @@ public class AppProxyScopeConfig {
|
|||||||
public SingletonBean singletonBean() {
|
public SingletonBean singletonBean() {
|
||||||
return new SingletonBean();
|
return new SingletonBean();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -9,4 +9,20 @@ public class PrototypeBean {
|
|||||||
public PrototypeBean() {
|
public PrototypeBean() {
|
||||||
logger.info("Prototype instance created");
|
logger.info("Prototype instance created");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
public PrototypeBean(String name) {
|
||||||
|
this.name = name;
|
||||||
|
logger.info("Prototype instance " + name + " created");
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,19 @@
|
|||||||
|
package com.baeldung.scope.singletone;
|
||||||
|
|
||||||
|
import java.util.function.Function;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
|
||||||
|
import com.baeldung.scope.prototype.PrototypeBean;
|
||||||
|
|
||||||
|
public class SingletonFunctionBean {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private Function<String, PrototypeBean> beanFactory;
|
||||||
|
|
||||||
|
public PrototypeBean getPrototypeInstance(String name) {
|
||||||
|
PrototypeBean bean = beanFactory.apply(name);
|
||||||
|
return bean;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,6 +1,7 @@
|
|||||||
package com.baeldung.scope;
|
package com.baeldung.scope;
|
||||||
|
|
||||||
import com.baeldung.scope.prototype.PrototypeBean;
|
import com.baeldung.scope.prototype.PrototypeBean;
|
||||||
|
import com.baeldung.scope.singletone.SingletonFunctionBean;
|
||||||
import com.baeldung.scope.singletone.SingletonLookupBean;
|
import com.baeldung.scope.singletone.SingletonLookupBean;
|
||||||
import com.baeldung.scope.singletone.SingletonObjectFactoryBean;
|
import com.baeldung.scope.singletone.SingletonObjectFactoryBean;
|
||||||
import com.baeldung.scope.singletone.SingletonProviderBean;
|
import com.baeldung.scope.singletone.SingletonProviderBean;
|
||||||
@ -58,4 +59,5 @@ public class PrototypeBeanInjectionIntegrationTest {
|
|||||||
|
|
||||||
Assert.assertTrue("New instance expected", firstInstance != secondInstance);
|
Assert.assertTrue("New instance expected", firstInstance != secondInstance);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,34 @@
|
|||||||
|
package com.baeldung.scope;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||||
|
import org.springframework.context.support.AbstractApplicationContext;
|
||||||
|
import org.springframework.test.context.ContextConfiguration;
|
||||||
|
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||||
|
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||||
|
|
||||||
|
import com.baeldung.config.scope.AppConfigFunctionBean;
|
||||||
|
import com.baeldung.scope.prototype.PrototypeBean;
|
||||||
|
import com.baeldung.scope.singletone.SingletonFunctionBean;
|
||||||
|
|
||||||
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
|
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = AppConfigFunctionBean.class)
|
||||||
|
public class PrototypeFunctionBeanIntegrationTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPrototypeInjection_WhenFunction_ThenNewInstanceReturn() {
|
||||||
|
|
||||||
|
AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfigFunctionBean.class);
|
||||||
|
|
||||||
|
SingletonFunctionBean firstContext = context.getBean(SingletonFunctionBean.class);
|
||||||
|
SingletonFunctionBean secondContext = context.getBean(SingletonFunctionBean.class);
|
||||||
|
|
||||||
|
PrototypeBean firstInstance = firstContext.getPrototypeInstance("instance1");
|
||||||
|
PrototypeBean secondInstance = secondContext.getPrototypeInstance("instance2");
|
||||||
|
|
||||||
|
Assert.assertTrue("New instance expected", firstInstance != secondInstance);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -9,9 +9,9 @@
|
|||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-spring-4</artifactId>
|
<artifactId>parent-spring-5</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<relativePath>../parent-spring-4</relativePath>
|
<relativePath>../parent-spring-5</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
@ -19,13 +19,14 @@
|
|||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-core</artifactId>
|
<artifactId>spring-core</artifactId>
|
||||||
<version>${spring.version}</version>
|
<version>${spring.version}</version>
|
||||||
<exclusions>
|
|
||||||
<exclusion>
|
|
||||||
<artifactId>commons-logging</artifactId>
|
|
||||||
<groupId>commons-logging</groupId>
|
|
||||||
</exclusion>
|
|
||||||
</exclusions>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-context</artifactId>
|
||||||
|
<version>${spring.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.data</groupId>
|
<groupId>org.springframework.data</groupId>
|
||||||
<artifactId>spring-data-elasticsearch</artifactId>
|
<artifactId>spring-data-elasticsearch</artifactId>
|
||||||
@ -33,7 +34,18 @@
|
|||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.spatial4j</groupId>
|
<groupId>org.elasticsearch</groupId>
|
||||||
|
<artifactId>elasticsearch</artifactId>
|
||||||
|
<version>${elasticsearch.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.alibaba</groupId>
|
||||||
|
<artifactId>fastjson</artifactId>
|
||||||
|
<version>${fastjson.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.locationtech.spatial4j</groupId>
|
||||||
<artifactId>spatial4j</artifactId>
|
<artifactId>spatial4j</artifactId>
|
||||||
<version>${spatial4j.version}</version>
|
<version>${spatial4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
@ -50,40 +62,43 @@
|
|||||||
</exclusions>
|
</exclusions>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.logging.log4j</groupId>
|
||||||
|
<artifactId>log4j-core</artifactId>
|
||||||
|
<version>${log4j.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.elasticsearch.client</groupId>
|
||||||
|
<artifactId>transport</artifactId>
|
||||||
|
<version>${elasticsearch.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-test</artifactId>
|
<artifactId>spring-test</artifactId>
|
||||||
<version>${spring.version}</version>
|
<version>${spring.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>net.java.dev.jna</groupId>
|
<groupId>net.java.dev.jna</groupId>
|
||||||
<artifactId>jna</artifactId>
|
<artifactId>jna</artifactId>
|
||||||
<version>${jna.version}</version>
|
<version>${jna.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.elasticsearch</groupId>
|
|
||||||
<artifactId>elasticsearch</artifactId>
|
|
||||||
<version>${elasticsearch.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.alibaba</groupId>
|
|
||||||
<artifactId>fastjson</artifactId>
|
|
||||||
<version>${fastjson.version}</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<maven.compiler.source>1.8</maven.compiler.source>
|
<maven.compiler.source>1.8</maven.compiler.source>
|
||||||
<maven.compiler.target>1.8</maven.compiler.target>
|
<maven.compiler.target>1.8</maven.compiler.target>
|
||||||
<spring-data-elasticsearch.version>2.0.5.RELEASE</spring-data-elasticsearch.version>
|
<spring-data-elasticsearch.version>3.0.8.RELEASE</spring-data-elasticsearch.version>
|
||||||
<jna.version>4.2.2</jna.version>
|
<jna.version>4.5.2</jna.version>
|
||||||
<elasticsearch.version>2.4.2</elasticsearch.version>
|
<elasticsearch.version>5.6.0</elasticsearch.version>
|
||||||
<fastjson.version>1.2.21</fastjson.version>
|
<fastjson.version>1.2.47</fastjson.version>
|
||||||
<spatial4j.version>0.4.1</spatial4j.version>
|
<spatial4j.version>0.6</spatial4j.version>
|
||||||
<jts.version>1.13</jts.version>
|
<jts.version>1.13</jts.version>
|
||||||
|
<log4j.version>2.9.1</log4j.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -1,15 +1,13 @@
|
|||||||
package com.baeldung.spring.data.es.config;
|
package com.baeldung.spring.data.es.config;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.net.InetAddress;
|
||||||
import java.nio.file.Files;
|
import java.net.UnknownHostException;
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.nio.file.Paths;
|
|
||||||
|
|
||||||
import org.elasticsearch.client.Client;
|
import org.elasticsearch.client.Client;
|
||||||
|
import org.elasticsearch.client.transport.TransportClient;
|
||||||
import org.elasticsearch.common.settings.Settings;
|
import org.elasticsearch.common.settings.Settings;
|
||||||
import org.elasticsearch.node.NodeBuilder;
|
import org.elasticsearch.common.transport.InetSocketTransportAddress;
|
||||||
import org.slf4j.Logger;
|
import org.elasticsearch.transport.client.PreBuiltTransportClient;
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.ComponentScan;
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
@ -23,35 +21,26 @@ import org.springframework.data.elasticsearch.repository.config.EnableElasticsea
|
|||||||
@ComponentScan(basePackages = { "com.baeldung.spring.data.es.service" })
|
@ComponentScan(basePackages = { "com.baeldung.spring.data.es.service" })
|
||||||
public class Config {
|
public class Config {
|
||||||
|
|
||||||
@Value("${elasticsearch.home:/usr/local/Cellar/elasticsearch/2.3.2}")
|
@Value("${elasticsearch.home:/usr/local/Cellar/elasticsearch/5.6.0}")
|
||||||
private String elasticsearchHome;
|
private String elasticsearchHome;
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(Config.class);
|
@Value("${elasticsearch.cluster.name:elasticsearch}")
|
||||||
|
private String clusterName;
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public Client client() {
|
public Client client() {
|
||||||
|
TransportClient client = null;
|
||||||
try {
|
try {
|
||||||
final Path tmpDir = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "elasticsearch_data");
|
final Settings elasticsearchSettings = Settings.builder()
|
||||||
logger.debug(tmpDir.toAbsolutePath().toString());
|
.put("client.transport.sniff", true)
|
||||||
|
.put("path.home", elasticsearchHome)
|
||||||
// @formatter:off
|
.put("cluster.name", clusterName).build();
|
||||||
|
client = new PreBuiltTransportClient(elasticsearchSettings);
|
||||||
final Settings.Builder elasticsearchSettings =
|
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
|
||||||
Settings.settingsBuilder().put("http.enabled", "false")
|
} catch (UnknownHostException e) {
|
||||||
.put("path.data", tmpDir.toAbsolutePath().toString())
|
e.printStackTrace();
|
||||||
.put("path.home", elasticsearchHome);
|
|
||||||
|
|
||||||
return new NodeBuilder()
|
|
||||||
.local(true)
|
|
||||||
.settings(elasticsearchSettings)
|
|
||||||
.node()
|
|
||||||
.client();
|
|
||||||
|
|
||||||
// @formatter:on
|
|
||||||
} catch (final IOException ioex) {
|
|
||||||
logger.error("Cannot create temp dir", ioex);
|
|
||||||
throw new RuntimeException();
|
|
||||||
}
|
}
|
||||||
|
return client;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
package com.baeldung.spring.data.es.model;
|
package com.baeldung.spring.data.es.model;
|
||||||
|
|
||||||
import static org.springframework.data.elasticsearch.annotations.FieldIndex.not_analyzed;
|
import static org.springframework.data.elasticsearch.annotations.FieldType.Keyword;
|
||||||
import static org.springframework.data.elasticsearch.annotations.FieldType.Nested;
|
import static org.springframework.data.elasticsearch.annotations.FieldType.Nested;
|
||||||
import static org.springframework.data.elasticsearch.annotations.FieldType.String;
|
import static org.springframework.data.elasticsearch.annotations.FieldType.Text;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@ -19,13 +19,13 @@ public class Article {
|
|||||||
@Id
|
@Id
|
||||||
private String id;
|
private String id;
|
||||||
|
|
||||||
@MultiField(mainField = @Field(type = String), otherFields = { @InnerField(index = not_analyzed, suffix = "verbatim", type = String) })
|
@MultiField(mainField = @Field(type = Text, fielddata = true), otherFields = { @InnerField(suffix = "verbatim", type = Keyword) })
|
||||||
private String title;
|
private String title;
|
||||||
|
|
||||||
@Field(type = Nested)
|
@Field(type = Nested, includeInParent = true)
|
||||||
private List<Author> authors;
|
private List<Author> authors;
|
||||||
|
|
||||||
@Field(type = String, index = not_analyzed)
|
@Field(type = Keyword)
|
||||||
private String[] tags;
|
private String[] tags;
|
||||||
|
|
||||||
public Article() {
|
public Article() {
|
||||||
|
@ -1,5 +1,7 @@
|
|||||||
package com.baeldung.spring.data.es.service;
|
package com.baeldung.spring.data.es.service;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
import org.springframework.data.domain.Pageable;
|
import org.springframework.data.domain.Pageable;
|
||||||
|
|
||||||
@ -8,7 +10,7 @@ import com.baeldung.spring.data.es.model.Article;
|
|||||||
public interface ArticleService {
|
public interface ArticleService {
|
||||||
Article save(Article article);
|
Article save(Article article);
|
||||||
|
|
||||||
Article findOne(String id);
|
Optional<Article> findOne(String id);
|
||||||
|
|
||||||
Iterable<Article> findAll();
|
Iterable<Article> findAll();
|
||||||
|
|
||||||
|
@ -1,5 +1,7 @@
|
|||||||
package com.baeldung.spring.data.es.service;
|
package com.baeldung.spring.data.es.service;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
import org.springframework.data.domain.Pageable;
|
import org.springframework.data.domain.Pageable;
|
||||||
@ -24,8 +26,8 @@ public class ArticleServiceImpl implements ArticleService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Article findOne(String id) {
|
public Optional<Article> findOne(String id) {
|
||||||
return articleRepository.findOne(id);
|
return articleRepository.findById(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -0,0 +1,6 @@
|
|||||||
|
appender.console.type = Console
|
||||||
|
appender.console.name = console
|
||||||
|
appender.console.layout.type = PatternLayout
|
||||||
|
|
||||||
|
rootLogger.level = info
|
||||||
|
rootLogger.appenderRef.console.ref = console
|
@ -1,19 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<configuration>
|
|
||||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
|
||||||
<encoder>
|
|
||||||
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
|
|
||||||
</pattern>
|
|
||||||
</encoder>
|
|
||||||
</appender>
|
|
||||||
|
|
||||||
<logger name="org.springframework" level="WARN" />
|
|
||||||
<logger name="org.springframework.transaction" level="WARN" />
|
|
||||||
|
|
||||||
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
|
||||||
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
|
|
||||||
|
|
||||||
<root level="INFO">
|
|
||||||
<appender-ref ref="STDOUT" />
|
|
||||||
</root>
|
|
||||||
</configuration>
|
|
@ -1,45 +1,49 @@
|
|||||||
package com.baeldung.elasticsearch;
|
package com.baeldung.elasticsearch;
|
||||||
|
|
||||||
import com.alibaba.fastjson.JSON;
|
import static org.junit.Assert.assertEquals;
|
||||||
import org.elasticsearch.action.delete.DeleteResponse;
|
|
||||||
import org.elasticsearch.action.index.IndexResponse;
|
|
||||||
import org.elasticsearch.action.search.SearchResponse;
|
|
||||||
import org.elasticsearch.action.search.SearchType;
|
|
||||||
import org.elasticsearch.client.Client;
|
|
||||||
import org.elasticsearch.common.xcontent.XContentBuilder;
|
|
||||||
import org.elasticsearch.common.xcontent.XContentFactory;
|
|
||||||
import org.elasticsearch.index.query.QueryBuilders;
|
|
||||||
import org.elasticsearch.node.Node;
|
|
||||||
import org.elasticsearch.search.SearchHit;
|
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.net.UnknownHostException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
import static org.elasticsearch.node.NodeBuilder.nodeBuilder;
|
import org.elasticsearch.action.DocWriteResponse.Result;
|
||||||
import static org.junit.Assert.assertEquals;
|
import org.elasticsearch.action.delete.DeleteResponse;
|
||||||
import static org.junit.Assert.assertTrue;
|
import org.elasticsearch.action.index.IndexResponse;
|
||||||
|
import org.elasticsearch.action.search.SearchResponse;
|
||||||
|
import org.elasticsearch.action.search.SearchType;
|
||||||
|
import org.elasticsearch.client.Client;
|
||||||
|
import org.elasticsearch.common.settings.Settings;
|
||||||
|
import org.elasticsearch.common.transport.InetSocketTransportAddress;
|
||||||
|
import org.elasticsearch.common.xcontent.XContentBuilder;
|
||||||
|
import org.elasticsearch.common.xcontent.XContentFactory;
|
||||||
|
import org.elasticsearch.common.xcontent.XContentType;
|
||||||
|
import org.elasticsearch.index.query.QueryBuilders;
|
||||||
|
import org.elasticsearch.search.SearchHit;
|
||||||
|
import org.elasticsearch.transport.client.PreBuiltTransportClient;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.alibaba.fastjson.JSON;
|
||||||
|
|
||||||
public class ElasticSearchManualTest {
|
public class ElasticSearchManualTest {
|
||||||
private List<Person> listOfPersons = new ArrayList<>();
|
private List<Person> listOfPersons = new ArrayList<>();
|
||||||
private Client client = null;
|
private Client client = null;
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setUp() {
|
public void setUp() throws UnknownHostException {
|
||||||
Person person1 = new Person(10, "John Doe", new Date());
|
Person person1 = new Person(10, "John Doe", new Date());
|
||||||
Person person2 = new Person(25, "Janette Doe", new Date());
|
Person person2 = new Person(25, "Janette Doe", new Date());
|
||||||
listOfPersons.add(person1);
|
listOfPersons.add(person1);
|
||||||
listOfPersons.add(person2);
|
listOfPersons.add(person2);
|
||||||
Node node = nodeBuilder()
|
|
||||||
.clusterName("elasticsearch")
|
client = new PreBuiltTransportClient(Settings.builder().put("client.transport.sniff", true)
|
||||||
.client(true)
|
.put("cluster.name","elasticsearch").build())
|
||||||
.node();
|
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
|
||||||
client = node.client();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -47,11 +51,12 @@ public class ElasticSearchManualTest {
|
|||||||
String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}";
|
String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}";
|
||||||
IndexResponse response = client
|
IndexResponse response = client
|
||||||
.prepareIndex("people", "Doe")
|
.prepareIndex("people", "Doe")
|
||||||
.setSource(jsonObject)
|
.setSource(jsonObject, XContentType.JSON)
|
||||||
.get();
|
.get();
|
||||||
String index = response.getIndex();
|
String index = response.getIndex();
|
||||||
String type = response.getType();
|
String type = response.getType();
|
||||||
assertTrue(response.isCreated());
|
|
||||||
|
assertEquals(Result.CREATED, response.getResult());
|
||||||
assertEquals(index, "people");
|
assertEquals(index, "people");
|
||||||
assertEquals(type, "Doe");
|
assertEquals(type, "Doe");
|
||||||
}
|
}
|
||||||
@ -61,13 +66,14 @@ public class ElasticSearchManualTest {
|
|||||||
String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}";
|
String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}";
|
||||||
IndexResponse response = client
|
IndexResponse response = client
|
||||||
.prepareIndex("people", "Doe")
|
.prepareIndex("people", "Doe")
|
||||||
.setSource(jsonObject)
|
.setSource(jsonObject, XContentType.JSON)
|
||||||
.get();
|
.get();
|
||||||
String id = response.getId();
|
String id = response.getId();
|
||||||
DeleteResponse deleteResponse = client
|
DeleteResponse deleteResponse = client
|
||||||
.prepareDelete("people", "Doe", id)
|
.prepareDelete("people", "Doe", id)
|
||||||
.get();
|
.get();
|
||||||
assertTrue(deleteResponse.isFound());
|
|
||||||
|
assertEquals(Result.DELETED,deleteResponse.getResult());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -142,6 +148,7 @@ public class ElasticSearchManualTest {
|
|||||||
.prepareIndex("people", "Doe")
|
.prepareIndex("people", "Doe")
|
||||||
.setSource(builder)
|
.setSource(builder)
|
||||||
.get();
|
.get();
|
||||||
assertTrue(response.isCreated());
|
|
||||||
|
assertEquals(Result.CREATED, response.getResult());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,13 +1,21 @@
|
|||||||
package com.baeldung.elasticsearch;
|
package com.baeldung.elasticsearch;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
import com.baeldung.spring.data.es.config.Config;
|
|
||||||
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
|
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
|
||||||
import org.elasticsearch.action.index.IndexResponse;
|
import org.elasticsearch.action.index.IndexResponse;
|
||||||
import org.elasticsearch.action.search.SearchResponse;
|
import org.elasticsearch.action.search.SearchResponse;
|
||||||
import org.elasticsearch.client.Client;
|
import org.elasticsearch.client.Client;
|
||||||
|
import org.elasticsearch.common.geo.GeoPoint;
|
||||||
import org.elasticsearch.common.geo.ShapeRelation;
|
import org.elasticsearch.common.geo.ShapeRelation;
|
||||||
import org.elasticsearch.common.geo.builders.ShapeBuilder;
|
import org.elasticsearch.common.geo.builders.ShapeBuilders;
|
||||||
import org.elasticsearch.common.unit.DistanceUnit;
|
import org.elasticsearch.common.unit.DistanceUnit;
|
||||||
|
import org.elasticsearch.common.xcontent.XContentType;
|
||||||
import org.elasticsearch.index.query.QueryBuilder;
|
import org.elasticsearch.index.query.QueryBuilder;
|
||||||
import org.elasticsearch.index.query.QueryBuilders;
|
import org.elasticsearch.index.query.QueryBuilders;
|
||||||
import org.elasticsearch.search.SearchHit;
|
import org.elasticsearch.search.SearchHit;
|
||||||
@ -20,11 +28,8 @@ import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
|
|||||||
import org.springframework.test.context.ContextConfiguration;
|
import org.springframework.test.context.ContextConfiguration;
|
||||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import com.baeldung.spring.data.es.config.Config;
|
||||||
import java.util.List;
|
import com.vividsolutions.jts.geom.Coordinate;
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@ContextConfiguration(classes = Config.class)
|
@ContextConfiguration(classes = Config.class)
|
||||||
@ -43,7 +48,7 @@ public class GeoQueriesIntegrationTest {
|
|||||||
public void setUp() {
|
public void setUp() {
|
||||||
String jsonObject = "{\"Wonders\":{\"properties\":{\"name\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"region\":{\"type\":\"geo_shape\",\"tree\":\"quadtree\",\"precision\":\"1m\"},\"location\":{\"type\":\"geo_point\"}}}}";
|
String jsonObject = "{\"Wonders\":{\"properties\":{\"name\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"region\":{\"type\":\"geo_shape\",\"tree\":\"quadtree\",\"precision\":\"1m\"},\"location\":{\"type\":\"geo_point\"}}}}";
|
||||||
CreateIndexRequest req = new CreateIndexRequest(WONDERS_OF_WORLD);
|
CreateIndexRequest req = new CreateIndexRequest(WONDERS_OF_WORLD);
|
||||||
req.mapping(WONDERS, jsonObject);
|
req.mapping(WONDERS, jsonObject, XContentType.JSON);
|
||||||
client.admin()
|
client.admin()
|
||||||
.indices()
|
.indices()
|
||||||
.create(req)
|
.create(req)
|
||||||
@ -51,31 +56,36 @@ public class GeoQueriesIntegrationTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenGeoShapeData_whenExecutedGeoShapeQuery_thenResultNonEmpty() {
|
public void givenGeoShapeData_whenExecutedGeoShapeQuery_thenResultNonEmpty() throws IOException{
|
||||||
String jsonObject = "{\"name\":\"Agra\",\"region\":{\"type\":\"envelope\",\"coordinates\":[[75,25],[80.1,30.2]]}}";
|
String jsonObject = "{\"name\":\"Agra\",\"region\":{\"type\":\"envelope\",\"coordinates\":[[75,30.2],[80.1, 25]]}}";
|
||||||
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
|
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
|
||||||
.setSource(jsonObject)
|
.setSource(jsonObject, XContentType.JSON)
|
||||||
.get();
|
.get();
|
||||||
|
|
||||||
String tajMahalId = response.getId();
|
String tajMahalId = response.getId();
|
||||||
client.admin()
|
client.admin()
|
||||||
.indices()
|
.indices()
|
||||||
.prepareRefresh(WONDERS_OF_WORLD)
|
.prepareRefresh(WONDERS_OF_WORLD)
|
||||||
.get();
|
.get();
|
||||||
|
|
||||||
QueryBuilder qb = QueryBuilders.geoShapeQuery("region", ShapeBuilder.newEnvelope()
|
Coordinate topLeft =new Coordinate(74, 31.2);
|
||||||
.topLeft(74.00, 24.0)
|
Coordinate bottomRight =new Coordinate(81.1, 24);
|
||||||
.bottomRight(81.1, 31.2))
|
QueryBuilder qb = QueryBuilders
|
||||||
|
.geoShapeQuery("region", ShapeBuilders.newEnvelope(topLeft, bottomRight))
|
||||||
.relation(ShapeRelation.WITHIN);
|
.relation(ShapeRelation.WITHIN);
|
||||||
|
|
||||||
|
|
||||||
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD)
|
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD)
|
||||||
.setTypes(WONDERS)
|
.setTypes(WONDERS)
|
||||||
.setQuery(qb)
|
.setQuery(qb)
|
||||||
.execute()
|
.execute()
|
||||||
.actionGet();
|
.actionGet();
|
||||||
|
|
||||||
List<String> ids = Arrays.stream(searchResponse.getHits()
|
List<String> ids = Arrays.stream(searchResponse.getHits()
|
||||||
.getHits())
|
.getHits())
|
||||||
.map(SearchHit::getId)
|
.map(SearchHit::getId)
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
assertTrue(ids.contains(tajMahalId));
|
assertTrue(ids.contains(tajMahalId));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -83,7 +93,7 @@ public class GeoQueriesIntegrationTest {
|
|||||||
public void givenGeoPointData_whenExecutedGeoBoundingBoxQuery_thenResultNonEmpty() {
|
public void givenGeoPointData_whenExecutedGeoBoundingBoxQuery_thenResultNonEmpty() {
|
||||||
String jsonObject = "{\"name\":\"Pyramids of Giza\",\"location\":[31.131302,29.976480]}";
|
String jsonObject = "{\"name\":\"Pyramids of Giza\",\"location\":[31.131302,29.976480]}";
|
||||||
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
|
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
|
||||||
.setSource(jsonObject)
|
.setSource(jsonObject, XContentType.JSON)
|
||||||
.get();
|
.get();
|
||||||
String pyramidsOfGizaId = response.getId();
|
String pyramidsOfGizaId = response.getId();
|
||||||
client.admin()
|
client.admin()
|
||||||
@ -92,8 +102,7 @@ public class GeoQueriesIntegrationTest {
|
|||||||
.get();
|
.get();
|
||||||
|
|
||||||
QueryBuilder qb = QueryBuilders.geoBoundingBoxQuery("location")
|
QueryBuilder qb = QueryBuilders.geoBoundingBoxQuery("location")
|
||||||
.bottomLeft(28, 30)
|
.setCorners(31,30,28,32);
|
||||||
.topRight(31, 32);
|
|
||||||
|
|
||||||
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD)
|
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD)
|
||||||
.setTypes(WONDERS)
|
.setTypes(WONDERS)
|
||||||
@ -111,7 +120,7 @@ public class GeoQueriesIntegrationTest {
|
|||||||
public void givenGeoPointData_whenExecutedGeoDistanceQuery_thenResultNonEmpty() {
|
public void givenGeoPointData_whenExecutedGeoDistanceQuery_thenResultNonEmpty() {
|
||||||
String jsonObject = "{\"name\":\"Lighthouse of alexandria\",\"location\":[31.131302,29.976480]}";
|
String jsonObject = "{\"name\":\"Lighthouse of alexandria\",\"location\":[31.131302,29.976480]}";
|
||||||
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
|
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
|
||||||
.setSource(jsonObject)
|
.setSource(jsonObject, XContentType.JSON)
|
||||||
.get();
|
.get();
|
||||||
String lighthouseOfAlexandriaId = response.getId();
|
String lighthouseOfAlexandriaId = response.getId();
|
||||||
client.admin()
|
client.admin()
|
||||||
@ -139,7 +148,7 @@ public class GeoQueriesIntegrationTest {
|
|||||||
public void givenGeoPointData_whenExecutedGeoPolygonQuery_thenResultNonEmpty() {
|
public void givenGeoPointData_whenExecutedGeoPolygonQuery_thenResultNonEmpty() {
|
||||||
String jsonObject = "{\"name\":\"The Great Rann of Kutch\",\"location\":[69.859741,23.733732]}";
|
String jsonObject = "{\"name\":\"The Great Rann of Kutch\",\"location\":[69.859741,23.733732]}";
|
||||||
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
|
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
|
||||||
.setSource(jsonObject)
|
.setSource(jsonObject, XContentType.JSON)
|
||||||
.get();
|
.get();
|
||||||
String greatRannOfKutchid = response.getId();
|
String greatRannOfKutchid = response.getId();
|
||||||
client.admin()
|
client.admin()
|
||||||
@ -147,10 +156,11 @@ public class GeoQueriesIntegrationTest {
|
|||||||
.prepareRefresh(WONDERS_OF_WORLD)
|
.prepareRefresh(WONDERS_OF_WORLD)
|
||||||
.get();
|
.get();
|
||||||
|
|
||||||
QueryBuilder qb = QueryBuilders.geoPolygonQuery("location")
|
List<GeoPoint> allPoints = new ArrayList<GeoPoint>();
|
||||||
.addPoint(22.733, 68.859)
|
allPoints.add(new GeoPoint(22.733, 68.859));
|
||||||
.addPoint(24.733, 68.859)
|
allPoints.add(new GeoPoint(24.733, 68.859));
|
||||||
.addPoint(23, 70.859);
|
allPoints.add(new GeoPoint(23, 70.859));
|
||||||
|
QueryBuilder qb = QueryBuilders.geoPolygonQuery("location", allPoints);
|
||||||
|
|
||||||
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD)
|
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD)
|
||||||
.setTypes(WONDERS)
|
.setTypes(WONDERS)
|
||||||
|
@ -1,9 +1,15 @@
|
|||||||
package com.baeldung.spring.data.es;
|
package com.baeldung.spring.data.es;
|
||||||
|
|
||||||
import com.baeldung.spring.data.es.config.Config;
|
import static java.util.Arrays.asList;
|
||||||
import com.baeldung.spring.data.es.model.Article;
|
import static org.elasticsearch.index.query.Operator.AND;
|
||||||
import com.baeldung.spring.data.es.model.Author;
|
import static org.elasticsearch.index.query.QueryBuilders.fuzzyQuery;
|
||||||
import com.baeldung.spring.data.es.service.ArticleService;
|
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
|
||||||
|
import static org.elasticsearch.index.query.QueryBuilders.regexpQuery;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
@ -16,15 +22,10 @@ import org.springframework.data.elasticsearch.core.query.SearchQuery;
|
|||||||
import org.springframework.test.context.ContextConfiguration;
|
import org.springframework.test.context.ContextConfiguration;
|
||||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||||
|
|
||||||
import java.util.List;
|
import com.baeldung.spring.data.es.config.Config;
|
||||||
|
import com.baeldung.spring.data.es.model.Article;
|
||||||
import static java.util.Arrays.asList;
|
import com.baeldung.spring.data.es.model.Author;
|
||||||
import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND;
|
import com.baeldung.spring.data.es.service.ArticleService;
|
||||||
import static org.elasticsearch.index.query.QueryBuilders.fuzzyQuery;
|
|
||||||
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
|
|
||||||
import static org.elasticsearch.index.query.QueryBuilders.regexpQuery;
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertNotNull;
|
|
||||||
|
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@ContextConfiguration(classes = Config.class)
|
@ContextConfiguration(classes = Config.class)
|
||||||
@ -81,25 +82,25 @@ public class ElasticSearchIntegrationTest {
|
|||||||
public void givenPersistedArticles_whenSearchByAuthorsName_thenRightFound() {
|
public void givenPersistedArticles_whenSearchByAuthorsName_thenRightFound() {
|
||||||
|
|
||||||
final Page<Article> articleByAuthorName = articleService
|
final Page<Article> articleByAuthorName = articleService
|
||||||
.findByAuthorName(johnSmith.getName(), new PageRequest(0, 10));
|
.findByAuthorName(johnSmith.getName(), PageRequest.of(0, 10));
|
||||||
assertEquals(2L, articleByAuthorName.getTotalElements());
|
assertEquals(2L, articleByAuthorName.getTotalElements());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenCustomQuery_whenSearchByAuthorsName_thenArticleIsFound() {
|
public void givenCustomQuery_whenSearchByAuthorsName_thenArticleIsFound() {
|
||||||
final Page<Article> articleByAuthorName = articleService.findByAuthorNameUsingCustomQuery("Smith", new PageRequest(0, 10));
|
final Page<Article> articleByAuthorName = articleService.findByAuthorNameUsingCustomQuery("Smith", PageRequest.of(0, 10));
|
||||||
assertEquals(2L, articleByAuthorName.getTotalElements());
|
assertEquals(2L, articleByAuthorName.getTotalElements());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenTagFilterQuery_whenSearchByTag_thenArticleIsFound() {
|
public void givenTagFilterQuery_whenSearchByTag_thenArticleIsFound() {
|
||||||
final Page<Article> articleByAuthorName = articleService.findByFilteredTagQuery("elasticsearch", new PageRequest(0, 10));
|
final Page<Article> articleByAuthorName = articleService.findByFilteredTagQuery("elasticsearch", PageRequest.of(0, 10));
|
||||||
assertEquals(3L, articleByAuthorName.getTotalElements());
|
assertEquals(3L, articleByAuthorName.getTotalElements());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenTagFilterQuery_whenSearchByAuthorsName_thenArticleIsFound() {
|
public void givenTagFilterQuery_whenSearchByAuthorsName_thenArticleIsFound() {
|
||||||
final Page<Article> articleByAuthorName = articleService.findByAuthorsNameAndFilteredTagQuery("Doe", "elasticsearch", new PageRequest(0, 10));
|
final Page<Article> articleByAuthorName = articleService.findByAuthorsNameAndFilteredTagQuery("Doe", "elasticsearch", PageRequest.of(0, 10));
|
||||||
assertEquals(2L, articleByAuthorName.getTotalElements());
|
assertEquals(2L, articleByAuthorName.getTotalElements());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -125,7 +126,7 @@ public class ElasticSearchIntegrationTest {
|
|||||||
article.setTitle(newTitle);
|
article.setTitle(newTitle);
|
||||||
articleService.save(article);
|
articleService.save(article);
|
||||||
|
|
||||||
assertEquals(newTitle, articleService.findOne(article.getId()).getTitle());
|
assertEquals(newTitle, articleService.findOne(article.getId()).get().getTitle());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -1,9 +1,20 @@
|
|||||||
package com.baeldung.spring.data.es;
|
package com.baeldung.spring.data.es;
|
||||||
|
|
||||||
import com.baeldung.spring.data.es.config.Config;
|
import static java.util.Arrays.asList;
|
||||||
import com.baeldung.spring.data.es.model.Article;
|
import static java.util.stream.Collectors.toList;
|
||||||
import com.baeldung.spring.data.es.model.Author;
|
import static org.elasticsearch.index.query.Operator.AND;
|
||||||
import com.baeldung.spring.data.es.service.ArticleService;
|
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
|
||||||
|
import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;
|
||||||
|
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
|
||||||
|
import static org.elasticsearch.index.query.QueryBuilders.multiMatchQuery;
|
||||||
|
import static org.elasticsearch.index.query.QueryBuilders.nestedQuery;
|
||||||
|
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.apache.lucene.search.join.ScoreMode;
|
||||||
import org.elasticsearch.action.search.SearchResponse;
|
import org.elasticsearch.action.search.SearchResponse;
|
||||||
import org.elasticsearch.client.Client;
|
import org.elasticsearch.client.Client;
|
||||||
import org.elasticsearch.common.unit.Fuzziness;
|
import org.elasticsearch.common.unit.Fuzziness;
|
||||||
@ -14,7 +25,7 @@ import org.elasticsearch.search.aggregations.AggregationBuilders;
|
|||||||
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
|
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
|
||||||
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
|
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
|
||||||
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
|
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
|
||||||
import org.elasticsearch.search.aggregations.bucket.terms.TermsBuilder;
|
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
@ -25,20 +36,10 @@ import org.springframework.data.elasticsearch.core.query.SearchQuery;
|
|||||||
import org.springframework.test.context.ContextConfiguration;
|
import org.springframework.test.context.ContextConfiguration;
|
||||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||||
|
|
||||||
import java.util.Collections;
|
import com.baeldung.spring.data.es.config.Config;
|
||||||
import java.util.List;
|
import com.baeldung.spring.data.es.model.Article;
|
||||||
import java.util.Map;
|
import com.baeldung.spring.data.es.model.Author;
|
||||||
|
import com.baeldung.spring.data.es.service.ArticleService;
|
||||||
import static java.util.Arrays.asList;
|
|
||||||
import static java.util.stream.Collectors.toList;
|
|
||||||
import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND;
|
|
||||||
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
|
|
||||||
import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;
|
|
||||||
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
|
|
||||||
import static org.elasticsearch.index.query.QueryBuilders.multiMatchQuery;
|
|
||||||
import static org.elasticsearch.index.query.QueryBuilders.nestedQuery;
|
|
||||||
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
|
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@ContextConfiguration(classes = Config.class)
|
@ContextConfiguration(classes = Config.class)
|
||||||
@ -124,7 +125,7 @@ public class ElasticSearchQueryIntegrationTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenNestedObject_whenQueryByAuthorsName_thenFoundArticlesByThatAuthor() {
|
public void givenNestedObject_whenQueryByAuthorsName_thenFoundArticlesByThatAuthor() {
|
||||||
final QueryBuilder builder = nestedQuery("authors", boolQuery().must(termQuery("authors.name", "smith")));
|
final QueryBuilder builder = nestedQuery("authors", boolQuery().must(termQuery("authors.name", "smith")), ScoreMode.None);
|
||||||
|
|
||||||
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
|
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
|
||||||
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
||||||
@ -134,7 +135,7 @@ public class ElasticSearchQueryIntegrationTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTokenCountsSeparately() {
|
public void givenAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTokenCountsSeparately() {
|
||||||
final TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("title");
|
final TermsAggregationBuilder aggregation = AggregationBuilders.terms("top_tags").field("title");
|
||||||
final SearchResponse response = client.prepareSearch("blog").setTypes("article").addAggregation(aggregation)
|
final SearchResponse response = client.prepareSearch("blog").setTypes("article").addAggregation(aggregation)
|
||||||
.execute().actionGet();
|
.execute().actionGet();
|
||||||
|
|
||||||
@ -150,8 +151,8 @@ public class ElasticSearchQueryIntegrationTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenNotAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTermCountsIndividually() {
|
public void givenNotAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTermCountsIndividually() {
|
||||||
final TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("tags")
|
final TermsAggregationBuilder aggregation = AggregationBuilders.terms("top_tags").field("tags")
|
||||||
.order(Terms.Order.aggregation("_count", false));
|
.order(Terms.Order.count(false));
|
||||||
final SearchResponse response = client.prepareSearch("blog").setTypes("article").addAggregation(aggregation)
|
final SearchResponse response = client.prepareSearch("blog").setTypes("article").addAggregation(aggregation)
|
||||||
.execute().actionGet();
|
.execute().actionGet();
|
||||||
|
|
||||||
@ -194,7 +195,7 @@ public class ElasticSearchQueryIntegrationTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenBoolQuery_whenQueryByAuthorsName_thenFoundArticlesByThatAuthorAndFilteredTag() {
|
public void givenBoolQuery_whenQueryByAuthorsName_thenFoundArticlesByThatAuthorAndFilteredTag() {
|
||||||
final QueryBuilder builder = boolQuery().must(nestedQuery("authors", boolQuery().must(termQuery("authors.name", "doe"))))
|
final QueryBuilder builder = boolQuery().must(nestedQuery("authors", boolQuery().must(termQuery("authors.name", "doe")), ScoreMode.None))
|
||||||
.filter(termQuery("tags", "elasticsearch"));
|
.filter(termQuery("tags", "elasticsearch"));
|
||||||
|
|
||||||
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder)
|
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder)
|
||||||
|
@ -11,9 +11,7 @@ public class PushController {
|
|||||||
@GetMapping(path = "/demoWithPush")
|
@GetMapping(path = "/demoWithPush")
|
||||||
public String demoWithPush(PushBuilder pushBuilder) {
|
public String demoWithPush(PushBuilder pushBuilder) {
|
||||||
if (null != pushBuilder) {
|
if (null != pushBuilder) {
|
||||||
pushBuilder.path("resources/logo.png")
|
pushBuilder.path("resources/logo.png").push();
|
||||||
.addHeader("Content-Type", "image/png")
|
|
||||||
.push();
|
|
||||||
}
|
}
|
||||||
return "demo";
|
return "demo";
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user