Merge branch 'master' into BAEL-3287

This commit is contained in:
maryarm 2020-06-03 12:59:30 +04:30 committed by GitHub
commit 19f75cc1d2
139 changed files with 3200 additions and 720 deletions

3
aws-app-sync/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [AWS AppSync With Spring Boot](https://www.baeldung.com/aws-appsync-spring)

View File

@ -12,3 +12,4 @@ This module contains articles about core Java features that have been introduced
- [Introduction to Java 9 StackWalking API](https://www.baeldung.com/java-9-stackwalking-api)
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
- [Java 9 Reactive Streams](https://www.baeldung.com/java-9-reactive-streams)
- [Multi-Release JAR Files with Maven](https://www.baeldung.com/maven-multi-release-jars)

View File

@ -33,8 +33,104 @@
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>incubator-features</id>
<build>
<finalName>core-java-9-new-features</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<compilerArgument>--add-modules=jdk.incubator.httpclient</compilerArgument>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>--add-modules=jdk.incubator.httpclient</argLine>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>mrjar-generation</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<executions>
<execution>
<id>compile-java-8</id>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compileSourceRoots>
<compileSourceRoot>${project.basedir}/src/main/java8</compileSourceRoot>
</compileSourceRoots>
</configuration>
</execution>
<execution>
<id>compile-java-9</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<release>9</release>
<compileSourceRoots>
<compileSourceRoot>${project.basedir}/src/main/java9</compileSourceRoot>
</compileSourceRoots>
<outputDirectory>${project.build.outputDirectory}/META-INF/versions/9</outputDirectory>
</configuration>
</execution>
<execution>
<id>default-testCompile</id>
<phase>test-compile</phase>
<goals>
<goal>testCompile</goal>
</goals>
<configuration>
<skip>true</skip>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<configuration>
<archive>
<manifestEntries>
<Multi-Release>true</Multi-Release>
</manifestEntries>
<manifest>
<mainClass>com.baeldung.multireleaseapp.App</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<build>
<finalName>core-java-9-new-features</finalName>
<plugins>
@ -61,8 +157,10 @@
<!-- testing -->
<assertj.version>3.10.0</assertj.version>
<junit.platform.version>1.2.0</junit.platform.version>
<awaitility.version>4.0.2</awaitility.version>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
<maven-jar-plugin.version>3.2.0</maven-jar-plugin.version>
<rxjava.version>3.0.0</rxjava.version>
</properties>

View File

@ -0,0 +1,14 @@
package com.baeldung.multireleaseapp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class App {
private static final Logger logger = LoggerFactory.getLogger(App.class);
public static void main(String[] args) {
logger.info(String.format("Running on %s", new DefaultVersion().version()));
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.multireleaseapp;
public class DefaultVersion implements Version {
@Override
public String version() {
return System.getProperty("java.version");
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.multireleaseapp;
interface Version {
public String version();
}

View File

@ -0,0 +1,9 @@
package com.baeldung.multireleaseapp;
public class DefaultVersion implements Version {
@Override
public String version() {
return Runtime.version().toString();
}
}

View File

@ -24,7 +24,7 @@ import static org.junit.Assert.assertThat;
/**
* Created by adam.
*/
public class HttpClientTest {
public class HttpClientIntegrationTest {
@Test
public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException {
@ -55,7 +55,7 @@ public class HttpClientTest {
.send(request, HttpResponse.BodyHandler.asString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM));
assertThat(response.body(), containsString("https://stackoverflow.com/"));
assertThat(response.body(), containsString(""));
}
@Test

View File

@ -22,7 +22,7 @@ import static org.junit.Assert.assertThat;
/**
* Created by adam.
*/
public class HttpRequestTest {
public class HttpRequestIntegrationTest {
@Test
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {

View File

@ -18,7 +18,7 @@ import static org.junit.Assert.assertThat;
/**
* Created by adam.
*/
public class HttpResponseTest {
public class HttpResponseIntegrationTest {
@Test
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {

View File

@ -5,10 +5,12 @@ import org.junit.Test;
import java.util.List;
import java.util.concurrent.SubmissionPublisher;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
public class ReactiveStreamsTest {
public class ReactiveStreamsUnitTest {
@Test
public void givenPublisher_whenSubscribeToIt_thenShouldConsumeAllElements() throws InterruptedException {
@ -25,7 +27,7 @@ public class ReactiveStreamsTest {
//then
await().atMost(1000, TimeUnit.MILLISECONDS).until(
await().atMost(1000, TimeUnit.MILLISECONDS).untilAsserted(
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(items)
);
}
@ -46,7 +48,7 @@ public class ReactiveStreamsTest {
publisher.close();
//then
await().atMost(1000, TimeUnit.MILLISECONDS).until(
await().atMost(1000, TimeUnit.MILLISECONDS).untilAsserted(
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(expectedResult)
);
}
@ -66,7 +68,7 @@ public class ReactiveStreamsTest {
publisher.close();
//then
await().atMost(1000, TimeUnit.MILLISECONDS).until(
await().atMost(1000, TimeUnit.MILLISECONDS).untilAsserted(
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(expected)
);
}

View File

@ -7,7 +7,7 @@ import java.lang.invoke.VarHandle;
import static org.assertj.core.api.Assertions.assertThat;
public class VariableHandlesTest {
public class VariableHandlesUnitTest {
public int publicTestVariable = 1;
private int privateTestVariable = 1;
@ -20,22 +20,22 @@ public class VariableHandlesTest {
public void whenVariableHandleForPublicVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
VarHandle publicIntHandle = MethodHandles
.lookup()
.in(VariableHandlesTest.class)
.findVarHandle(VariableHandlesTest.class, "publicTestVariable", int.class);
.in(VariableHandlesUnitTest.class)
.findVarHandle(VariableHandlesUnitTest.class, "publicTestVariable", int.class);
assertThat(publicIntHandle.coordinateTypes().size() == 1);
assertThat(publicIntHandle.coordinateTypes().get(0) == VariableHandles.class);
assertThat(publicIntHandle.coordinateTypes().get(0) == VariableHandlesUnitTest.class);
}
@Test
public void whenVariableHandleForPrivateVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
VarHandle privateIntHandle = MethodHandles
.privateLookupIn(VariableHandlesTest.class, MethodHandles.lookup())
.findVarHandle(VariableHandlesTest.class, "privateTestVariable", int.class);
.privateLookupIn(VariableHandlesUnitTest.class, MethodHandles.lookup())
.findVarHandle(VariableHandlesUnitTest.class, "privateTestVariable", int.class);
assertThat(privateIntHandle.coordinateTypes().size() == 1);
assertThat(privateIntHandle.coordinateTypes().get(0) == VariableHandlesTest.class);
assertThat(privateIntHandle.coordinateTypes().get(0) == VariableHandlesUnitTest.class);
}
@ -52,8 +52,8 @@ public class VariableHandlesTest {
public void givenVarHandle_whenGetIsInvoked_ThenValueOfVariableIsReturned() throws NoSuchFieldException, IllegalAccessException {
VarHandle publicIntHandle = MethodHandles
.lookup()
.in(VariableHandlesTest.class)
.findVarHandle(VariableHandlesTest.class, "publicTestVariable", int.class);
.in(VariableHandlesUnitTest.class)
.findVarHandle(VariableHandlesUnitTest.class, "publicTestVariable", int.class);
assertThat((int) publicIntHandle.get(this) == 1);
}
@ -62,8 +62,8 @@ public class VariableHandlesTest {
public void givenVarHandle_whenSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
VarHandle publicIntHandle = MethodHandles
.lookup()
.in(VariableHandlesTest.class)
.findVarHandle(VariableHandlesTest.class, "variableToSet", int.class);
.in(VariableHandlesUnitTest.class)
.findVarHandle(VariableHandlesUnitTest.class, "variableToSet", int.class);
publicIntHandle.set(this, 15);
assertThat((int) publicIntHandle.get(this) == 15);
@ -73,8 +73,8 @@ public class VariableHandlesTest {
public void givenVarHandle_whenCompareAndSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
VarHandle publicIntHandle = MethodHandles
.lookup()
.in(VariableHandlesTest.class)
.findVarHandle(VariableHandlesTest.class, "variableToCompareAndSet", int.class);
.in(VariableHandlesUnitTest.class)
.findVarHandle(VariableHandlesUnitTest.class, "variableToCompareAndSet", int.class);
publicIntHandle.compareAndSet(this, 1, 100);
assertThat((int) publicIntHandle.get(this) == 100);
@ -84,8 +84,8 @@ public class VariableHandlesTest {
public void givenVarHandle_whenGetAndAddIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
VarHandle publicIntHandle = MethodHandles
.lookup()
.in(VariableHandlesTest.class)
.findVarHandle(VariableHandlesTest.class, "variableToGetAndAdd", int.class);
.in(VariableHandlesUnitTest.class)
.findVarHandle(VariableHandlesUnitTest.class, "variableToGetAndAdd", int.class);
int before = (int) publicIntHandle.getAndAdd(this, 200);
assertThat(before == 0);
@ -96,8 +96,8 @@ public class VariableHandlesTest {
public void givenVarHandle_whenGetAndBitwiseOrIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
VarHandle publicIntHandle = MethodHandles
.lookup()
.in(VariableHandlesTest.class)
.findVarHandle(VariableHandlesTest.class, "variableToBitwiseOr", byte.class);
.in(VariableHandlesUnitTest.class)
.findVarHandle(VariableHandlesUnitTest.class, "variableToBitwiseOr", byte.class);
byte before = (byte) publicIntHandle.getAndBitwiseOr(this, (byte) 127);
assertThat(before == 0);

View File

@ -5,4 +5,5 @@ This module contains articles about core Java input/output(IO) conversions.
### Relevant Articles:
- [Java InputStream to String](https://www.baeldung.com/convert-input-stream-to-string)
- [Java Write an InputStream to a File](https://www.baeldung.com/convert-input-stream-to-a-file)
- [Converting a BufferedReader to a JSONObject](https://www.baeldung.com/java-bufferedreader-to-jsonobject)
- More articles: [[<-- prev]](/core-java-modules/core-java-io-conversions)

View File

@ -21,6 +21,11 @@
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20200518</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,48 @@
package com.baeldung.bufferedreadertojsonobject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.junit.Test;
public class JavaBufferedReaderToJSONObjectUnitTest {
@Test
public void givenValidJson_whenUsingBufferedReader_thenJSONTokenerConverts() {
byte[] b = "{ \"name\" : \"John\", \"age\" : 18 }".getBytes(StandardCharsets.UTF_8);
InputStream is = new ByteArrayInputStream(b);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
JSONTokener tokener = new JSONTokener(bufferedReader);
JSONObject json = new JSONObject(tokener);
assertNotNull(json);
assertEquals("John", json.get("name"));
assertEquals(18, json.get("age"));
}
@Test
public void givenValidJson_whenUsingString_thenJSONObjectConverts() throws IOException {
byte[] b = "{ \"name\" : \"John\", \"age\" : 18 }".getBytes(StandardCharsets.UTF_8);
InputStream is = new ByteArrayInputStream(b);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
JSONObject json = new JSONObject(sb.toString());
assertNotNull(json);
assertEquals("John", json.get("name"));
assertEquals(18, json.get("age"));
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.error.oom;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
public class ExecutorServiceUnitTest {
@Test
public void givenAnExecutorService_WhenMoreTasksSubmitted_ThenAdditionalTasksWait() {
// Given
int noOfThreads = 5;
ExecutorService executorService = Executors.newFixedThreadPool(noOfThreads);
Runnable runnableTask = () -> {
try {
TimeUnit.HOURS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
// When
IntStream.rangeClosed(1, 10)
.forEach(i -> executorService.submit(runnableTask));
// Then
assertThat(((ThreadPoolExecutor) executorService).getQueue()
.size(), is(equalTo(5)));
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.inttoenum;
import java.util.HashMap;
import java.util.Map;
public enum PizzaStatus {
ORDERED(5),
READY(2),
DELIVERED(0);
private int timeToDelivery;
PizzaStatus(int timeToDelivery) {
this.timeToDelivery = timeToDelivery;
}
public int getTimeToDelivery() {
return timeToDelivery;
}
private static Map<Integer, PizzaStatus> timeToDeliveryToEnumValuesMapping = new HashMap<>();
static {
PizzaStatus[] pizzaStatuses = PizzaStatus.values();
for (int pizzaStatusIndex = 0; pizzaStatusIndex < pizzaStatuses.length; pizzaStatusIndex++) {
timeToDeliveryToEnumValuesMapping.put(
pizzaStatuses[pizzaStatusIndex].getTimeToDelivery(),
pizzaStatuses[pizzaStatusIndex]
);
}
}
public static PizzaStatus castIntToEnum(int timeToDelivery) {
return timeToDeliveryToEnumValuesMapping.get(timeToDelivery);
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.inttoenum;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class IntToEnumUnitTest {
@Test
public void whenIntToEnumUsingValuesMethod_thenReturnEnumObject() {
int timeToDeliveryForOrderedPizzaStatus = 5;
PizzaStatus[] pizzaStatuses = PizzaStatus.values();
PizzaStatus pizzaOrderedStatus = null;
for (int pizzaStatusIndex = 0; pizzaStatusIndex < pizzaStatuses.length; pizzaStatusIndex++) {
if (pizzaStatuses[pizzaStatusIndex].getTimeToDelivery() == timeToDeliveryForOrderedPizzaStatus) {
pizzaOrderedStatus = pizzaStatuses[pizzaStatusIndex];
}
}
assertEquals(pizzaOrderedStatus, PizzaStatus.ORDERED);
}
@Test
public void whenIntToEnumUsingMap_thenReturnEnumObject() {
int timeToDeliveryForOrderedPizzaStatus = 5;
assertEquals(PizzaStatus.castIntToEnum(timeToDeliveryForOrderedPizzaStatus), PizzaStatus.ORDERED);
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.supertype;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public abstract class TypeReference<T> {
private final Type type;
public TypeReference() {
Type superclass = getClass().getGenericSuperclass();
type = ((ParameterizedType) superclass).getActualTypeArguments()[0];
}
public Type getType() {
return type;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.supertype;
import org.junit.Test;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class TypeReferenceUnitTest {
@Test
public void givenGenericToken_whenUsingSuperTypeToken_thenPreservesTheTypeInfo() {
TypeReference<Map<String, Integer>> token = new TypeReference<Map<String, Integer>>() {};
Type type = token.getType();
assertEquals("java.util.Map<java.lang.String, java.lang.Integer>", type.getTypeName());
Type[] typeArguments = ((ParameterizedType) type).getActualTypeArguments();
assertEquals("java.lang.String", typeArguments[0].getTypeName());
assertEquals("java.lang.Integer", typeArguments[1].getTypeName());
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.nullassertion
import org.junit.Test
import kotlin.test.assertEquals
class NotNullAssertionUnitTest {
@Test
fun givenNullableValue_WhenNotNull_ShouldExtractTheValue() {
val answer: String? = "42"
assertEquals(42, answer!!.toInt())
}
@Test(expected = KotlinNullPointerException::class)
fun givenNullableValue_WhenIsNull_ThenShouldThrow() {
val noAnswer: String? = null
noAnswer!!
}
}

View File

@ -19,9 +19,9 @@ class StringComparisonUnitTest {
fun `compare using referential equals operator`() {
val first = "kotlin"
val second = "kotlin"
val copyOfFirst = buildString { "kotlin" }
val third = String("kotlin".toCharArray())
assertTrue { first === second }
assertFalse { first === copyOfFirst }
assertFalse { first === third }
}
@Test

View File

@ -221,6 +221,7 @@
<systemPropertyVariables>
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
<jboss.home>${project.basedir}/target/wildfly-${wildfly.version}</jboss.home>
<jboss.http.port>8756</jboss.http.port>
<module.path>${project.basedir}/target/wildfly-${wildfly.version}/modules</module.path>
</systemPropertyVariables>
<redirectTestOutputToFile>false</redirectTestOutputToFile>
@ -278,9 +279,10 @@
<arquillian-drone-bom.version>2.0.1.Final</arquillian-drone-bom.version>
<arquillian-rest-client.version>1.0.0.Alpha4</arquillian-rest-client.version>
<logback.version>1.1.7</logback.version>
<resteasy.version>3.8.0.Final</resteasy.version>
<shrinkwrap.version>3.1.3</shrinkwrap.version>
</properties>
</project>

View File

@ -7,7 +7,7 @@
<jta-data-source>java:jboss/datasources/ExampleDS</jta-data-source>
<class>com.enpy.entity.Student</class>
<class>com.baeldung.jeekotlin.entity.Student</class>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create"/>

View File

@ -14,6 +14,7 @@ import org.zalando.problem.Problem;
import org.zalando.problem.ProblemBuilder;
import org.zalando.problem.Status;
import org.zalando.problem.spring.web.advice.ProblemHandling;
import org.zalando.problem.spring.web.advice.security.SecurityAdviceTrait;
import org.zalando.problem.violations.ConstraintViolationProblem;
import javax.annotation.Nonnull;
@ -28,7 +29,7 @@ import java.util.stream.Collectors;
* The error response follows RFC7807 - Problem Details for HTTP APIs (https://tools.ietf.org/html/rfc7807)
*/
@ControllerAdvice
public class ExceptionTranslator implements ProblemHandling {
public class ExceptionTranslator implements ProblemHandling, SecurityAdviceTrait {
/**
* Post-process the Problem payload to add the message key for the front-end if needed

View File

@ -14,6 +14,7 @@ import org.zalando.problem.Problem;
import org.zalando.problem.ProblemBuilder;
import org.zalando.problem.Status;
import org.zalando.problem.spring.web.advice.ProblemHandling;
import org.zalando.problem.spring.web.advice.security.SecurityAdviceTrait;
import org.zalando.problem.violations.ConstraintViolationProblem;
import javax.annotation.Nonnull;
@ -28,7 +29,7 @@ import java.util.stream.Collectors;
* The error response follows RFC7807 - Problem Details for HTTP APIs (https://tools.ietf.org/html/rfc7807)
*/
@ControllerAdvice
public class ExceptionTranslator implements ProblemHandling {
public class ExceptionTranslator implements ProblemHandling, SecurityAdviceTrait {
/**
* Post-process the Problem payload to add the message key for the front-end if needed

View File

@ -14,6 +14,7 @@ import org.zalando.problem.Problem;
import org.zalando.problem.ProblemBuilder;
import org.zalando.problem.Status;
import org.zalando.problem.spring.web.advice.ProblemHandling;
import org.zalando.problem.spring.web.advice.security.SecurityAdviceTrait;
import org.zalando.problem.violations.ConstraintViolationProblem;
import javax.annotation.Nonnull;
@ -28,7 +29,7 @@ import java.util.stream.Collectors;
* The error response follows RFC7807 - Problem Details for HTTP APIs (https://tools.ietf.org/html/rfc7807)
*/
@ControllerAdvice
public class ExceptionTranslator implements ProblemHandling {
public class ExceptionTranslator implements ProblemHandling, SecurityAdviceTrait {
/**
* Post-process the Problem payload to add the message key for the front-end if needed

View File

@ -1,14 +1,20 @@
package com.baeldung;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
public class BenchMark {
@State(Scope.Benchmark)
public static class Log {
public int x = 8;
}
@State(Scope.Benchmark)
public static class ExecutionPlan {
@ -45,4 +51,44 @@ public class BenchMark {
// Do nothing
}
@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public void doNothing() {
}
@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public void objectCreation() {
new Object();
}
@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public Object pillarsOfCreation() {
return new Object();
}
@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public void blackHole(Blackhole blackhole) {
blackhole.consume(new Object());
}
@Benchmark
public double foldedLog() {
int x = 8;
return Math.log(x);
}
@Benchmark
public double log(Log input) {
return Math.log(input.x);
}
}

View File

@ -3,3 +3,5 @@
This module contains articles about Java interop with other language integrations.
### Relevant Articles:
- [How to Call Python From Java](https://www.baeldung.com/java-working-with-python)

View File

@ -121,6 +121,11 @@
<artifactId>univocity-parsers</artifactId>
<version>${univocity.version}</version>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>${kafka.version}</version>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
@ -184,6 +189,7 @@
<renjin.version>RELEASE</renjin.version>
<rcaller.version>3.0</rcaller.version>
<rserve.version>1.8.1</rserve.version>
<kafka.version>2.5.0</kafka.version>
</properties>
<build>

View File

@ -0,0 +1,28 @@
package com.baeldung.kafka.consumer;
class CountryPopulation {
private String country;
private Integer population;
public CountryPopulation(String country, Integer population) {
this.country = country;
this.population = population;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Integer getPopulation() {
return population;
}
public void setPopulation(Integer population) {
this.population = population;
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.kafka.consumer;
import java.time.Duration;
import java.util.Collections;
import java.util.stream.StreamSupport;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.errors.WakeupException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CountryPopulationConsumer {
private static Logger logger = LoggerFactory.getLogger(CountryPopulationConsumer.class);
private Consumer<String, Integer> consumer;
private java.util.function.Consumer<Throwable> exceptionConsumer;
private java.util.function.Consumer<CountryPopulation> countryPopulationConsumer;
public CountryPopulationConsumer(
Consumer<String, Integer> consumer, java.util.function.Consumer<Throwable> exceptionConsumer,
java.util.function.Consumer<CountryPopulation> countryPopulationConsumer) {
this.consumer = consumer;
this.exceptionConsumer = exceptionConsumer;
this.countryPopulationConsumer = countryPopulationConsumer;
}
void startBySubscribing(String topic) {
consume(() -> consumer.subscribe(Collections.singleton(topic)));
}
void startByAssigning(String topic, int partition) {
consume(() -> consumer.assign(Collections.singleton(new TopicPartition(topic, partition))));
}
private void consume(Runnable beforePollingTask) {
try {
beforePollingTask.run();
while (true) {
ConsumerRecords<String, Integer> records = consumer.poll(Duration.ofMillis(1000));
StreamSupport.stream(records.spliterator(), false)
.map(record -> new CountryPopulation(record.key(), record.value()))
.forEach(countryPopulationConsumer);
consumer.commitSync();
}
} catch (WakeupException e) {
logger.info("Shutting down...");
} catch (RuntimeException ex) {
exceptionConsumer.accept(ex);
} finally {
consumer.close();
}
}
public void stop() {
consumer.wakeup();
}
}

View File

@ -0,0 +1,100 @@
package com.baeldung.kafka.consumer;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.MockConsumer;
import org.apache.kafka.clients.consumer.OffsetResetStrategy;
import org.apache.kafka.common.KafkaException;
import org.apache.kafka.common.TopicPartition;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class CountryPopulationConsumerUnitTest {
private static final String TOPIC = "topic";
private static final int PARTITION = 0;
private CountryPopulationConsumer countryPopulationConsumer;
private List<CountryPopulation> updates;
private Throwable pollException;
private MockConsumer<String, Integer> consumer;
@BeforeEach
void setUp() {
consumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST);
updates = new ArrayList<>();
countryPopulationConsumer = new CountryPopulationConsumer(consumer, ex -> this.pollException = ex, updates::add);
}
@Test
void whenStartingByAssigningTopicPartition_thenExpectUpdatesAreConsumedCorrectly() {
// GIVEN
consumer.schedulePollTask(() -> consumer.addRecord(record(TOPIC, PARTITION, "Romania", 19_410_000)));
consumer.schedulePollTask(() -> countryPopulationConsumer.stop());
HashMap<TopicPartition, Long> startOffsets = new HashMap<>();
TopicPartition tp = new TopicPartition(TOPIC, PARTITION);
startOffsets.put(tp, 0L);
consumer.updateBeginningOffsets(startOffsets);
// WHEN
countryPopulationConsumer.startByAssigning(TOPIC, PARTITION);
// THEN
assertThat(updates).hasSize(1);
assertThat(consumer.closed()).isTrue();
}
@Test
void whenStartingBySubscribingToTopic_thenExpectUpdatesAreConsumedCorrectly() {
// GIVEN
consumer.schedulePollTask(() -> {
consumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC, 0)));
consumer.addRecord(record(TOPIC, PARTITION, "Romania", 19_410_000));
});
consumer.schedulePollTask(() -> countryPopulationConsumer.stop());
HashMap<TopicPartition, Long> startOffsets = new HashMap<>();
TopicPartition tp = new TopicPartition(TOPIC, PARTITION);
startOffsets.put(tp, 0L);
consumer.updateBeginningOffsets(startOffsets);
// WHEN
countryPopulationConsumer.startBySubscribing(TOPIC);
// THEN
assertThat(updates).hasSize(1);
assertThat(consumer.closed()).isTrue();
}
@Test
void whenStartingBySubscribingToTopicAndExceptionOccurs_thenExpectExceptionIsHandledCorrectly() {
// GIVEN
consumer.schedulePollTask(() -> consumer.setPollException(new KafkaException("poll exception")));
consumer.schedulePollTask(() -> countryPopulationConsumer.stop());
HashMap<TopicPartition, Long> startOffsets = new HashMap<>();
TopicPartition tp = new TopicPartition(TOPIC, 0);
startOffsets.put(tp, 0L);
consumer.updateBeginningOffsets(startOffsets);
// WHEN
countryPopulationConsumer.startBySubscribing(TOPIC);
// THEN
assertThat(pollException).isInstanceOf(KafkaException.class).hasMessage("poll exception");
assertThat(consumer.closed()).isTrue();
}
private ConsumerRecord<String, Integer> record(String topic, int partition, String country, int population) {
return new ConsumerRecord<>(topic, partition, 0, country, population);
}
}

View File

@ -211,7 +211,7 @@
<datanucleus-maven-plugin.version>5.0.2</datanucleus-maven-plugin.version>
<datanucleus-jdo-query.version>5.0.4</datanucleus-jdo-query.version>
<javax.jdo.version>3.2.0-m7</javax.jdo.version>
<HikariCP.version>2.7.2</HikariCP.version>
<HikariCP.version>3.4.5</HikariCP.version>
<ebean.version>11.22.4</ebean.version>
</properties>

3
libraries-rpc/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Introduction to Finagle](https://www.baeldung.com/java-finagle)

9
libraries-server-2/.gitignore vendored Normal file
View File

@ -0,0 +1,9 @@
*.class
# Folders #
/gensrc
/target
# Packaged files #
*.jar
/bin/

View File

@ -0,0 +1,8 @@
## Server
This module contains articles about server libraries.
### Relevant Articles:
- [HTTP/2 in Jetty](https://www.baeldung.com/jetty-http-2)
- More articles: [[<-- prev]](../libraries-server)

View File

@ -0,0 +1,77 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>libraries-server-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>libraries-server-2</name>
<packaging>war</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>${jetty.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jetty.version}</version>
<configuration>
<stopPort>8888</stopPort>
<stopKey>quit</stopKey>
<jvmArgs>
-Xbootclasspath/p:${settings.localRepository}/org/mortbay/jetty/alpn/alpn-boot/${alpn.version}/alpn-boot-${alpn.version}.jar
</jvmArgs>
<jettyXml>${basedir}/src/main/config/jetty.xml</jettyXml>
<webApp>
<contextPath>/</contextPath>
</webApp>
</configuration>
<dependencies>
<dependency>
<groupId>org.eclipse.jetty.http2</groupId>
<artifactId>http2-server</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-alpn-openjdk8-server</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlets</artifactId>
<version>${jetty.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<properties>
<jetty.version>9.4.27.v20200227</jetty.version>
<alpn.version>8.1.11.v20170118</alpn.version>
</properties>
</project>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 20 KiB

View File

@ -13,4 +13,4 @@ This module contains articles about server libraries.
- [MQTT Client in Java](https://www.baeldung.com/java-mqtt-client)
- [Guide to XMPP Smack Client](https://www.baeldung.com/xmpp-smack-chat-client)
- [A Guide to NanoHTTPD](https://www.baeldung.com/nanohttpd)
- [HTTP/2 in Jetty](https://www.baeldung.com/jetty-http-2)
- More articles: [[more -->]](../libraries-server-2)

View File

@ -5,7 +5,6 @@
<artifactId>libraries-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>libraries-server</name>
<packaging>war</packaging>
<parent>
<groupId>com.baeldung</groupId>
@ -107,50 +106,11 @@
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jetty.version}</version>
<configuration>
<stopPort>8888</stopPort>
<stopKey>quit</stopKey>
<jvmArgs>
-Xbootclasspath/p:${settings.localRepository}/org/mortbay/jetty/alpn/alpn-boot/${alpn.version}/alpn-boot-${alpn.version}.jar
</jvmArgs>
<jettyXml>${basedir}/src/main/config/jetty.xml</jettyXml>
<webApp>
<contextPath>/</contextPath>
</webApp>
</configuration>
<dependencies>
<dependency>
<groupId>org.eclipse.jetty.http2</groupId>
<artifactId>http2-server</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-alpn-openjdk8-server</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlets</artifactId>
<version>${jetty.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<properties>
<assertj.version>3.6.2</assertj.version>
<httpclient.version>4.5.3</httpclient.version>
<jetty.version>9.4.27.v20200227</jetty.version>
<netty.version>4.1.20.Final</netty.version>
<alpn.version>8.1.11.v20170118</alpn.version>
<tomcat.version>8.5.24</tomcat.version>
<smack.version>4.3.1</smack.version>
<eclipse.paho.client.mqttv3.version>1.2.0</eclipse.paho.client.mqttv3.version>

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Introduction to Netflix Genie](https://www.baeldung.com/netflix-genie-intro)

View File

@ -13,7 +13,7 @@ import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
public class HibernateTypesIntegrationTest {
public class HibernateTypesLiveTest {
@Autowired
AlbumRepository albumRepository;

View File

@ -4,3 +4,4 @@
- [Introduction to Lettuce the Java Redis Client](https://www.baeldung.com/java-redis-lettuce)
- [List All Available Redis Keys](https://www.baeldung.com/redis-list-available-keys)
- [Spring Data Rediss Property-Based Configuration](https://www.baeldung.com/spring-data-redis-properties)
- [Delete Everything in Redis](https://www.baeldung.com/redis-delete-data)

View File

@ -33,7 +33,8 @@
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.github.kstyrc</groupId>
<artifactId>embedded-redis</artifactId>

View File

@ -0,0 +1,91 @@
package com.baeldung.redis.deleteeverything;
import org.junit.*;
import redis.clients.jedis.Jedis;
import redis.embedded.RedisServer;
import java.io.IOException;
import java.net.ServerSocket;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class DeleteEverythingInRedisIntegrationTest {
private Jedis jedis;
private RedisServer redisServer;
private int port;
@Before
public void setUp() throws IOException {
// Take an available port
ServerSocket s = new ServerSocket(0);
port = s.getLocalPort();
s.close();
redisServer = new RedisServer(port);
redisServer.start();
// Configure JEDIS
jedis = new Jedis("localhost", port);
}
@After
public void destroy() {
redisServer.stop();
}
@Test
public void whenPutDataIntoRedis_thenCanBeFound() {
String key = "key";
String value = "value";
jedis.set(key, value);
String received = jedis.get(key);
assertEquals(value, received);
}
@Test
public void whenPutDataIntoRedisAndThenFlush_thenCannotBeFound() {
String key = "key";
String value = "value";
jedis.set(key, value);
jedis.flushDB();
String received = jedis.get(key);
assertNull(received);
}
@Test
public void whenPutDataIntoMultipleDatabases_thenFlushAllRemovesAll() {
// add keys in different databases
jedis.select(0);
jedis.set("key1", "value1");
jedis.select(1);
jedis.set("key2", "value2");
// we'll find the correct keys in the correct dbs
jedis.select(0);
assertEquals("value1", jedis.get("key1"));
assertNull(jedis.get("key2"));
jedis.select(1);
assertEquals("value2", jedis.get("key2"));
assertNull(jedis.get("key1"));
// then, when we flush
jedis.flushAll();
// the keys will have gone
jedis.select(0);
assertNull(jedis.get("key1"));
assertNull(jedis.get("key2"));
jedis.select(1);
assertNull(jedis.get("key1"));
assertNull(jedis.get("key2"));
}
}

View File

@ -3,6 +3,6 @@
- [Using JDBI with Spring Boot](https://www.baeldung.com/spring-boot-jdbi)
- [Configuring a Tomcat Connection Pool in Spring Boot](https://www.baeldung.com/spring-boot-tomcat-connection-pool)
- [Integrating Spring Boot with HSQLDB](https://www.baeldung.com/spring-boot-hsqldb)
- [List of In-Memory Databases](http://www.baeldung.com/java-in-memory-databases)
- [List of In-Memory Databases](https://www.baeldung.com/java-in-memory-databases)
- [Oracle Connection Pooling With Spring](https://www.baeldung.com/spring-oracle-connection-pooling)
- More articles: [[<-- prev]](../spring-boot-persistence)

View File

@ -4,6 +4,7 @@ import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.tomcatconnectionpool.application.SpringBootConsoleApplication;
@ -13,6 +14,7 @@ import org.springframework.boot.test.context.SpringBootTest;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SpringBootConsoleApplication.class})
@TestPropertySource(properties = "spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource")
public class SpringBootTomcatConnectionPoolIntegrationTest {
@Autowired

View File

@ -35,23 +35,21 @@
<version>${lombok.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>db-util</artifactId>
<version>${db-util.version}</version>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>${byte-buddy.version}</version>
</dependency>
</dependencies>
<properties>
<!-- The main class to start by executing java -jar -->
<start-class>com.baeldung.h2db.demo.server.SpringBootApp</start-class>
<spring-boot.version>2.0.4.RELEASE</spring-boot.version>
<hibernate.version>5.3.11.Final</hibernate.version>
<db-util.version>1.0.4</db-util.version>
</properties>

View File

@ -8,5 +8,4 @@ spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.validator.apply_to_ddl=false
#spring.jpa.properties.hibernate.check_nullability=true
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
debug=true
spring.h2.console.path=/h2-console

View File

@ -1,8 +1,8 @@
### Relevant Articles:
- [Spring Boot with Multiple SQL Import Files](http://www.baeldung.com/spring-boot-sql-import-files)
- [Configuring Separate Spring DataSource for Tests](http://www.baeldung.com/spring-testing-separate-data-source)
- [Quick Guide on Loading Initial Data with Spring Boot](http://www.baeldung.com/spring-boot-data-sql-and-schema-sql)
- [Spring Boot with Multiple SQL Import Files](https://www.baeldung.com/spring-boot-sql-import-files)
- [Configuring Separate Spring DataSource for Tests](https://www.baeldung.com/spring-testing-separate-data-source)
- [Quick Guide on Loading Initial Data with Spring Boot](https://www.baeldung.com/spring-boot-data-sql-and-schema-sql)
- [Configuring a DataSource Programmatically in Spring Boot](https://www.baeldung.com/spring-boot-configure-data-source-programmatic)
- [Resolving “Failed to Configure a DataSource” Error](https://www.baeldung.com/spring-boot-failed-to-configure-data-source)
- [Hibernate Field Naming with Spring Boot](https://www.baeldung.com/hibernate-field-naming-spring-boot)

View File

@ -15,13 +15,7 @@
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
@ -36,6 +30,7 @@
<artifactId>elasticsearch</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
@ -49,8 +44,8 @@
</dependency>
<dependency>
<groupId>com.vividsolutions</groupId>
<artifactId>jts</artifactId>
<groupId>org.locationtech.jts</groupId>
<artifactId>jts-core</artifactId>
<version>${jts.version}</version>
<exclusions>
<exclusion>
@ -60,41 +55,19 @@
</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>
<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>
<spring-data-elasticsearch.version>4.0.0.RELEASE</spring-data-elasticsearch.version>
<elasticsearch.version>7.6.2</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>
<spatial4j.version>0.7</spatial4j.version>
<jts.version>1.15.0</jts.version>
</properties>
</project>

View File

@ -1,19 +1,13 @@
package com.baeldung.spring.data.es.config;
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.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
@Configuration
@ -21,30 +15,18 @@ 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/5.6.0}")
private String elasticsearchHome;
@Value("${elasticsearch.cluster.name:elasticsearch}")
private String clusterName;
@Bean
public Client client() {
TransportClient client = null;
try {
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;
RestHighLevelClient client() {
ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo("localhost:9200")
.build();
return RestClients.create(clientConfiguration)
.rest();
}
@Bean
public ElasticsearchOperations elasticsearchTemplate() {
return new ElasticsearchTemplate(client());
return new ElasticsearchRestTemplate(client());
}
}

View File

@ -1,7 +1,12 @@
package com.baeldung.spring.data.es.model;
import static org.springframework.data.elasticsearch.annotations.FieldType.Text;
import org.springframework.data.elasticsearch.annotations.Field;
public class Author {
@Field(type = Text)
private String name;
public Author() {

View File

@ -1,28 +0,0 @@
package com.baeldung.spring.data.es.service;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.baeldung.spring.data.es.model.Article;
public interface ArticleService {
Article save(Article article);
Optional<Article> findOne(String id);
Iterable<Article> findAll();
Page<Article> findByAuthorName(String name, Pageable pageable);
Page<Article> findByAuthorNameUsingCustomQuery(String name, Pageable pageable);
Page<Article> findByFilteredTagQuery(String tag, Pageable pageable);
Page<Article> findByAuthorsNameAndFilteredTagQuery(String name, String tag, Pageable pageable);
long count();
void delete(Article article);
}

View File

@ -1,67 +0,0 @@
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;
import org.springframework.stereotype.Service;
import com.baeldung.spring.data.es.model.Article;
import com.baeldung.spring.data.es.repository.ArticleRepository;
@Service
public class ArticleServiceImpl implements ArticleService {
private final ArticleRepository articleRepository;
@Autowired
public ArticleServiceImpl(ArticleRepository articleRepository) {
this.articleRepository = articleRepository;
}
@Override
public Article save(Article article) {
return articleRepository.save(article);
}
@Override
public Optional<Article> findOne(String id) {
return articleRepository.findById(id);
}
@Override
public Iterable<Article> findAll() {
return articleRepository.findAll();
}
@Override
public Page<Article> findByAuthorName(String name, Pageable pageable) {
return articleRepository.findByAuthorsName(name, pageable);
}
@Override
public Page<Article> findByAuthorNameUsingCustomQuery(String name, Pageable pageable) {
return articleRepository.findByAuthorsNameUsingCustomQuery(name, pageable);
}
@Override
public Page<Article> findByFilteredTagQuery(String tag, Pageable pageable) {
return articleRepository.findByFilteredTagQuery(tag, pageable);
}
@Override
public Page<Article> findByAuthorsNameAndFilteredTagQuery(String name, String tag, Pageable pageable) {
return articleRepository.findByAuthorsNameAndFilteredTagQuery(name, tag, pageable);
}
@Override
public long count() {
return articleRepository.count();
}
@Override
public void delete(Article article) {
articleRepository.delete(article);
}
}

View File

@ -8,10 +8,10 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.spring.data.es.config.Config;
/**
* This Manual test requires: Elasticsearch instance running on localhost:9200.
*
* This Manual test requires:
* * Elasticsearch instance running on host
*
* The following docker command can be used: docker run -d --name es762 -p
* 9200:9200 -e "discovery.type=single-node" elasticsearch:7.6.2
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)

View File

@ -3,43 +3,48 @@ package com.baeldung.elasticsearch;
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 java.util.stream.Stream;
import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.DocWriteResponse.Result;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
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.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
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.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Before;
import org.junit.Test;
import com.alibaba.fastjson.JSON;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
/**
* This Manual test requires: Elasticsearch instance running on localhost:9200.
*
* This Manual test requires:
* * Elasticsearch instance running on host
* * with cluster name = elasticsearch
*
* The following docker command can be used: docker run -d --name es762 -p
* 9200:9200 -e "discovery.type=single-node" elasticsearch:7.6.2
*/
public class ElasticSearchManualTest {
private List<Person> listOfPersons = new ArrayList<>();
private Client client = null;
private RestHighLevelClient client = null;
@Before
public void setUp() throws UnknownHostException {
@ -47,115 +52,122 @@ public class ElasticSearchManualTest {
Person person2 = new Person(25, "Janette Doe", new Date());
listOfPersons.add(person1);
listOfPersons.add(person2);
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));
ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo("localhost:9200")
.build();
client = RestClients.create(clientConfiguration)
.rest();
}
@Test
public void givenJsonString_whenJavaObject_thenIndexDocument() {
public void givenJsonString_whenJavaObject_thenIndexDocument() throws Exception {
String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}";
IndexResponse response = client
.prepareIndex("people", "Doe")
.setSource(jsonObject, XContentType.JSON)
.get();
IndexRequest request = new IndexRequest("people");
request.source(jsonObject, XContentType.JSON);
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
String index = response.getIndex();
String type = response.getType();
long version = response.getVersion();
assertEquals(Result.CREATED, response.getResult());
assertEquals(index, "people");
assertEquals(type, "Doe");
assertEquals(1, version);
assertEquals("people", index);
}
@Test
public void givenDocumentId_whenJavaObject_thenDeleteDocument() {
public void givenDocumentId_whenJavaObject_thenDeleteDocument() throws Exception {
String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}";
IndexResponse response = client
.prepareIndex("people", "Doe")
.setSource(jsonObject, XContentType.JSON)
.get();
IndexRequest indexRequest = new IndexRequest("people");
indexRequest.source(jsonObject, XContentType.JSON);
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
String id = response.getId();
DeleteResponse deleteResponse = client
.prepareDelete("people", "Doe", id)
.get();
assertEquals(Result.DELETED,deleteResponse.getResult());
GetRequest getRequest = new GetRequest("people");
getRequest.id(id);
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
System.out.println(getResponse.getSourceAsString());
DeleteRequest deleteRequest = new DeleteRequest("people");
deleteRequest.id(id);
DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
assertEquals(Result.DELETED, deleteResponse.getResult());
}
@Test
public void givenSearchRequest_whenMatchAll_thenReturnAllResults() {
SearchResponse response = client
.prepareSearch()
.execute()
.actionGet();
SearchHit[] searchHits = response
.getHits()
.getHits();
public void givenSearchRequest_whenMatchAll_thenReturnAllResults() throws Exception {
SearchRequest searchRequest = new SearchRequest();
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] searchHits = response.getHits()
.getHits();
List<Person> results = Arrays.stream(searchHits)
.map(hit -> JSON.parseObject(hit.getSourceAsString(), Person.class))
.collect(Collectors.toList());
.map(hit -> JSON.parseObject(hit.getSourceAsString(), Person.class))
.collect(Collectors.toList());
results.forEach(System.out::println);
}
@Test
public void givenSearchParameters_thenReturnResults() {
SearchResponse response = client
.prepareSearch()
.setTypes()
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setPostFilter(QueryBuilders
.rangeQuery("age")
public void givenSearchParameters_thenReturnResults() throws Exception {
SearchSourceBuilder builder = new SearchSourceBuilder().postFilter(QueryBuilders.rangeQuery("age")
.from(5)
.to(15))
.setFrom(0)
.setSize(60)
.setExplain(true)
.execute()
.actionGet();
.to(15));
SearchResponse response2 = client
.prepareSearch()
.setTypes()
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setPostFilter(QueryBuilders.simpleQueryStringQuery("+John -Doe OR Janette"))
.setFrom(0)
.setSize(60)
.setExplain(true)
.execute()
.actionGet();
SearchRequest searchRequest = new SearchRequest();
searchRequest.searchType(SearchType.DFS_QUERY_THEN_FETCH);
searchRequest.source(builder);
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
builder = new SearchSourceBuilder().postFilter(QueryBuilders.simpleQueryStringQuery("+John -Doe OR Janette"));
searchRequest = new SearchRequest();
searchRequest.searchType(SearchType.DFS_QUERY_THEN_FETCH);
searchRequest.source(builder);
SearchResponse response2 = client.search(searchRequest, RequestOptions.DEFAULT);
builder = new SearchSourceBuilder().postFilter(QueryBuilders.matchQuery("John", "Name*"));
searchRequest = new SearchRequest();
searchRequest.searchType(SearchType.DFS_QUERY_THEN_FETCH);
searchRequest.source(builder);
SearchResponse response3 = client.search(searchRequest, RequestOptions.DEFAULT);
SearchResponse response3 = client
.prepareSearch()
.setTypes()
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setPostFilter(QueryBuilders.matchQuery("John", "Name*"))
.setFrom(0)
.setSize(60)
.setExplain(true)
.execute()
.actionGet();
response2.getHits();
response3.getHits();
final List<Person> results = Arrays.stream(response.getHits().getHits())
.map(hit -> JSON.parseObject(hit.getSourceAsString(), Person.class))
.collect(Collectors.toList());
final List<Person> results = Stream.of(response.getHits()
.getHits(),
response2.getHits()
.getHits(),
response3.getHits()
.getHits())
.flatMap(Arrays::stream)
.map(hit -> JSON.parseObject(hit.getSourceAsString(), Person.class))
.collect(Collectors.toList());
results.forEach(System.out::println);
}
@Test
public void givenContentBuilder_whenHelpers_thanIndexJson() throws IOException {
XContentBuilder builder = XContentFactory
.jsonBuilder()
.startObject()
.field("fullName", "Test")
.field("salary", "11500")
.field("age", "10")
.endObject();
IndexResponse response = client
.prepareIndex("people", "Doe")
.setSource(builder)
.get();
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.field("fullName", "Test")
.field("salary", "11500")
.field("age", "10")
.endObject();
assertEquals(Result.CREATED, response.getResult());
IndexRequest indexRequest = new IndexRequest("people");
indexRequest.source(builder);
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
assertEquals(Result.CREATED, response.getResult());
}
}

View File

@ -1,4 +1,5 @@
package com.baeldung.elasticsearch;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
@ -7,162 +8,169 @@ import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import com.baeldung.spring.data.es.config.Config;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.refresh.RefreshRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.geo.ShapeRelation;
import org.elasticsearch.common.geo.builders.ShapeBuilders;
import org.elasticsearch.common.geo.builders.EnvelopeBuilder;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.GeoShapeQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.locationtech.jts.geom.Coordinate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.spring.data.es.config.Config;
import com.vividsolutions.jts.geom.Coordinate;
/**
* This Manual test requires: Elasticsearch instance running on localhost:9200.
*
* This Manual test requires:
* * Elasticsearch instance running on host
* * with cluster name = elasticsearch
* * and further configurations
*
* The following docker command can be used: docker run -d --name es762 -p
* 9200:9200 -e "discovery.type=single-node" elasticsearch:7.6.2
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
public class GeoQueriesManualTest {
private static final String WONDERS_OF_WORLD = "wonders-of-world";
private static final String WONDERS = "Wonders";
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Autowired
private Client client;
private RestHighLevelClient client;
@Before
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\"}}}}";
public void setUp() throws Exception {
String jsonObject = "{\"properties\":{\"name\":{\"type\":\"text\",\"index\":false},\"region\":{\"type\":\"geo_shape\"},\"location\":{\"type\":\"geo_point\"}}}";
CreateIndexRequest req = new CreateIndexRequest(WONDERS_OF_WORLD);
req.mapping(WONDERS, jsonObject, XContentType.JSON);
client.admin()
.indices()
.create(req)
.actionGet();
req.mapping(jsonObject, XContentType.JSON);
client.indices()
.create(req, RequestOptions.DEFAULT);
}
@Test
public void givenGeoShapeData_whenExecutedGeoShapeQuery_thenResultNonEmpty() throws IOException{
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, XContentType.JSON)
.get();
IndexRequest indexRequest = new IndexRequest(WONDERS_OF_WORLD);
indexRequest.source(jsonObject, XContentType.JSON);
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
String tajMahalId = response.getId();
client.admin()
.indices()
.prepareRefresh(WONDERS_OF_WORLD)
.get();
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);
RefreshRequest refreshRequest = new RefreshRequest(WONDERS_OF_WORLD);
client.indices()
.refresh(refreshRequest, RequestOptions.DEFAULT);
Coordinate topLeft = new Coordinate(74, 31.2);
Coordinate bottomRight = new Coordinate(81.1, 24);
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD)
.setTypes(WONDERS)
.setQuery(qb)
.execute()
.actionGet();
GeoShapeQueryBuilder qb = QueryBuilders.geoShapeQuery("region", new EnvelopeBuilder(topLeft, bottomRight).buildGeometry());
qb.relation(ShapeRelation.INTERSECTS);
SearchSourceBuilder source = new SearchSourceBuilder().query(qb);
SearchRequest searchRequest = new SearchRequest(WONDERS_OF_WORLD);
searchRequest.source(source);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
List<String> ids = Arrays.stream(searchResponse.getHits()
.getHits())
.map(SearchHit::getId)
.collect(Collectors.toList());
.getHits())
.map(SearchHit::getId)
.collect(Collectors.toList());
assertTrue(ids.contains(tajMahalId));
}
@Test
public void givenGeoPointData_whenExecutedGeoBoundingBoxQuery_thenResultNonEmpty() {
public void givenGeoPointData_whenExecutedGeoBoundingBoxQuery_thenResultNonEmpty() throws Exception {
String jsonObject = "{\"name\":\"Pyramids of Giza\",\"location\":[31.131302,29.976480]}";
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
.setSource(jsonObject, XContentType.JSON)
.get();
IndexRequest indexRequest = new IndexRequest(WONDERS_OF_WORLD);
indexRequest.source(jsonObject, XContentType.JSON);
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
String pyramidsOfGizaId = response.getId();
client.admin()
.indices()
.prepareRefresh(WONDERS_OF_WORLD)
.get();
RefreshRequest refreshRequest = new RefreshRequest(WONDERS_OF_WORLD);
client.indices()
.refresh(refreshRequest, RequestOptions.DEFAULT);
QueryBuilder qb = QueryBuilders.geoBoundingBoxQuery("location")
.setCorners(31,30,28,32);
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD)
.setTypes(WONDERS)
.setQuery(qb)
.execute()
.actionGet();
.setCorners(31, 30, 28, 32);
SearchSourceBuilder source = new SearchSourceBuilder().query(qb);
SearchRequest searchRequest = new SearchRequest(WONDERS_OF_WORLD);
searchRequest.source(source);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
List<String> ids = Arrays.stream(searchResponse.getHits()
.getHits())
.map(SearchHit::getId)
.collect(Collectors.toList());
.getHits())
.map(SearchHit::getId)
.collect(Collectors.toList());
assertTrue(ids.contains(pyramidsOfGizaId));
}
@Test
public void givenGeoPointData_whenExecutedGeoDistanceQuery_thenResultNonEmpty() {
public void givenGeoPointData_whenExecutedGeoDistanceQuery_thenResultNonEmpty() throws Exception {
String jsonObject = "{\"name\":\"Lighthouse of alexandria\",\"location\":[31.131302,29.976480]}";
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
.setSource(jsonObject, XContentType.JSON)
.get();
IndexRequest indexRequest = new IndexRequest(WONDERS_OF_WORLD);
indexRequest.source(jsonObject, XContentType.JSON);
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
String lighthouseOfAlexandriaId = response.getId();
client.admin()
.indices()
.prepareRefresh(WONDERS_OF_WORLD)
.get();
RefreshRequest refreshRequest = new RefreshRequest(WONDERS_OF_WORLD);
client.indices()
.refresh(refreshRequest, RequestOptions.DEFAULT);
QueryBuilder qb = QueryBuilders.geoDistanceQuery("location")
.point(29.976, 31.131)
.distance(10, DistanceUnit.MILES);
.point(29.976, 31.131)
.distance(10, DistanceUnit.MILES);
SearchSourceBuilder source = new SearchSourceBuilder().query(qb);
SearchRequest searchRequest = new SearchRequest(WONDERS_OF_WORLD);
searchRequest.source(source);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
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());
.getHits())
.map(SearchHit::getId)
.collect(Collectors.toList());
assertTrue(ids.contains(lighthouseOfAlexandriaId));
}
@Test
public void givenGeoPointData_whenExecutedGeoPolygonQuery_thenResultNonEmpty() {
public void givenGeoPointData_whenExecutedGeoPolygonQuery_thenResultNonEmpty() throws Exception {
String jsonObject = "{\"name\":\"The Great Rann of Kutch\",\"location\":[69.859741,23.733732]}";
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
.setSource(jsonObject, XContentType.JSON)
.get();
IndexRequest indexRequest = new IndexRequest(WONDERS_OF_WORLD);
indexRequest.source(jsonObject, XContentType.JSON);
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
String greatRannOfKutchid = response.getId();
client.admin()
.indices()
.prepareRefresh(WONDERS_OF_WORLD)
.get();
RefreshRequest refreshRequest = new RefreshRequest(WONDERS_OF_WORLD);
client.indices()
.refresh(refreshRequest, RequestOptions.DEFAULT);
List<GeoPoint> allPoints = new ArrayList<GeoPoint>();
allPoints.add(new GeoPoint(22.733, 68.859));
@ -170,20 +178,23 @@ public class GeoQueriesManualTest {
allPoints.add(new GeoPoint(23, 70.859));
QueryBuilder qb = QueryBuilders.geoPolygonQuery("location", allPoints);
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD)
.setTypes(WONDERS)
.setQuery(qb)
.execute()
.actionGet();
SearchSourceBuilder source = new SearchSourceBuilder().query(qb);
SearchRequest searchRequest = new SearchRequest(WONDERS_OF_WORLD);
searchRequest.source(source);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
List<String> ids = Arrays.stream(searchResponse.getHits()
.getHits())
.map(SearchHit::getId)
.collect(Collectors.toList());
.getHits())
.map(SearchHit::getId)
.collect(Collectors.toList());
assertTrue(ids.contains(greatRannOfKutchid));
}
@After
public void destroy() {
elasticsearchTemplate.deleteIndex(WONDERS_OF_WORLD);
public void destroy() throws Exception {
DeleteIndexRequest deleteIndex = new DeleteIndexRequest(WONDERS_OF_WORLD);
client.indices()
.delete(deleteIndex, RequestOptions.DEFAULT);
}
}

View File

@ -10,68 +10,71 @@ import static org.junit.Assert.assertNotNull;
import java.util.List;
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.repository.ArticleRepository;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
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;
/**
* This Manual test requires: Elasticsearch instance running on localhost:9200.
*
* This Manual test requires:
* * Elasticsearch instance running on host
* * with cluster name = elasticsearch
*
* The following docker command can be used: docker run -d --name es762 -p
* 9200:9200 -e "discovery.type=single-node" elasticsearch:7.6.2
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
public class ElasticSearchManualTest {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
private ElasticsearchRestTemplate elasticsearchTemplate;
@Autowired
private ArticleService articleService;
private ArticleRepository articleRepository;
private final Author johnSmith = new Author("John Smith");
private final Author johnDoe = new Author("John Doe");
@Before
public void before() {
elasticsearchTemplate.deleteIndex(Article.class);
elasticsearchTemplate.createIndex(Article.class);
// don't call putMapping() to test the default mappings
Article article = new Article("Spring Data Elasticsearch");
article.setAuthors(asList(johnSmith, johnDoe));
article.setTags("elasticsearch", "spring data");
articleService.save(article);
articleRepository.save(article);
article = new Article("Search engines");
article.setAuthors(asList(johnDoe));
article.setTags("search engines", "tutorial");
articleService.save(article);
articleRepository.save(article);
article = new Article("Second Article About Elasticsearch");
article.setAuthors(asList(johnSmith));
article.setTags("elasticsearch", "spring data");
articleService.save(article);
articleRepository.save(article);
article = new Article("Elasticsearch Tutorial");
article.setAuthors(asList(johnDoe));
article.setTags("elasticsearch");
articleService.save(article);
articleRepository.save(article);
}
@After
public void after() {
articleRepository.deleteAll();
}
@Test
@ -81,82 +84,85 @@ public class ElasticSearchManualTest {
Article article = new Article("Making Search Elastic");
article.setAuthors(authors);
article = articleService.save(article);
article = articleRepository.save(article);
assertNotNull(article.getId());
}
@Test
public void givenPersistedArticles_whenSearchByAuthorsName_thenRightFound() {
final Page<Article> articleByAuthorName = articleService
.findByAuthorName(johnSmith.getName(), PageRequest.of(0, 10));
final Page<Article> articleByAuthorName = articleRepository.findByAuthorsName(johnSmith.getName(), PageRequest.of(0, 10));
assertEquals(2L, articleByAuthorName.getTotalElements());
}
@Test
public void givenCustomQuery_whenSearchByAuthorsName_thenArticleIsFound() {
final Page<Article> articleByAuthorName = articleService.findByAuthorNameUsingCustomQuery("Smith", PageRequest.of(0, 10));
final Page<Article> articleByAuthorName = articleRepository.findByAuthorsNameUsingCustomQuery("Smith", PageRequest.of(0, 10));
assertEquals(2L, articleByAuthorName.getTotalElements());
}
@Test
public void givenTagFilterQuery_whenSearchByTag_thenArticleIsFound() {
final Page<Article> articleByAuthorName = articleService.findByFilteredTagQuery("elasticsearch", PageRequest.of(0, 10));
final Page<Article> articleByAuthorName = articleRepository.findByFilteredTagQuery("elasticsearch", PageRequest.of(0, 10));
assertEquals(3L, articleByAuthorName.getTotalElements());
}
@Test
public void givenTagFilterQuery_whenSearchByAuthorsName_thenArticleIsFound() {
final Page<Article> articleByAuthorName = articleService.findByAuthorsNameAndFilteredTagQuery("Doe", "elasticsearch", PageRequest.of(0, 10));
final Page<Article> articleByAuthorName = articleRepository.findByAuthorsNameAndFilteredTagQuery("Doe", "elasticsearch", PageRequest.of(0, 10));
assertEquals(2L, articleByAuthorName.getTotalElements());
}
@Test
public void givenPersistedArticles_whenUseRegexQuery_thenRightArticlesFound() {
final Query searchQuery = new NativeSearchQueryBuilder().withFilter(regexpQuery("title", ".*data.*"))
.build();
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withFilter(regexpQuery("title", ".*data.*"))
.build();
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.size());
assertEquals(1, articles.getTotalHits());
}
@Test
public void givenSavedDoc_whenTitleUpdated_thenCouldFindByUpdatedTitle() {
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(fuzzyQuery("title", "serch")).build();
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
final Query searchQuery = new NativeSearchQueryBuilder().withQuery(fuzzyQuery("title", "serch"))
.build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.size());
assertEquals(1, articles.getTotalHits());
final Article article = articles.get(0);
final Article article = articles.getSearchHit(0)
.getContent();
final String newTitle = "Getting started with Search Engines";
article.setTitle(newTitle);
articleService.save(article);
articleRepository.save(article);
assertEquals(newTitle, articleService.findOne(article.getId()).get().getTitle());
assertEquals(newTitle, articleRepository.findById(article.getId())
.get()
.getTitle());
}
@Test
public void givenSavedDoc_whenDelete_thenRemovedFromIndex() {
final String articleTitle = "Spring Data Elasticsearch";
final SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(matchQuery("title", articleTitle).minimumShouldMatch("75%")).build();
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(1, articles.size());
final long count = articleService.count();
final Query searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", articleTitle).minimumShouldMatch("75%"))
.build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
articleService.delete(articles.get(0));
assertEquals(1, articles.getTotalHits());
final long count = articleRepository.count();
assertEquals(count - 1, articleService.count());
articleRepository.delete(articles.getSearchHit(0)
.getContent());
assertEquals(count - 1, articleRepository.count());
}
@Test
public void givenSavedDoc_whenOneTermMatches_thenFindByTitle() {
final SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(matchQuery("title", "Search engines").operator(AND)).build();
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(1, articles.size());
final Query searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Search engines").operator(AND))
.build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.getTotalHits());
}
}

View File

@ -2,7 +2,6 @@ package com.baeldung.spring.data.es;
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;
@ -14,190 +13,225 @@ import static org.junit.Assert.assertEquals;
import java.util.List;
import java.util.Map;
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.repository.ArticleRepository;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.BucketOrder;
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.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
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;
/**
* This Manual test requires: Elasticsearch instance running on localhost:9200.
*
* This Manual test requires:
* * Elasticsearch instance running on host
* * with cluster name = elasticsearch
*
* The following docker command can be used: docker run -d --name es762 -p
* 9200:9200 -e "discovery.type=single-node" elasticsearch:7.6.2
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
public class ElasticSearchQueryManualTest {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
private ElasticsearchRestTemplate elasticsearchTemplate;
@Autowired
private ArticleService articleService;
private ArticleRepository articleRepository;
@Autowired
private Client client;
private RestHighLevelClient client;
private final Author johnSmith = new Author("John Smith");
private final Author johnDoe = new Author("John Doe");
@Before
public void before() {
elasticsearchTemplate.deleteIndex(Article.class);
elasticsearchTemplate.createIndex(Article.class);
elasticsearchTemplate.putMapping(Article.class);
elasticsearchTemplate.refresh(Article.class);
Article article = new Article("Spring Data Elasticsearch");
article.setAuthors(asList(johnSmith, johnDoe));
article.setTags("elasticsearch", "spring data");
articleService.save(article);
articleRepository.save(article);
article = new Article("Search engines");
article.setAuthors(asList(johnDoe));
article.setTags("search engines", "tutorial");
articleService.save(article);
articleRepository.save(article);
article = new Article("Second Article About Elasticsearch");
article.setAuthors(asList(johnSmith));
article.setTags("elasticsearch", "spring data");
articleService.save(article);
articleRepository.save(article);
article = new Article("Elasticsearch Tutorial");
article.setAuthors(asList(johnDoe));
article.setTags("elasticsearch");
articleService.save(article);
articleRepository.save(article);
}
@After
public void after() {
articleRepository.deleteAll();
}
@Test
public void givenFullTitle_whenRunMatchQuery_thenDocIsFound() {
final SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(matchQuery("title", "Search engines").operator(AND)).build();
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(1, articles.size());
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Search engines").operator(Operator.AND))
.build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.getTotalHits());
}
@Test
public void givenOneTermFromTitle_whenRunMatchQuery_thenDocIsFound() {
final SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(matchQuery("title", "Engines Solutions")).build();
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(1, articles.size());
assertEquals("Search engines", articles.get(0).getTitle());
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Engines Solutions"))
.build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.getTotalHits());
assertEquals("Search engines", articles.getSearchHit(0)
.getContent()
.getTitle());
}
@Test
public void givenPartTitle_whenRunMatchQuery_thenDocIsFound() {
final SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(matchQuery("title", "elasticsearch data")).build();
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(3, articles.size());
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "elasticsearch data"))
.build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(3, articles.getTotalHits());
}
@Test
public void givenFullTitle_whenRunMatchQueryOnVerbatimField_thenDocIsFound() {
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(matchQuery("title.verbatim", "Second Article About Elasticsearch")).build();
List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(1, articles.size());
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title.verbatim", "Second Article About Elasticsearch"))
.build();
SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.getTotalHits());
searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title.verbatim", "Second Article About"))
.build();
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(0, articles.size());
.build();
articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(0, articles.getTotalHits());
}
@Test
public void givenNestedObject_whenQueryByAuthorsName_thenFoundArticlesByThatAuthor() {
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);
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder)
.build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(2, articles.size());
assertEquals(2, articles.getTotalHits());
}
@Test
public void givenAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTokenCountsSeparately() {
final TermsAggregationBuilder aggregation = AggregationBuilders.terms("top_tags").field("title");
final SearchResponse response = client.prepareSearch("blog").setTypes("article").addAggregation(aggregation)
.execute().actionGet();
public void givenAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTokenCountsSeparately() throws Exception {
final TermsAggregationBuilder aggregation = AggregationBuilders.terms("top_tags")
.field("title");
final Map<String, Aggregation> results = response.getAggregations().asMap();
final StringTerms topTags = (StringTerms) results.get("top_tags");
final SearchSourceBuilder builder = new SearchSourceBuilder().aggregation(aggregation);
final SearchRequest searchRequest = new SearchRequest("blog").source(builder);
final List<String> keys = topTags.getBuckets().stream()
.map(MultiBucketsAggregation.Bucket::getKeyAsString)
.sorted()
.collect(toList());
final SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
final Map<String, Aggregation> results = response.getAggregations()
.asMap();
final ParsedStringTerms topTags = (ParsedStringTerms) results.get("top_tags");
final List<String> keys = topTags.getBuckets()
.stream()
.map(MultiBucketsAggregation.Bucket::getKeyAsString)
.sorted()
.collect(toList());
assertEquals(asList("about", "article", "data", "elasticsearch", "engines", "search", "second", "spring", "tutorial"), keys);
}
@Test
public void givenNotAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTermCountsIndividually() {
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();
public void givenNotAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTermCountsIndividually() throws Exception {
final TermsAggregationBuilder aggregation = AggregationBuilders.terms("top_tags")
.field("tags")
.order(BucketOrder.count(false));
final Map<String, Aggregation> results = response.getAggregations().asMap();
final StringTerms topTags = (StringTerms) results.get("top_tags");
final SearchSourceBuilder builder = new SearchSourceBuilder().aggregation(aggregation);
final SearchRequest searchRequest = new SearchRequest().indices("blog")
.source(builder);
final List<String> keys = topTags.getBuckets().stream()
.map(MultiBucketsAggregation.Bucket::getKeyAsString)
.collect(toList());
final SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
final Map<String, Aggregation> results = response.getAggregations()
.asMap();
final ParsedStringTerms topTags = (ParsedStringTerms) results.get("top_tags");
final List<String> keys = topTags.getBuckets()
.stream()
.map(MultiBucketsAggregation.Bucket::getKeyAsString)
.collect(toList());
assertEquals(asList("elasticsearch", "spring data", "search engines", "tutorial"), keys);
}
@Test
public void givenNotExactPhrase_whenUseSlop_thenQueryMatches() {
final SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(matchPhraseQuery("title", "spring elasticsearch").slop(1)).build();
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(1, articles.size());
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchPhraseQuery("title", "spring elasticsearch").slop(1))
.build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.getTotalHits());
}
@Test
public void givenPhraseWithType_whenUseFuzziness_thenQueryMatches() {
final SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(matchQuery("title", "spring date elasticserch").operator(AND).fuzziness(Fuzziness.ONE)
.prefixLength(3)).build();
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "spring date elasticserch").operator(Operator.AND)
.fuzziness(Fuzziness.ONE)
.prefixLength(3))
.build();
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(1, articles.size());
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.getTotalHits());
}
@Test
public void givenMultimatchQuery_whenDoSearch_thenAllProvidedFieldsMatch() {
final SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(multiMatchQuery("tutorial").field("title").field("tags")
.type(MultiMatchQueryBuilder.Type.BEST_FIELDS)).build();
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(multiMatchQuery("tutorial").field("title")
.field("tags")
.type(MultiMatchQueryBuilder.Type.BEST_FIELDS))
.build();
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(2, articles.size());
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(2, articles.getTotalHits());
}
@Test
@ -205,10 +239,10 @@ public class ElasticSearchQueryManualTest {
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)
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder)
.build();
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(2, articles.size());
assertEquals(2, articles.getTotalHits());
}
}

View File

@ -1,6 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-data-jpa-5</artifactId>
<name>spring-data-jpa-5</name>
@ -11,7 +12,7 @@
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
@ -28,10 +29,43 @@
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>1.3.1.Final</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.3.1.Final</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,12 @@
package com.baeldung.partialupdate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class PartialUpdateApplication {
public static void main(String[] args) {
SpringApplication.run(PartialUpdateApplication.class, args);
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.partialupdate.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class ContactPhone {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public long id;
@Column(nullable=false)
public long customerId;
public String phone;
@Override
public String toString() {
return phone;
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.partialupdate.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public long id;
public String name;
public String phone;
//...
public String phone99;
@Override public String toString() {
return String.format("Customer %s, Phone: %s",
this.name, this.phone);
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.partialupdate.model;
public class CustomerDto {
private long id;
public String name;
public String phone;
//...
private String phone99;
public CustomerDto(long id) {
this.id = id;
}
public CustomerDto(Customer c) {
this.id = c.id;
this.name = c.name;
this.phone = c.phone;
}
public long getId() {
return this.id;
}
public Customer convertToEntity() {
Customer c = new Customer();
c.id = id;
c.name = name;
c.phone = phone;
return c;
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.partialupdate.model;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class CustomerStructured {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public long id;
public String name;
@OneToMany(fetch = FetchType.EAGER, targetEntity = ContactPhone.class, mappedBy = "customerId")
public List<ContactPhone> contactPhones;
@Override public String toString() {
return String.format("Customer %s, Phone: %s",
this.name, this.contactPhones.stream()
.map(e -> e.toString()).reduce("", String::concat));
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.partialupdate.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.baeldung.partialupdate.model.ContactPhone;
@Repository
public interface ContactPhoneRepository extends CrudRepository<ContactPhone, Long> {
ContactPhone findById(long id);
ContactPhone findByCustomerId(long id);
}

View File

@ -0,0 +1,18 @@
package com.baeldung.partialupdate.repository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.baeldung.partialupdate.model.Customer;
@Repository
public interface CustomerRepository extends CrudRepository<Customer, Long> {
Customer findById(long id);
@Modifying
@Query("update Customer u set u.phone = :phone where u.id = :id")
void updatePhone(@Param(value = "id") long id, @Param(value = "phone") String phone);
}

View File

@ -0,0 +1,11 @@
package com.baeldung.partialupdate.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.baeldung.partialupdate.model.CustomerStructured;
@Repository
public interface CustomerStructuredRepository extends CrudRepository<CustomerStructured, Long> {
CustomerStructured findById(long id);
}

View File

@ -0,0 +1,87 @@
package com.baeldung.partialupdate.service;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baeldung.partialupdate.model.ContactPhone;
import com.baeldung.partialupdate.model.Customer;
import com.baeldung.partialupdate.model.CustomerDto;
import com.baeldung.partialupdate.model.CustomerStructured;
import com.baeldung.partialupdate.repository.ContactPhoneRepository;
import com.baeldung.partialupdate.repository.CustomerRepository;
import com.baeldung.partialupdate.repository.CustomerStructuredRepository;
import com.baeldung.partialupdate.util.CustomerMapper;
@Service
@Transactional
public class CustomerService {
@Autowired
CustomerRepository repo;
@Autowired
CustomerStructuredRepository repo2;
@Autowired
ContactPhoneRepository repo3;
@Autowired
CustomerMapper mapper;
public Customer getCustomer(long id) {
return repo.findById(id);
}
public void updateCustomerWithCustomQuery(long id, String phone) {
repo.updatePhone(id, phone);
}
public Customer addCustomer(String name) {
Customer myCustomer = new Customer();
myCustomer.name = name;
repo.save(myCustomer);
return myCustomer;
}
public Customer updateCustomer(long id, String phone) {
Customer myCustomer = repo.findById(id);
myCustomer.phone = phone;
repo.save(myCustomer);
return myCustomer;
}
public Customer addCustomer(CustomerDto dto) {
Customer myCustomer = new Customer();
mapper.updateCustomerFromDto(dto, myCustomer);
repo.save(myCustomer);
return myCustomer;
}
public Customer updateCustomer(CustomerDto dto) {
Customer myCustomer = repo.findById(dto.getId());
mapper.updateCustomerFromDto(dto, myCustomer);
repo.save(myCustomer);
return myCustomer;
}
public CustomerStructured addCustomerStructured(String name) {
CustomerStructured myCustomer = new CustomerStructured();
myCustomer.name = name;
repo2.save(myCustomer);
return myCustomer;
}
public void addCustomerPhone(long customerId, String phone) {
ContactPhone myPhone = new ContactPhone();
myPhone.phone = phone;
myPhone.customerId = customerId;
repo3.save(myPhone);
}
public CustomerStructured updateCustomerStructured(long id, String name) {
CustomerStructured myCustomer = repo2.findById(id);
myCustomer.name = name;
repo2.save(myCustomer);
return myCustomer;
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.partialupdate.util;
import org.mapstruct.BeanMapping;
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
import org.mapstruct.NullValuePropertyMappingStrategy;
import com.baeldung.partialupdate.model.Customer;
import com.baeldung.partialupdate.model.CustomerDto;
@Mapper(componentModel = "spring")
public interface CustomerMapper {
@BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
void updateCustomerFromDto(CustomerDto dto, @MappingTarget Customer entity);
}

View File

@ -0,0 +1,63 @@
package com.baeldung.partialupdate;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
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.junit4.SpringRunner;
import com.baeldung.partialupdate.model.Customer;
import com.baeldung.partialupdate.model.CustomerDto;
import com.baeldung.partialupdate.model.CustomerStructured;
import com.baeldung.partialupdate.service.CustomerService;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = PartialUpdateApplication.class)
public class PartialUpdateUnitTest {
@Autowired
CustomerService service;
@Test
public void givenCustomer_whenUpdate_thenSuccess() {
Customer myCustomer = service.addCustomer("John");
myCustomer = service.updateCustomer(myCustomer.id, "+00");
assertEquals("+00", myCustomer.phone);
}
@Test
public void givenCustomer_whenUpdateWithQuery_thenSuccess() {
Customer myCustomer = service.addCustomer("John");
service.updateCustomerWithCustomQuery(myCustomer.id, "+88");
myCustomer = service.getCustomer(myCustomer.id);
assertEquals("+88", myCustomer.phone);
}
@Test
public void givenCustomerDto_whenUpdateWithMapper_thenSuccess() {
CustomerDto dto = new CustomerDto(new Customer());
dto.name = "Johnny";
Customer entity = service.addCustomer(dto);
CustomerDto dto2 = new CustomerDto(entity.id);
dto2.phone = "+44";
entity = service.updateCustomer(dto2);
assertEquals("Johnny", entity.name);
}
@Test
public void givenCustomerStructured_whenUpdateCustomerPhone_thenSuccess() {
CustomerStructured myCustomer = service.addCustomerStructured("John");
assertEquals(null, myCustomer.contactPhones);
service.addCustomerPhone(myCustomer.id, "+44");
myCustomer = service.updateCustomerStructured(myCustomer.id, "Mr. John");
assertNotEquals(null, myCustomer.contactPhones);
assertEquals(1, myCustomer.contactPhones.size());
}
}

View File

@ -4,7 +4,6 @@
- [Introduction to Spring Data Redis](https://www.baeldung.com/spring-data-redis-tutorial)
- [PubSub Messaging with Spring Data Redis](https://www.baeldung.com/spring-data-redis-pub-sub)
- [An Introduction to Spring Data Redis Reactive](https://www.baeldung.com/spring-data-redis-reactive)
- [Delete Everything in Redis](https://www.baeldung.com/redis-delete-data)
### Build the Project with Tests Running
```
@ -15,4 +14,3 @@ mvn clean install
```
mvn test
```

View File

@ -35,18 +35,6 @@ public class RedisConfig {
template.setValueSerializer(new GenericToStringSerializer<Object>(Object.class));
return template;
}
@Bean
public LettuceConnectionFactory lettuceConnectionFactory() {
return new LettuceConnectionFactory();
}
@Bean(name = "flushRedisTemplate")
public RedisTemplate<String, String> flushRedisTemplate() {
RedisTemplate<String, String> template = new RedisTemplate<>();
template.setConnectionFactory(lettuceConnectionFactory());
return template;
}
@Bean
MessageListenerAdapter messageListener() {

View File

@ -1,92 +0,0 @@
package com.baeldung.spring.data.redis.delete;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.spring.data.redis.config.RedisConfig;
import redis.embedded.RedisServer;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { RedisConfig.class })
@DirtiesContext(classMode = ClassMode.BEFORE_CLASS)
public class RedisFlushDatabaseIntegrationTest {
private RedisServer redisServer;
@Autowired
@Qualifier("flushRedisTemplate")
private RedisTemplate<String, String> flushRedisTemplate;
@Before
public void setup() throws IOException {
redisServer = new RedisServer(6390);
redisServer.start();
}
@After
public void tearDown() {
redisServer.stop();
}
@Test
public void whenFlushDB_thenAllKeysInDatabaseAreCleared() {
ValueOperations<String, String> simpleValues = flushRedisTemplate.opsForValue();
String key = "key";
String value = "value";
simpleValues.set(key, value);
assertThat(simpleValues.get(key)).isEqualTo(value);
flushRedisTemplate.execute(new RedisCallback<Void>() {
@Override
public Void doInRedis(RedisConnection connection) throws DataAccessException {
connection.flushDb();
return null;
}
});
assertThat(simpleValues.get(key)).isNull();
}
@Test
public void whenFlushAll_thenAllKeysInDatabasesAreCleared() {
ValueOperations<String, String> simpleValues = flushRedisTemplate.opsForValue();
String key = "key";
String value = "value";
simpleValues.set(key, value);
assertThat(simpleValues.get(key)).isEqualTo(value);
flushRedisTemplate.execute(new RedisCallback<Void>() {
@Override
public Void doInRedis(RedisConnection connection) throws DataAccessException {
connection.flushAll();
return null;
}
});
assertThat(simpleValues.get(key)).isNull();
}
}

View File

@ -513,6 +513,7 @@
<module>libraries-rpc</module>
<module>libraries-security</module>
<module>libraries-server</module>
<module>libraries-server-2</module>
<module>libraries-testing</module>
<module>linkrest</module>
<module>logging-modules</module>
@ -1032,6 +1033,7 @@
<module>libraries-primitive</module>
<module>libraries-security</module>
<module>libraries-server</module>
<module>libraries-server-2</module>
<module>libraries-testing</module>
<module>linkrest</module>
<module>logging-modules</module>

View File

@ -87,7 +87,35 @@
<artifactId>javase</artifactId>
<version>${zxing.version}</version>
</dependency>
<!-- Bucket4j -->
<dependency>
<groupId>com.github.vladimir-bukhtoyarov</groupId>
<artifactId>bucket4j-core</artifactId>
<version>${bucket4j.version}</version>
</dependency>
<dependency>
<groupId>com.giffing.bucket4j.spring.boot.starter</groupId>
<artifactId>bucket4j-spring-boot-starter</artifactId>
<version>${bucket4j-spring-boot-starter.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>${caffeine.version}</version>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>jcache</artifactId>
<version>${caffeine.version}</version>
</dependency>
</dependencies>
<repositories>
@ -200,6 +228,9 @@
<barcode4j.version>2.1</barcode4j.version>
<qrgen.version>2.6.0</qrgen.version>
<zxing.version>3.3.0</zxing.version>
<bucket4j.version>4.10.0</bucket4j.version>
<bucket4j-spring-boot-starter.version>0.2.0</bucket4j-spring-boot-starter.version>
<caffeine.version>2.8.2</caffeine.version>
</properties>
</project>

View File

@ -0,0 +1,21 @@
package com.baeldung.ratelimiting.bootstarterapp;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication(scanBasePackages = "com.baeldung.ratelimiting", exclude = {
DataSourceAutoConfiguration.class,
SecurityAutoConfiguration.class,
})
@EnableCaching
public class Bucket4jRateLimitApp {
public static void main(String[] args) {
new SpringApplicationBuilder(Bucket4jRateLimitApp.class)
.properties("spring.config.location=classpath:ratelimiting/application-bucket4j-starter.yml")
.run(args);
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.ratelimiting.bucket4japp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.baeldung.ratelimiting.bucket4japp.interceptor.RateLimitInterceptor;
@SpringBootApplication(scanBasePackages = "com.baeldung.ratelimiting", exclude = {
DataSourceAutoConfiguration.class,
SecurityAutoConfiguration.class
})
public class Bucket4jRateLimitApp implements WebMvcConfigurer {
@Autowired
@Lazy
private RateLimitInterceptor interceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(interceptor)
.addPathPatterns("/api/v1/area/**");
}
public static void main(String[] args) {
new SpringApplicationBuilder(Bucket4jRateLimitApp.class)
.properties("spring.config.location=classpath:ratelimiting/application-bucket4j.yml")
.run(args);
}
}

View File

@ -0,0 +1,57 @@
package com.baeldung.ratelimiting.bucket4japp.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import com.baeldung.ratelimiting.bucket4japp.service.PricingPlanService;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.ConsumptionProbe;
@Component
public class RateLimitInterceptor implements HandlerInterceptor {
private static final String HEADER_API_KEY = "X-api-key";
private static final String HEADER_LIMIT_REMAINING = "X-Rate-Limit-Remaining";
private static final String HEADER_RETRY_AFTER = "X-Rate-Limit-Retry-After-Seconds";
@Autowired
private PricingPlanService pricingPlanService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String apiKey = request.getHeader(HEADER_API_KEY);
if (apiKey == null || apiKey.isEmpty()) {
response.sendError(HttpStatus.BAD_REQUEST.value(), "Missing Header: " + HEADER_API_KEY);
return false;
}
Bucket tokenBucket = pricingPlanService.resolveBucket(apiKey);
ConsumptionProbe probe = tokenBucket.tryConsumeAndReturnRemaining(1);
if (probe.isConsumed()) {
response.addHeader(HEADER_LIMIT_REMAINING, String.valueOf(probe.getRemainingTokens()));
return true;
} else {
long waitForRefill = probe.getNanosToWaitForRefill() / 1_000_000_000;
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.addHeader(HEADER_RETRY_AFTER, String.valueOf(waitForRefill));
response.sendError(HttpStatus.TOO_MANY_REQUESTS.value(), "You have exhausted your API Request Quota"); // 429
return false;
}
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.ratelimiting.bucket4japp.service;
import java.time.Duration;
import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Refill;
public enum PricingPlan {
FREE(20),
BASIC(40),
PROFESSIONAL(100);
private int bucketCapacity;
private PricingPlan(int bucketCapacity) {
this.bucketCapacity = bucketCapacity;
}
Bandwidth getLimit() {
return Bandwidth.classic(bucketCapacity, Refill.intervally(bucketCapacity, Duration.ofHours(1)));
}
public int bucketCapacity() {
return bucketCapacity;
}
static PricingPlan resolvePlanFromApiKey(String apiKey) {
if (apiKey == null || apiKey.isEmpty()) {
return FREE;
} else if (apiKey.startsWith("PX001-")) {
return PROFESSIONAL;
} else if (apiKey.startsWith("BX001-")) {
return BASIC;
}
return FREE;
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.ratelimiting.bucket4japp.service;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.stereotype.Service;
import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.Bucket4j;
@Service
public class PricingPlanService {
private final Map<String, Bucket> cache = new ConcurrentHashMap<>();
public Bucket resolveBucket(String apiKey) {
return cache.computeIfAbsent(apiKey, this::newBucket);
}
private Bucket newBucket(String apiKey) {
PricingPlan pricingPlan = PricingPlan.resolvePlanFromApiKey(apiKey);
return bucket(pricingPlan.getLimit());
}
private Bucket bucket(Bandwidth limit) {
return Bucket4j.builder()
.addLimit(limit)
.build();
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.ratelimiting.controller;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.ratelimiting.dto.AreaV1;
import com.baeldung.ratelimiting.dto.RectangleDimensionsV1;
import com.baeldung.ratelimiting.dto.TriangleDimensionsV1;
@RestController
@RequestMapping(value = "/api/v1/area", consumes = MediaType.APPLICATION_JSON_VALUE)
class AreaCalculationController {
@PostMapping(value = "/rectangle", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<AreaV1> rectangle(@RequestBody RectangleDimensionsV1 dimensions) {
return ResponseEntity.ok(new AreaV1("rectangle", dimensions.getLength() * dimensions.getWidth()));
}
@PostMapping(value = "/triangle", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<AreaV1> triangle(@RequestBody TriangleDimensionsV1 dimensions) {
return ResponseEntity.ok(new AreaV1("triangle", 0.5d * dimensions.getHeight() * dimensions.getBase()));
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.ratelimiting.dto;
public class AreaV1 {
private String shape;
private Double area;
public AreaV1(String shape, Double area) {
this.area = area;
this.shape = shape;
}
public Double getArea() {
return area;
}
public String getShape() {
return shape;
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.ratelimiting.dto;
public class RectangleDimensionsV1 {
private double length;
private double width;
public double getLength() {
return length;
}
public double getWidth() {
return width;
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.ratelimiting.dto;
public class TriangleDimensionsV1 {
private double base;
private double height;
public double getBase() {
return base;
}
public double getHeight() {
return height;
}
}

View File

@ -0,0 +1,40 @@
server:
port: 9001
spring:
application:
name: bucket4j-starter-api-rate-limit-app
mvc:
throw-exception-if-no-handler-found: true
resources:
add-mappings: false
cache:
cache-names:
- rate-limit-buckets
caffeine:
spec: maximumSize=100000,expireAfterAccess=3600s
bucket4j:
enabled: true
filters:
- cache-name: rate-limit-buckets
url: /api/v1/area.*
http-response-body: "{ \"status\": 429, \"error\": \"Too Many Requests\", \"message\": \"You have exhausted your API Request Quota\" }"
rate-limits:
- expression: "getHeader('X-api-key')"
execute-condition: "getHeader('X-api-key').startsWith('PX001-')"
bandwidths:
- capacity: 100
time: 1
unit: hours
- expression: "getHeader('X-api-key')"
execute-condition: "getHeader('X-api-key').startsWith('BX001-')"
bandwidths:
- capacity: 40
time: 1
unit: hours
- expression: "getHeader('X-api-key')"
bandwidths:
- capacity: 20
time: 1
unit: hours

View File

@ -0,0 +1,10 @@
server:
port: 9000
spring:
application:
name: bucket4j-api-rate-limit-app
mvc:
throw-exception-if-no-handler-found: true
resources:
add-mappings: false

View File

@ -0,0 +1,63 @@
package com.baeldung.ratelimiting.bootstarterapp;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import com.baeldung.ratelimiting.bucket4japp.service.PricingPlan;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Bucket4jRateLimitApp.class)
@TestPropertySource(properties = "spring.config.location=classpath:ratelimiting/application-bucket4j-starter.yml")
@AutoConfigureMockMvc
public class Bucket4jBootStarterRateLimitIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Test
public void givenTriangleAreaCalculator_whenRequestsWithinRateLimit_thenAccepted() throws Exception {
RequestBuilder request = post("/api/v1/area/triangle").contentType(MediaType.APPLICATION_JSON_VALUE)
.content("{ \"height\": 8, \"base\": 10 }")
.header("X-api-key", "FX001-UBSZ5YRYQ");
for (int i = 1; i <= PricingPlan.FREE.bucketCapacity(); i++) {
mockMvc.perform(request)
.andExpect(status().isOk())
.andExpect(header().exists("X-Rate-Limit-Remaining"))
.andExpect(jsonPath("$.shape", equalTo("triangle")))
.andExpect(jsonPath("$.area", equalTo(40d)));
}
}
@Test
public void givenTriangleAreaCalculator_whenRequestRateLimitTriggered_thenRejected() throws Exception {
RequestBuilder request = post("/api/v1/area/triangle").contentType(MediaType.APPLICATION_JSON_VALUE)
.content("{ \"height\": 8, \"base\": 10 }")
.header("X-api-key", "FX001-ZBSY6YSLP");
for (int i = 1; i <= PricingPlan.FREE.bucketCapacity(); i++) {
mockMvc.perform(request); // exhaust limit
}
mockMvc.perform(request)
.andExpect(status().isTooManyRequests())
.andExpect(jsonPath("$.message", equalTo("You have exhausted your API Request Quota")))
.andExpect(header().exists("X-Rate-Limit-Retry-After-Seconds"));
}
}

Some files were not shown because too many files have changed in this diff Show More