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,85 +1,92 @@
|
||||
package com.baeldung.connectionpool.connectionpools;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class BasicConnectionPool implements ConnectionPool {
|
||||
|
||||
private final String url;
|
||||
private final String user;
|
||||
private final String password;
|
||||
private final List<Connection> connectionPool;
|
||||
private final List<Connection> usedConnections = new ArrayList<>();
|
||||
private static final int INITIAL_POOL_SIZE = 10;
|
||||
private final int MAX_POOL_SIZE = 20;
|
||||
|
||||
public static BasicConnectionPool create(String url, String user, String password) throws SQLException {
|
||||
List<Connection> pool = new ArrayList<>(INITIAL_POOL_SIZE);
|
||||
for (int i = 0; i < INITIAL_POOL_SIZE; i++) {
|
||||
pool.add(createConnection(url, user, password));
|
||||
}
|
||||
return new BasicConnectionPool(url, user, password, pool);
|
||||
}
|
||||
|
||||
private BasicConnectionPool(String url, String user, String password, List<Connection> connectionPool) {
|
||||
this.url = url;
|
||||
this.user = user;
|
||||
this.password = password;
|
||||
this.connectionPool = connectionPool;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Connection getConnection() throws SQLException {
|
||||
if (connectionPool.isEmpty()) {
|
||||
if (usedConnections.size() < MAX_POOL_SIZE) {
|
||||
connectionPool.add(createConnection(url, user, password));
|
||||
} else {
|
||||
throw new RuntimeException("Maximum pool size reached, no available connections!");
|
||||
}
|
||||
}
|
||||
|
||||
Connection connection = connectionPool.remove(connectionPool.size() - 1);
|
||||
usedConnections.add(connection);
|
||||
return connection;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean releaseConnection(Connection connection) {
|
||||
connectionPool.add(connection);
|
||||
return usedConnections.remove(connection);
|
||||
}
|
||||
|
||||
private static Connection createConnection(String url, String user, String password) throws SQLException {
|
||||
return DriverManager.getConnection(url, user, password);
|
||||
}
|
||||
|
||||
public int getSize() {
|
||||
return connectionPool.size() + usedConnections.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void shutdown() throws SQLException {
|
||||
usedConnections.forEach(this::releaseConnection);
|
||||
for (Connection c : connectionPool) {
|
||||
c.close();
|
||||
}
|
||||
connectionPool.clear();
|
||||
}
|
||||
}
|
||||
package com.baeldung.connectionpool;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class BasicConnectionPool implements ConnectionPool {
|
||||
|
||||
private final String url;
|
||||
private final String user;
|
||||
private final String password;
|
||||
private final List<Connection> connectionPool;
|
||||
private final List<Connection> usedConnections = new ArrayList<>();
|
||||
private static final int INITIAL_POOL_SIZE = 10;
|
||||
private final int MAX_POOL_SIZE = 20;
|
||||
|
||||
public static BasicConnectionPool create(String url, String user, String password) throws SQLException {
|
||||
List<Connection> pool = new ArrayList<>(INITIAL_POOL_SIZE);
|
||||
for (int i = 0; i < INITIAL_POOL_SIZE; i++) {
|
||||
pool.add(createConnection(url, user, password));
|
||||
}
|
||||
return new BasicConnectionPool(url, user, password, pool);
|
||||
}
|
||||
|
||||
private BasicConnectionPool(String url, String user, String password, List<Connection> connectionPool) {
|
||||
this.url = url;
|
||||
this.user = user;
|
||||
this.password = password;
|
||||
this.connectionPool = connectionPool;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Connection getConnection() throws SQLException {
|
||||
if (connectionPool.isEmpty()) {
|
||||
if (usedConnections.size() < MAX_POOL_SIZE) {
|
||||
connectionPool.add(createConnection(url, user, password));
|
||||
} else {
|
||||
throw new RuntimeException("Maximum pool size reached, no available connections!");
|
||||
}
|
||||
}
|
||||
|
||||
Connection connection = connectionPool.remove(connectionPool.size() - 1);
|
||||
usedConnections.add(connection);
|
||||
return connection;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean releaseConnection(Connection connection) {
|
||||
connectionPool.add(connection);
|
||||
return usedConnections.remove(connection);
|
||||
}
|
||||
|
||||
private static Connection createConnection(String url, String user, String password) throws SQLException {
|
||||
return DriverManager.getConnection(url, user, password);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getSize() {
|
||||
return connectionPool.size() + usedConnections.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Connection> getConnectionPool() {
|
||||
return connectionPool;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() throws SQLException {
|
||||
usedConnections.forEach(this::releaseConnection);
|
||||
for (Connection c : connectionPool) {
|
||||
c.close();
|
||||
}
|
||||
connectionPool.clear();
|
||||
}
|
||||
}
|
@ -1,28 +1,28 @@
|
||||
package com.baeldung.connectionpool.connectionpools;
|
||||
|
||||
import com.mchange.v2.c3p0.ComboPooledDataSource;
|
||||
import java.beans.PropertyVetoException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class C3poDataSource {
|
||||
|
||||
private static final ComboPooledDataSource cpds = new ComboPooledDataSource();
|
||||
|
||||
static {
|
||||
try {
|
||||
cpds.setDriverClass("org.h2.Driver");
|
||||
cpds.setJdbcUrl("jdbc:h2:mem:test");
|
||||
cpds.setUser("user");
|
||||
cpds.setPassword("password");
|
||||
} catch (PropertyVetoException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static Connection getConnection() throws SQLException {
|
||||
return cpds.getConnection();
|
||||
}
|
||||
|
||||
private C3poDataSource(){}
|
||||
package com.baeldung.connectionpool;
|
||||
|
||||
import com.mchange.v2.c3p0.ComboPooledDataSource;
|
||||
import java.beans.PropertyVetoException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class C3poDataSource {
|
||||
|
||||
private static final ComboPooledDataSource cpds = new ComboPooledDataSource();
|
||||
|
||||
static {
|
||||
try {
|
||||
cpds.setDriverClass("org.h2.Driver");
|
||||
cpds.setJdbcUrl("jdbc:h2:mem:test");
|
||||
cpds.setUser("user");
|
||||
cpds.setPassword("password");
|
||||
} catch (PropertyVetoException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static Connection getConnection() throws SQLException {
|
||||
return cpds.getConnection();
|
||||
}
|
||||
|
||||
private C3poDataSource(){}
|
||||
}
|
@ -1,18 +1,24 @@
|
||||
package com.baeldung.connectionpool.connectionpools;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
public interface ConnectionPool {
|
||||
|
||||
Connection getConnection() throws SQLException;
|
||||
|
||||
boolean releaseConnection(Connection connection);
|
||||
|
||||
String getUrl();
|
||||
|
||||
String getUser();
|
||||
|
||||
String getPassword();
|
||||
package com.baeldung.connectionpool;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
public interface ConnectionPool {
|
||||
|
||||
Connection getConnection() throws SQLException;
|
||||
|
||||
boolean releaseConnection(Connection connection);
|
||||
|
||||
List<Connection> getConnectionPool();
|
||||
|
||||
int getSize();
|
||||
|
||||
String getUrl();
|
||||
|
||||
String getUser();
|
||||
|
||||
String getPassword();
|
||||
|
||||
void shutdown() throws SQLException;;
|
||||
}
|
@ -1,25 +1,25 @@
|
||||
package com.baeldung.connectionpool.connectionpools;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import org.apache.commons.dbcp2.BasicDataSource;
|
||||
|
||||
public class DBCPDataSource {
|
||||
|
||||
private static final BasicDataSource ds = new BasicDataSource();
|
||||
|
||||
static {
|
||||
ds.setUrl("jdbc:h2:mem:test");
|
||||
ds.setUsername("user");
|
||||
ds.setPassword("password");
|
||||
ds.setMinIdle(5);
|
||||
ds.setMaxIdle(10);
|
||||
ds.setMaxOpenPreparedStatements(100);
|
||||
}
|
||||
|
||||
public static Connection getConnection() throws SQLException {
|
||||
return ds.getConnection();
|
||||
}
|
||||
|
||||
private DBCPDataSource(){}
|
||||
}
|
||||
package com.baeldung.connectionpool;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import org.apache.commons.dbcp2.BasicDataSource;
|
||||
|
||||
public class DBCPDataSource {
|
||||
|
||||
private static final BasicDataSource ds = new BasicDataSource();
|
||||
|
||||
static {
|
||||
ds.setUrl("jdbc:h2:mem:test");
|
||||
ds.setUsername("user");
|
||||
ds.setPassword("password");
|
||||
ds.setMinIdle(5);
|
||||
ds.setMaxIdle(10);
|
||||
ds.setMaxOpenPreparedStatements(100);
|
||||
}
|
||||
|
||||
public static Connection getConnection() throws SQLException {
|
||||
return ds.getConnection();
|
||||
}
|
||||
|
||||
private DBCPDataSource(){}
|
||||
}
|
@ -1,28 +1,28 @@
|
||||
package com.baeldung.connectionpool.connectionpools;
|
||||
|
||||
import com.zaxxer.hikari.HikariConfig;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class HikariCPDataSource {
|
||||
|
||||
private static final HikariConfig config = new HikariConfig();
|
||||
private static final HikariDataSource ds;
|
||||
|
||||
static {
|
||||
config.setJdbcUrl("jdbc:h2:mem:test");
|
||||
config.setUsername("user");
|
||||
config.setPassword("password");
|
||||
config.addDataSourceProperty("cachePrepStmts", "true");
|
||||
config.addDataSourceProperty("prepStmtCacheSize", "250");
|
||||
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
|
||||
ds = new HikariDataSource(config);
|
||||
}
|
||||
|
||||
public static Connection getConnection() throws SQLException {
|
||||
return ds.getConnection();
|
||||
}
|
||||
|
||||
private HikariCPDataSource(){}
|
||||
}
|
||||
package com.baeldung.connectionpool;
|
||||
|
||||
import com.zaxxer.hikari.HikariConfig;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class HikariCPDataSource {
|
||||
|
||||
private static final HikariConfig config = new HikariConfig();
|
||||
private static final HikariDataSource ds;
|
||||
|
||||
static {
|
||||
config.setJdbcUrl("jdbc:h2:mem:test");
|
||||
config.setUsername("user");
|
||||
config.setPassword("password");
|
||||
config.addDataSourceProperty("cachePrepStmts", "true");
|
||||
config.addDataSourceProperty("prepStmtCacheSize", "250");
|
||||
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
|
||||
ds = new HikariDataSource(config);
|
||||
}
|
||||
|
||||
public static Connection getConnection() throws SQLException {
|
||||
return ds.getConnection();
|
||||
}
|
||||
|
||||
private HikariCPDataSource(){}
|
||||
}
|
@ -1,10 +1,8 @@
|
||||
package com.baeldung.connectionpool;
|
||||
|
||||
import com.baeldung.connectionpool.connectionpools.BasicConnectionPool;
|
||||
import com.baeldung.connectionpool.connectionpools.ConnectionPool;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
@ -1,6 +1,5 @@
|
||||
package com.baeldung.connectionpool;
|
||||
|
||||
import com.baeldung.connectionpool.connectionpools.C3poDataSource;
|
||||
import java.sql.SQLException;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import org.junit.Test;
|
@ -1,6 +1,5 @@
|
||||
package com.baeldung.connectionpool;
|
||||
|
||||
import com.baeldung.connectionpool.connectionpools.DBCPDataSource;
|
||||
import java.sql.SQLException;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import org.junit.Test;
|
@ -1,6 +1,5 @@
|
||||
package com.baeldung.connectionpool;
|
||||
|
||||
import com.baeldung.connectionpool.connectionpools.HikariCPDataSource;
|
||||
import java.sql.SQLException;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import org.junit.Test;
|
@ -158,21 +158,6 @@
|
||||
<artifactId>jmimemagic</artifactId>
|
||||
<version>${jmime-magic.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>
|
||||
<!-- instrumentation -->
|
||||
<dependency>
|
||||
<groupId>org.javassist</groupId>
|
||||
@ -544,11 +529,6 @@
|
||||
<!-- testing -->
|
||||
<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-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
|
||||
|
@ -771,12 +771,19 @@
|
||||
<version>${hamcrest-all.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.yaml</groupId>
|
||||
<artifactId>snakeyaml</artifactId>
|
||||
<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>
|
||||
|
||||
@ -1026,4 +1033,4 @@
|
||||
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
</project>
|
||||
|
@ -0,0 +1,49 @@
|
||||
package com.baeldung.mqtt;
|
||||
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import org.eclipse.paho.client.mqttv3.IMqttClient;
|
||||
import org.eclipse.paho.client.mqttv3.MqttMessage;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class EngineTemperatureSensor implements Callable<Void> {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(EngineTemperatureSensor.class);
|
||||
public static final String TOPIC = "engine/temperature";
|
||||
|
||||
private IMqttClient client;
|
||||
private Random rnd = new Random();
|
||||
|
||||
public EngineTemperatureSensor(IMqttClient client) {
|
||||
this.client = client;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Void call() throws Exception {
|
||||
|
||||
if ( !client.isConnected()) {
|
||||
log.info("[I31] Client not connected.");
|
||||
return null;
|
||||
}
|
||||
|
||||
MqttMessage msg = readEngineTemp();
|
||||
msg.setQos(0);
|
||||
msg.setRetained(true);
|
||||
client.publish(TOPIC,msg);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method simulates reading the engine temperature
|
||||
* @return
|
||||
*/
|
||||
private MqttMessage readEngineTemp() {
|
||||
double temp = 80 + rnd.nextDouble() * 20.0;
|
||||
byte[] payload = String.format("T:%04.2f",temp).getBytes();
|
||||
MqttMessage msg = new MqttMessage(payload);
|
||||
return msg;
|
||||
}
|
||||
}
|
@ -4,7 +4,8 @@ public class Contact {
|
||||
|
||||
private String type;
|
||||
|
||||
private Integer number;
|
||||
private int number;
|
||||
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
@ -14,11 +15,11 @@ public class Contact {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public Integer getNumber() {
|
||||
public int getNumber() {
|
||||
return number;
|
||||
}
|
||||
|
||||
public void setNumber(Integer number) {
|
||||
public void setNumber(int number) {
|
||||
this.number = number;
|
||||
}
|
||||
|
||||
|
@ -6,7 +6,7 @@ public class Customer {
|
||||
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private Integer age;
|
||||
private int age;
|
||||
private List<Contact> contactDetails;
|
||||
private Address homeAddress;
|
||||
|
||||
@ -26,11 +26,11 @@ public class Customer {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(Integer age) {
|
||||
public void setAge(int 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();
|
||||
StringWriter writer = new StringWriter();
|
||||
yaml.dump(data, writer);
|
||||
System.out.println(writer.toString());
|
||||
String expectedYaml = "name: Silenthand Olleander\nrace: Human\ntraits: [ONE_HAND, ONE_EYE]\n";
|
||||
assertEquals(expectedYaml, writer.toString());
|
||||
}
|
||||
@ -48,7 +47,6 @@ public class JavaToYAMLSerializationUnitTest {
|
||||
customer.setFirstName("Greg");
|
||||
customer.setLastName("McDowell");
|
||||
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";
|
||||
assertEquals(expectedYaml, yaml.dumpAs(customer, Tag.MAP, null));
|
||||
}
|
||||
|
@ -1,20 +1,15 @@
|
||||
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.yaml.snakeyaml.TypeDescription;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
import org.yaml.snakeyaml.constructor.Constructor;
|
||||
|
||||
import com.baeldung.snakeyaml.Contact;
|
||||
import com.baeldung.snakeyaml.Customer;
|
||||
import java.io.InputStream;
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class YAMLToJavaDeserialisationUnitTest {
|
||||
|
||||
@ -25,6 +20,9 @@ public class YAMLToJavaDeserialisationUnitTest {
|
||||
.getClassLoader()
|
||||
.getResourceAsStream("yaml/customer.yaml");
|
||||
Map<String, Object> obj = yaml.load(inputStream);
|
||||
assertEquals("John", obj.get("firstName"));
|
||||
assertEquals("Doe", obj.get("lastName"));
|
||||
assertEquals(20, obj.get("age"));
|
||||
System.out.println(obj);
|
||||
}
|
||||
|
||||
@ -35,6 +33,9 @@ public class YAMLToJavaDeserialisationUnitTest {
|
||||
.getClassLoader()
|
||||
.getResourceAsStream("yaml/customer.yaml");
|
||||
Customer customer = yaml.load(inputStream);
|
||||
assertEquals("John", customer.getFirstName());
|
||||
assertEquals("Doe", customer.getLastName());
|
||||
assertEquals(20, customer.getAge());
|
||||
System.out.println(customer);
|
||||
}
|
||||
|
||||
@ -45,6 +46,9 @@ public class YAMLToJavaDeserialisationUnitTest {
|
||||
.getClassLoader()
|
||||
.getResourceAsStream("yaml/customer_with_type.yaml");
|
||||
Customer customer = yaml.load(inputStream);
|
||||
assertEquals("John", customer.getFirstName());
|
||||
assertEquals("Doe", customer.getLastName());
|
||||
assertEquals(20, customer.getAge());
|
||||
System.out.println(customer);
|
||||
}
|
||||
|
||||
@ -53,9 +57,9 @@ public class YAMLToJavaDeserialisationUnitTest {
|
||||
Yaml yaml = new Yaml();
|
||||
Map<Object, Object> document = yaml.load("3.0: 2018-07-22");
|
||||
assertNotNull(document);
|
||||
assertTrue(document.size() == 1);
|
||||
assertTrue(document.containsKey(Double.valueOf(3.0)));
|
||||
assertTrue(document.get(Double.valueOf(3.0)) instanceof Date);
|
||||
assertEquals(1, document.size());
|
||||
assertTrue(document.containsKey(3.0d));
|
||||
assertTrue(document.get(3.0d) instanceof Date);
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -68,22 +72,21 @@ public class YAMLToJavaDeserialisationUnitTest {
|
||||
assertNotNull(customer);
|
||||
assertEquals("John", customer.getFirstName());
|
||||
assertEquals("Doe", customer.getLastName());
|
||||
assertTrue(customer.getAge() == 31);
|
||||
assertEquals(31, customer.getAge());
|
||||
assertNotNull(customer.getContactDetails());
|
||||
assertTrue(customer.getContactDetails()
|
||||
.size() == 2);
|
||||
assertEquals(2, customer.getContactDetails().size());
|
||||
assertEquals("mobile", customer.getContactDetails()
|
||||
.get(0)
|
||||
.getType());
|
||||
assertTrue(customer.getContactDetails()
|
||||
assertEquals(123456789,customer.getContactDetails()
|
||||
.get(0)
|
||||
.getNumber() == 123456789);
|
||||
.getNumber());
|
||||
assertEquals("landline", customer.getContactDetails()
|
||||
.get(1)
|
||||
.getType());
|
||||
assertTrue(customer.getContactDetails()
|
||||
assertEquals(456786868, customer.getContactDetails()
|
||||
.get(1)
|
||||
.getNumber() == 456786868);
|
||||
.getNumber());
|
||||
assertNotNull(customer.getHomeAddress());
|
||||
assertEquals("Xyz, DEF Street", customer.getHomeAddress()
|
||||
.getLine());
|
||||
@ -103,10 +106,9 @@ public class YAMLToJavaDeserialisationUnitTest {
|
||||
assertNotNull(customer);
|
||||
assertEquals("John", customer.getFirstName());
|
||||
assertEquals("Doe", customer.getLastName());
|
||||
assertTrue(customer.getAge() == 31);
|
||||
assertEquals(31, customer.getAge());
|
||||
assertNotNull(customer.getContactDetails());
|
||||
assertTrue(customer.getContactDetails()
|
||||
.size() == 2);
|
||||
assertEquals(2, customer.getContactDetails().size());
|
||||
assertEquals("mobile", customer.getContactDetails()
|
||||
.get(0)
|
||||
.getType());
|
||||
@ -126,7 +128,7 @@ public class YAMLToJavaDeserialisationUnitTest {
|
||||
count++;
|
||||
assertTrue(object instanceof Customer);
|
||||
}
|
||||
assertTrue(count == 2);
|
||||
assertEquals(2, count);
|
||||
}
|
||||
|
||||
}
|
||||
|
41
pom.xml
41
pom.xml
@ -312,6 +312,7 @@
|
||||
<module>core-java-collections</module>
|
||||
<module>core-java-io</module>
|
||||
<module>core-java-8</module>
|
||||
<module>core-java-persistence</module>
|
||||
<module>core-kotlin</module>
|
||||
<module>core-groovy</module>
|
||||
<module>core-java-concurrency</module>
|
||||
@ -858,7 +859,7 @@
|
||||
<module>core-java-io</module>
|
||||
<module>core-java-8</module>
|
||||
<module>core-groovy</module>
|
||||
<module>core-java-concurrency</module>
|
||||
|
||||
<module>couchbase</module>
|
||||
<module>deltaspike</module>
|
||||
<module>dozer</module>
|
||||
@ -877,7 +878,7 @@
|
||||
<module>spring-static-resources</module>
|
||||
<module>hazelcast</module>
|
||||
<module>hbase</module>
|
||||
|
||||
|
||||
<module>hystrix</module>
|
||||
<module>image-processing</module>
|
||||
<module>immutables</module>
|
||||
@ -906,11 +907,11 @@
|
||||
<module>linkrest</module>
|
||||
<module>logging-modules/log-mdc</module>
|
||||
<module>logging-modules/log4j</module>
|
||||
|
||||
|
||||
<module>logging-modules/logback</module>
|
||||
<module>lombok</module>
|
||||
<module>mapstruct</module>
|
||||
|
||||
|
||||
<module>maven</module>
|
||||
<module>mesos-marathon</module>
|
||||
<module>msf4j</module>
|
||||
@ -962,25 +963,25 @@
|
||||
<module>spring-cucumber</module>
|
||||
<module>spring-ejb</module>
|
||||
<module>spring-aop</module>
|
||||
|
||||
|
||||
<module>persistence-modules/spring-data-dynamodb</module>
|
||||
<module>spring-data-keyvalue</module>
|
||||
<module>spring-data-mongodb</module>
|
||||
<module>persistence-modules/spring-data-neo4j</module>
|
||||
|
||||
|
||||
<module>spring-data-rest</module>
|
||||
<module>persistence-modules/spring-data-solr</module>
|
||||
<module>spring-dispatcher-servlet</module>
|
||||
<module>spring-exceptions</module>
|
||||
<module>spring-freemarker</module>
|
||||
<module>persistence-modules/spring-hibernate-3</module>
|
||||
|
||||
|
||||
<module>persistence-modules/spring-hibernate-5</module>
|
||||
<module>persistence-modules/spring-data-eclipselink</module>
|
||||
<module>spring-integration</module>
|
||||
<module>spring-jenkins-pipeline</module>
|
||||
<module>spring-jersey</module>
|
||||
|
||||
|
||||
<module>spring-jms</module>
|
||||
<module>spring-jooq</module>
|
||||
<module>persistence-modules/spring-jpa</module>
|
||||
@ -1041,13 +1042,13 @@
|
||||
<module>testing-modules/testing</module>
|
||||
<module>testing-modules/testng</module>
|
||||
<module>video-tutorials</module>
|
||||
|
||||
|
||||
<module>xmlunit-2</module>
|
||||
<module>struts-2</module>
|
||||
<module>apache-velocity</module>
|
||||
<module>apache-solrj</module>
|
||||
<module>rabbitmq</module>
|
||||
|
||||
|
||||
<module>persistence-modules/spring-data-gemfire</module>
|
||||
<module>mybatis</module>
|
||||
<module>spring-drools</module>
|
||||
@ -1077,6 +1078,12 @@
|
||||
<module>apache-meecrowave</module>
|
||||
<module>testing-modules/junit-abstract</module>
|
||||
|
||||
<module>spring-hibernate4</module>
|
||||
<module>xml</module>
|
||||
<module>vertx</module>
|
||||
<module>metrics</module>
|
||||
<module>httpclient</module>
|
||||
|
||||
<!-- problematic -->
|
||||
<!--
|
||||
<module>ejb</module>
|
||||
@ -1085,12 +1092,7 @@
|
||||
<module>logging-modules/log4j2</module>
|
||||
<module>spring-data-couchbase-2</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>
|
||||
-->
|
||||
|
||||
@ -1107,6 +1109,7 @@
|
||||
<module>core-java</module>
|
||||
<module>google-web-toolkit</module>
|
||||
<module>spring-security-mvc-custom</module>
|
||||
<module>core-java-concurrency</module>
|
||||
-->
|
||||
|
||||
<!-- 30:32 min -->
|
||||
@ -1169,7 +1172,7 @@
|
||||
<module>spring-security-mvc-custom</module>
|
||||
<module>hibernate5</module>
|
||||
<module>spring-data-elasticsearch</module>
|
||||
|
||||
<module>core-java-concurrency</module>
|
||||
</modules>
|
||||
|
||||
</profile>
|
||||
@ -1233,6 +1236,4 @@
|
||||
<!-- <maven-pmd-plugin.version>3.9.0</maven-pmd-plugin.version> -->
|
||||
<maven-pmd-plugin.version>3.8</maven-pmd-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
</project>
|
@ -34,8 +34,7 @@ public class FormHandler {
|
||||
|
||||
private AtomicLong extractData(List<DataBuffer> dataBuffers) {
|
||||
AtomicLong atomicLong = new AtomicLong(0);
|
||||
dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer()
|
||||
.array().length));
|
||||
dataBuffers.forEach(d -> atomicLong.addAndGet(d.readableByteCount()));
|
||||
return atomicLong;
|
||||
}
|
||||
}
|
||||
|
@ -13,6 +13,7 @@ import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import org.apache.catalina.Context;
|
||||
import org.apache.catalina.Wrapper;
|
||||
import org.apache.catalina.startup.Tomcat;
|
||||
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
|
||||
import org.springframework.boot.web.server.WebServer;
|
||||
@ -61,7 +62,8 @@ public class FunctionalWebApplication {
|
||||
tomcat.setPort(9090);
|
||||
Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
|
||||
ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler);
|
||||
Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet);
|
||||
Wrapper servletWrapper = Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet);
|
||||
servletWrapper.setAsyncSupported(true);
|
||||
rootContext.addServletMappingDecoded("/", "httpHandlerServlet");
|
||||
|
||||
TomcatWebServer server = new TomcatWebServer(tomcat);
|
||||
|
@ -8,7 +8,7 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@RestController
|
||||
@RestController("FurtherCorsConfigsController-cors-on-global-config-and-more")
|
||||
@RequestMapping("/cors-on-global-config-and-more")
|
||||
public class FurtherCorsConfigsController {
|
||||
|
||||
|
@ -7,7 +7,7 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@RestController
|
||||
@RestController("RegularRestController-cors-on-global-config")
|
||||
@RequestMapping("/cors-on-global-config")
|
||||
public class RegularRestController {
|
||||
|
||||
|
@ -7,6 +7,7 @@ import static org.springframework.web.reactive.function.server.RouterFunctions.t
|
||||
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
|
||||
|
||||
import org.apache.catalina.Context;
|
||||
import org.apache.catalina.Wrapper;
|
||||
import org.apache.catalina.startup.Tomcat;
|
||||
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
|
||||
import org.springframework.boot.web.server.WebServer;
|
||||
@ -41,7 +42,8 @@ public class ExploreSpring5URLPatternUsingRouterFunctions {
|
||||
tomcat.setPort(9090);
|
||||
Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
|
||||
ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler);
|
||||
Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet);
|
||||
Wrapper servletWrapper = Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet);
|
||||
servletWrapper.setAsyncSupported(true);
|
||||
rootContext.addServletMappingDecoded("/", "httpHandlerServlet");
|
||||
|
||||
TomcatWebServer server = new TomcatWebServer(tomcat);
|
||||
|
@ -4,8 +4,12 @@ import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class EmployeeCreationEvent {
|
||||
private String employeeId;
|
||||
private String creationTime;
|
||||
public EmployeeCreationEvent(String employeeId, String creationTime) {
|
||||
super();
|
||||
this.employeeId = employeeId;
|
||||
this.creationTime = creationTime;
|
||||
}
|
||||
}
|
||||
|
@ -15,7 +15,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Component
|
||||
@Component("EmployeeWebSocketHandler")
|
||||
public class EmployeeWebSocketHandler implements WebSocketHandler {
|
||||
|
||||
ObjectMapper om = new ObjectMapper();
|
||||
|
@ -1,19 +1,22 @@
|
||||
package com.baeldung.websocket;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.reactive.HandlerMapping;
|
||||
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
|
||||
import org.springframework.web.reactive.socket.WebSocketHandler;
|
||||
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Configuration
|
||||
public class ReactiveWebSocketConfiguration {
|
||||
|
||||
@Autowired
|
||||
@Qualifier("ReactiveWebSocketHandler")
|
||||
private WebSocketHandler webSocketHandler;
|
||||
|
||||
@Bean
|
||||
|
@ -14,7 +14,7 @@ import java.time.Duration;
|
||||
import static java.time.LocalDateTime.now;
|
||||
import static java.util.UUID.randomUUID;
|
||||
|
||||
@Component
|
||||
@Component("ReactiveWebSocketHandler")
|
||||
public class ReactiveWebSocketHandler implements WebSocketHandler {
|
||||
|
||||
private static final ObjectMapper json = new ObjectMapper();
|
||||
|
@ -1,5 +1,8 @@
|
||||
package com.baeldung.functional;
|
||||
|
||||
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
|
||||
import static org.springframework.web.reactive.function.BodyInserters.fromResource;
|
||||
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
@ -12,9 +15,6 @@ import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.reactive.function.BodyInserters;
|
||||
|
||||
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
|
||||
import static org.springframework.web.reactive.function.BodyInserters.fromResource;
|
||||
|
||||
public class FunctionalWebApplicationIntegrationTest {
|
||||
|
||||
private static WebTestClient client;
|
||||
|
@ -6,8 +6,6 @@ import org.junit.Test;
|
||||
import org.springframework.boot.web.server.WebServer;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
|
||||
import com.baeldung.reactive.urlmatch.ExploreSpring5URLPatternUsingRouterFunctions;
|
||||
|
||||
public class ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest {
|
||||
|
||||
private static WebTestClient client;
|
||||
|
@ -28,7 +28,7 @@ public class SecurityIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void whenNoCredentials_thenRedirectToLogin() {
|
||||
this.rest.get().uri("/").exchange().expectStatus().is3xxRedirection();
|
||||
this.rest.get().uri("/").exchange().expectStatus().is4xxClientError();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -53,7 +53,7 @@ public class WebTestClientIntegrationTest {
|
||||
.uri("/resource")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.is3xxRedirection()
|
||||
.isOk()
|
||||
.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>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.security.oauth.boot</groupId>
|
||||
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
|
||||
<version>2.0.1.RELEASE</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<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 org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
@ -14,9 +15,9 @@ public class FooController {
|
||||
private FooService fooService;
|
||||
|
||||
@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("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.junit.Assert.assertThat;
|
||||
|
||||
import org.baeldung.boot.ApplicationIntegrationTest;
|
||||
import org.baeldung.boot.DemoApplicationIntegrationTest;
|
||||
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.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Transactional
|
||||
@TestPropertySource("classpath:exception-hibernate.properties")
|
||||
public class HibernateSessionIntegrationTest extends ApplicationIntegrationTest {
|
||||
public class HibernateSessionIntegrationTest extends DemoApplicationIntegrationTest {
|
||||
@Autowired
|
||||
private FooRepository fooRepository;
|
||||
|
||||
@ -23,7 +21,7 @@ public class HibernateSessionIntegrationTest extends ApplicationIntegrationTest
|
||||
Foo foo = new Foo("Exception Solved");
|
||||
fooRepository.save(foo);
|
||||
foo = null;
|
||||
foo = fooRepository.get(1);
|
||||
foo = fooRepository.findByName("Exception Solved");
|
||||
|
||||
assertThat(foo, notNullValue());
|
||||
assertThat(foo.getId(), is(1));
|
||||
|
@ -6,9 +6,11 @@ import org.baeldung.session.exception.repository.FooRepository;
|
||||
import org.hibernate.HibernateException;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Transactional
|
||||
@TestPropertySource("classpath:exception-hibernate.properties")
|
||||
public class NoHibernateSessionIntegrationTest extends ApplicationIntegrationTest {
|
||||
@Autowired
|
||||
private FooRepository fooRepository;
|
||||
|
@ -43,7 +43,7 @@ public class CustomConverterIntegrationTest {
|
||||
|
||||
@Test
|
||||
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("2.32", BigDecimal.class)).isEqualTo(BigDecimal.valueOf(2.32));
|
||||
}
|
||||
|
@ -1,9 +1,11 @@
|
||||
package org.baeldung.demo.boottest;
|
||||
|
||||
import org.baeldung.demo.boottest.Employee;
|
||||
import org.baeldung.demo.boottest.EmployeeRepository;
|
||||
import org.baeldung.demo.boottest.EmployeeService;
|
||||
import org.baeldung.demo.boottest.EmployeeServiceImpl;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
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.test.context.junit4.SpringRunner;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
public class EmployeeServiceImplIntegrationTest {
|
||||
|
||||
@ -50,9 +47,9 @@ public class EmployeeServiceImplIntegrationTest {
|
||||
Mockito.when(employeeRepository.findByName(john.getName())).thenReturn(john);
|
||||
Mockito.when(employeeRepository.findByName(alex.getName())).thenReturn(alex);
|
||||
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.findById(-99L).orElse(null)).thenReturn(null);
|
||||
Mockito.when(employeeRepository.findById(-99L)).thenReturn(Optional.empty());
|
||||
}
|
||||
|
||||
@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() {
|
||||
return new SingletonObjectFactoryBean();
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -2,6 +2,7 @@ package com.baeldung.scope;
|
||||
|
||||
import com.baeldung.scope.prototype.PrototypeBean;
|
||||
import com.baeldung.scope.singletone.SingletonBean;
|
||||
|
||||
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
|
||||
import org.springframework.context.annotation.*;
|
||||
|
||||
@ -19,4 +20,5 @@ public class AppProxyScopeConfig {
|
||||
public SingletonBean singletonBean() {
|
||||
return new SingletonBean();
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -9,4 +9,20 @@ public class PrototypeBean {
|
||||
public PrototypeBean() {
|
||||
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;
|
||||
|
||||
import com.baeldung.scope.prototype.PrototypeBean;
|
||||
import com.baeldung.scope.singletone.SingletonFunctionBean;
|
||||
import com.baeldung.scope.singletone.SingletonLookupBean;
|
||||
import com.baeldung.scope.singletone.SingletonObjectFactoryBean;
|
||||
import com.baeldung.scope.singletone.SingletonProviderBean;
|
||||
@ -58,4 +59,5 @@ public class PrototypeBeanInjectionIntegrationTest {
|
||||
|
||||
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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-spring-4</artifactId>
|
||||
<artifactId>parent-spring-5</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-spring-4</relativePath>
|
||||
<relativePath>../parent-spring-5</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
@ -19,50 +19,20 @@
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-elasticsearch</artifactId>
|
||||
<version>${spring-data-elasticsearch.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.spatial4j</groupId>
|
||||
<artifactId>spatial4j</artifactId>
|
||||
<version>${spatial4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.vividsolutions</groupId>
|
||||
<artifactId>jts</artifactId>
|
||||
<version>${jts.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>xerces</groupId>
|
||||
<artifactId>xercesImpl</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.java.dev.jna</groupId>
|
||||
<artifactId>jna</artifactId>
|
||||
<version>${jna.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.elasticsearch</groupId>
|
||||
<artifactId>elasticsearch</artifactId>
|
||||
@ -73,17 +43,62 @@
|
||||
<artifactId>fastjson</artifactId>
|
||||
<version>${fastjson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.locationtech.spatial4j</groupId>
|
||||
<artifactId>spatial4j</artifactId>
|
||||
<version>${spatial4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.vividsolutions</groupId>
|
||||
<artifactId>jts</artifactId>
|
||||
<version>${jts.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>xerces</groupId>
|
||||
<artifactId>xercesImpl</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</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>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.java.dev.jna</groupId>
|
||||
<artifactId>jna</artifactId>
|
||||
<version>${jna.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<spring-data-elasticsearch.version>2.0.5.RELEASE</spring-data-elasticsearch.version>
|
||||
<jna.version>4.2.2</jna.version>
|
||||
<elasticsearch.version>2.4.2</elasticsearch.version>
|
||||
<fastjson.version>1.2.21</fastjson.version>
|
||||
<spatial4j.version>0.4.1</spatial4j.version>
|
||||
<spring-data-elasticsearch.version>3.0.8.RELEASE</spring-data-elasticsearch.version>
|
||||
<jna.version>4.5.2</jna.version>
|
||||
<elasticsearch.version>5.6.0</elasticsearch.version>
|
||||
<fastjson.version>1.2.47</fastjson.version>
|
||||
<spatial4j.version>0.6</spatial4j.version>
|
||||
<jts.version>1.13</jts.version>
|
||||
<log4j.version>2.9.1</log4j.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -1,15 +1,13 @@
|
||||
package com.baeldung.spring.data.es.config;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
|
||||
import org.elasticsearch.client.Client;
|
||||
import org.elasticsearch.client.transport.TransportClient;
|
||||
import org.elasticsearch.common.settings.Settings;
|
||||
import org.elasticsearch.node.NodeBuilder;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.elasticsearch.common.transport.InetSocketTransportAddress;
|
||||
import org.elasticsearch.transport.client.PreBuiltTransportClient;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
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" })
|
||||
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 static Logger logger = LoggerFactory.getLogger(Config.class);
|
||||
@Value("${elasticsearch.cluster.name:elasticsearch}")
|
||||
private String clusterName;
|
||||
|
||||
@Bean
|
||||
public Client client() {
|
||||
TransportClient client = null;
|
||||
try {
|
||||
final Path tmpDir = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "elasticsearch_data");
|
||||
logger.debug(tmpDir.toAbsolutePath().toString());
|
||||
|
||||
// @formatter:off
|
||||
|
||||
final Settings.Builder elasticsearchSettings =
|
||||
Settings.settingsBuilder().put("http.enabled", "false")
|
||||
.put("path.data", tmpDir.toAbsolutePath().toString())
|
||||
.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();
|
||||
final Settings elasticsearchSettings = Settings.builder()
|
||||
.put("client.transport.sniff", true)
|
||||
.put("path.home", elasticsearchHome)
|
||||
.put("cluster.name", clusterName).build();
|
||||
client = new PreBuiltTransportClient(elasticsearchSettings);
|
||||
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
|
||||
} catch (UnknownHostException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
@ -1,8 +1,8 @@
|
||||
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.String;
|
||||
import static org.springframework.data.elasticsearch.annotations.FieldType.Text;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
@ -19,13 +19,13 @@ public class Article {
|
||||
@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;
|
||||
|
||||
@Field(type = Nested)
|
||||
@Field(type = Nested, includeInParent = true)
|
||||
private List<Author> authors;
|
||||
|
||||
@Field(type = String, index = not_analyzed)
|
||||
@Field(type = Keyword)
|
||||
private String[] tags;
|
||||
|
||||
public Article() {
|
||||
|
@ -1,5 +1,7 @@
|
||||
package com.baeldung.spring.data.es.service;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
|
||||
@ -8,7 +10,7 @@ import com.baeldung.spring.data.es.model.Article;
|
||||
public interface ArticleService {
|
||||
Article save(Article article);
|
||||
|
||||
Article findOne(String id);
|
||||
Optional<Article> findOne(String id);
|
||||
|
||||
Iterable<Article> findAll();
|
||||
|
||||
|
@ -1,5 +1,7 @@
|
||||
package com.baeldung.spring.data.es.service;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
@ -24,8 +26,8 @@ public class ArticleServiceImpl implements ArticleService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Article findOne(String id) {
|
||||
return articleRepository.findOne(id);
|
||||
public Optional<Article> findOne(String id) {
|
||||
return articleRepository.findById(id);
|
||||
}
|
||||
|
||||
@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;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
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 static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.elasticsearch.node.NodeBuilder.nodeBuilder;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import org.elasticsearch.action.DocWriteResponse.Result;
|
||||
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.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 {
|
||||
private List<Person> listOfPersons = new ArrayList<>();
|
||||
private Client client = null;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
public void setUp() throws UnknownHostException {
|
||||
Person person1 = new Person(10, "John Doe", new Date());
|
||||
Person person2 = new Person(25, "Janette Doe", new Date());
|
||||
listOfPersons.add(person1);
|
||||
listOfPersons.add(person2);
|
||||
Node node = nodeBuilder()
|
||||
.clusterName("elasticsearch")
|
||||
.client(true)
|
||||
.node();
|
||||
client = node.client();
|
||||
|
||||
client = new PreBuiltTransportClient(Settings.builder().put("client.transport.sniff", true)
|
||||
.put("cluster.name","elasticsearch").build())
|
||||
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -47,11 +51,12 @@ public class ElasticSearchManualTest {
|
||||
String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}";
|
||||
IndexResponse response = client
|
||||
.prepareIndex("people", "Doe")
|
||||
.setSource(jsonObject)
|
||||
.setSource(jsonObject, XContentType.JSON)
|
||||
.get();
|
||||
String index = response.getIndex();
|
||||
String type = response.getType();
|
||||
assertTrue(response.isCreated());
|
||||
|
||||
assertEquals(Result.CREATED, response.getResult());
|
||||
assertEquals(index, "people");
|
||||
assertEquals(type, "Doe");
|
||||
}
|
||||
@ -61,13 +66,14 @@ public class ElasticSearchManualTest {
|
||||
String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}";
|
||||
IndexResponse response = client
|
||||
.prepareIndex("people", "Doe")
|
||||
.setSource(jsonObject)
|
||||
.setSource(jsonObject, XContentType.JSON)
|
||||
.get();
|
||||
String id = response.getId();
|
||||
DeleteResponse deleteResponse = client
|
||||
.prepareDelete("people", "Doe", id)
|
||||
.get();
|
||||
assertTrue(deleteResponse.isFound());
|
||||
|
||||
assertEquals(Result.DELETED,deleteResponse.getResult());
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -142,6 +148,7 @@ public class ElasticSearchManualTest {
|
||||
.prepareIndex("people", "Doe")
|
||||
.setSource(builder)
|
||||
.get();
|
||||
assertTrue(response.isCreated());
|
||||
|
||||
assertEquals(Result.CREATED, response.getResult());
|
||||
}
|
||||
}
|
||||
|
@ -1,13 +1,21 @@
|
||||
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.index.IndexResponse;
|
||||
import org.elasticsearch.action.search.SearchResponse;
|
||||
import org.elasticsearch.client.Client;
|
||||
import org.elasticsearch.common.geo.GeoPoint;
|
||||
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.xcontent.XContentType;
|
||||
import org.elasticsearch.index.query.QueryBuilder;
|
||||
import org.elasticsearch.index.query.QueryBuilders;
|
||||
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.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import com.baeldung.spring.data.es.config.Config;
|
||||
import com.vividsolutions.jts.geom.Coordinate;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = Config.class)
|
||||
@ -43,7 +48,7 @@ public class GeoQueriesIntegrationTest {
|
||||
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\"}}}}";
|
||||
CreateIndexRequest req = new CreateIndexRequest(WONDERS_OF_WORLD);
|
||||
req.mapping(WONDERS, jsonObject);
|
||||
req.mapping(WONDERS, jsonObject, XContentType.JSON);
|
||||
client.admin()
|
||||
.indices()
|
||||
.create(req)
|
||||
@ -51,31 +56,36 @@ public class GeoQueriesIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGeoShapeData_whenExecutedGeoShapeQuery_thenResultNonEmpty() {
|
||||
String jsonObject = "{\"name\":\"Agra\",\"region\":{\"type\":\"envelope\",\"coordinates\":[[75,25],[80.1,30.2]]}}";
|
||||
public void givenGeoShapeData_whenExecutedGeoShapeQuery_thenResultNonEmpty() throws IOException{
|
||||
String jsonObject = "{\"name\":\"Agra\",\"region\":{\"type\":\"envelope\",\"coordinates\":[[75,30.2],[80.1, 25]]}}";
|
||||
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
|
||||
.setSource(jsonObject)
|
||||
.setSource(jsonObject, XContentType.JSON)
|
||||
.get();
|
||||
|
||||
String tajMahalId = response.getId();
|
||||
client.admin()
|
||||
.indices()
|
||||
.prepareRefresh(WONDERS_OF_WORLD)
|
||||
.get();
|
||||
|
||||
QueryBuilder qb = QueryBuilders.geoShapeQuery("region", ShapeBuilder.newEnvelope()
|
||||
.topLeft(74.00, 24.0)
|
||||
.bottomRight(81.1, 31.2))
|
||||
.relation(ShapeRelation.WITHIN);
|
||||
Coordinate topLeft =new Coordinate(74, 31.2);
|
||||
Coordinate bottomRight =new Coordinate(81.1, 24);
|
||||
QueryBuilder qb = QueryBuilders
|
||||
.geoShapeQuery("region", ShapeBuilders.newEnvelope(topLeft, bottomRight))
|
||||
.relation(ShapeRelation.WITHIN);
|
||||
|
||||
|
||||
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD)
|
||||
.setTypes(WONDERS)
|
||||
.setQuery(qb)
|
||||
.execute()
|
||||
.actionGet();
|
||||
|
||||
List<String> ids = Arrays.stream(searchResponse.getHits()
|
||||
.getHits())
|
||||
.map(SearchHit::getId)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertTrue(ids.contains(tajMahalId));
|
||||
}
|
||||
|
||||
@ -83,7 +93,7 @@ public class GeoQueriesIntegrationTest {
|
||||
public void givenGeoPointData_whenExecutedGeoBoundingBoxQuery_thenResultNonEmpty() {
|
||||
String jsonObject = "{\"name\":\"Pyramids of Giza\",\"location\":[31.131302,29.976480]}";
|
||||
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
|
||||
.setSource(jsonObject)
|
||||
.setSource(jsonObject, XContentType.JSON)
|
||||
.get();
|
||||
String pyramidsOfGizaId = response.getId();
|
||||
client.admin()
|
||||
@ -92,9 +102,8 @@ public class GeoQueriesIntegrationTest {
|
||||
.get();
|
||||
|
||||
QueryBuilder qb = QueryBuilders.geoBoundingBoxQuery("location")
|
||||
.bottomLeft(28, 30)
|
||||
.topRight(31, 32);
|
||||
|
||||
.setCorners(31,30,28,32);
|
||||
|
||||
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD)
|
||||
.setTypes(WONDERS)
|
||||
.setQuery(qb)
|
||||
@ -111,7 +120,7 @@ public class GeoQueriesIntegrationTest {
|
||||
public void givenGeoPointData_whenExecutedGeoDistanceQuery_thenResultNonEmpty() {
|
||||
String jsonObject = "{\"name\":\"Lighthouse of alexandria\",\"location\":[31.131302,29.976480]}";
|
||||
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
|
||||
.setSource(jsonObject)
|
||||
.setSource(jsonObject, XContentType.JSON)
|
||||
.get();
|
||||
String lighthouseOfAlexandriaId = response.getId();
|
||||
client.admin()
|
||||
@ -139,7 +148,7 @@ public class GeoQueriesIntegrationTest {
|
||||
public void givenGeoPointData_whenExecutedGeoPolygonQuery_thenResultNonEmpty() {
|
||||
String jsonObject = "{\"name\":\"The Great Rann of Kutch\",\"location\":[69.859741,23.733732]}";
|
||||
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
|
||||
.setSource(jsonObject)
|
||||
.setSource(jsonObject, XContentType.JSON)
|
||||
.get();
|
||||
String greatRannOfKutchid = response.getId();
|
||||
client.admin()
|
||||
@ -147,10 +156,11 @@ public class GeoQueriesIntegrationTest {
|
||||
.prepareRefresh(WONDERS_OF_WORLD)
|
||||
.get();
|
||||
|
||||
QueryBuilder qb = QueryBuilders.geoPolygonQuery("location")
|
||||
.addPoint(22.733, 68.859)
|
||||
.addPoint(24.733, 68.859)
|
||||
.addPoint(23, 70.859);
|
||||
List<GeoPoint> allPoints = new ArrayList<GeoPoint>();
|
||||
allPoints.add(new GeoPoint(22.733, 68.859));
|
||||
allPoints.add(new GeoPoint(24.733, 68.859));
|
||||
allPoints.add(new GeoPoint(23, 70.859));
|
||||
QueryBuilder qb = QueryBuilders.geoPolygonQuery("location", allPoints);
|
||||
|
||||
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD)
|
||||
.setTypes(WONDERS)
|
||||
|
@ -1,9 +1,15 @@
|
||||
package com.baeldung.spring.data.es;
|
||||
|
||||
import com.baeldung.spring.data.es.config.Config;
|
||||
import com.baeldung.spring.data.es.model.Article;
|
||||
import com.baeldung.spring.data.es.model.Author;
|
||||
import com.baeldung.spring.data.es.service.ArticleService;
|
||||
import static java.util.Arrays.asList;
|
||||
import static org.elasticsearch.index.query.Operator.AND;
|
||||
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;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
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.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND;
|
||||
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;
|
||||
import com.baeldung.spring.data.es.config.Config;
|
||||
import com.baeldung.spring.data.es.model.Article;
|
||||
import com.baeldung.spring.data.es.model.Author;
|
||||
import com.baeldung.spring.data.es.service.ArticleService;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = Config.class)
|
||||
@ -81,25 +82,25 @@ public class ElasticSearchIntegrationTest {
|
||||
public void givenPersistedArticles_whenSearchByAuthorsName_thenRightFound() {
|
||||
|
||||
final Page<Article> articleByAuthorName = articleService
|
||||
.findByAuthorName(johnSmith.getName(), new PageRequest(0, 10));
|
||||
.findByAuthorName(johnSmith.getName(), PageRequest.of(0, 10));
|
||||
assertEquals(2L, articleByAuthorName.getTotalElements());
|
||||
}
|
||||
|
||||
@Test
|
||||
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());
|
||||
}
|
||||
|
||||
@Test
|
||||
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());
|
||||
}
|
||||
|
||||
@Test
|
||||
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());
|
||||
}
|
||||
|
||||
@ -125,7 +126,7 @@ public class ElasticSearchIntegrationTest {
|
||||
article.setTitle(newTitle);
|
||||
articleService.save(article);
|
||||
|
||||
assertEquals(newTitle, articleService.findOne(article.getId()).getTitle());
|
||||
assertEquals(newTitle, articleService.findOne(article.getId()).get().getTitle());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -1,9 +1,20 @@
|
||||
package com.baeldung.spring.data.es;
|
||||
|
||||
import com.baeldung.spring.data.es.config.Config;
|
||||
import com.baeldung.spring.data.es.model.Article;
|
||||
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.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;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.lucene.search.join.ScoreMode;
|
||||
import org.elasticsearch.action.search.SearchResponse;
|
||||
import org.elasticsearch.client.Client;
|
||||
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.terms.StringTerms;
|
||||
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.Test;
|
||||
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.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
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;
|
||||
import com.baeldung.spring.data.es.config.Config;
|
||||
import com.baeldung.spring.data.es.model.Article;
|
||||
import com.baeldung.spring.data.es.model.Author;
|
||||
import com.baeldung.spring.data.es.service.ArticleService;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = Config.class)
|
||||
@ -124,7 +125,7 @@ public class ElasticSearchQueryIntegrationTest {
|
||||
|
||||
@Test
|
||||
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 List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
||||
@ -134,7 +135,7 @@ public class ElasticSearchQueryIntegrationTest {
|
||||
|
||||
@Test
|
||||
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)
|
||||
.execute().actionGet();
|
||||
|
||||
@ -150,8 +151,8 @@ public class ElasticSearchQueryIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenNotAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTermCountsIndividually() {
|
||||
final TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("tags")
|
||||
.order(Terms.Order.aggregation("_count", false));
|
||||
final TermsAggregationBuilder aggregation = AggregationBuilders.terms("top_tags").field("tags")
|
||||
.order(Terms.Order.count(false));
|
||||
final SearchResponse response = client.prepareSearch("blog").setTypes("article").addAggregation(aggregation)
|
||||
.execute().actionGet();
|
||||
|
||||
@ -194,7 +195,7 @@ public class ElasticSearchQueryIntegrationTest {
|
||||
|
||||
@Test
|
||||
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"));
|
||||
|
||||
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder)
|
||||
|
@ -11,9 +11,7 @@ public class PushController {
|
||||
@GetMapping(path = "/demoWithPush")
|
||||
public String demoWithPush(PushBuilder pushBuilder) {
|
||||
if (null != pushBuilder) {
|
||||
pushBuilder.path("resources/logo.png")
|
||||
.addHeader("Content-Type", "image/png")
|
||||
.push();
|
||||
pushBuilder.path("resources/logo.png").push();
|
||||
}
|
||||
return "demo";
|
||||
}
|
||||
@ -22,4 +20,4 @@ public class PushController {
|
||||
public String demoWithoutPush() {
|
||||
return "demo";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user