Merge remote-tracking branch 'baeldung/master' into BAEL-3841#declarative-caching-testing
This commit is contained in:
commit
a7f1ca3500
|
@ -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)
|
- [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 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
|
||||||
- [Java 9 Reactive Streams](https://www.baeldung.com/java-9-reactive-streams)
|
- [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)
|
||||||
|
|
|
@ -28,8 +28,104 @@
|
||||||
<version>${junit.platform.version}</version>
|
<version>${junit.platform.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.awaitility</groupId>
|
||||||
|
<artifactId>awaitility</artifactId>
|
||||||
|
<version>${awaitility.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</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>
|
<build>
|
||||||
<finalName>core-java-9-new-features</finalName>
|
<finalName>core-java-9-new-features</finalName>
|
||||||
<plugins>
|
<plugins>
|
||||||
|
@ -56,8 +152,10 @@
|
||||||
<!-- testing -->
|
<!-- testing -->
|
||||||
<assertj.version>3.10.0</assertj.version>
|
<assertj.version>3.10.0</assertj.version>
|
||||||
<junit.platform.version>1.2.0</junit.platform.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.source>1.9</maven.compiler.source>
|
||||||
<maven.compiler.target>1.9</maven.compiler.target>
|
<maven.compiler.target>1.9</maven.compiler.target>
|
||||||
|
<maven-jar-plugin.version>3.2.0</maven-jar-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -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()));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,9 @@
|
||||||
|
package com.baeldung.multireleaseapp;
|
||||||
|
|
||||||
|
public class DefaultVersion implements Version {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String version() {
|
||||||
|
return System.getProperty("java.version");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,5 @@
|
||||||
|
package com.baeldung.multireleaseapp;
|
||||||
|
|
||||||
|
interface Version {
|
||||||
|
public String version();
|
||||||
|
}
|
|
@ -0,0 +1,9 @@
|
||||||
|
package com.baeldung.multireleaseapp;
|
||||||
|
|
||||||
|
public class DefaultVersion implements Version {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String version() {
|
||||||
|
return Runtime.version().toString();
|
||||||
|
}
|
||||||
|
}
|
|
@ -24,7 +24,7 @@ import static org.junit.Assert.assertThat;
|
||||||
/**
|
/**
|
||||||
* Created by adam.
|
* Created by adam.
|
||||||
*/
|
*/
|
||||||
public class HttpClientTest {
|
public class HttpClientIntegrationTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException {
|
public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException {
|
||||||
|
@ -55,7 +55,7 @@ public class HttpClientTest {
|
||||||
.send(request, HttpResponse.BodyHandler.asString());
|
.send(request, HttpResponse.BodyHandler.asString());
|
||||||
|
|
||||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM));
|
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM));
|
||||||
assertThat(response.body(), containsString("https://stackoverflow.com/"));
|
assertThat(response.body(), containsString(""));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
|
@ -22,7 +22,7 @@ import static org.junit.Assert.assertThat;
|
||||||
/**
|
/**
|
||||||
* Created by adam.
|
* Created by adam.
|
||||||
*/
|
*/
|
||||||
public class HttpRequestTest {
|
public class HttpRequestIntegrationTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
|
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
|
|
@ -18,7 +18,7 @@ import static org.junit.Assert.assertThat;
|
||||||
/**
|
/**
|
||||||
* Created by adam.
|
* Created by adam.
|
||||||
*/
|
*/
|
||||||
public class HttpResponseTest {
|
public class HttpResponseIntegrationTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
|
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
|
|
@ -5,10 +5,12 @@ import org.junit.Test;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.concurrent.SubmissionPublisher;
|
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
|
@Test
|
||||||
public void givenPublisher_whenSubscribeToIt_thenShouldConsumeAllElements() throws InterruptedException {
|
public void givenPublisher_whenSubscribeToIt_thenShouldConsumeAllElements() throws InterruptedException {
|
||||||
|
@ -25,7 +27,7 @@ public class ReactiveStreamsTest {
|
||||||
|
|
||||||
//then
|
//then
|
||||||
|
|
||||||
await().atMost(1000, TimeUnit.MILLISECONDS).until(
|
await().atMost(1000, TimeUnit.MILLISECONDS).untilAsserted(
|
||||||
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(items)
|
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(items)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -46,7 +48,7 @@ public class ReactiveStreamsTest {
|
||||||
publisher.close();
|
publisher.close();
|
||||||
|
|
||||||
//then
|
//then
|
||||||
await().atMost(1000, TimeUnit.MILLISECONDS).until(
|
await().atMost(1000, TimeUnit.MILLISECONDS).untilAsserted(
|
||||||
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(expectedResult)
|
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(expectedResult)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -66,7 +68,7 @@ public class ReactiveStreamsTest {
|
||||||
publisher.close();
|
publisher.close();
|
||||||
|
|
||||||
//then
|
//then
|
||||||
await().atMost(1000, TimeUnit.MILLISECONDS).until(
|
await().atMost(1000, TimeUnit.MILLISECONDS).untilAsserted(
|
||||||
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(expected)
|
() -> assertThat(subscriber.consumedElements).containsExactlyElementsOf(expected)
|
||||||
);
|
);
|
||||||
}
|
}
|
|
@ -7,7 +7,7 @@ import java.lang.invoke.VarHandle;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
public class VariableHandlesTest {
|
public class VariableHandlesUnitTest {
|
||||||
|
|
||||||
public int publicTestVariable = 1;
|
public int publicTestVariable = 1;
|
||||||
private int privateTestVariable = 1;
|
private int privateTestVariable = 1;
|
||||||
|
@ -20,22 +20,22 @@ public class VariableHandlesTest {
|
||||||
public void whenVariableHandleForPublicVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
public void whenVariableHandleForPublicVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
||||||
VarHandle publicIntHandle = MethodHandles
|
VarHandle publicIntHandle = MethodHandles
|
||||||
.lookup()
|
.lookup()
|
||||||
.in(VariableHandlesTest.class)
|
.in(VariableHandlesUnitTest.class)
|
||||||
.findVarHandle(VariableHandlesTest.class, "publicTestVariable", int.class);
|
.findVarHandle(VariableHandlesUnitTest.class, "publicTestVariable", int.class);
|
||||||
|
|
||||||
assertThat(publicIntHandle.coordinateTypes().size() == 1);
|
assertThat(publicIntHandle.coordinateTypes().size() == 1);
|
||||||
assertThat(publicIntHandle.coordinateTypes().get(0) == VariableHandles.class);
|
assertThat(publicIntHandle.coordinateTypes().get(0) == VariableHandlesUnitTest.class);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenVariableHandleForPrivateVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
public void whenVariableHandleForPrivateVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
||||||
VarHandle privateIntHandle = MethodHandles
|
VarHandle privateIntHandle = MethodHandles
|
||||||
.privateLookupIn(VariableHandlesTest.class, MethodHandles.lookup())
|
.privateLookupIn(VariableHandlesUnitTest.class, MethodHandles.lookup())
|
||||||
.findVarHandle(VariableHandlesTest.class, "privateTestVariable", int.class);
|
.findVarHandle(VariableHandlesUnitTest.class, "privateTestVariable", int.class);
|
||||||
|
|
||||||
assertThat(privateIntHandle.coordinateTypes().size() == 1);
|
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 {
|
public void givenVarHandle_whenGetIsInvoked_ThenValueOfVariableIsReturned() throws NoSuchFieldException, IllegalAccessException {
|
||||||
VarHandle publicIntHandle = MethodHandles
|
VarHandle publicIntHandle = MethodHandles
|
||||||
.lookup()
|
.lookup()
|
||||||
.in(VariableHandlesTest.class)
|
.in(VariableHandlesUnitTest.class)
|
||||||
.findVarHandle(VariableHandlesTest.class, "publicTestVariable", int.class);
|
.findVarHandle(VariableHandlesUnitTest.class, "publicTestVariable", int.class);
|
||||||
|
|
||||||
assertThat((int) publicIntHandle.get(this) == 1);
|
assertThat((int) publicIntHandle.get(this) == 1);
|
||||||
}
|
}
|
||||||
|
@ -62,8 +62,8 @@ public class VariableHandlesTest {
|
||||||
public void givenVarHandle_whenSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
public void givenVarHandle_whenSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||||
VarHandle publicIntHandle = MethodHandles
|
VarHandle publicIntHandle = MethodHandles
|
||||||
.lookup()
|
.lookup()
|
||||||
.in(VariableHandlesTest.class)
|
.in(VariableHandlesUnitTest.class)
|
||||||
.findVarHandle(VariableHandlesTest.class, "variableToSet", int.class);
|
.findVarHandle(VariableHandlesUnitTest.class, "variableToSet", int.class);
|
||||||
publicIntHandle.set(this, 15);
|
publicIntHandle.set(this, 15);
|
||||||
|
|
||||||
assertThat((int) publicIntHandle.get(this) == 15);
|
assertThat((int) publicIntHandle.get(this) == 15);
|
||||||
|
@ -73,8 +73,8 @@ public class VariableHandlesTest {
|
||||||
public void givenVarHandle_whenCompareAndSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
public void givenVarHandle_whenCompareAndSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||||
VarHandle publicIntHandle = MethodHandles
|
VarHandle publicIntHandle = MethodHandles
|
||||||
.lookup()
|
.lookup()
|
||||||
.in(VariableHandlesTest.class)
|
.in(VariableHandlesUnitTest.class)
|
||||||
.findVarHandle(VariableHandlesTest.class, "variableToCompareAndSet", int.class);
|
.findVarHandle(VariableHandlesUnitTest.class, "variableToCompareAndSet", int.class);
|
||||||
publicIntHandle.compareAndSet(this, 1, 100);
|
publicIntHandle.compareAndSet(this, 1, 100);
|
||||||
|
|
||||||
assertThat((int) publicIntHandle.get(this) == 100);
|
assertThat((int) publicIntHandle.get(this) == 100);
|
||||||
|
@ -84,8 +84,8 @@ public class VariableHandlesTest {
|
||||||
public void givenVarHandle_whenGetAndAddIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
public void givenVarHandle_whenGetAndAddIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||||
VarHandle publicIntHandle = MethodHandles
|
VarHandle publicIntHandle = MethodHandles
|
||||||
.lookup()
|
.lookup()
|
||||||
.in(VariableHandlesTest.class)
|
.in(VariableHandlesUnitTest.class)
|
||||||
.findVarHandle(VariableHandlesTest.class, "variableToGetAndAdd", int.class);
|
.findVarHandle(VariableHandlesUnitTest.class, "variableToGetAndAdd", int.class);
|
||||||
int before = (int) publicIntHandle.getAndAdd(this, 200);
|
int before = (int) publicIntHandle.getAndAdd(this, 200);
|
||||||
|
|
||||||
assertThat(before == 0);
|
assertThat(before == 0);
|
||||||
|
@ -96,8 +96,8 @@ public class VariableHandlesTest {
|
||||||
public void givenVarHandle_whenGetAndBitwiseOrIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
public void givenVarHandle_whenGetAndBitwiseOrIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||||
VarHandle publicIntHandle = MethodHandles
|
VarHandle publicIntHandle = MethodHandles
|
||||||
.lookup()
|
.lookup()
|
||||||
.in(VariableHandlesTest.class)
|
.in(VariableHandlesUnitTest.class)
|
||||||
.findVarHandle(VariableHandlesTest.class, "variableToBitwiseOr", byte.class);
|
.findVarHandle(VariableHandlesUnitTest.class, "variableToBitwiseOr", byte.class);
|
||||||
byte before = (byte) publicIntHandle.getAndBitwiseOr(this, (byte) 127);
|
byte before = (byte) publicIntHandle.getAndBitwiseOr(this, (byte) 127);
|
||||||
|
|
||||||
assertThat(before == 0);
|
assertThat(before == 0);
|
|
@ -5,4 +5,5 @@ This module contains articles about core Java input/output(IO) conversions.
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Java InputStream to String](https://www.baeldung.com/convert-input-stream-to-string)
|
- [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)
|
- [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)
|
- More articles: [[<-- prev]](/core-java-modules/core-java-io-conversions)
|
||||||
|
|
|
@ -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)));
|
||||||
|
}
|
||||||
|
}
|
|
@ -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!!
|
||||||
|
}
|
||||||
|
}
|
|
@ -14,6 +14,7 @@ import org.zalando.problem.Problem;
|
||||||
import org.zalando.problem.ProblemBuilder;
|
import org.zalando.problem.ProblemBuilder;
|
||||||
import org.zalando.problem.Status;
|
import org.zalando.problem.Status;
|
||||||
import org.zalando.problem.spring.web.advice.ProblemHandling;
|
import org.zalando.problem.spring.web.advice.ProblemHandling;
|
||||||
|
import org.zalando.problem.spring.web.advice.security.SecurityAdviceTrait;
|
||||||
import org.zalando.problem.violations.ConstraintViolationProblem;
|
import org.zalando.problem.violations.ConstraintViolationProblem;
|
||||||
|
|
||||||
import javax.annotation.Nonnull;
|
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)
|
* The error response follows RFC7807 - Problem Details for HTTP APIs (https://tools.ietf.org/html/rfc7807)
|
||||||
*/
|
*/
|
||||||
@ControllerAdvice
|
@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
|
* Post-process the Problem payload to add the message key for the front-end if needed
|
||||||
|
|
|
@ -14,6 +14,7 @@ import org.zalando.problem.Problem;
|
||||||
import org.zalando.problem.ProblemBuilder;
|
import org.zalando.problem.ProblemBuilder;
|
||||||
import org.zalando.problem.Status;
|
import org.zalando.problem.Status;
|
||||||
import org.zalando.problem.spring.web.advice.ProblemHandling;
|
import org.zalando.problem.spring.web.advice.ProblemHandling;
|
||||||
|
import org.zalando.problem.spring.web.advice.security.SecurityAdviceTrait;
|
||||||
import org.zalando.problem.violations.ConstraintViolationProblem;
|
import org.zalando.problem.violations.ConstraintViolationProblem;
|
||||||
|
|
||||||
import javax.annotation.Nonnull;
|
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)
|
* The error response follows RFC7807 - Problem Details for HTTP APIs (https://tools.ietf.org/html/rfc7807)
|
||||||
*/
|
*/
|
||||||
@ControllerAdvice
|
@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
|
* Post-process the Problem payload to add the message key for the front-end if needed
|
||||||
|
|
|
@ -14,6 +14,7 @@ import org.zalando.problem.Problem;
|
||||||
import org.zalando.problem.ProblemBuilder;
|
import org.zalando.problem.ProblemBuilder;
|
||||||
import org.zalando.problem.Status;
|
import org.zalando.problem.Status;
|
||||||
import org.zalando.problem.spring.web.advice.ProblemHandling;
|
import org.zalando.problem.spring.web.advice.ProblemHandling;
|
||||||
|
import org.zalando.problem.spring.web.advice.security.SecurityAdviceTrait;
|
||||||
import org.zalando.problem.violations.ConstraintViolationProblem;
|
import org.zalando.problem.violations.ConstraintViolationProblem;
|
||||||
|
|
||||||
import javax.annotation.Nonnull;
|
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)
|
* The error response follows RFC7807 - Problem Details for HTTP APIs (https://tools.ietf.org/html/rfc7807)
|
||||||
*/
|
*/
|
||||||
@ControllerAdvice
|
@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
|
* Post-process the Problem payload to add the message key for the front-end if needed
|
||||||
|
|
|
@ -1,14 +1,20 @@
|
||||||
package com.baeldung;
|
package com.baeldung;
|
||||||
|
|
||||||
import com.google.common.hash.HashFunction;
|
|
||||||
import com.google.common.hash.Hasher;
|
import com.google.common.hash.Hasher;
|
||||||
import com.google.common.hash.Hashing;
|
import com.google.common.hash.Hashing;
|
||||||
import org.openjdk.jmh.annotations.*;
|
import org.openjdk.jmh.annotations.*;
|
||||||
|
import org.openjdk.jmh.infra.Blackhole;
|
||||||
|
|
||||||
import java.nio.charset.Charset;
|
import java.nio.charset.Charset;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
public class BenchMark {
|
public class BenchMark {
|
||||||
|
|
||||||
|
@State(Scope.Benchmark)
|
||||||
|
public static class Log {
|
||||||
|
public int x = 8;
|
||||||
|
}
|
||||||
|
|
||||||
@State(Scope.Benchmark)
|
@State(Scope.Benchmark)
|
||||||
public static class ExecutionPlan {
|
public static class ExecutionPlan {
|
||||||
|
|
||||||
|
@ -45,4 +51,44 @@ public class BenchMark {
|
||||||
// Do nothing
|
// 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);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -211,7 +211,7 @@
|
||||||
<datanucleus-maven-plugin.version>5.0.2</datanucleus-maven-plugin.version>
|
<datanucleus-maven-plugin.version>5.0.2</datanucleus-maven-plugin.version>
|
||||||
<datanucleus-jdo-query.version>5.0.4</datanucleus-jdo-query.version>
|
<datanucleus-jdo-query.version>5.0.4</datanucleus-jdo-query.version>
|
||||||
<javax.jdo.version>3.2.0-m7</javax.jdo.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>
|
<ebean.version>11.22.4</ebean.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,9 @@
|
||||||
|
*.class
|
||||||
|
|
||||||
|
# Folders #
|
||||||
|
/gensrc
|
||||||
|
/target
|
||||||
|
|
||||||
|
# Packaged files #
|
||||||
|
*.jar
|
||||||
|
/bin/
|
|
@ -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)
|
|
@ -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>
|
|
@ -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>
|
Before Width: | Height: | Size: 18 KiB After Width: | Height: | Size: 18 KiB |
Before Width: | Height: | Size: 18 KiB After Width: | Height: | Size: 18 KiB |
Before Width: | Height: | Size: 20 KiB After Width: | Height: | Size: 20 KiB |
|
@ -13,4 +13,4 @@ This module contains articles about server libraries.
|
||||||
- [MQTT Client in Java](https://www.baeldung.com/java-mqtt-client)
|
- [MQTT Client in Java](https://www.baeldung.com/java-mqtt-client)
|
||||||
- [Guide to XMPP Smack Client](https://www.baeldung.com/xmpp-smack-chat-client)
|
- [Guide to XMPP Smack Client](https://www.baeldung.com/xmpp-smack-chat-client)
|
||||||
- [A Guide to NanoHTTPD](https://www.baeldung.com/nanohttpd)
|
- [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)
|
|
@ -5,7 +5,6 @@
|
||||||
<artifactId>libraries-server</artifactId>
|
<artifactId>libraries-server</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<name>libraries-server</name>
|
<name>libraries-server</name>
|
||||||
<packaging>war</packaging>
|
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
|
@ -107,50 +106,11 @@
|
||||||
|
|
||||||
</dependencies>
|
</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>
|
<properties>
|
||||||
<assertj.version>3.6.2</assertj.version>
|
<assertj.version>3.6.2</assertj.version>
|
||||||
<httpclient.version>4.5.3</httpclient.version>
|
<httpclient.version>4.5.3</httpclient.version>
|
||||||
<jetty.version>9.4.27.v20200227</jetty.version>
|
<jetty.version>9.4.27.v20200227</jetty.version>
|
||||||
<netty.version>4.1.20.Final</netty.version>
|
<netty.version>4.1.20.Final</netty.version>
|
||||||
<alpn.version>8.1.11.v20170118</alpn.version>
|
|
||||||
<tomcat.version>8.5.24</tomcat.version>
|
<tomcat.version>8.5.24</tomcat.version>
|
||||||
<smack.version>4.3.1</smack.version>
|
<smack.version>4.3.1</smack.version>
|
||||||
<eclipse.paho.client.mqttv3.version>1.2.0</eclipse.paho.client.mqttv3.version>
|
<eclipse.paho.client.mqttv3.version>1.2.0</eclipse.paho.client.mqttv3.version>
|
||||||
|
|
|
@ -0,0 +1,116 @@
|
||||||
|
package com.baeldung.http.server;
|
||||||
|
|
||||||
|
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
|
||||||
|
import static io.netty.handler.codec.http.HttpResponseStatus.CONTINUE;
|
||||||
|
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
|
||||||
|
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
|
||||||
|
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import io.netty.buffer.Unpooled;
|
||||||
|
import io.netty.channel.ChannelFutureListener;
|
||||||
|
import io.netty.channel.ChannelHandlerContext;
|
||||||
|
import io.netty.channel.SimpleChannelInboundHandler;
|
||||||
|
import io.netty.handler.codec.http.DefaultFullHttpResponse;
|
||||||
|
import io.netty.handler.codec.http.FullHttpResponse;
|
||||||
|
import io.netty.handler.codec.http.HttpContent;
|
||||||
|
import io.netty.handler.codec.http.HttpHeaderNames;
|
||||||
|
import io.netty.handler.codec.http.HttpHeaderValues;
|
||||||
|
import io.netty.handler.codec.http.HttpObject;
|
||||||
|
import io.netty.handler.codec.http.HttpRequest;
|
||||||
|
import io.netty.handler.codec.http.HttpUtil;
|
||||||
|
import io.netty.handler.codec.http.LastHttpContent;
|
||||||
|
import io.netty.handler.codec.http.cookie.Cookie;
|
||||||
|
import io.netty.handler.codec.http.cookie.ServerCookieDecoder;
|
||||||
|
import io.netty.handler.codec.http.cookie.ServerCookieEncoder;
|
||||||
|
import io.netty.util.CharsetUtil;
|
||||||
|
|
||||||
|
public class CustomHttpServerHandler extends SimpleChannelInboundHandler<Object> {
|
||||||
|
|
||||||
|
private HttpRequest request;
|
||||||
|
StringBuilder responseData = new StringBuilder();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void channelReadComplete(ChannelHandlerContext ctx) {
|
||||||
|
ctx.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
|
||||||
|
if (msg instanceof HttpRequest) {
|
||||||
|
HttpRequest request = this.request = (HttpRequest) msg;
|
||||||
|
|
||||||
|
if (HttpUtil.is100ContinueExpected(request)) {
|
||||||
|
writeResponse(ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
responseData.setLength(0);
|
||||||
|
responseData.append(ResponseBuilder.addRequestAttributes(request));
|
||||||
|
responseData.append(ResponseBuilder.addHeaders(request));
|
||||||
|
responseData.append(ResponseBuilder.addParams(request));
|
||||||
|
}
|
||||||
|
|
||||||
|
responseData.append(ResponseBuilder.addDecoderResult(request));
|
||||||
|
|
||||||
|
if (msg instanceof HttpContent) {
|
||||||
|
HttpContent httpContent = (HttpContent) msg;
|
||||||
|
|
||||||
|
responseData.append(ResponseBuilder.addBody(httpContent));
|
||||||
|
responseData.append(ResponseBuilder.addDecoderResult(request));
|
||||||
|
|
||||||
|
if (msg instanceof LastHttpContent) {
|
||||||
|
LastHttpContent trailer = (LastHttpContent) msg;
|
||||||
|
responseData.append(ResponseBuilder.addLastResponse(request, trailer));
|
||||||
|
writeResponse(ctx, trailer, responseData);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void writeResponse(ChannelHandlerContext ctx) {
|
||||||
|
FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, CONTINUE, Unpooled.EMPTY_BUFFER);
|
||||||
|
ctx.write(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void writeResponse(ChannelHandlerContext ctx, LastHttpContent trailer, StringBuilder responseData) {
|
||||||
|
boolean keepAlive = HttpUtil.isKeepAlive(request);
|
||||||
|
|
||||||
|
FullHttpResponse httpResponse = new DefaultFullHttpResponse(HTTP_1_1, ((HttpObject) trailer).decoderResult()
|
||||||
|
.isSuccess() ? OK : BAD_REQUEST, Unpooled.copiedBuffer(responseData.toString(), CharsetUtil.UTF_8));
|
||||||
|
|
||||||
|
httpResponse.headers()
|
||||||
|
.set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
|
||||||
|
|
||||||
|
if (keepAlive) {
|
||||||
|
httpResponse.headers()
|
||||||
|
.setInt(HttpHeaderNames.CONTENT_LENGTH, httpResponse.content()
|
||||||
|
.readableBytes());
|
||||||
|
httpResponse.headers()
|
||||||
|
.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
|
||||||
|
}
|
||||||
|
|
||||||
|
String cookieString = request.headers()
|
||||||
|
.get(HttpHeaderNames.COOKIE);
|
||||||
|
if (cookieString != null) {
|
||||||
|
Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieString);
|
||||||
|
if (!cookies.isEmpty()) {
|
||||||
|
for (Cookie cookie : cookies) {
|
||||||
|
httpResponse.headers()
|
||||||
|
.add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.write(httpResponse);
|
||||||
|
|
||||||
|
if (!keepAlive) {
|
||||||
|
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
|
||||||
|
.addListener(ChannelFutureListener.CLOSE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
|
||||||
|
cause.printStackTrace();
|
||||||
|
ctx.close();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,64 @@
|
||||||
|
package com.baeldung.http.server;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import io.netty.bootstrap.ServerBootstrap;
|
||||||
|
import io.netty.channel.ChannelFuture;
|
||||||
|
import io.netty.channel.ChannelInitializer;
|
||||||
|
import io.netty.channel.ChannelPipeline;
|
||||||
|
import io.netty.channel.EventLoopGroup;
|
||||||
|
import io.netty.channel.nio.NioEventLoopGroup;
|
||||||
|
import io.netty.channel.socket.SocketChannel;
|
||||||
|
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
||||||
|
import io.netty.handler.codec.http.HttpRequestDecoder;
|
||||||
|
import io.netty.handler.codec.http.HttpResponseEncoder;
|
||||||
|
import io.netty.handler.logging.LogLevel;
|
||||||
|
import io.netty.handler.logging.LoggingHandler;
|
||||||
|
|
||||||
|
public class HttpServer {
|
||||||
|
|
||||||
|
private int port;
|
||||||
|
static Logger logger = LoggerFactory.getLogger(HttpServer.class);
|
||||||
|
|
||||||
|
public HttpServer(int port) {
|
||||||
|
this.port = port;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
|
||||||
|
int port = args.length > 0 ? Integer.parseInt(args[0]) : 8080;
|
||||||
|
|
||||||
|
new HttpServer(port).run();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void run() throws Exception {
|
||||||
|
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
|
||||||
|
EventLoopGroup workerGroup = new NioEventLoopGroup();
|
||||||
|
try {
|
||||||
|
ServerBootstrap b = new ServerBootstrap();
|
||||||
|
b.group(bossGroup, workerGroup)
|
||||||
|
.channel(NioServerSocketChannel.class)
|
||||||
|
.handler(new LoggingHandler(LogLevel.INFO))
|
||||||
|
.childHandler(new ChannelInitializer<SocketChannel>() {
|
||||||
|
@Override
|
||||||
|
protected void initChannel(SocketChannel ch) throws Exception {
|
||||||
|
ChannelPipeline p = ch.pipeline();
|
||||||
|
p.addLast(new HttpRequestDecoder());
|
||||||
|
p.addLast(new HttpResponseEncoder());
|
||||||
|
p.addLast(new CustomHttpServerHandler());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
ChannelFuture f = b.bind(port)
|
||||||
|
.sync();
|
||||||
|
f.channel()
|
||||||
|
.closeFuture()
|
||||||
|
.sync();
|
||||||
|
|
||||||
|
} finally {
|
||||||
|
bossGroup.shutdownGracefully();
|
||||||
|
workerGroup.shutdownGracefully();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,120 @@
|
||||||
|
package com.baeldung.http.server;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Map.Entry;
|
||||||
|
|
||||||
|
import io.netty.buffer.ByteBuf;
|
||||||
|
import io.netty.handler.codec.DecoderResult;
|
||||||
|
import io.netty.handler.codec.http.HttpContent;
|
||||||
|
import io.netty.handler.codec.http.HttpHeaderNames;
|
||||||
|
import io.netty.handler.codec.http.HttpHeaders;
|
||||||
|
import io.netty.handler.codec.http.HttpObject;
|
||||||
|
import io.netty.handler.codec.http.HttpRequest;
|
||||||
|
import io.netty.handler.codec.http.LastHttpContent;
|
||||||
|
import io.netty.handler.codec.http.QueryStringDecoder;
|
||||||
|
import io.netty.util.CharsetUtil;
|
||||||
|
|
||||||
|
class ResponseBuilder {
|
||||||
|
|
||||||
|
static StringBuilder addRequestAttributes(HttpRequest request) {
|
||||||
|
StringBuilder responseData = new StringBuilder();
|
||||||
|
responseData.append("Version: ")
|
||||||
|
.append(request.protocolVersion())
|
||||||
|
.append("\r\n");
|
||||||
|
responseData.append("Host: ")
|
||||||
|
.append(request.headers()
|
||||||
|
.get(HttpHeaderNames.HOST, "unknown"))
|
||||||
|
.append("\r\n");
|
||||||
|
responseData.append("URI: ")
|
||||||
|
.append(request.uri())
|
||||||
|
.append("\r\n\r\n");
|
||||||
|
return responseData;
|
||||||
|
}
|
||||||
|
|
||||||
|
static StringBuilder addParams(HttpRequest request) {
|
||||||
|
StringBuilder responseData = new StringBuilder();
|
||||||
|
QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
|
||||||
|
Map<String, List<String>> params = queryStringDecoder.parameters();
|
||||||
|
if (!params.isEmpty()) {
|
||||||
|
for (Entry<String, List<String>> p : params.entrySet()) {
|
||||||
|
String key = p.getKey();
|
||||||
|
List<String> vals = p.getValue();
|
||||||
|
for (String val : vals) {
|
||||||
|
responseData.append("Parameter: ")
|
||||||
|
.append(key)
|
||||||
|
.append(" = ")
|
||||||
|
.append(val)
|
||||||
|
.append("\r\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
responseData.append("\r\n");
|
||||||
|
}
|
||||||
|
return responseData;
|
||||||
|
}
|
||||||
|
|
||||||
|
static StringBuilder addHeaders(HttpRequest request) {
|
||||||
|
StringBuilder responseData = new StringBuilder();
|
||||||
|
HttpHeaders headers = request.headers();
|
||||||
|
if (!headers.isEmpty()) {
|
||||||
|
for (Map.Entry<String, String> header : headers) {
|
||||||
|
CharSequence key = header.getKey();
|
||||||
|
CharSequence value = header.getValue();
|
||||||
|
responseData.append(key)
|
||||||
|
.append(" = ")
|
||||||
|
.append(value)
|
||||||
|
.append("\r\n");
|
||||||
|
}
|
||||||
|
responseData.append("\r\n");
|
||||||
|
}
|
||||||
|
return responseData;
|
||||||
|
}
|
||||||
|
|
||||||
|
static StringBuilder addBody(HttpContent httpContent) {
|
||||||
|
StringBuilder responseData = new StringBuilder();
|
||||||
|
ByteBuf content = httpContent.content();
|
||||||
|
if (content.isReadable()) {
|
||||||
|
responseData.append(content.toString(CharsetUtil.UTF_8)
|
||||||
|
.toUpperCase());
|
||||||
|
responseData.append("\r\n");
|
||||||
|
}
|
||||||
|
return responseData;
|
||||||
|
}
|
||||||
|
|
||||||
|
static StringBuilder addDecoderResult(HttpObject o) {
|
||||||
|
StringBuilder responseData = new StringBuilder();
|
||||||
|
DecoderResult result = o.decoderResult();
|
||||||
|
|
||||||
|
if (!result.isSuccess()) {
|
||||||
|
responseData.append("..Decoder Failure: ");
|
||||||
|
responseData.append(result.cause());
|
||||||
|
responseData.append("\r\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
return responseData;
|
||||||
|
}
|
||||||
|
|
||||||
|
static StringBuilder addLastResponse(HttpRequest request, LastHttpContent trailer) {
|
||||||
|
StringBuilder responseData = new StringBuilder();
|
||||||
|
responseData.append("Good Bye!\r\n");
|
||||||
|
|
||||||
|
if (!trailer.trailingHeaders()
|
||||||
|
.isEmpty()) {
|
||||||
|
responseData.append("\r\n");
|
||||||
|
for (CharSequence name : trailer.trailingHeaders()
|
||||||
|
.names()) {
|
||||||
|
for (CharSequence value : trailer.trailingHeaders()
|
||||||
|
.getAll(name)) {
|
||||||
|
responseData.append("P.S. Trailing Header: ");
|
||||||
|
responseData.append(name)
|
||||||
|
.append(" = ")
|
||||||
|
.append(value)
|
||||||
|
.append("\r\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
responseData.append("\r\n");
|
||||||
|
}
|
||||||
|
return responseData;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,180 @@
|
||||||
|
package com.baeldung.http.server;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import io.netty.bootstrap.Bootstrap;
|
||||||
|
import io.netty.buffer.Unpooled;
|
||||||
|
import io.netty.channel.Channel;
|
||||||
|
import io.netty.channel.ChannelHandlerContext;
|
||||||
|
import io.netty.channel.ChannelInitializer;
|
||||||
|
import io.netty.channel.ChannelPipeline;
|
||||||
|
import io.netty.channel.EventLoopGroup;
|
||||||
|
import io.netty.channel.SimpleChannelInboundHandler;
|
||||||
|
import io.netty.channel.nio.NioEventLoopGroup;
|
||||||
|
import io.netty.channel.socket.SocketChannel;
|
||||||
|
import io.netty.channel.socket.nio.NioSocketChannel;
|
||||||
|
import io.netty.handler.codec.http.DefaultFullHttpRequest;
|
||||||
|
import io.netty.handler.codec.http.HttpClientCodec;
|
||||||
|
import io.netty.handler.codec.http.HttpContent;
|
||||||
|
import io.netty.handler.codec.http.HttpContentDecompressor;
|
||||||
|
import io.netty.handler.codec.http.HttpHeaderNames;
|
||||||
|
import io.netty.handler.codec.http.HttpHeaderValues;
|
||||||
|
import io.netty.handler.codec.http.HttpMethod;
|
||||||
|
import io.netty.handler.codec.http.HttpObject;
|
||||||
|
import io.netty.handler.codec.http.HttpResponse;
|
||||||
|
import io.netty.handler.codec.http.HttpUtil;
|
||||||
|
import io.netty.handler.codec.http.HttpVersion;
|
||||||
|
import io.netty.handler.codec.http.LastHttpContent;
|
||||||
|
import io.netty.handler.codec.http.cookie.ClientCookieEncoder;
|
||||||
|
import io.netty.handler.codec.http.cookie.DefaultCookie;
|
||||||
|
import io.netty.util.CharsetUtil;
|
||||||
|
|
||||||
|
//Ensure the server class - HttpServer.java is already started before running this test
|
||||||
|
public class HttpServerLiveTest {
|
||||||
|
|
||||||
|
private static final String HOST = "127.0.0.1";
|
||||||
|
private static final int PORT = 8080;
|
||||||
|
private Channel channel;
|
||||||
|
private EventLoopGroup group = new NioEventLoopGroup();
|
||||||
|
ResponseAggregator response = new ResponseAggregator();
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setup() throws Exception {
|
||||||
|
Bootstrap b = new Bootstrap();
|
||||||
|
b.group(group)
|
||||||
|
.channel(NioSocketChannel.class)
|
||||||
|
.handler(new ChannelInitializer<SocketChannel>() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void initChannel(SocketChannel ch) throws Exception {
|
||||||
|
ChannelPipeline p = ch.pipeline();
|
||||||
|
p.addLast(new HttpClientCodec());
|
||||||
|
p.addLast(new HttpContentDecompressor());
|
||||||
|
p.addLast(new SimpleChannelInboundHandler<HttpObject>() {
|
||||||
|
@Override
|
||||||
|
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
|
||||||
|
response = prepareResponse(ctx, msg, response);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
channel = b.connect(HOST, PORT)
|
||||||
|
.sync()
|
||||||
|
.channel();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPostSent_thenContentReceivedInUppercase() throws Exception {
|
||||||
|
String body = "Hello World!";
|
||||||
|
|
||||||
|
DefaultFullHttpRequest request = createRequest(body);
|
||||||
|
|
||||||
|
channel.writeAndFlush(request);
|
||||||
|
Thread.sleep(200);
|
||||||
|
|
||||||
|
assertEquals(200, response.getStatus());
|
||||||
|
assertEquals("HTTP/1.1", response.getVersion());
|
||||||
|
|
||||||
|
assertTrue(response.getContent()
|
||||||
|
.contains(body.toUpperCase()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenGetSent_thenCookieReceivedInResponse() throws Exception {
|
||||||
|
DefaultFullHttpRequest request = createRequest(null);
|
||||||
|
|
||||||
|
channel.writeAndFlush(request);
|
||||||
|
Thread.sleep(200);
|
||||||
|
|
||||||
|
assertEquals(200, response.getStatus());
|
||||||
|
assertEquals("HTTP/1.1", response.getVersion());
|
||||||
|
|
||||||
|
Map<String, String> headers = response.getHeaders();
|
||||||
|
String cookies = headers.get("set-cookie");
|
||||||
|
assertTrue(cookies.contains("my-cookie"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void cleanup() throws InterruptedException {
|
||||||
|
channel.closeFuture()
|
||||||
|
.sync();
|
||||||
|
group.shutdownGracefully();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DefaultFullHttpRequest createRequest(final CharSequence body) throws Exception {
|
||||||
|
DefaultFullHttpRequest request;
|
||||||
|
if (body != null) {
|
||||||
|
request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
|
||||||
|
request.content()
|
||||||
|
.writeBytes(body.toString()
|
||||||
|
.getBytes(CharsetUtil.UTF_8.name()));
|
||||||
|
request.headers()
|
||||||
|
.set(HttpHeaderNames.CONTENT_TYPE, "application/json");
|
||||||
|
request.headers()
|
||||||
|
.set(HttpHeaderNames.CONTENT_LENGTH, request.content()
|
||||||
|
.readableBytes());
|
||||||
|
} else {
|
||||||
|
request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/", Unpooled.EMPTY_BUFFER);
|
||||||
|
request.headers()
|
||||||
|
.set(HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT.encode(new DefaultCookie("my-cookie", "foo")));
|
||||||
|
}
|
||||||
|
|
||||||
|
request.headers()
|
||||||
|
.set(HttpHeaderNames.HOST, HOST);
|
||||||
|
request.headers()
|
||||||
|
.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
|
||||||
|
|
||||||
|
return request;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ResponseAggregator prepareResponse(ChannelHandlerContext ctx, HttpObject msg, ResponseAggregator responseAgg) {
|
||||||
|
|
||||||
|
if (msg instanceof HttpResponse) {
|
||||||
|
HttpResponse response = (HttpResponse) msg;
|
||||||
|
|
||||||
|
responseAgg.setStatus(response.status()
|
||||||
|
.code());
|
||||||
|
|
||||||
|
responseAgg.setVersion(response.protocolVersion()
|
||||||
|
.text());
|
||||||
|
|
||||||
|
if (!response.headers()
|
||||||
|
.isEmpty()) {
|
||||||
|
Map<String, String> headers = new HashMap<String, String>();
|
||||||
|
for (CharSequence name : response.headers()
|
||||||
|
.names()) {
|
||||||
|
for (CharSequence value : response.headers()
|
||||||
|
.getAll(name)) {
|
||||||
|
headers.put(name.toString(), value.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
responseAgg.setHeaders(headers);
|
||||||
|
}
|
||||||
|
if (HttpUtil.isTransferEncodingChunked(response)) {
|
||||||
|
responseAgg.setChunked(true);
|
||||||
|
} else {
|
||||||
|
responseAgg.setChunked(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (msg instanceof HttpContent) {
|
||||||
|
HttpContent content = (HttpContent) msg;
|
||||||
|
String responseData = content.content()
|
||||||
|
.toString(CharsetUtil.UTF_8);
|
||||||
|
|
||||||
|
if (content instanceof LastHttpContent) {
|
||||||
|
responseAgg.setContent(responseData + "} End Of Content");
|
||||||
|
ctx.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return responseAgg;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,52 @@
|
||||||
|
package com.baeldung.http.server;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class ResponseAggregator {
|
||||||
|
int status;
|
||||||
|
String version;
|
||||||
|
Map<String, String> headers;
|
||||||
|
boolean isChunked;
|
||||||
|
String content;
|
||||||
|
|
||||||
|
public int getStatus() {
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setStatus(int status) {
|
||||||
|
this.status = status;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getVersion() {
|
||||||
|
return version;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setVersion(String version) {
|
||||||
|
this.version = version;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, String> getHeaders() {
|
||||||
|
return headers;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setHeaders(Map<String, String> headers) {
|
||||||
|
this.headers = headers;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isChunked() {
|
||||||
|
return isChunked;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setChunked(boolean isChunked) {
|
||||||
|
this.isChunked = isChunked;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getContent() {
|
||||||
|
return content;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setContent(String content) {
|
||||||
|
this.content = content;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -4,3 +4,4 @@
|
||||||
- [Introduction to Lettuce – the Java Redis Client](https://www.baeldung.com/java-redis-lettuce)
|
- [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)
|
- [List All Available Redis Keys](https://www.baeldung.com/redis-list-available-keys)
|
||||||
- [Spring Data Redis’s Property-Based Configuration](https://www.baeldung.com/spring-data-redis-properties)
|
- [Spring Data Redis’s Property-Based Configuration](https://www.baeldung.com/spring-data-redis-properties)
|
||||||
|
- [Delete Everything in Redis](https://www.baeldung.com/redis-delete-data)
|
||||||
|
|
|
@ -33,7 +33,8 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>redis.clients</groupId>
|
<groupId>redis.clients</groupId>
|
||||||
<artifactId>jedis</artifactId>
|
<artifactId>jedis</artifactId>
|
||||||
</dependency>
|
<version>3.3.0</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.github.kstyrc</groupId>
|
<groupId>com.github.kstyrc</groupId>
|
||||||
<artifactId>embedded-redis</artifactId>
|
<artifactId>embedded-redis</artifactId>
|
||||||
|
|
|
@ -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"));
|
||||||
|
}
|
||||||
|
}
|
|
@ -15,13 +15,7 @@
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-core</artifactId>
|
<artifactId>spring-web</artifactId>
|
||||||
<version>${spring.version}</version>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework</groupId>
|
|
||||||
<artifactId>spring-context</artifactId>
|
|
||||||
<version>${spring.version}</version>
|
<version>${spring.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
@ -36,6 +30,7 @@
|
||||||
<artifactId>elasticsearch</artifactId>
|
<artifactId>elasticsearch</artifactId>
|
||||||
<version>${elasticsearch.version}</version>
|
<version>${elasticsearch.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.alibaba</groupId>
|
<groupId>com.alibaba</groupId>
|
||||||
<artifactId>fastjson</artifactId>
|
<artifactId>fastjson</artifactId>
|
||||||
|
@ -49,8 +44,8 @@
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.vividsolutions</groupId>
|
<groupId>org.locationtech.jts</groupId>
|
||||||
<artifactId>jts</artifactId>
|
<artifactId>jts-core</artifactId>
|
||||||
<version>${jts.version}</version>
|
<version>${jts.version}</version>
|
||||||
<exclusions>
|
<exclusions>
|
||||||
<exclusion>
|
<exclusion>
|
||||||
|
@ -60,41 +55,19 @@
|
||||||
</exclusions>
|
</exclusions>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.logging.log4j</groupId>
|
|
||||||
<artifactId>log4j-core</artifactId>
|
|
||||||
<version>${log4j.version}</version>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.elasticsearch.client</groupId>
|
|
||||||
<artifactId>transport</artifactId>
|
|
||||||
<version>${elasticsearch.version}</version>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-test</artifactId>
|
<artifactId>spring-test</artifactId>
|
||||||
<version>${spring.version}</version>
|
<version>${spring.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>net.java.dev.jna</groupId>
|
|
||||||
<artifactId>jna</artifactId>
|
|
||||||
<version>${jna.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<spring-data-elasticsearch.version>3.0.8.RELEASE</spring-data-elasticsearch.version>
|
<spring-data-elasticsearch.version>4.0.0.RELEASE</spring-data-elasticsearch.version>
|
||||||
<jna.version>4.5.2</jna.version>
|
<elasticsearch.version>7.6.2</elasticsearch.version>
|
||||||
<elasticsearch.version>5.6.0</elasticsearch.version>
|
|
||||||
<fastjson.version>1.2.47</fastjson.version>
|
<fastjson.version>1.2.47</fastjson.version>
|
||||||
<spatial4j.version>0.6</spatial4j.version>
|
<spatial4j.version>0.7</spatial4j.version>
|
||||||
<jts.version>1.13</jts.version>
|
<jts.version>1.15.0</jts.version>
|
||||||
<log4j.version>2.9.1</log4j.version>
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -1,19 +1,13 @@
|
||||||
package com.baeldung.spring.data.es.config;
|
package com.baeldung.spring.data.es.config;
|
||||||
|
|
||||||
import java.net.InetAddress;
|
import org.elasticsearch.client.RestHighLevelClient;
|
||||||
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.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.ComponentScan;
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
import org.springframework.context.annotation.Configuration;
|
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.ElasticsearchOperations;
|
||||||
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
|
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
|
||||||
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
|
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
|
@ -21,30 +15,18 @@ import org.springframework.data.elasticsearch.repository.config.EnableElasticsea
|
||||||
@ComponentScan(basePackages = { "com.baeldung.spring.data.es.service" })
|
@ComponentScan(basePackages = { "com.baeldung.spring.data.es.service" })
|
||||||
public class Config {
|
public class Config {
|
||||||
|
|
||||||
@Value("${elasticsearch.home:/usr/local/Cellar/elasticsearch/5.6.0}")
|
|
||||||
private String elasticsearchHome;
|
|
||||||
|
|
||||||
@Value("${elasticsearch.cluster.name:elasticsearch}")
|
|
||||||
private String clusterName;
|
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public Client client() {
|
RestHighLevelClient client() {
|
||||||
TransportClient client = null;
|
ClientConfiguration clientConfiguration = ClientConfiguration.builder()
|
||||||
try {
|
.connectedTo("localhost:9200")
|
||||||
final Settings elasticsearchSettings = Settings.builder()
|
.build();
|
||||||
.put("client.transport.sniff", true)
|
|
||||||
.put("path.home", elasticsearchHome)
|
return RestClients.create(clientConfiguration)
|
||||||
.put("cluster.name", clusterName).build();
|
.rest();
|
||||||
client = new PreBuiltTransportClient(elasticsearchSettings);
|
|
||||||
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
|
|
||||||
} catch (UnknownHostException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return client;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public ElasticsearchOperations elasticsearchTemplate() {
|
public ElasticsearchOperations elasticsearchTemplate() {
|
||||||
return new ElasticsearchTemplate(client());
|
return new ElasticsearchRestTemplate(client());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,7 +1,12 @@
|
||||||
package com.baeldung.spring.data.es.model;
|
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 {
|
public class Author {
|
||||||
|
|
||||||
|
@Field(type = Text)
|
||||||
private String name;
|
private String name;
|
||||||
|
|
||||||
public Author() {
|
public Author() {
|
||||||
|
|
|
@ -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);
|
|
||||||
}
|
|
|
@ -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);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -8,10 +8,10 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||||
import com.baeldung.spring.data.es.config.Config;
|
import com.baeldung.spring.data.es.config.Config;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
* This Manual test requires: Elasticsearch instance running on localhost:9200.
|
||||||
*
|
*
|
||||||
* This Manual test requires:
|
* The following docker command can be used: docker run -d --name es762 -p
|
||||||
* * Elasticsearch instance running on host
|
* 9200:9200 -e "discovery.type=single-node" elasticsearch:7.6.2
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@ContextConfiguration(classes = Config.class)
|
@ContextConfiguration(classes = Config.class)
|
||||||
|
|
|
@ -3,43 +3,48 @@ package com.baeldung.elasticsearch;
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.InetAddress;
|
|
||||||
import java.net.UnknownHostException;
|
import java.net.UnknownHostException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import com.alibaba.fastjson.JSON;
|
||||||
|
|
||||||
import org.elasticsearch.action.DocWriteResponse.Result;
|
import org.elasticsearch.action.DocWriteResponse.Result;
|
||||||
|
import org.elasticsearch.action.delete.DeleteRequest;
|
||||||
import org.elasticsearch.action.delete.DeleteResponse;
|
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.index.IndexResponse;
|
||||||
|
import org.elasticsearch.action.search.SearchRequest;
|
||||||
import org.elasticsearch.action.search.SearchResponse;
|
import org.elasticsearch.action.search.SearchResponse;
|
||||||
import org.elasticsearch.action.search.SearchType;
|
import org.elasticsearch.action.search.SearchType;
|
||||||
import org.elasticsearch.client.Client;
|
import org.elasticsearch.client.RequestOptions;
|
||||||
import org.elasticsearch.common.settings.Settings;
|
import org.elasticsearch.client.RestHighLevelClient;
|
||||||
import org.elasticsearch.common.transport.InetSocketTransportAddress;
|
|
||||||
import org.elasticsearch.common.xcontent.XContentBuilder;
|
import org.elasticsearch.common.xcontent.XContentBuilder;
|
||||||
import org.elasticsearch.common.xcontent.XContentFactory;
|
import org.elasticsearch.common.xcontent.XContentFactory;
|
||||||
import org.elasticsearch.common.xcontent.XContentType;
|
import org.elasticsearch.common.xcontent.XContentType;
|
||||||
import org.elasticsearch.index.query.QueryBuilders;
|
import org.elasticsearch.index.query.QueryBuilders;
|
||||||
import org.elasticsearch.search.SearchHit;
|
import org.elasticsearch.search.SearchHit;
|
||||||
import org.elasticsearch.transport.client.PreBuiltTransportClient;
|
import org.elasticsearch.search.builder.SearchSourceBuilder;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
import org.springframework.data.elasticsearch.client.ClientConfiguration;
|
||||||
import com.alibaba.fastjson.JSON;
|
import org.springframework.data.elasticsearch.client.RestClients;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
* This Manual test requires: Elasticsearch instance running on localhost:9200.
|
||||||
*
|
*
|
||||||
* This Manual test requires:
|
* The following docker command can be used: docker run -d --name es762 -p
|
||||||
* * Elasticsearch instance running on host
|
* 9200:9200 -e "discovery.type=single-node" elasticsearch:7.6.2
|
||||||
* * with cluster name = elasticsearch
|
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
public class ElasticSearchManualTest {
|
public class ElasticSearchManualTest {
|
||||||
private List<Person> listOfPersons = new ArrayList<>();
|
private List<Person> listOfPersons = new ArrayList<>();
|
||||||
private Client client = null;
|
private RestHighLevelClient client = null;
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setUp() throws UnknownHostException {
|
public void setUp() throws UnknownHostException {
|
||||||
|
@ -47,115 +52,122 @@ public class ElasticSearchManualTest {
|
||||||
Person person2 = new Person(25, "Janette Doe", new Date());
|
Person person2 = new Person(25, "Janette Doe", new Date());
|
||||||
listOfPersons.add(person1);
|
listOfPersons.add(person1);
|
||||||
listOfPersons.add(person2);
|
listOfPersons.add(person2);
|
||||||
|
|
||||||
client = new PreBuiltTransportClient(Settings.builder().put("client.transport.sniff", true)
|
ClientConfiguration clientConfiguration = ClientConfiguration.builder()
|
||||||
.put("cluster.name","elasticsearch").build())
|
.connectedTo("localhost:9200")
|
||||||
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
|
.build();
|
||||||
|
client = RestClients.create(clientConfiguration)
|
||||||
|
.rest();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenJsonString_whenJavaObject_thenIndexDocument() {
|
public void givenJsonString_whenJavaObject_thenIndexDocument() throws Exception {
|
||||||
String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}";
|
String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}";
|
||||||
IndexResponse response = client
|
IndexRequest request = new IndexRequest("people");
|
||||||
.prepareIndex("people", "Doe")
|
request.source(jsonObject, XContentType.JSON);
|
||||||
.setSource(jsonObject, XContentType.JSON)
|
|
||||||
.get();
|
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
|
||||||
String index = response.getIndex();
|
String index = response.getIndex();
|
||||||
String type = response.getType();
|
long version = response.getVersion();
|
||||||
|
|
||||||
assertEquals(Result.CREATED, response.getResult());
|
assertEquals(Result.CREATED, response.getResult());
|
||||||
assertEquals(index, "people");
|
assertEquals(1, version);
|
||||||
assertEquals(type, "Doe");
|
assertEquals("people", index);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDocumentId_whenJavaObject_thenDeleteDocument() {
|
public void givenDocumentId_whenJavaObject_thenDeleteDocument() throws Exception {
|
||||||
String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}";
|
String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}";
|
||||||
IndexResponse response = client
|
IndexRequest indexRequest = new IndexRequest("people");
|
||||||
.prepareIndex("people", "Doe")
|
indexRequest.source(jsonObject, XContentType.JSON);
|
||||||
.setSource(jsonObject, XContentType.JSON)
|
|
||||||
.get();
|
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
|
||||||
String id = response.getId();
|
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
|
@Test
|
||||||
public void givenSearchRequest_whenMatchAll_thenReturnAllResults() {
|
public void givenSearchRequest_whenMatchAll_thenReturnAllResults() throws Exception {
|
||||||
SearchResponse response = client
|
SearchRequest searchRequest = new SearchRequest();
|
||||||
.prepareSearch()
|
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
|
||||||
.execute()
|
SearchHit[] searchHits = response.getHits()
|
||||||
.actionGet();
|
.getHits();
|
||||||
SearchHit[] searchHits = response
|
|
||||||
.getHits()
|
|
||||||
.getHits();
|
|
||||||
List<Person> results = Arrays.stream(searchHits)
|
List<Person> results = Arrays.stream(searchHits)
|
||||||
.map(hit -> JSON.parseObject(hit.getSourceAsString(), Person.class))
|
.map(hit -> JSON.parseObject(hit.getSourceAsString(), Person.class))
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
results.forEach(System.out::println);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenSearchParameters_thenReturnResults() {
|
public void givenSearchParameters_thenReturnResults() throws Exception {
|
||||||
SearchResponse response = client
|
SearchSourceBuilder builder = new SearchSourceBuilder().postFilter(QueryBuilders.rangeQuery("age")
|
||||||
.prepareSearch()
|
|
||||||
.setTypes()
|
|
||||||
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
|
|
||||||
.setPostFilter(QueryBuilders
|
|
||||||
.rangeQuery("age")
|
|
||||||
.from(5)
|
.from(5)
|
||||||
.to(15))
|
.to(15));
|
||||||
.setFrom(0)
|
|
||||||
.setSize(60)
|
|
||||||
.setExplain(true)
|
|
||||||
.execute()
|
|
||||||
.actionGet();
|
|
||||||
|
|
||||||
SearchResponse response2 = client
|
SearchRequest searchRequest = new SearchRequest();
|
||||||
.prepareSearch()
|
searchRequest.searchType(SearchType.DFS_QUERY_THEN_FETCH);
|
||||||
.setTypes()
|
searchRequest.source(builder);
|
||||||
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
|
|
||||||
.setPostFilter(QueryBuilders.simpleQueryStringQuery("+John -Doe OR Janette"))
|
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
|
||||||
.setFrom(0)
|
|
||||||
.setSize(60)
|
builder = new SearchSourceBuilder().postFilter(QueryBuilders.simpleQueryStringQuery("+John -Doe OR Janette"));
|
||||||
.setExplain(true)
|
|
||||||
.execute()
|
searchRequest = new SearchRequest();
|
||||||
.actionGet();
|
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();
|
response2.getHits();
|
||||||
response3.getHits();
|
response3.getHits();
|
||||||
|
|
||||||
final List<Person> results = Arrays.stream(response.getHits().getHits())
|
final List<Person> results = Stream.of(response.getHits()
|
||||||
.map(hit -> JSON.parseObject(hit.getSourceAsString(), Person.class))
|
.getHits(),
|
||||||
.collect(Collectors.toList());
|
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
|
@Test
|
||||||
public void givenContentBuilder_whenHelpers_thanIndexJson() throws IOException {
|
public void givenContentBuilder_whenHelpers_thanIndexJson() throws IOException {
|
||||||
XContentBuilder builder = XContentFactory
|
XContentBuilder builder = XContentFactory.jsonBuilder()
|
||||||
.jsonBuilder()
|
.startObject()
|
||||||
.startObject()
|
.field("fullName", "Test")
|
||||||
.field("fullName", "Test")
|
.field("salary", "11500")
|
||||||
.field("salary", "11500")
|
.field("age", "10")
|
||||||
.field("age", "10")
|
.endObject();
|
||||||
.endObject();
|
|
||||||
IndexResponse response = client
|
|
||||||
.prepareIndex("people", "Doe")
|
|
||||||
.setSource(builder)
|
|
||||||
.get();
|
|
||||||
|
|
||||||
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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,5 @@
|
||||||
package com.baeldung.elasticsearch;
|
package com.baeldung.elasticsearch;
|
||||||
|
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
@ -7,162 +8,169 @@ import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.stream.Collectors;
|
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.index.IndexResponse;
|
||||||
|
import org.elasticsearch.action.search.SearchRequest;
|
||||||
import org.elasticsearch.action.search.SearchResponse;
|
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.GeoPoint;
|
||||||
import org.elasticsearch.common.geo.ShapeRelation;
|
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.unit.DistanceUnit;
|
||||||
import org.elasticsearch.common.xcontent.XContentType;
|
import org.elasticsearch.common.xcontent.XContentType;
|
||||||
|
import org.elasticsearch.index.query.GeoShapeQueryBuilder;
|
||||||
import org.elasticsearch.index.query.QueryBuilder;
|
import org.elasticsearch.index.query.QueryBuilder;
|
||||||
import org.elasticsearch.index.query.QueryBuilders;
|
import org.elasticsearch.index.query.QueryBuilders;
|
||||||
import org.elasticsearch.search.SearchHit;
|
import org.elasticsearch.search.SearchHit;
|
||||||
|
import org.elasticsearch.search.builder.SearchSourceBuilder;
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
|
import org.locationtech.jts.geom.Coordinate;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
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.ContextConfiguration;
|
||||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
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:
|
* The following docker command can be used: docker run -d --name es762 -p
|
||||||
* * Elasticsearch instance running on host
|
* 9200:9200 -e "discovery.type=single-node" elasticsearch:7.6.2
|
||||||
* * with cluster name = elasticsearch
|
|
||||||
* * and further configurations
|
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@ContextConfiguration(classes = Config.class)
|
@ContextConfiguration(classes = Config.class)
|
||||||
public class GeoQueriesManualTest {
|
public class GeoQueriesManualTest {
|
||||||
|
|
||||||
private static final String WONDERS_OF_WORLD = "wonders-of-world";
|
private static final String WONDERS_OF_WORLD = "wonders-of-world";
|
||||||
private static final String WONDERS = "Wonders";
|
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private ElasticsearchTemplate elasticsearchTemplate;
|
private RestHighLevelClient client;
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private Client client;
|
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setUp() {
|
public void setUp() throws Exception {
|
||||||
String jsonObject = "{\"Wonders\":{\"properties\":{\"name\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"region\":{\"type\":\"geo_shape\",\"tree\":\"quadtree\",\"precision\":\"1m\"},\"location\":{\"type\":\"geo_point\"}}}}";
|
String jsonObject = "{\"properties\":{\"name\":{\"type\":\"text\",\"index\":false},\"region\":{\"type\":\"geo_shape\"},\"location\":{\"type\":\"geo_point\"}}}";
|
||||||
|
|
||||||
CreateIndexRequest req = new CreateIndexRequest(WONDERS_OF_WORLD);
|
CreateIndexRequest req = new CreateIndexRequest(WONDERS_OF_WORLD);
|
||||||
req.mapping(WONDERS, jsonObject, XContentType.JSON);
|
req.mapping(jsonObject, XContentType.JSON);
|
||||||
client.admin()
|
|
||||||
.indices()
|
client.indices()
|
||||||
.create(req)
|
.create(req, RequestOptions.DEFAULT);
|
||||||
.actionGet();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@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]]}}";
|
String jsonObject = "{\"name\":\"Agra\",\"region\":{\"type\":\"envelope\",\"coordinates\":[[75,30.2],[80.1, 25]]}}";
|
||||||
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
|
IndexRequest indexRequest = new IndexRequest(WONDERS_OF_WORLD);
|
||||||
.setSource(jsonObject, XContentType.JSON)
|
indexRequest.source(jsonObject, XContentType.JSON);
|
||||||
.get();
|
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
|
||||||
|
|
||||||
String tajMahalId = response.getId();
|
String tajMahalId = response.getId();
|
||||||
client.admin()
|
|
||||||
.indices()
|
|
||||||
.prepareRefresh(WONDERS_OF_WORLD)
|
|
||||||
.get();
|
|
||||||
|
|
||||||
Coordinate topLeft =new Coordinate(74, 31.2);
|
RefreshRequest refreshRequest = new RefreshRequest(WONDERS_OF_WORLD);
|
||||||
Coordinate bottomRight =new Coordinate(81.1, 24);
|
client.indices()
|
||||||
QueryBuilder qb = QueryBuilders
|
.refresh(refreshRequest, RequestOptions.DEFAULT);
|
||||||
.geoShapeQuery("region", ShapeBuilders.newEnvelope(topLeft, bottomRight))
|
|
||||||
.relation(ShapeRelation.WITHIN);
|
|
||||||
|
|
||||||
|
Coordinate topLeft = new Coordinate(74, 31.2);
|
||||||
|
Coordinate bottomRight = new Coordinate(81.1, 24);
|
||||||
|
|
||||||
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD)
|
GeoShapeQueryBuilder qb = QueryBuilders.geoShapeQuery("region", new EnvelopeBuilder(topLeft, bottomRight).buildGeometry());
|
||||||
.setTypes(WONDERS)
|
qb.relation(ShapeRelation.INTERSECTS);
|
||||||
.setQuery(qb)
|
|
||||||
.execute()
|
SearchSourceBuilder source = new SearchSourceBuilder().query(qb);
|
||||||
.actionGet();
|
SearchRequest searchRequest = new SearchRequest(WONDERS_OF_WORLD);
|
||||||
|
searchRequest.source(source);
|
||||||
|
|
||||||
|
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
|
||||||
|
|
||||||
List<String> ids = Arrays.stream(searchResponse.getHits()
|
List<String> ids = Arrays.stream(searchResponse.getHits()
|
||||||
.getHits())
|
.getHits())
|
||||||
.map(SearchHit::getId)
|
.map(SearchHit::getId)
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
assertTrue(ids.contains(tajMahalId));
|
assertTrue(ids.contains(tajMahalId));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenGeoPointData_whenExecutedGeoBoundingBoxQuery_thenResultNonEmpty() {
|
public void givenGeoPointData_whenExecutedGeoBoundingBoxQuery_thenResultNonEmpty() throws Exception {
|
||||||
String jsonObject = "{\"name\":\"Pyramids of Giza\",\"location\":[31.131302,29.976480]}";
|
String jsonObject = "{\"name\":\"Pyramids of Giza\",\"location\":[31.131302,29.976480]}";
|
||||||
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
|
|
||||||
.setSource(jsonObject, XContentType.JSON)
|
IndexRequest indexRequest = new IndexRequest(WONDERS_OF_WORLD);
|
||||||
.get();
|
indexRequest.source(jsonObject, XContentType.JSON);
|
||||||
|
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
|
||||||
|
|
||||||
String pyramidsOfGizaId = response.getId();
|
String pyramidsOfGizaId = response.getId();
|
||||||
client.admin()
|
|
||||||
.indices()
|
RefreshRequest refreshRequest = new RefreshRequest(WONDERS_OF_WORLD);
|
||||||
.prepareRefresh(WONDERS_OF_WORLD)
|
client.indices()
|
||||||
.get();
|
.refresh(refreshRequest, RequestOptions.DEFAULT);
|
||||||
|
|
||||||
QueryBuilder qb = QueryBuilders.geoBoundingBoxQuery("location")
|
QueryBuilder qb = QueryBuilders.geoBoundingBoxQuery("location")
|
||||||
.setCorners(31,30,28,32);
|
.setCorners(31, 30, 28, 32);
|
||||||
|
|
||||||
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD)
|
SearchSourceBuilder source = new SearchSourceBuilder().query(qb);
|
||||||
.setTypes(WONDERS)
|
SearchRequest searchRequest = new SearchRequest(WONDERS_OF_WORLD);
|
||||||
.setQuery(qb)
|
searchRequest.source(source);
|
||||||
.execute()
|
|
||||||
.actionGet();
|
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
|
||||||
|
|
||||||
List<String> ids = Arrays.stream(searchResponse.getHits()
|
List<String> ids = Arrays.stream(searchResponse.getHits()
|
||||||
.getHits())
|
.getHits())
|
||||||
.map(SearchHit::getId)
|
.map(SearchHit::getId)
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
assertTrue(ids.contains(pyramidsOfGizaId));
|
assertTrue(ids.contains(pyramidsOfGizaId));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenGeoPointData_whenExecutedGeoDistanceQuery_thenResultNonEmpty() {
|
public void givenGeoPointData_whenExecutedGeoDistanceQuery_thenResultNonEmpty() throws Exception {
|
||||||
String jsonObject = "{\"name\":\"Lighthouse of alexandria\",\"location\":[31.131302,29.976480]}";
|
String jsonObject = "{\"name\":\"Lighthouse of alexandria\",\"location\":[31.131302,29.976480]}";
|
||||||
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
|
|
||||||
.setSource(jsonObject, XContentType.JSON)
|
IndexRequest indexRequest = new IndexRequest(WONDERS_OF_WORLD);
|
||||||
.get();
|
indexRequest.source(jsonObject, XContentType.JSON);
|
||||||
|
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
|
||||||
|
|
||||||
String lighthouseOfAlexandriaId = response.getId();
|
String lighthouseOfAlexandriaId = response.getId();
|
||||||
client.admin()
|
|
||||||
.indices()
|
RefreshRequest refreshRequest = new RefreshRequest(WONDERS_OF_WORLD);
|
||||||
.prepareRefresh(WONDERS_OF_WORLD)
|
client.indices()
|
||||||
.get();
|
.refresh(refreshRequest, RequestOptions.DEFAULT);
|
||||||
|
|
||||||
QueryBuilder qb = QueryBuilders.geoDistanceQuery("location")
|
QueryBuilder qb = QueryBuilders.geoDistanceQuery("location")
|
||||||
.point(29.976, 31.131)
|
.point(29.976, 31.131)
|
||||||
.distance(10, DistanceUnit.MILES);
|
.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()
|
List<String> ids = Arrays.stream(searchResponse.getHits()
|
||||||
.getHits())
|
.getHits())
|
||||||
.map(SearchHit::getId)
|
.map(SearchHit::getId)
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
assertTrue(ids.contains(lighthouseOfAlexandriaId));
|
assertTrue(ids.contains(lighthouseOfAlexandriaId));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@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]}";
|
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)
|
IndexRequest indexRequest = new IndexRequest(WONDERS_OF_WORLD);
|
||||||
.get();
|
indexRequest.source(jsonObject, XContentType.JSON);
|
||||||
|
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
|
||||||
|
|
||||||
String greatRannOfKutchid = response.getId();
|
String greatRannOfKutchid = response.getId();
|
||||||
client.admin()
|
|
||||||
.indices()
|
RefreshRequest refreshRequest = new RefreshRequest(WONDERS_OF_WORLD);
|
||||||
.prepareRefresh(WONDERS_OF_WORLD)
|
client.indices()
|
||||||
.get();
|
.refresh(refreshRequest, RequestOptions.DEFAULT);
|
||||||
|
|
||||||
List<GeoPoint> allPoints = new ArrayList<GeoPoint>();
|
List<GeoPoint> allPoints = new ArrayList<GeoPoint>();
|
||||||
allPoints.add(new GeoPoint(22.733, 68.859));
|
allPoints.add(new GeoPoint(22.733, 68.859));
|
||||||
|
@ -170,20 +178,23 @@ public class GeoQueriesManualTest {
|
||||||
allPoints.add(new GeoPoint(23, 70.859));
|
allPoints.add(new GeoPoint(23, 70.859));
|
||||||
QueryBuilder qb = QueryBuilders.geoPolygonQuery("location", allPoints);
|
QueryBuilder qb = QueryBuilders.geoPolygonQuery("location", allPoints);
|
||||||
|
|
||||||
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD)
|
SearchSourceBuilder source = new SearchSourceBuilder().query(qb);
|
||||||
.setTypes(WONDERS)
|
SearchRequest searchRequest = new SearchRequest(WONDERS_OF_WORLD);
|
||||||
.setQuery(qb)
|
searchRequest.source(source);
|
||||||
.execute()
|
|
||||||
.actionGet();
|
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
|
||||||
|
|
||||||
List<String> ids = Arrays.stream(searchResponse.getHits()
|
List<String> ids = Arrays.stream(searchResponse.getHits()
|
||||||
.getHits())
|
.getHits())
|
||||||
.map(SearchHit::getId)
|
.map(SearchHit::getId)
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
assertTrue(ids.contains(greatRannOfKutchid));
|
assertTrue(ids.contains(greatRannOfKutchid));
|
||||||
}
|
}
|
||||||
|
|
||||||
@After
|
@After
|
||||||
public void destroy() {
|
public void destroy() throws Exception {
|
||||||
elasticsearchTemplate.deleteIndex(WONDERS_OF_WORLD);
|
DeleteIndexRequest deleteIndex = new DeleteIndexRequest(WONDERS_OF_WORLD);
|
||||||
|
client.indices()
|
||||||
|
.delete(deleteIndex, RequestOptions.DEFAULT);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,68 +10,71 @@ import static org.junit.Assert.assertNotNull;
|
||||||
|
|
||||||
import java.util.List;
|
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.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
import org.springframework.data.domain.PageRequest;
|
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.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.ContextConfiguration;
|
||||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
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:
|
* The following docker command can be used: docker run -d --name es762 -p
|
||||||
* * Elasticsearch instance running on host
|
* 9200:9200 -e "discovery.type=single-node" elasticsearch:7.6.2
|
||||||
* * with cluster name = elasticsearch
|
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@ContextConfiguration(classes = Config.class)
|
@ContextConfiguration(classes = Config.class)
|
||||||
public class ElasticSearchManualTest {
|
public class ElasticSearchManualTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private ElasticsearchTemplate elasticsearchTemplate;
|
private ElasticsearchRestTemplate elasticsearchTemplate;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private ArticleService articleService;
|
private ArticleRepository articleRepository;
|
||||||
|
|
||||||
private final Author johnSmith = new Author("John Smith");
|
private final Author johnSmith = new Author("John Smith");
|
||||||
private final Author johnDoe = new Author("John Doe");
|
private final Author johnDoe = new Author("John Doe");
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void 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 article = new Article("Spring Data Elasticsearch");
|
||||||
article.setAuthors(asList(johnSmith, johnDoe));
|
article.setAuthors(asList(johnSmith, johnDoe));
|
||||||
article.setTags("elasticsearch", "spring data");
|
article.setTags("elasticsearch", "spring data");
|
||||||
articleService.save(article);
|
articleRepository.save(article);
|
||||||
|
|
||||||
article = new Article("Search engines");
|
article = new Article("Search engines");
|
||||||
article.setAuthors(asList(johnDoe));
|
article.setAuthors(asList(johnDoe));
|
||||||
article.setTags("search engines", "tutorial");
|
article.setTags("search engines", "tutorial");
|
||||||
articleService.save(article);
|
articleRepository.save(article);
|
||||||
|
|
||||||
article = new Article("Second Article About Elasticsearch");
|
article = new Article("Second Article About Elasticsearch");
|
||||||
article.setAuthors(asList(johnSmith));
|
article.setAuthors(asList(johnSmith));
|
||||||
article.setTags("elasticsearch", "spring data");
|
article.setTags("elasticsearch", "spring data");
|
||||||
articleService.save(article);
|
articleRepository.save(article);
|
||||||
|
|
||||||
article = new Article("Elasticsearch Tutorial");
|
article = new Article("Elasticsearch Tutorial");
|
||||||
article.setAuthors(asList(johnDoe));
|
article.setAuthors(asList(johnDoe));
|
||||||
article.setTags("elasticsearch");
|
article.setTags("elasticsearch");
|
||||||
articleService.save(article);
|
articleRepository.save(article);
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void after() {
|
||||||
|
articleRepository.deleteAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -81,82 +84,85 @@ public class ElasticSearchManualTest {
|
||||||
Article article = new Article("Making Search Elastic");
|
Article article = new Article("Making Search Elastic");
|
||||||
article.setAuthors(authors);
|
article.setAuthors(authors);
|
||||||
|
|
||||||
article = articleService.save(article);
|
article = articleRepository.save(article);
|
||||||
assertNotNull(article.getId());
|
assertNotNull(article.getId());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPersistedArticles_whenSearchByAuthorsName_thenRightFound() {
|
public void givenPersistedArticles_whenSearchByAuthorsName_thenRightFound() {
|
||||||
|
final Page<Article> articleByAuthorName = articleRepository.findByAuthorsName(johnSmith.getName(), PageRequest.of(0, 10));
|
||||||
final Page<Article> articleByAuthorName = articleService
|
|
||||||
.findByAuthorName(johnSmith.getName(), PageRequest.of(0, 10));
|
|
||||||
assertEquals(2L, articleByAuthorName.getTotalElements());
|
assertEquals(2L, articleByAuthorName.getTotalElements());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenCustomQuery_whenSearchByAuthorsName_thenArticleIsFound() {
|
public void givenCustomQuery_whenSearchByAuthorsName_thenArticleIsFound() {
|
||||||
final Page<Article> articleByAuthorName = articleService.findByAuthorNameUsingCustomQuery("Smith", PageRequest.of(0, 10));
|
final Page<Article> articleByAuthorName = articleRepository.findByAuthorsNameUsingCustomQuery("Smith", PageRequest.of(0, 10));
|
||||||
assertEquals(2L, articleByAuthorName.getTotalElements());
|
assertEquals(2L, articleByAuthorName.getTotalElements());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenTagFilterQuery_whenSearchByTag_thenArticleIsFound() {
|
public void givenTagFilterQuery_whenSearchByTag_thenArticleIsFound() {
|
||||||
final Page<Article> articleByAuthorName = articleService.findByFilteredTagQuery("elasticsearch", PageRequest.of(0, 10));
|
final Page<Article> articleByAuthorName = articleRepository.findByFilteredTagQuery("elasticsearch", PageRequest.of(0, 10));
|
||||||
assertEquals(3L, articleByAuthorName.getTotalElements());
|
assertEquals(3L, articleByAuthorName.getTotalElements());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenTagFilterQuery_whenSearchByAuthorsName_thenArticleIsFound() {
|
public void givenTagFilterQuery_whenSearchByAuthorsName_thenArticleIsFound() {
|
||||||
final Page<Article> articleByAuthorName = articleService.findByAuthorsNameAndFilteredTagQuery("Doe", "elasticsearch", PageRequest.of(0, 10));
|
final Page<Article> articleByAuthorName = articleRepository.findByAuthorsNameAndFilteredTagQuery("Doe", "elasticsearch", PageRequest.of(0, 10));
|
||||||
assertEquals(2L, articleByAuthorName.getTotalElements());
|
assertEquals(2L, articleByAuthorName.getTotalElements());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPersistedArticles_whenUseRegexQuery_thenRightArticlesFound() {
|
public void givenPersistedArticles_whenUseRegexQuery_thenRightArticlesFound() {
|
||||||
|
final Query searchQuery = new NativeSearchQueryBuilder().withFilter(regexpQuery("title", ".*data.*"))
|
||||||
|
.build();
|
||||||
|
|
||||||
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withFilter(regexpQuery("title", ".*data.*"))
|
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
|
||||||
.build();
|
|
||||||
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
|
||||||
|
|
||||||
assertEquals(1, articles.size());
|
assertEquals(1, articles.getTotalHits());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenSavedDoc_whenTitleUpdated_thenCouldFindByUpdatedTitle() {
|
public void givenSavedDoc_whenTitleUpdated_thenCouldFindByUpdatedTitle() {
|
||||||
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(fuzzyQuery("title", "serch")).build();
|
final Query searchQuery = new NativeSearchQueryBuilder().withQuery(fuzzyQuery("title", "serch"))
|
||||||
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
.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";
|
final String newTitle = "Getting started with Search Engines";
|
||||||
article.setTitle(newTitle);
|
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
|
@Test
|
||||||
public void givenSavedDoc_whenDelete_thenRemovedFromIndex() {
|
public void givenSavedDoc_whenDelete_thenRemovedFromIndex() {
|
||||||
|
|
||||||
final String articleTitle = "Spring Data Elasticsearch";
|
final String articleTitle = "Spring Data Elasticsearch";
|
||||||
|
|
||||||
final SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
final Query searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", articleTitle).minimumShouldMatch("75%"))
|
||||||
.withQuery(matchQuery("title", articleTitle).minimumShouldMatch("75%")).build();
|
.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());
|
|
||||||
final long count = articleService.count();
|
|
||||||
|
|
||||||
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
|
@Test
|
||||||
public void givenSavedDoc_whenOneTermMatches_thenFindByTitle() {
|
public void givenSavedDoc_whenOneTermMatches_thenFindByTitle() {
|
||||||
final SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
final Query searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Search engines").operator(AND))
|
||||||
.withQuery(matchQuery("title", "Search engines").operator(AND)).build();
|
.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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,7 +2,6 @@ package com.baeldung.spring.data.es;
|
||||||
|
|
||||||
import static java.util.Arrays.asList;
|
import static java.util.Arrays.asList;
|
||||||
import static java.util.stream.Collectors.toList;
|
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.boolQuery;
|
||||||
import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;
|
import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;
|
||||||
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
|
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.List;
|
||||||
import java.util.Map;
|
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.apache.lucene.search.join.ScoreMode;
|
||||||
|
import org.elasticsearch.action.search.SearchRequest;
|
||||||
import org.elasticsearch.action.search.SearchResponse;
|
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.common.unit.Fuzziness;
|
||||||
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
|
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
|
||||||
|
import org.elasticsearch.index.query.Operator;
|
||||||
import org.elasticsearch.index.query.QueryBuilder;
|
import org.elasticsearch.index.query.QueryBuilder;
|
||||||
import org.elasticsearch.search.aggregations.Aggregation;
|
import org.elasticsearch.search.aggregations.Aggregation;
|
||||||
import org.elasticsearch.search.aggregations.AggregationBuilders;
|
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.MultiBucketsAggregation;
|
||||||
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
|
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
|
||||||
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
|
|
||||||
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
|
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.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
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.NativeSearchQueryBuilder;
|
||||||
import org.springframework.data.elasticsearch.core.query.SearchQuery;
|
|
||||||
import org.springframework.test.context.ContextConfiguration;
|
import org.springframework.test.context.ContextConfiguration;
|
||||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||||
|
|
||||||
import 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:
|
* The following docker command can be used: docker run -d --name es762 -p
|
||||||
* * Elasticsearch instance running on host
|
* 9200:9200 -e "discovery.type=single-node" elasticsearch:7.6.2
|
||||||
* * with cluster name = elasticsearch
|
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@ContextConfiguration(classes = Config.class)
|
@ContextConfiguration(classes = Config.class)
|
||||||
public class ElasticSearchQueryManualTest {
|
public class ElasticSearchQueryManualTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private ElasticsearchTemplate elasticsearchTemplate;
|
private ElasticsearchRestTemplate elasticsearchTemplate;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private ArticleService articleService;
|
private ArticleRepository articleRepository;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private Client client;
|
private RestHighLevelClient client;
|
||||||
|
|
||||||
private final Author johnSmith = new Author("John Smith");
|
private final Author johnSmith = new Author("John Smith");
|
||||||
private final Author johnDoe = new Author("John Doe");
|
private final Author johnDoe = new Author("John Doe");
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void 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 article = new Article("Spring Data Elasticsearch");
|
||||||
article.setAuthors(asList(johnSmith, johnDoe));
|
article.setAuthors(asList(johnSmith, johnDoe));
|
||||||
article.setTags("elasticsearch", "spring data");
|
article.setTags("elasticsearch", "spring data");
|
||||||
articleService.save(article);
|
articleRepository.save(article);
|
||||||
|
|
||||||
article = new Article("Search engines");
|
article = new Article("Search engines");
|
||||||
article.setAuthors(asList(johnDoe));
|
article.setAuthors(asList(johnDoe));
|
||||||
article.setTags("search engines", "tutorial");
|
article.setTags("search engines", "tutorial");
|
||||||
articleService.save(article);
|
articleRepository.save(article);
|
||||||
|
|
||||||
article = new Article("Second Article About Elasticsearch");
|
article = new Article("Second Article About Elasticsearch");
|
||||||
article.setAuthors(asList(johnSmith));
|
article.setAuthors(asList(johnSmith));
|
||||||
article.setTags("elasticsearch", "spring data");
|
article.setTags("elasticsearch", "spring data");
|
||||||
articleService.save(article);
|
articleRepository.save(article);
|
||||||
|
|
||||||
article = new Article("Elasticsearch Tutorial");
|
article = new Article("Elasticsearch Tutorial");
|
||||||
article.setAuthors(asList(johnDoe));
|
article.setAuthors(asList(johnDoe));
|
||||||
article.setTags("elasticsearch");
|
article.setTags("elasticsearch");
|
||||||
articleService.save(article);
|
articleRepository.save(article);
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void after() {
|
||||||
|
articleRepository.deleteAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenFullTitle_whenRunMatchQuery_thenDocIsFound() {
|
public void givenFullTitle_whenRunMatchQuery_thenDocIsFound() {
|
||||||
final SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Search engines").operator(Operator.AND))
|
||||||
.withQuery(matchQuery("title", "Search engines").operator(AND)).build();
|
.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
|
@Test
|
||||||
public void givenOneTermFromTitle_whenRunMatchQuery_thenDocIsFound() {
|
public void givenOneTermFromTitle_whenRunMatchQuery_thenDocIsFound() {
|
||||||
final SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Engines Solutions"))
|
||||||
.withQuery(matchQuery("title", "Engines Solutions")).build();
|
.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("Search engines", articles.get(0).getTitle());
|
|
||||||
|
assertEquals(1, articles.getTotalHits());
|
||||||
|
assertEquals("Search engines", articles.getSearchHit(0)
|
||||||
|
.getContent()
|
||||||
|
.getTitle());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPartTitle_whenRunMatchQuery_thenDocIsFound() {
|
public void givenPartTitle_whenRunMatchQuery_thenDocIsFound() {
|
||||||
final SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "elasticsearch data"))
|
||||||
.withQuery(matchQuery("title", "elasticsearch data")).build();
|
.build();
|
||||||
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
|
||||||
assertEquals(3, articles.size());
|
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
|
||||||
|
|
||||||
|
assertEquals(3, articles.getTotalHits());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenFullTitle_whenRunMatchQueryOnVerbatimField_thenDocIsFound() {
|
public void givenFullTitle_whenRunMatchQueryOnVerbatimField_thenDocIsFound() {
|
||||||
SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title.verbatim", "Second Article About Elasticsearch"))
|
||||||
.withQuery(matchQuery("title.verbatim", "Second Article About Elasticsearch")).build();
|
.build();
|
||||||
List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
|
||||||
assertEquals(1, articles.size());
|
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"))
|
searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title.verbatim", "Second Article About"))
|
||||||
.build();
|
.build();
|
||||||
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
|
||||||
assertEquals(0, articles.size());
|
articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
|
||||||
|
assertEquals(0, articles.getTotalHits());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenNestedObject_whenQueryByAuthorsName_thenFoundArticlesByThatAuthor() {
|
public void givenNestedObject_whenQueryByAuthorsName_thenFoundArticlesByThatAuthor() {
|
||||||
final QueryBuilder builder = nestedQuery("authors", boolQuery().must(termQuery("authors.name", "smith")), ScoreMode.None);
|
final QueryBuilder builder = nestedQuery("authors", boolQuery().must(termQuery("authors.name", "smith")), ScoreMode.None);
|
||||||
|
|
||||||
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
|
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder)
|
||||||
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
.build();
|
||||||
|
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
|
||||||
|
|
||||||
assertEquals(2, articles.size());
|
assertEquals(2, articles.getTotalHits());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTokenCountsSeparately() {
|
public void givenAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTokenCountsSeparately() throws Exception {
|
||||||
final TermsAggregationBuilder aggregation = AggregationBuilders.terms("top_tags").field("title");
|
final TermsAggregationBuilder aggregation = AggregationBuilders.terms("top_tags")
|
||||||
final SearchResponse response = client.prepareSearch("blog").setTypes("article").addAggregation(aggregation)
|
.field("title");
|
||||||
.execute().actionGet();
|
|
||||||
|
|
||||||
final Map<String, Aggregation> results = response.getAggregations().asMap();
|
final SearchSourceBuilder builder = new SearchSourceBuilder().aggregation(aggregation);
|
||||||
final StringTerms topTags = (StringTerms) results.get("top_tags");
|
final SearchRequest searchRequest = new SearchRequest("blog").source(builder);
|
||||||
|
|
||||||
final List<String> keys = topTags.getBuckets().stream()
|
final SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
|
||||||
.map(MultiBucketsAggregation.Bucket::getKeyAsString)
|
|
||||||
.sorted()
|
final Map<String, Aggregation> results = response.getAggregations()
|
||||||
.collect(toList());
|
.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);
|
assertEquals(asList("about", "article", "data", "elasticsearch", "engines", "search", "second", "spring", "tutorial"), keys);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenNotAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTermCountsIndividually() {
|
public void givenNotAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTermCountsIndividually() throws Exception {
|
||||||
final TermsAggregationBuilder aggregation = AggregationBuilders.terms("top_tags").field("tags")
|
final TermsAggregationBuilder aggregation = AggregationBuilders.terms("top_tags")
|
||||||
.order(Terms.Order.count(false));
|
.field("tags")
|
||||||
final SearchResponse response = client.prepareSearch("blog").setTypes("article").addAggregation(aggregation)
|
.order(BucketOrder.count(false));
|
||||||
.execute().actionGet();
|
|
||||||
|
|
||||||
final Map<String, Aggregation> results = response.getAggregations().asMap();
|
final SearchSourceBuilder builder = new SearchSourceBuilder().aggregation(aggregation);
|
||||||
final StringTerms topTags = (StringTerms) results.get("top_tags");
|
final SearchRequest searchRequest = new SearchRequest().indices("blog")
|
||||||
|
.source(builder);
|
||||||
|
|
||||||
final List<String> keys = topTags.getBuckets().stream()
|
final SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
|
||||||
.map(MultiBucketsAggregation.Bucket::getKeyAsString)
|
|
||||||
.collect(toList());
|
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);
|
assertEquals(asList("elasticsearch", "spring data", "search engines", "tutorial"), keys);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenNotExactPhrase_whenUseSlop_thenQueryMatches() {
|
public void givenNotExactPhrase_whenUseSlop_thenQueryMatches() {
|
||||||
final SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchPhraseQuery("title", "spring elasticsearch").slop(1))
|
||||||
.withQuery(matchPhraseQuery("title", "spring elasticsearch").slop(1)).build();
|
.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
|
@Test
|
||||||
public void givenPhraseWithType_whenUseFuzziness_thenQueryMatches() {
|
public void givenPhraseWithType_whenUseFuzziness_thenQueryMatches() {
|
||||||
final SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "spring date elasticserch").operator(Operator.AND)
|
||||||
.withQuery(matchQuery("title", "spring date elasticserch").operator(AND).fuzziness(Fuzziness.ONE)
|
.fuzziness(Fuzziness.ONE)
|
||||||
.prefixLength(3)).build();
|
.prefixLength(3))
|
||||||
|
.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
|
@Test
|
||||||
public void givenMultimatchQuery_whenDoSearch_thenAllProvidedFieldsMatch() {
|
public void givenMultimatchQuery_whenDoSearch_thenAllProvidedFieldsMatch() {
|
||||||
final SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(multiMatchQuery("tutorial").field("title")
|
||||||
.withQuery(multiMatchQuery("tutorial").field("title").field("tags")
|
.field("tags")
|
||||||
.type(MultiMatchQueryBuilder.Type.BEST_FIELDS)).build();
|
.type(MultiMatchQueryBuilder.Type.BEST_FIELDS))
|
||||||
|
.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());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -205,10 +239,10 @@ public class ElasticSearchQueryManualTest {
|
||||||
final QueryBuilder builder = boolQuery().must(nestedQuery("authors", boolQuery().must(termQuery("authors.name", "doe")), ScoreMode.None))
|
final QueryBuilder builder = boolQuery().must(nestedQuery("authors", boolQuery().must(termQuery("authors.name", "doe")), ScoreMode.None))
|
||||||
.filter(termQuery("tags", "elasticsearch"));
|
.filter(termQuery("tags", "elasticsearch"));
|
||||||
|
|
||||||
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder)
|
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder)
|
||||||
.build();
|
.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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?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"
|
<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">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>spring-data-jpa-5</artifactId>
|
<artifactId>spring-data-jpa-5</artifactId>
|
||||||
<name>spring-data-jpa-5</name>
|
<name>spring-data-jpa-5</name>
|
||||||
|
@ -11,7 +12,7 @@
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<relativePath>../../parent-boot-2</relativePath>
|
<relativePath>../../parent-boot-2</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
@ -28,10 +29,43 @@
|
||||||
<artifactId>spring-boot-starter-data-jdbc</artifactId>
|
<artifactId>spring-boot-starter-data-jdbc</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-cache</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.h2database</groupId>
|
<groupId>com.h2database</groupId>
|
||||||
<artifactId>h2</artifactId>
|
<artifactId>h2</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.mapstruct</groupId>
|
||||||
|
<artifactId>mapstruct-jdk8</artifactId>
|
||||||
|
<version>1.3.1.Final</version>
|
||||||
|
<scope>provided</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</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>
|
||||||
|
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
|
@ -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));
|
||||||
|
}
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
|
@ -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());
|
||||||
|
}
|
||||||
|
}
|
|
@ -4,7 +4,6 @@
|
||||||
- [Introduction to Spring Data Redis](https://www.baeldung.com/spring-data-redis-tutorial)
|
- [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)
|
- [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)
|
- [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
|
### Build the Project with Tests Running
|
||||||
```
|
```
|
||||||
|
@ -15,4 +14,3 @@ mvn clean install
|
||||||
```
|
```
|
||||||
mvn test
|
mvn test
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
|
@ -35,18 +35,6 @@ public class RedisConfig {
|
||||||
template.setValueSerializer(new GenericToStringSerializer<Object>(Object.class));
|
template.setValueSerializer(new GenericToStringSerializer<Object>(Object.class));
|
||||||
return template;
|
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
|
@Bean
|
||||||
MessageListenerAdapter messageListener() {
|
MessageListenerAdapter messageListener() {
|
||||||
|
|
|
@ -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();
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
2
pom.xml
2
pom.xml
|
@ -513,6 +513,7 @@
|
||||||
<module>libraries-rpc</module>
|
<module>libraries-rpc</module>
|
||||||
<module>libraries-security</module>
|
<module>libraries-security</module>
|
||||||
<module>libraries-server</module>
|
<module>libraries-server</module>
|
||||||
|
<module>libraries-server-2</module>
|
||||||
<module>libraries-testing</module>
|
<module>libraries-testing</module>
|
||||||
<module>linkrest</module>
|
<module>linkrest</module>
|
||||||
<module>logging-modules</module>
|
<module>logging-modules</module>
|
||||||
|
@ -1032,6 +1033,7 @@
|
||||||
<module>libraries-primitive</module>
|
<module>libraries-primitive</module>
|
||||||
<module>libraries-security</module>
|
<module>libraries-security</module>
|
||||||
<module>libraries-server</module>
|
<module>libraries-server</module>
|
||||||
|
<module>libraries-server-2</module>
|
||||||
<module>libraries-testing</module>
|
<module>libraries-testing</module>
|
||||||
<module>linkrest</module>
|
<module>linkrest</module>
|
||||||
<module>logging-modules</module>
|
<module>logging-modules</module>
|
||||||
|
|
|
@ -15,6 +15,7 @@
|
||||||
|
|
||||||
<modules>
|
<modules>
|
||||||
<module>spring-boot</module>
|
<module>spring-boot</module>
|
||||||
|
<module>spring-boot-1</module>
|
||||||
<module>spring-boot-admin</module>
|
<module>spring-boot-admin</module>
|
||||||
<module>spring-boot-angular</module>
|
<module>spring-boot-angular</module>
|
||||||
<module>spring-boot-annotations</module>
|
<module>spring-boot-annotations</module>
|
||||||
|
|
|
@ -0,0 +1 @@
|
||||||
|
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip
|
|
@ -0,0 +1,6 @@
|
||||||
|
## Spring Boot 1.x Actuator
|
||||||
|
|
||||||
|
This module contains articles about Spring Boot Actuator in Spring Boot version 1.x.
|
||||||
|
|
||||||
|
## Relevant articles:
|
||||||
|
- [Spring Boot Actuator](https://www.baeldung.com/spring-boot-actuators)
|
|
@ -0,0 +1,234 @@
|
||||||
|
#!/bin/sh
|
||||||
|
# ----------------------------------------------------------------------------
|
||||||
|
# Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
# or more contributor license agreements. See the NOTICE file
|
||||||
|
# distributed with this work for additional information
|
||||||
|
# regarding copyright ownership. The ASF licenses this file
|
||||||
|
# to you under the Apache License, Version 2.0 (the
|
||||||
|
# "License"); you may not use this file except in compliance
|
||||||
|
# with the License. You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing,
|
||||||
|
# software distributed under the License is distributed on an
|
||||||
|
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
# KIND, either express or implied. See the License for the
|
||||||
|
# specific language governing permissions and limitations
|
||||||
|
# under the License.
|
||||||
|
# ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------------------
|
||||||
|
# Maven2 Start Up Batch script
|
||||||
|
#
|
||||||
|
# Required ENV vars:
|
||||||
|
# ------------------
|
||||||
|
# JAVA_HOME - location of a JDK home dir
|
||||||
|
#
|
||||||
|
# Optional ENV vars
|
||||||
|
# -----------------
|
||||||
|
# M2_HOME - location of maven2's installed home dir
|
||||||
|
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||||
|
# e.g. to debug Maven itself, use
|
||||||
|
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||||
|
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||||
|
# ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
if [ -z "$MAVEN_SKIP_RC" ]; then
|
||||||
|
|
||||||
|
if [ -f /etc/mavenrc ]; then
|
||||||
|
. /etc/mavenrc
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -f "$HOME/.mavenrc" ]; then
|
||||||
|
. "$HOME/.mavenrc"
|
||||||
|
fi
|
||||||
|
|
||||||
|
fi
|
||||||
|
|
||||||
|
# OS specific support. $var _must_ be set to either true or false.
|
||||||
|
cygwin=false
|
||||||
|
darwin=false
|
||||||
|
mingw=false
|
||||||
|
case "$(uname)" in
|
||||||
|
CYGWIN*) cygwin=true ;;
|
||||||
|
MINGW*) mingw=true ;;
|
||||||
|
Darwin*)
|
||||||
|
darwin=true
|
||||||
|
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
|
||||||
|
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
|
||||||
|
if [ -z "$JAVA_HOME" ]; then
|
||||||
|
if [ -x "/usr/libexec/java_home" ]; then
|
||||||
|
export JAVA_HOME="$(/usr/libexec/java_home)"
|
||||||
|
else
|
||||||
|
export JAVA_HOME="/Library/Java/Home"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [ -z "$JAVA_HOME" ]; then
|
||||||
|
if [ -r /etc/gentoo-release ]; then
|
||||||
|
JAVA_HOME=$(java-config --jre-home)
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -z "$M2_HOME" ]; then
|
||||||
|
## resolve links - $0 may be a link to maven's home
|
||||||
|
PRG="$0"
|
||||||
|
|
||||||
|
# need this for relative symlinks
|
||||||
|
while [ -h "$PRG" ]; do
|
||||||
|
ls=$(ls -ld "$PRG")
|
||||||
|
link=$(expr "$ls" : '.*-> \(.*\)$')
|
||||||
|
if expr "$link" : '/.*' >/dev/null; then
|
||||||
|
PRG="$link"
|
||||||
|
else
|
||||||
|
PRG="$(dirname "$PRG")/$link"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
saveddir=$(pwd)
|
||||||
|
|
||||||
|
M2_HOME=$(dirname "$PRG")/..
|
||||||
|
|
||||||
|
# make it fully qualified
|
||||||
|
M2_HOME=$(cd "$M2_HOME" && pwd)
|
||||||
|
|
||||||
|
cd "$saveddir"
|
||||||
|
# echo Using m2 at $M2_HOME
|
||||||
|
fi
|
||||||
|
|
||||||
|
# For Cygwin, ensure paths are in UNIX format before anything is touched
|
||||||
|
if $cygwin; then
|
||||||
|
[ -n "$M2_HOME" ] &&
|
||||||
|
M2_HOME=$(cygpath --unix "$M2_HOME")
|
||||||
|
[ -n "$JAVA_HOME" ] &&
|
||||||
|
JAVA_HOME=$(cygpath --unix "$JAVA_HOME")
|
||||||
|
[ -n "$CLASSPATH" ] &&
|
||||||
|
CLASSPATH=$(cygpath --path --unix "$CLASSPATH")
|
||||||
|
fi
|
||||||
|
|
||||||
|
# For Migwn, ensure paths are in UNIX format before anything is touched
|
||||||
|
if $mingw; then
|
||||||
|
[ -n "$M2_HOME" ] &&
|
||||||
|
M2_HOME="$( (
|
||||||
|
cd "$M2_HOME"
|
||||||
|
pwd
|
||||||
|
))"
|
||||||
|
[ -n "$JAVA_HOME" ] &&
|
||||||
|
JAVA_HOME="$( (
|
||||||
|
cd "$JAVA_HOME"
|
||||||
|
pwd
|
||||||
|
))"
|
||||||
|
# TODO classpath?
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -z "$JAVA_HOME" ]; then
|
||||||
|
javaExecutable="$(which javac)"
|
||||||
|
if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then
|
||||||
|
# readlink(1) is not available as standard on Solaris 10.
|
||||||
|
readLink=$(which readlink)
|
||||||
|
if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then
|
||||||
|
if $darwin; then
|
||||||
|
javaHome="$(dirname \"$javaExecutable\")"
|
||||||
|
javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac"
|
||||||
|
else
|
||||||
|
javaExecutable="$(readlink -f \"$javaExecutable\")"
|
||||||
|
fi
|
||||||
|
javaHome="$(dirname \"$javaExecutable\")"
|
||||||
|
javaHome=$(expr "$javaHome" : '\(.*\)/bin')
|
||||||
|
JAVA_HOME="$javaHome"
|
||||||
|
export JAVA_HOME
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -z "$JAVACMD" ]; then
|
||||||
|
if [ -n "$JAVA_HOME" ]; then
|
||||||
|
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
|
||||||
|
# IBM's JDK on AIX uses strange locations for the executables
|
||||||
|
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||||
|
else
|
||||||
|
JAVACMD="$JAVA_HOME/bin/java"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
JAVACMD="$(which java)"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ ! -x "$JAVACMD" ]; then
|
||||||
|
echo "Error: JAVA_HOME is not defined correctly." >&2
|
||||||
|
echo " We cannot execute $JAVACMD" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -z "$JAVA_HOME" ]; then
|
||||||
|
echo "Warning: JAVA_HOME environment variable is not set."
|
||||||
|
fi
|
||||||
|
|
||||||
|
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
|
||||||
|
|
||||||
|
# traverses directory structure from process work directory to filesystem root
|
||||||
|
# first directory with .mvn subdirectory is considered project base directory
|
||||||
|
find_maven_basedir() {
|
||||||
|
|
||||||
|
if [ -z "$1" ]; then
|
||||||
|
echo "Path not specified to find_maven_basedir"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
basedir="$1"
|
||||||
|
wdir="$1"
|
||||||
|
while [ "$wdir" != '/' ]; do
|
||||||
|
if [ -d "$wdir"/.mvn ]; then
|
||||||
|
basedir=$wdir
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
|
||||||
|
if [ -d "${wdir}" ]; then
|
||||||
|
wdir=$(
|
||||||
|
cd "$wdir/.."
|
||||||
|
pwd
|
||||||
|
)
|
||||||
|
fi
|
||||||
|
# end of workaround
|
||||||
|
done
|
||||||
|
echo "${basedir}"
|
||||||
|
}
|
||||||
|
|
||||||
|
# concatenates all lines of a file
|
||||||
|
concat_lines() {
|
||||||
|
if [ -f "$1" ]; then
|
||||||
|
echo "$(tr -s '\n' ' ' <"$1")"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
BASE_DIR=$(find_maven_basedir "$(pwd)")
|
||||||
|
if [ -z "$BASE_DIR" ]; then
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
|
||||||
|
echo $MAVEN_PROJECTBASEDIR
|
||||||
|
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
|
||||||
|
|
||||||
|
# For Cygwin, switch paths to Windows format before running java
|
||||||
|
if $cygwin; then
|
||||||
|
[ -n "$M2_HOME" ] &&
|
||||||
|
M2_HOME=$(cygpath --path --windows "$M2_HOME")
|
||||||
|
[ -n "$JAVA_HOME" ] &&
|
||||||
|
JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME")
|
||||||
|
[ -n "$CLASSPATH" ] &&
|
||||||
|
CLASSPATH=$(cygpath --path --windows "$CLASSPATH")
|
||||||
|
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
|
||||||
|
MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR")
|
||||||
|
fi
|
||||||
|
|
||||||
|
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||||
|
|
||||||
|
exec "$JAVACMD" \
|
||||||
|
$MAVEN_OPTS \
|
||||||
|
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
|
||||||
|
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
|
||||||
|
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
|
|
@ -0,0 +1,143 @@
|
||||||
|
@REM ----------------------------------------------------------------------------
|
||||||
|
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
@REM or more contributor license agreements. See the NOTICE file
|
||||||
|
@REM distributed with this work for additional information
|
||||||
|
@REM regarding copyright ownership. The ASF licenses this file
|
||||||
|
@REM to you under the Apache License, Version 2.0 (the
|
||||||
|
@REM "License"); you may not use this file except in compliance
|
||||||
|
@REM with the License. You may obtain a copy of the License at
|
||||||
|
@REM
|
||||||
|
@REM http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
@REM
|
||||||
|
@REM Unless required by applicable law or agreed to in writing,
|
||||||
|
@REM software distributed under the License is distributed on an
|
||||||
|
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
@REM KIND, either express or implied. See the License for the
|
||||||
|
@REM specific language governing permissions and limitations
|
||||||
|
@REM under the License.
|
||||||
|
@REM ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@REM ----------------------------------------------------------------------------
|
||||||
|
@REM Maven2 Start Up Batch script
|
||||||
|
@REM
|
||||||
|
@REM Required ENV vars:
|
||||||
|
@REM JAVA_HOME - location of a JDK home dir
|
||||||
|
@REM
|
||||||
|
@REM Optional ENV vars
|
||||||
|
@REM M2_HOME - location of maven2's installed home dir
|
||||||
|
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
|
||||||
|
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
|
||||||
|
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||||
|
@REM e.g. to debug Maven itself, use
|
||||||
|
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||||
|
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||||
|
@REM ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
|
||||||
|
@echo off
|
||||||
|
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
|
||||||
|
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
|
||||||
|
|
||||||
|
@REM set %HOME% to equivalent of $HOME
|
||||||
|
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
|
||||||
|
|
||||||
|
@REM Execute a user defined script before this one
|
||||||
|
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
|
||||||
|
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
|
||||||
|
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
|
||||||
|
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
|
||||||
|
:skipRcPre
|
||||||
|
|
||||||
|
@setlocal
|
||||||
|
|
||||||
|
set ERROR_CODE=0
|
||||||
|
|
||||||
|
@REM To isolate internal variables from possible post scripts, we use another setlocal
|
||||||
|
@setlocal
|
||||||
|
|
||||||
|
@REM ==== START VALIDATION ====
|
||||||
|
if not "%JAVA_HOME%" == "" goto OkJHome
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo Error: JAVA_HOME not found in your environment. >&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||||
|
echo location of your Java installation. >&2
|
||||||
|
echo.
|
||||||
|
goto error
|
||||||
|
|
||||||
|
:OkJHome
|
||||||
|
if exist "%JAVA_HOME%\bin\java.exe" goto init
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo Error: JAVA_HOME is set to an invalid directory. >&2
|
||||||
|
echo JAVA_HOME = "%JAVA_HOME%" >&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||||
|
echo location of your Java installation. >&2
|
||||||
|
echo.
|
||||||
|
goto error
|
||||||
|
|
||||||
|
@REM ==== END VALIDATION ====
|
||||||
|
|
||||||
|
:init
|
||||||
|
|
||||||
|
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
|
||||||
|
@REM Fallback to current working directory if not found.
|
||||||
|
|
||||||
|
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
|
||||||
|
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
|
||||||
|
|
||||||
|
set EXEC_DIR=%CD%
|
||||||
|
set WDIR=%EXEC_DIR%
|
||||||
|
:findBaseDir
|
||||||
|
IF EXIST "%WDIR%"\.mvn goto baseDirFound
|
||||||
|
cd ..
|
||||||
|
IF "%WDIR%"=="%CD%" goto baseDirNotFound
|
||||||
|
set WDIR=%CD%
|
||||||
|
goto findBaseDir
|
||||||
|
|
||||||
|
:baseDirFound
|
||||||
|
set MAVEN_PROJECTBASEDIR=%WDIR%
|
||||||
|
cd "%EXEC_DIR%"
|
||||||
|
goto endDetectBaseDir
|
||||||
|
|
||||||
|
:baseDirNotFound
|
||||||
|
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
|
||||||
|
cd "%EXEC_DIR%"
|
||||||
|
|
||||||
|
:endDetectBaseDir
|
||||||
|
|
||||||
|
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
|
||||||
|
|
||||||
|
@setlocal EnableExtensions EnableDelayedExpansion
|
||||||
|
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
|
||||||
|
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
|
||||||
|
|
||||||
|
:endReadAdditionalConfig
|
||||||
|
|
||||||
|
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
|
||||||
|
|
||||||
|
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
|
||||||
|
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||||
|
|
||||||
|
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
|
||||||
|
if ERRORLEVEL 1 goto error
|
||||||
|
goto end
|
||||||
|
|
||||||
|
:error
|
||||||
|
set ERROR_CODE=1
|
||||||
|
|
||||||
|
:end
|
||||||
|
@endlocal & set ERROR_CODE=%ERROR_CODE%
|
||||||
|
|
||||||
|
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
|
||||||
|
@REM check for post script, once with legacy .bat ending and once with .cmd ending
|
||||||
|
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
|
||||||
|
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
|
||||||
|
:skipRcPost
|
||||||
|
|
||||||
|
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
|
||||||
|
if "%MAVEN_BATCH_PAUSE%" == "on" pause
|
||||||
|
|
||||||
|
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
|
||||||
|
|
||||||
|
exit /B %ERROR_CODE%
|
|
@ -0,0 +1,45 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<artifactId>spring-boot-1</artifactId>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
<description>Module for Spring Boot version 1.x</description>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-boot-1</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../../parent-boot-1</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
</project>
|
|
@ -0,0 +1,35 @@
|
||||||
|
package com.baeldung.actuator;
|
||||||
|
|
||||||
|
import org.springframework.boot.actuate.endpoint.Endpoint;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class CustomEndpoint implements Endpoint<List<String>> {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getId() {
|
||||||
|
return "customEndpoint";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isEnabled() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isSensitive() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<String> invoke() {
|
||||||
|
// Custom logic to build the output
|
||||||
|
List<String> messages = new ArrayList<>();
|
||||||
|
messages.add("This is message 1");
|
||||||
|
messages.add("This is message 2");
|
||||||
|
return messages;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,23 @@
|
||||||
|
package com.baeldung.actuator;
|
||||||
|
|
||||||
|
import org.springframework.boot.actuate.health.Health;
|
||||||
|
import org.springframework.boot.actuate.health.HealthIndicator;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Component("myHealthCheck")
|
||||||
|
public class HealthCheck implements HealthIndicator {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Health health() {
|
||||||
|
int errorCode = check(); // perform some specific health check
|
||||||
|
if (errorCode != 0) {
|
||||||
|
return Health.down().withDetail("Error Code", errorCode).build();
|
||||||
|
}
|
||||||
|
return Health.up().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
public int check() {
|
||||||
|
// Our logic to check health
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
package com.baeldung.actuator;
|
||||||
|
|
||||||
|
import org.springframework.boot.actuate.metrics.CounterService;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class LoginServiceImpl {
|
||||||
|
|
||||||
|
private final CounterService counterService;
|
||||||
|
|
||||||
|
public LoginServiceImpl(CounterService counterService) {
|
||||||
|
this.counterService = counterService;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean login(String userName, char[] password) {
|
||||||
|
boolean success;
|
||||||
|
if (userName.equals("admin") && Arrays.equals("secret".toCharArray(), password)) {
|
||||||
|
counterService.increment("counter.login.success");
|
||||||
|
success = true;
|
||||||
|
} else {
|
||||||
|
counterService.increment("counter.login.failure");
|
||||||
|
success = false;
|
||||||
|
}
|
||||||
|
return success;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,13 @@
|
||||||
|
package com.baeldung.actuator;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
public class SpringBoot {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(SpringBoot.class, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,19 @@
|
||||||
|
### server port
|
||||||
|
server.port=8080
|
||||||
|
#port used to expose actuator
|
||||||
|
management.port=8081
|
||||||
|
#CIDR allowed to hit actuator
|
||||||
|
management.address=127.0.0.1
|
||||||
|
# Actuator Configuration
|
||||||
|
# customize /beans endpoint
|
||||||
|
endpoints.beans.id=springbeans
|
||||||
|
endpoints.beans.sensitive=false
|
||||||
|
endpoints.beans.enabled=true
|
||||||
|
# for the Spring Boot version 1.5.0 and above, we have to disable security to expose the health endpoint fully for unauthorized access.
|
||||||
|
# see: https://docs.spring.io/spring-boot/docs/1.5.x/reference/html/production-ready-monitoring.html
|
||||||
|
management.security.enabled=false
|
||||||
|
endpoints.health.sensitive=false
|
||||||
|
# customize /info endpoint
|
||||||
|
info.app.name=Spring Sample Application
|
||||||
|
info.app.description=This is my first spring boot application
|
||||||
|
info.app.version=1.0.0
|
|
@ -0,0 +1,46 @@
|
||||||
|
package com.baeldung.actuator;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.type.TypeReference;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.actuate.autoconfigure.LocalManagementPort;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.hasItems;
|
||||||
|
import static org.hamcrest.CoreMatchers.is;
|
||||||
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = "management.port=0")
|
||||||
|
public class CustomEndpointIntegrationTest {
|
||||||
|
|
||||||
|
@LocalManagementPort
|
||||||
|
private int port;
|
||||||
|
|
||||||
|
private RestTemplate restTemplate = new RestTemplate();
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenSpringContextIsBootstrapped_thenActuatorCustomEndpointWorks() throws IOException {
|
||||||
|
ResponseEntity<String> entity = restTemplate.getForEntity("http://localhost:" + port + "/customEndpoint", String.class);
|
||||||
|
|
||||||
|
assertThat(entity.getStatusCode(), is(HttpStatus.OK));
|
||||||
|
|
||||||
|
List<String> response = objectMapper.readValue(entity.getBody(), new TypeReference<ArrayList<String>>() {
|
||||||
|
});
|
||||||
|
|
||||||
|
assertThat(response, hasItems("This is message 1", "This is message 2"));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,49 @@
|
||||||
|
package com.baeldung.actuator;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.type.TypeReference;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.actuate.autoconfigure.LocalManagementPort;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.is;
|
||||||
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
|
import static org.hamcrest.collection.IsMapContaining.hasEntry;
|
||||||
|
import static org.hamcrest.collection.IsMapContaining.hasKey;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = "management.port=0")
|
||||||
|
public class HealthCheckIntegrationTest {
|
||||||
|
|
||||||
|
@LocalManagementPort
|
||||||
|
private int port;
|
||||||
|
|
||||||
|
private RestTemplate restTemplate = new RestTemplate();
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenSpringContextIsBootstrapped_thenActuatorHealthEndpointWorks() throws IOException {
|
||||||
|
ResponseEntity<String> entity = restTemplate.getForEntity("http://localhost:" + port + "/health", String.class);
|
||||||
|
|
||||||
|
assertThat(entity.getStatusCode(), is(HttpStatus.OK));
|
||||||
|
|
||||||
|
Map<String, Object> response = objectMapper.readValue(entity.getBody(), new TypeReference<LinkedHashMap<String, Object>>() {
|
||||||
|
});
|
||||||
|
|
||||||
|
assertThat(response, hasEntry("status", "UP"));
|
||||||
|
assertThat(response, hasKey("myHealthCheck"));
|
||||||
|
assertThat(response, hasKey("diskSpace"));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,35 @@
|
||||||
|
package com.baeldung.actuator;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.mockito.Mockito;
|
||||||
|
import org.mockito.junit.MockitoJUnitRunner;
|
||||||
|
import org.springframework.boot.actuate.health.Health;
|
||||||
|
import org.springframework.boot.actuate.health.Status;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.is;
|
||||||
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
@RunWith(MockitoJUnitRunner.class)
|
||||||
|
public class HealthCheckUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCheckMethodReturnsZero_thenHealthMethodReturnsStatusUP() {
|
||||||
|
HealthCheck healthCheck = Mockito.spy(new HealthCheck());
|
||||||
|
when(healthCheck.check()).thenReturn(0);
|
||||||
|
Health health = healthCheck.health();
|
||||||
|
|
||||||
|
assertThat(health.getStatus(), is(Status.UP));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCheckMethodReturnsOtherThanZero_thenHealthMethodReturnsStatusDOWN() {
|
||||||
|
HealthCheck healthCheck = Mockito.spy(new HealthCheck());
|
||||||
|
when(healthCheck.check()).thenReturn(-1);
|
||||||
|
Health health = healthCheck.health();
|
||||||
|
|
||||||
|
assertThat(health.getStatus(), is(Status.DOWN));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,61 @@
|
||||||
|
package com.baeldung.actuator;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.type.TypeReference;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.actuate.autoconfigure.LocalManagementPort;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.is;
|
||||||
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
|
import static org.hamcrest.Matchers.hasEntry;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = "management.port=0")
|
||||||
|
public class LoginServiceIntegrationTest {
|
||||||
|
|
||||||
|
@LocalManagementPort
|
||||||
|
private int port;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private LoginServiceImpl loginService;
|
||||||
|
|
||||||
|
private RestTemplate restTemplate = new RestTemplate();
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenLoginIsAdmin_thenSuccessCounterIsIncremented() throws IOException {
|
||||||
|
boolean success = loginService.login("admin", "secret".toCharArray());
|
||||||
|
ResponseEntity<String> entity = restTemplate.getForEntity("http://localhost:" + port + "/metrics", String.class);
|
||||||
|
Map<String, Object> response = objectMapper.readValue(entity.getBody(), new TypeReference<HashMap<String, Object>>() {
|
||||||
|
});
|
||||||
|
|
||||||
|
assertThat(success, is(true));
|
||||||
|
assertThat(entity.getStatusCode(), is(HttpStatus.OK));
|
||||||
|
assertThat(response, hasEntry("counter.login.success", 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenLoginIsNotAdmin_thenFailureCounterIsIncremented() throws IOException {
|
||||||
|
boolean success = loginService.login("user", "notsecret".toCharArray());
|
||||||
|
ResponseEntity<String> entity = restTemplate.getForEntity("http://localhost:" + port + "/metrics", String.class);
|
||||||
|
Map<String, Object> response = objectMapper.readValue(entity.getBody(), new TypeReference<HashMap<String, Object>>() {
|
||||||
|
});
|
||||||
|
|
||||||
|
assertThat(success, is(false));
|
||||||
|
assertThat(entity.getStatusCode(), is(HttpStatus.OK));
|
||||||
|
assertThat(response, hasEntry("counter.login.failure", 1));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,41 @@
|
||||||
|
package com.baeldung.actuator;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.actuate.metrics.CounterService;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.is;
|
||||||
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
|
import static org.mockito.Mockito.times;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest(classes = LoginServiceImpl.class)
|
||||||
|
public class LoginServiceUnitTest {
|
||||||
|
|
||||||
|
@MockBean
|
||||||
|
CounterService counterService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
LoginServiceImpl loginService;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenLoginUserIsAdmin_thenSuccessCounterIsIncremented() {
|
||||||
|
boolean loginResult = loginService.login("admin", "secret".toCharArray());
|
||||||
|
assertThat(loginResult, is(true));
|
||||||
|
verify(counterService, times(1)).increment("counter.login.success");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenLoginUserIsNotAdmin_thenFailureCounterIsIncremented() {
|
||||||
|
boolean loginResult = loginService.login("user", "notsecret".toCharArray());
|
||||||
|
assertThat(loginResult, is(false));
|
||||||
|
verify(counterService, times(1)).increment("counter.login.failure");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -17,7 +17,7 @@ import com.baeldung.multiplecachemanager.repository.OrderDetailRepository;
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
@SpringBootTest
|
@SpringBootTest
|
||||||
public class MultipleCacheManagerIntegrationUnitTest {
|
public class MultipleCacheManagerIntegrationTest {
|
||||||
|
|
||||||
@MockBean
|
@MockBean
|
||||||
private OrderDetailRepository orderDetailRepository;
|
private OrderDetailRepository orderDetailRepository;
|
|
@ -11,9 +11,9 @@
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-boot-1</artifactId>
|
<artifactId>parent-boot-2</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<relativePath>../parent-boot-1</relativePath>
|
<relativePath>../parent-boot-2</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<modules>
|
<modules>
|
||||||
|
@ -34,7 +34,7 @@
|
||||||
</dependencyManagement>
|
</dependencyManagement>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<spring-cloud-dependencies.version>Brixton.SR7</spring-cloud-dependencies.version>
|
<spring-cloud-dependencies.version>Hoxton.SR4</spring-cloud-dependencies.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -33,6 +33,11 @@
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-actuator</artifactId>
|
<artifactId>spring-boot-actuator</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-actuator-autoconfigure</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.cloud</groupId>
|
<groupId>org.springframework.cloud</groupId>
|
||||||
|
|
|
@ -4,4 +4,14 @@ spring:
|
||||||
host: localhost
|
host: localhost
|
||||||
port: 5672
|
port: 5672
|
||||||
username: guest
|
username: guest
|
||||||
password: guest
|
password: guest
|
||||||
|
cloud:
|
||||||
|
bus:
|
||||||
|
enabled: true
|
||||||
|
refresh:
|
||||||
|
enabled: true
|
||||||
|
management:
|
||||||
|
endpoints:
|
||||||
|
web:
|
||||||
|
exposure:
|
||||||
|
include: "*"
|
|
@ -1,11 +1,8 @@
|
||||||
server.port=8888
|
server.port=8888
|
||||||
spring.cloud.config.server.git.uri=
|
spring.cloud.config.server.git.uri=
|
||||||
security.user.name=root
|
spring.cloud.bus.enabled=true
|
||||||
security.user.password=s3cr3t
|
spring.security.user.name=root
|
||||||
encrypt.key-store.location=classpath:/config-server.jks
|
spring.security.user.password=s3cr3t
|
||||||
encrypt.key-store.password=my-s70r3-s3cr3t
|
|
||||||
encrypt.key-store.alias=config-server-key
|
|
||||||
encrypt.key-store.secret=my-k34-s3cr3t
|
|
||||||
spring.rabbitmq.host=localhost
|
spring.rabbitmq.host=localhost
|
||||||
spring.rabbitmq.port=5672
|
spring.rabbitmq.port=5672
|
||||||
spring.rabbitmq.username=guest
|
spring.rabbitmq.username=guest
|
||||||
|
|
|
@ -0,0 +1,4 @@
|
||||||
|
encrypt.key-store.location=classpath:/config-server.jks
|
||||||
|
encrypt.key-store.password=my-s70r3-s3cr3t
|
||||||
|
encrypt.key-store.alias=config-server-key
|
||||||
|
encrypt.key-store.secret=my-k34-s3cr3t
|
|
@ -32,6 +32,7 @@
|
||||||
<module>spring-cloud-zuul-eureka-integration</module>
|
<module>spring-cloud-zuul-eureka-integration</module>
|
||||||
<module>spring-cloud-contract</module>
|
<module>spring-cloud-contract</module>
|
||||||
<module>spring-cloud-kubernetes</module>
|
<module>spring-cloud-kubernetes</module>
|
||||||
|
<module>spring-cloud-open-service-broker</module>
|
||||||
<module>spring-cloud-archaius</module>
|
<module>spring-cloud-archaius</module>
|
||||||
<module>spring-cloud-functions</module>
|
<module>spring-cloud-functions</module>
|
||||||
<module>spring-cloud-vault</module>
|
<module>spring-cloud-vault</module>
|
||||||
|
|
|
@ -8,10 +8,10 @@
|
||||||
<version>1.0-SNAPSHOT</version>
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung.spring.cloud</groupId>
|
||||||
<artifactId>parent-boot-1</artifactId>
|
<artifactId>spring-cloud-kubernetes</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>1.0-SNAPSHOT</version>
|
||||||
<relativePath>../../../../parent-boot-1</relativePath>
|
<relativePath>../../../spring-cloud-kubernetes</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
@ -44,7 +44,6 @@
|
||||||
<properties>
|
<properties>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||||
<spring-boot.version>1.5.17.RELEASE</spring-boot.version>
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -8,10 +8,10 @@
|
||||||
<version>1.0-SNAPSHOT</version>
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung.spring.cloud</groupId>
|
||||||
<artifactId>parent-boot-1</artifactId>
|
<artifactId>spring-cloud-kubernetes</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>1.0-SNAPSHOT</version>
|
||||||
<relativePath>../../../../parent-boot-1</relativePath>
|
<relativePath>../../../spring-cloud-kubernetes</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
@ -44,7 +44,6 @@
|
||||||
<properties>
|
<properties>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||||
<spring-boot.version>1.5.17.RELEASE</spring-boot.version>
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -0,0 +1,3 @@
|
||||||
|
### Relevant Articles:
|
||||||
|
|
||||||
|
- [Quick Guide to Spring Cloud Open Service Broker](https://www.baeldung.com/spring-cloud-open-service-broker)
|
|
@ -0,0 +1,41 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>spring-cloud-open-service-broker</artifactId>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung.spring.cloud</groupId>
|
||||||
|
<artifactId>spring-cloud</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<spring-cloud-starter-open-service-broker.version>3.1.1.RELEASE</spring-cloud-starter-open-service-broker.version>
|
||||||
|
<spring-boot-starter-web.version>2.2.7.RELEASE</spring-boot-starter-web.version>
|
||||||
|
<reactor-test.version>3.3.5.RELEASE</reactor-test.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.cloud</groupId>
|
||||||
|
<artifactId>spring-cloud-starter-open-service-broker</artifactId>
|
||||||
|
<version>${spring-cloud-starter-open-service-broker.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
|
<version>${spring-boot-starter-web.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.projectreactor</groupId>
|
||||||
|
<artifactId>reactor-test</artifactId>
|
||||||
|
<version>${reactor-test.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
</project>
|
|
@ -0,0 +1,13 @@
|
||||||
|
package com.baeldung.spring.cloud.openservicebroker;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
public class ServiceBrokerApplication {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(ServiceBrokerApplication.class, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,34 @@
|
||||||
|
package com.baeldung.spring.cloud.openservicebroker.config;
|
||||||
|
|
||||||
|
import org.springframework.cloud.servicebroker.model.catalog.Catalog;
|
||||||
|
import org.springframework.cloud.servicebroker.model.catalog.Plan;
|
||||||
|
import org.springframework.cloud.servicebroker.model.catalog.ServiceDefinition;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class CatalogConfiguration {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public Catalog catalog() {
|
||||||
|
Plan mailFreePlan = Plan.builder()
|
||||||
|
.id("fd81196c-a414-43e5-bd81-1dbb082a3c55")
|
||||||
|
.name("mail-free-plan")
|
||||||
|
.description("Mail Service Free Plan")
|
||||||
|
.free(true)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
ServiceDefinition serviceDefinition = ServiceDefinition.builder()
|
||||||
|
.id("b92c0ca7-c162-4029-b567-0d92978c0a97")
|
||||||
|
.name("mail-service")
|
||||||
|
.description("Mail Service")
|
||||||
|
.bindable(true)
|
||||||
|
.tags("mail", "service")
|
||||||
|
.plans(mailFreePlan)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
return Catalog.builder()
|
||||||
|
.serviceDefinitions(serviceDefinition)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,19 @@
|
||||||
|
package com.baeldung.spring.cloud.openservicebroker.mail;
|
||||||
|
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
public class MailController {
|
||||||
|
|
||||||
|
@GetMapping("/mail-dashboard/{mailSystemId}")
|
||||||
|
public String dashboard(@PathVariable("mailSystemId") String mailSystemId) {
|
||||||
|
return "Mail Dashboard - " + mailSystemId;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/mail-system/{mailSystemId}")
|
||||||
|
public String mailSystem(@PathVariable("mailSystemId") String mailSystemId) {
|
||||||
|
return "Mail System - " + mailSystemId;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,95 @@
|
||||||
|
package com.baeldung.spring.cloud.openservicebroker.mail;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class MailService {
|
||||||
|
|
||||||
|
public static final String URI_KEY = "uri";
|
||||||
|
public static final String USERNAME_KEY = "username";
|
||||||
|
public static final String PASSWORD_KEY = "password";
|
||||||
|
|
||||||
|
private final String mailDashboardBaseURL;
|
||||||
|
private final String mailSystemBaseURL;
|
||||||
|
|
||||||
|
private Map<String, MailServiceInstance> mailServices = new HashMap<>();
|
||||||
|
|
||||||
|
private Map<String, MailServiceBinding> mailServiceBindings = new HashMap<>();
|
||||||
|
|
||||||
|
public MailService(@Value("${mail.system.dashboard.base-url}") String mailDashboardBaseURL,
|
||||||
|
@Value("${mail.system.base-url}") String mailSystemBaseURL) {
|
||||||
|
this.mailDashboardBaseURL = mailDashboardBaseURL;
|
||||||
|
this.mailSystemBaseURL = mailSystemBaseURL;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Mono<MailServiceInstance> createServiceInstance(String instanceId, String serviceDefinitionId, String planId) {
|
||||||
|
MailServiceInstance mailServiceInstance = new MailServiceInstance(
|
||||||
|
instanceId, serviceDefinitionId, planId, mailDashboardBaseURL + instanceId);
|
||||||
|
mailServices.put(instanceId, mailServiceInstance);
|
||||||
|
return Mono.just(mailServiceInstance);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Mono<Boolean> serviceInstanceExists(String instanceId) {
|
||||||
|
return Mono.just(mailServices.containsKey(instanceId));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Mono<MailServiceInstance> getServiceInstance(String instanceId) {
|
||||||
|
if (mailServices.containsKey(instanceId)) {
|
||||||
|
return Mono.just(mailServices.get(instanceId));
|
||||||
|
}
|
||||||
|
return Mono.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Mono<Void> deleteServiceInstance(String instanceId) {
|
||||||
|
mailServices.remove(instanceId);
|
||||||
|
mailServiceBindings.remove(instanceId);
|
||||||
|
return Mono.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Mono<MailServiceBinding> createServiceBinding(String instanceId, String bindingId) {
|
||||||
|
return this.serviceInstanceExists(instanceId)
|
||||||
|
.flatMap(exists -> {
|
||||||
|
if (exists) {
|
||||||
|
MailServiceBinding mailServiceBinding =
|
||||||
|
new MailServiceBinding(bindingId, buildCredentials(instanceId, bindingId));
|
||||||
|
mailServiceBindings.put(instanceId, mailServiceBinding);
|
||||||
|
return Mono.just(mailServiceBinding);
|
||||||
|
} else {
|
||||||
|
return Mono.empty();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public Mono<Boolean> serviceBindingExists(String instanceId, String bindingId) {
|
||||||
|
return Mono.just(mailServiceBindings.containsKey(instanceId) &&
|
||||||
|
mailServiceBindings.get(instanceId).getBindingId().equalsIgnoreCase(bindingId));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Mono<MailServiceBinding> getServiceBinding(String instanceId, String bindingId) {
|
||||||
|
if (mailServiceBindings.containsKey(instanceId) &&
|
||||||
|
mailServiceBindings.get(instanceId).getBindingId().equalsIgnoreCase(bindingId)) {
|
||||||
|
return Mono.just(mailServiceBindings.get(instanceId));
|
||||||
|
}
|
||||||
|
return Mono.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Mono<Void> deleteServiceBinding(String instanceId) {
|
||||||
|
mailServiceBindings.remove(instanceId);
|
||||||
|
return Mono.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> buildCredentials(String instanceId, String bindingId) {
|
||||||
|
Map<String, Object> credentials = new HashMap<>();
|
||||||
|
credentials.put(URI_KEY, mailSystemBaseURL + instanceId);
|
||||||
|
credentials.put(USERNAME_KEY, bindingId);
|
||||||
|
credentials.put(PASSWORD_KEY, UUID.randomUUID().toString());
|
||||||
|
return credentials;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue