Merge branch 'eugenp:master' into master

This commit is contained in:
edizor 2023-01-20 16:10:28 +08:00 committed by GitHub
commit cf1f2e87c2
32 changed files with 797 additions and 137 deletions

View File

@ -72,6 +72,13 @@ Building a single module
To build a specific module, run the command: `mvn clean install` in the module directory.
Building modules from the root of the repository
====================
To build specific modules from the root of the repository, run the command: `mvn clean install --pl asm,atomikos -Pdefault-first` in the root directory.
Here `asm` and `atomikos` are the modules that we want to build and `default-first` is the maven profile in which these modules are present.
Running a Spring Boot module
====================
To run a Spring Boot module, run the command: `mvn spring-boot:run` in the module directory.

View File

@ -5,6 +5,33 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-array-list</artifactId>
<version>0.1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven-compiler-plugin.source}</source>
<target>${maven-compiler-plugin.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.plugin.version}</version>
<configuration>
<argLine>
--add-opens java.base/java.util=ALL-UNNAMED
</argLine>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven-compiler-plugin.source>16</maven-compiler-plugin.source>
<maven-compiler-plugin.target>16</maven-compiler-plugin.target>
<surefire.plugin.version>3.0.0-M3</surefire.plugin.version>
</properties>
<name>core-java-collections-array-list</name>
<packaging>jar</packaging>
@ -20,6 +47,12 @@
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,17 @@
package com.baeldung.listofobjectstolistofstring;
public class Node {
private final int x;
private final int y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Node (" + "x=" + x + ", y=" + y + ')';
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.listofobjectstolistofstring;
public class User {
private final String fullName;
public User(String fullName) {
this.fullName = fullName;
}
@Override
public String toString() {
return "User (" + "full name='" + fullName + ')';
}
}

View File

@ -0,0 +1,92 @@
package com.baeldung.listofobjectstolistofstring;
import com.google.common.collect.Lists;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class ConvertObjectListToStringListUnitTest {
@Test
public void givenObjectList_whenForEachUsedToConvert_thenReturnSuccess() {
List<String> outputList = new ArrayList<>(objectListWithNull().size());
for (Object obj : objectListWithNull()) {
outputList.add(Objects.toString(obj, null));
}
Assert.assertEquals(expectedStringListWithNull(), outputList);
}
@Test
public void givenObjectList_whenUsingStreamsToConvert_thenReturnSuccess() {
List<String> outputList;
outputList = objectListWithNull().stream()
.map((obj) -> Objects.toString(obj, null))
.collect(Collectors.toList());
Assert.assertEquals(expectedStringListWithNull(), outputList);
}
@Test
public void givenObjectList_whenUsingStreamsUnmodifiableListToConvert_thenReturnSuccess() {
List<String> outputList;
outputList = objectListWithNull().stream()
.filter(Objects::nonNull)
.map((obj) -> Objects.toString(obj, null))
.collect(Collectors.toUnmodifiableList());
Assert.assertEquals(expectedStringListWithoutNull(), outputList);
}
@Test
public void givenObjectList_whenUsingGuavaTransform_thenReturnSuccess() {
List<String> outputList;
outputList = Lists.transform(objectListWithNull(), obj -> Objects.toString(obj, null));
Assert.assertEquals(expectedStringListWithNull(), outputList);
}
@Test
public void givenObjectListWithNoNull_whenUsingToList_thenReturnSuccess() {
List<String> outputList;
outputList = objectListWithoutNull().stream()
.map((obj) -> Objects.toString(obj, null))
.toList();
Assert.assertEquals(expectedStringListWithoutNull(), outputList);
}
private List<String> expectedStringListWithNull() {
List<String> listOfStrings = new ArrayList<>();
listOfStrings.add("1");
listOfStrings.add("true");
listOfStrings.add("hello");
listOfStrings.add(Double.toString(273773.98));
listOfStrings.add(null);
listOfStrings.add(new Node(2, 4).toString());
listOfStrings.add(new User("John Doe").toString());
return listOfStrings;
}
private List<Object> objectListWithNull() {
List<Object> listOfStrings = new ArrayList<>();
listOfStrings.add(1);
listOfStrings.add(true);
listOfStrings.add("hello");
listOfStrings.add(Double.valueOf(273773.98));
listOfStrings.add(null);
listOfStrings.add(new Node(2, 4));
listOfStrings.add(new User("John Doe"));
return listOfStrings;
}
private List<String> expectedStringListWithoutNull() {
return List.of("1", "true", "hello", Double.toString(273773.98), new Node(2, 4).toString(), new User("John Doe").toString());
}
private List<Object> objectListWithoutNull() {
return List.of(1, true, "hello", Double.valueOf(273773.98), new Node(2, 4), new User("John Doe"));
}
}

View File

@ -2,68 +2,76 @@ package com.baeldung.convertnumberbases;
public class ConvertNumberBases {
public static String convertNumberToNewBase(String number, int base, int newBase){
public static String convertNumberToNewBase(String number, int base, int newBase) {
return Integer.toString(Integer.parseInt(number, base), newBase);
}
public static String convertNumberToNewBaseCustom(String num, int base, int newBase) {
int decimalNumber = convertFromAnyBaseToDecimal(num, base);
return convertFromDecimalToBaseX(decimalNumber, newBase);
String targetBase = "";
try {
targetBase = convertFromDecimalToBaseX(decimalNumber, newBase);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return targetBase;
}
public static String convertFromDecimalToBaseX(int num, int newBase) {
public static String convertFromDecimalToBaseX(int num, int newBase) throws IllegalArgumentException {
if ((newBase < 2 || newBase > 10) && newBase != 16) {
throw new IllegalArgumentException("New base must be from 2 - 10 or 16");
}
String result = "";
int remainder;
while (num > 0) {
remainder = num % newBase;
if (newBase == 16) {
if (remainder == 10)
if (remainder == 10) {
result += 'A';
else if (remainder == 11)
} else if (remainder == 11) {
result += 'B';
else if (remainder == 12)
} else if (remainder == 12) {
result += 'C';
else if (remainder == 13)
} else if (remainder == 13) {
result += 'D';
else if (remainder == 14)
} else if (remainder == 14) {
result += 'E';
else if (remainder == 15)
} else if (remainder == 15) {
result += 'F';
else
} else {
result += remainder;
} else
}
} else {
result += remainder;
}
num /= newBase;
}
return new StringBuffer(result).reverse().toString();
}
public static int convertFromAnyBaseToDecimal(String num, int base) {
if (base < 2 || (base > 10 && base != 16))
if (base < 2 || (base > 10 && base != 16)) {
return -1;
}
int val = 0;
int power = 1;
for (int i = num.length() - 1; i >= 0; i--) {
int digit = charToDecimal(num.charAt(i));
if (digit < 0 || digit >= base)
if (digit < 0 || digit >= base) {
return -1;
}
val += digit * power;
power = power * base;
}
return val;
}
public static int charToDecimal(char c) {
if (c >= '0' && c <= '9')
if (c >= '0' && c <= '9') {
return (int) c - '0';
else
} else {
return (int) c - 'A' + 10;
}
}
}

View File

@ -1,5 +1,6 @@
package com.baeldung.convertnumberbases;
import static com.baeldung.convertnumberbases.ConvertNumberBases.convertFromDecimalToBaseX;
import static com.baeldung.convertnumberbases.ConvertNumberBases.convertNumberToNewBase;
import static com.baeldung.convertnumberbases.ConvertNumberBases.convertNumberToNewBaseCustom;
import static org.junit.jupiter.api.Assertions.*;
@ -17,4 +18,15 @@ class ConvertNumberBasesUnitTest {
assertEquals(convertNumberToNewBaseCustom("11001000", 2, 8), "310");
}
@Test
void whenInputIsOutOfRange_thenIllegalArgumentExceptionIsThrown() {
Exception exception = assertThrows(IllegalArgumentException.class, ()-> {
convertFromDecimalToBaseX(100, 12);
});
String expectedMessage = "New base must be from 2 - 10 or 16";
String actualMessage = exception.getMessage();
assertTrue(actualMessage.contains(expectedMessage));
}
}

View File

@ -31,7 +31,6 @@
<module>core-java-collections-2</module>
<module>core-java-collections-3</module>
<module>core-java-collections-4</module>
<module>core-java-collections-array-list</module>
<module>core-java-collections-conversions</module>
<module>core-java-collections-conversions-2</module>
<module>core-java-collections-set-2</module>

View File

@ -112,6 +112,18 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5-fluent</artifactId>
<version>${httpclient5-fluent.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- utils -->
<dependency>
<groupId>org.apache.commons</groupId>
@ -308,6 +320,7 @@
<!-- http client & core 5 -->
<httpcore5.version>5.2</httpcore5.version>
<httpclient5.version>5.2</httpclient5.version>
<httpclient5-fluent.version>5.2</httpclient5-fluent.version>
<!-- maven plugins -->
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
</properties>

View File

@ -1,74 +1,88 @@
package com.baeldung.httpclient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.jupiter.api.Test;
import org.apache.hc.client5.http.auth.AuthScope;
import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.client5.http.fluent.Form;
import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import com.baeldung.handler.CustomHttpClientResponseHandler;
/*
* NOTE : Need module spring-rest to be running
*/
public class HttpClientPostingLiveTest {
class HttpClientPostingLiveTest {
private static final String SAMPLE_URL = "http://www.example.com";
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php";
private static final String DEFAULT_USER = "test";
private static final String DEFAULT_PASS = "test";
@Test
public void whenSendPostRequestUsingHttpClient_thenCorrect() throws IOException {
final CloseableHttpClient client = HttpClients.createDefault();
void whenSendPostRequestUsingHttpClient_thenCorrect() throws IOException {
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
final List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", DEFAULT_USER));
params.add(new BasicNameValuePair("password", DEFAULT_PASS));
httpPost.setEntity(new UrlEncodedFormEntity(params));
final CloseableHttpResponse response = client.execute(httpPost);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
try (CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = (CloseableHttpResponse) client
.execute(httpPost, new CustomHttpClientResponseHandler())) {
final int statusCode = response.getCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
}
}
@Test
public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws IOException, AuthenticationException {
final CloseableHttpClient client = HttpClients.createDefault();
void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws IOException {
final HttpPost httpPost = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION);
httpPost.setEntity(new StringEntity("test post"));
final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null));
final CloseableHttpResponse response = client.execute(httpPost);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
final UsernamePasswordCredentials credentials =
new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS.toCharArray());
credsProvider.setCredentials(new AuthScope(URL_SECURED_BY_BASIC_AUTHENTICATION, 80) ,credentials);
try (CloseableHttpClient client = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.build();
CloseableHttpResponse response = (CloseableHttpResponse) client
.execute(httpPost, new CustomHttpClientResponseHandler())) {
final int statusCode = response.getCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
}
}
@Test
public void whenPostJsonUsingHttpClient_thenCorrect() throws IOException {
final CloseableHttpClient client = HttpClients.createDefault();
void whenPostJsonUsingHttpClient_thenCorrect() throws IOException {
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
final String json = "{\"id\":1,\"name\":\"John\"}";
@ -77,68 +91,91 @@ public class HttpClientPostingLiveTest {
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
final CloseableHttpResponse response = client.execute(httpPost);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
try (CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = (CloseableHttpResponse) client
.execute(httpPost, new CustomHttpClientResponseHandler())) {
final int statusCode = response.getCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
}
}
@Test
public void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws IOException {
final HttpResponse response = Request.Post(SAMPLE_URL).bodyForm(Form.form().add("username", DEFAULT_USER).add("password", DEFAULT_PASS).build()).execute().returnResponse();
void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws IOException {
Request request = Request.post(SAMPLE_URL)
.bodyForm(Form.form()
.add("username", DEFAULT_USER)
.add("password", DEFAULT_PASS)
.build());
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
HttpResponse response = request.execute()
.returnResponse();
assertThat(response.getCode(), equalTo(HttpStatus.SC_OK));
}
@Test
public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws IOException {
final CloseableHttpClient client = HttpClients.createDefault();
void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws IOException {
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("username", DEFAULT_USER);
builder.addTextBody("password", DEFAULT_PASS);
builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
builder.addBinaryBody(
"file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
final HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
try (CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = (CloseableHttpResponse) client
.execute(httpPost, new CustomHttpClientResponseHandler())) {
final int statusCode = response.getCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
}
}
@Test
void whenUploadFileUsingHttpClient_thenCorrect() throws IOException {
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody(
"file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
final HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
final CloseableHttpResponse response = client.execute(httpPost);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
try (CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = (CloseableHttpResponse) client
.execute(httpPost, new CustomHttpClientResponseHandler())) {
final int statusCode = response.getCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
}
}
@Test
public void whenUploadFileUsingHttpClient_thenCorrect() throws IOException {
final CloseableHttpClient client = HttpClients.createDefault();
void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws IOException {
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
builder.addBinaryBody(
"file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
final HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
final CloseableHttpResponse response = client.execute(httpPost);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
@Test
public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws IOException {
final CloseableHttpClient client = HttpClients.createDefault();
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
final HttpEntity multipart = builder.build();
final ProgressEntityWrapper.ProgressListener pListener = percentage -> assertFalse(Float.compare(percentage, 100) > 0);
final ProgressEntityWrapper.ProgressListener pListener =
percentage -> assertFalse(Float.compare(percentage, 100) > 0);
httpPost.setEntity(new ProgressEntityWrapper(multipart, pListener));
final CloseableHttpResponse response = client.execute(httpPost);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
try (CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = (CloseableHttpResponse) client
.execute(httpPost, new CustomHttpClientResponseHandler())) {
final int statusCode = response.getCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
}
}
}

View File

@ -4,8 +4,8 @@ import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.HttpEntityWrapper;
public class ProgressEntityWrapper extends HttpEntityWrapper {
private final ProgressListener listener;

View File

@ -0,0 +1,16 @@
pipeline {
agent any
stages {
stage('tryCatch') {
steps {
script {
try {
sh 'test_script.sh'
} catch (e) {
echo "An error occurred: ${e}"
}
}
}
}
}
}

View File

@ -6,17 +6,17 @@ import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
@Configuration
@EnableElasticsearchRepositories(basePackages = "com.baeldung.spring.data.es.repository")
@ComponentScan(basePackages = { "com.baeldung.spring.data.es.service" })
public class Config {
public class Config extends AbstractElasticsearchConfiguration {
@Bean
RestHighLevelClient client() {
@Override
public RestHighLevelClient elasticsearchClient() {
ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo("localhost:9200")
.build();
@ -24,9 +24,4 @@ public class Config {
return RestClients.create(clientConfiguration)
.rest();
}
@Bean
public ElasticsearchOperations elasticsearchTemplate() {
return new ElasticsearchRestTemplate(client());
}
}

View File

@ -22,7 +22,7 @@ import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
@ -41,7 +41,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
public class ElasticSearchManualTest {
@Autowired
private ElasticsearchRestTemplate elasticsearchTemplate;
private ElasticsearchOperations elasticsearchOperations;
@Autowired
private ArticleRepository articleRepository;
@ -117,7 +117,7 @@ public class ElasticSearchManualTest {
final Query searchQuery = new NativeSearchQueryBuilder().withFilter(regexpQuery("title", ".*data.*"))
.build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
final SearchHits<Article> articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.getTotalHits());
}
@ -126,7 +126,7 @@ public class ElasticSearchManualTest {
public void givenSavedDoc_whenTitleUpdated_thenCouldFindByUpdatedTitle() {
final Query searchQuery = new NativeSearchQueryBuilder().withQuery(fuzzyQuery("title", "serch"))
.build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
final SearchHits<Article> articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.getTotalHits());
@ -147,7 +147,7 @@ public class ElasticSearchManualTest {
final Query searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", articleTitle).minimumShouldMatch("75%"))
.build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
final SearchHits<Article> articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.getTotalHits());
final long count = articleRepository.count();
@ -162,7 +162,7 @@ public class ElasticSearchManualTest {
public void givenSavedDoc_whenOneTermMatches_thenFindByTitle() {
final Query searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Search engines").operator(AND))
.build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
final SearchHits<Article> articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.getTotalHits());
}
}

View File

@ -39,7 +39,7 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
@ -58,7 +58,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
public class ElasticSearchQueryManualTest {
@Autowired
private ElasticsearchRestTemplate elasticsearchTemplate;
private ElasticsearchOperations elasticsearchOperations;
@Autowired
private ArticleRepository articleRepository;
@ -101,7 +101,7 @@ public class ElasticSearchQueryManualTest {
public void givenFullTitle_whenRunMatchQuery_thenDocIsFound() {
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Search engines").operator(Operator.AND))
.build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
final SearchHits<Article> articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.getTotalHits());
}
@ -110,7 +110,7 @@ public class ElasticSearchQueryManualTest {
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Engines Solutions"))
.build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
final SearchHits<Article> articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.getTotalHits());
assertEquals("Search engines", articles.getSearchHit(0)
@ -123,7 +123,7 @@ public class ElasticSearchQueryManualTest {
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "elasticsearch data"))
.build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
final SearchHits<Article> articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(3, articles.getTotalHits());
}
@ -133,14 +133,14 @@ public class ElasticSearchQueryManualTest {
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title.verbatim", "Second Article About Elasticsearch"))
.build();
SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
SearchHits<Article> articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.getTotalHits());
searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title.verbatim", "Second Article About"))
.build();
articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(0, articles.getTotalHits());
}
@ -150,7 +150,7 @@ public class ElasticSearchQueryManualTest {
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder)
.build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
final SearchHits<Article> articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(2, articles.getTotalHits());
}
@ -205,7 +205,7 @@ public class ElasticSearchQueryManualTest {
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchPhraseQuery("title", "spring elasticsearch").slop(1))
.build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
final SearchHits<Article> articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.getTotalHits());
}
@ -217,7 +217,7 @@ public class ElasticSearchQueryManualTest {
.prefixLength(3))
.build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
final SearchHits<Article> articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.getTotalHits());
}
@ -229,7 +229,7 @@ public class ElasticSearchQueryManualTest {
.type(MultiMatchQueryBuilder.Type.BEST_FIELDS))
.build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
final SearchHits<Article> articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(2, articles.getTotalHits());
}
@ -241,7 +241,7 @@ public class ElasticSearchQueryManualTest {
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder)
.build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
final SearchHits<Article> articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(2, articles.getTotalHits());
}

View File

@ -0,0 +1,75 @@
package com.baeldung.spring.data.persistence.search;
import java.util.Objects;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private int score;
public Student() {
}
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", score=" + score + "]";
}
@Override
public int hashCode() {
return Objects.hash(id, name, score);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
return id == other.id && Objects.equals(name, other.name) && score == other.score;
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.spring.data.persistence.search;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class StudentApplication {
private static final Logger log = LoggerFactory.getLogger(StudentApplication.class);
public static void main(String[] args) {
SpringApplication.run(StudentApplication.class, args);
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.spring.data.persistence.search;
import java.util.List;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
Student findFirstByOrderByScoreDesc();
Student findFirstBy(Sort sort);
Student findFirstByNameLike(String name, Sort sort);
List<Student> findFirst3ByOrderByScoreDesc();
List<Student> findFirst2ByScoreBetween(int startScore, int endScore, Sort sort);
Student findTopByOrderByScoreDesc();
Student findTopBy(Sort sort);
Student findTopByNameLike(String name, Sort sort);
List<Student> findTop3ByOrderByScoreDesc();
List<Student> findTop2ByScoreBetween(int startScore, int endScore, Sort sort);
}

View File

@ -3,3 +3,4 @@ spring.datasource.username=sa
spring.datasource.password=sa
spring.jpa.properties.hibernate.globally_quoted_identifiers=true
logging.level.com.baeldung.spring.data.persistence.search=debug

View File

@ -0,0 +1,100 @@
package com.baeldung.spring.data.persistence.search;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class StudentApplicationUnitTest {
@Autowired
private StudentRepository studentRepo;
private List<Student> students;
@Before
public void fillData() {
students = new ArrayList<>();
int count = 10;
Random r = new Random();
List<Integer> scores = r.ints(0, 101)
.distinct()
.limit(count)
.boxed()
.collect(Collectors.toList());
for (int i = 0; i < count; i++) {
Integer score = scores.get(i);
Student s = new Student("Student-" + i, score);
students.add(s);
}
studentRepo.saveAll(students);
Comparator<Student> c = Comparator.comparing(a -> a.getScore());
c = c.reversed();
students.sort(c);
}
@After
public void clearData() {
studentRepo.deleteAll();
}
@Test
public void givenStudentScores_whenMoreThanOne_thenFindFirst() {
Student student = studentRepo.findFirstByOrderByScoreDesc();
Student s = students.get(0);
assertEquals(student, s);
}
@Test
public void givenStudentScores_whenMoreThan3_thenFindFirstThree() {
List<Student> firstThree = studentRepo.findFirst3ByOrderByScoreDesc();
List<Student> sList = students.subList(0, 3);
assertArrayEquals(firstThree.toArray(), sList.toArray());
}
@Test
public void givenStudentScores_whenNameMatches_thenFindFirstStudent() {
String matchString = "3";
Student student = studentRepo.findFirstByNameLike("%" + matchString + "%", Sort.by("score")
.descending());
Student s = students.stream()
.filter(a -> a.getName()
.contains(matchString))
.findFirst()
.orElse(null);
assertEquals(student, s);
}
@Test
public void givenStudentScores_whenBetweenRange_thenFindFirstTwoStudents() {
List<Student> topTwoBetweenRange = studentRepo.findFirst2ByScoreBetween(50, 60, Sort.by("score")
.descending());
List<Student> _students = students.stream()
.filter(a -> a.getScore() >= 50 && a.getScore() <= 60)
.limit(2)
.collect(Collectors.toList());
assertArrayEquals(_students.toArray(), topTwoBetweenRange.toArray());
}
}

View File

@ -1133,6 +1133,7 @@
<!-- <module>core-java-modules/core-java-19</module> --> <!-- uses preview features, to be decided how to handle -->
<module>core-java-modules/core-java-collections-set</module>
<module>core-java-modules/core-java-collections-list-4</module>
<module>core-java-modules/core-java-collections-array-list</module>
<module>core-java-modules/core-java-collections-maps-4</module>
<module>core-java-modules/core-java-collections-maps-5</module>
<module>core-java-modules/core-java-concurrency-simple</module>

View File

@ -0,0 +1,21 @@
package com.baeldung.requestheader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.requestheader.interceptor.OperatorHolder;
@RestController
public class BuzzController {
private final OperatorHolder operatorHolder;
public BuzzController(OperatorHolder operatorHolder) {
this.operatorHolder = operatorHolder;
}
@GetMapping("buzz")
public String buzz() {
return "hello, " + operatorHolder.getOperator();
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.requestheader;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class FooBarController {
@GetMapping("foo")
public String foo(HttpServletRequest request) {
String operator = request.getHeader("operator");
return "hello, " + operator;
}
@GetMapping("bar")
public String bar(@RequestHeader("operator") String operator) {
return "hello, " + operator;
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.requestheader;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@SpringBootApplication
@EnableWebMvc
public class HeaderInterceptorApplication {
public static void main(String[] args) {
SpringApplication.run(HeaderInterceptorApplication.class, args);
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.requestheader.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.baeldung.requestheader.interceptor.OperatorHolder;
import com.baeldung.requestheader.interceptor.OperatorInterceptor;
@Configuration
public class HeaderInterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(final InterceptorRegistry registry) {
registry.addInterceptor(operatorInterceptor());
}
@Bean
public OperatorInterceptor operatorInterceptor() {
return new OperatorInterceptor(operatorHolder());
}
@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public OperatorHolder operatorHolder() {
return new OperatorHolder();
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.requestheader.interceptor;
public class OperatorHolder {
private String operator;
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.requestheader.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
public class OperatorInterceptor implements HandlerInterceptor {
private final OperatorHolder operatorHolder;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String operator = request.getHeader("operator");
operatorHolder.setOperator(operator);
return true;
}
public OperatorInterceptor(OperatorHolder operatorHolder) {
this.operatorHolder = operatorHolder;
}
}

View File

@ -0,0 +1,65 @@
package com.baeldung.requestheader;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = { HeaderInterceptorApplication.class })
@WebAppConfiguration
public class HeaderInterceptorIntegrationTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@BeforeEach
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext)
.build();
}
@Test
public void givenARequestWithOperatorHeader_whenWeCallFooEndpoint_thenOperatorIsExtracted() throws Exception {
MockHttpServletResponse response = this.mockMvc.perform(get("/foo").header("operator", "John.Doe"))
.andDo(print())
.andReturn()
.getResponse();
assertThat(response.getContentAsString()).isEqualTo("hello, John.Doe");
}
@Test
public void givenARequestWithOperatorHeader_whenWeCallBarEndpoint_thenOperatorIsExtracted() throws Exception {
MockHttpServletResponse response = this.mockMvc.perform(get("/bar").header("operator", "John.Doe"))
.andDo(print())
.andReturn()
.getResponse();
assertThat(response.getContentAsString()).isEqualTo("hello, John.Doe");
}
@Test
public void givenARequestWithOperatorHeader_whenWeCallBuzzEndpoint_thenOperatorIsIntercepted() throws Exception {
MockHttpServletResponse response = this.mockMvc.perform(get("/buzz").header("operator", "John.Doe"))
.andDo(print())
.andReturn()
.getResponse();
assertThat(response.getContentAsString()).isEqualTo("hello, John.Doe");
}
}

View File

@ -2,7 +2,6 @@ keycloak:
auth-server-url: https://api.example.com/auth # Keycloak server url
realm: todos-service-realm # Keycloak Realm
resource: todos-service-clients # Keycloak Client
public-client: true
principal-attribute: preferred_username
ssl-required: external
credentials:

View File

@ -1,5 +1,7 @@
package com.baeldung.springbootsecurityrest.basicauth.config;
import static org.springframework.security.config.Customizer.withDefaults;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
@ -27,6 +29,7 @@ public class BasicAuthConfiguration {
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.cors(withDefaults())
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**")
.permitAll()

View File

@ -7,11 +7,11 @@ import org.doctester.testbrowser.Response;
import org.junit.Test;
import ninja.NinjaDocTester;
public class ApiControllerDocTesterIntegrationTest extends NinjaDocTester {
public class ApiControllerDocTesterUnitTest extends NinjaDocTester {
String URL_INDEX = "/";
String URL_HELLO = "/hello";
@Test
public void testGetIndex() {
Response response = makeRequest(Request.GET().url(testServerUrl().path(URL_INDEX)));
@ -23,5 +23,5 @@ public class ApiControllerDocTesterIntegrationTest extends NinjaDocTester {
Response response = makeRequest(Request.GET().url(testServerUrl().path(URL_HELLO)));
assertThat(response.payload, containsString("Bonjour, bienvenue dans Ninja Framework!"));
}
}

View File

@ -1,23 +1,23 @@
package controllers;
import static org.junit.Assert.assertEquals;
import javax.inject.Inject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import ninja.NinjaRunner;
import ninja.NinjaTest;
import ninja.Result;
import services.UserService;
@RunWith(NinjaRunner.class)
public class ApiControllerMockIntegrationTest {
public class ApiControllerMockUnitTest extends NinjaTest {
@Inject private UserService userService;
private UserService userService;
ApplicationController applicationController;
private ApplicationController applicationController;
@Before
public void setupTest() {
userService = this.ninjaTestServer.getInjector().getInstance(UserService.class);
applicationController = new ApplicationController();
applicationController.userService = userService;
}
@ -28,5 +28,5 @@ public class ApiControllerMockIntegrationTest {
System.out.println(result.getRenderable());
assertEquals(userService.getUserMap().toString(), result.getRenderable().toString());
}
}