Merge branch 'eugenp:master' into master

This commit is contained in:
cesarevalenti90 2023-01-23 09:43:50 +01:00 committed by GitHub
commit e10ffa8b75
71 changed files with 1267 additions and 140 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

@ -20,4 +20,4 @@ Two scripts are included to easily start middleware using Docker matching the pr
- [Multi-Entity Aggregates in Axon](https://www.baeldung.com/java-axon-multi-entity-aggregates)
- [Snapshotting Aggregates in Axon](https://www.baeldung.com/axon-snapshotting-aggregates)
- [Dispatching Queries in Axon Framework](https://www.baeldung.com/axon-query-dispatching)
- [Persisting the Query Model](https://www.baeldung.com/persisting-the-query-model)
- [Persisting the Query Model](https://www.baeldung.com/axon-persisting-query-model)

View File

@ -11,4 +11,5 @@ This module contains articles about Java 8 core features
- [Finding Min/Max in an Array with Java](https://www.baeldung.com/java-array-min-max)
- [Internationalization and Localization in Java 8](https://www.baeldung.com/java-8-localization)
- [Generalized Target-Type Inference in Java](https://www.baeldung.com/java-generalized-target-type-inference)
- [Monads in Java](https://www.baeldung.com/java-monads)
- [[More -->]](/core-java-modules/core-java-8-2)

View File

@ -9,3 +9,6 @@ This module contains articles about the Java ArrayList collection
- [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist)
- [Removing an Element From an ArrayList](https://www.baeldung.com/java-arraylist-remove-element)
- [The Capacity of an ArrayList vs the Size of an Array in Java](https://www.baeldung.com/java-list-capacity-array-size)
- [Case-Insensitive Searching in ArrayList](https://www.baeldung.com/java-arraylist-case-insensitive-search)
- [Storing Data Triple in a List in Java](https://www.baeldung.com/java-list-storing-triple)
- [Convert an ArrayList of Object to an ArrayList of String Elements](https://www.baeldung.com/java-object-list-to-strings)

View File

@ -0,0 +1,5 @@
## Core Java Collections List (Part 5)
This module contains articles about the Java List collection
### Relevant Articles:

View File

@ -0,0 +1,35 @@
<?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>core-java-collections-list-5</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-list-5</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>${commons-lang.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
<properties>
<commons-lang.version>2.2</commons-lang.version>
<commons-lang3.version>3.12.0</commons-lang3.version>
</properties>
</project>

View File

@ -0,0 +1,126 @@
package com.baeldung.java.list;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.junit.Test;
public class ListUnitTest {
@Test
public void givenAFruitList_whenAddNewFruit_thenFruitIsAdded(){
List<String> fruits = new ArrayList<>();
assertEquals("Unexpected number of fruits in the list, should have been 0", 0, fruits.size());
fruits.add("Apple");
assertEquals("Unexpected number of fruits in the list, should have been 1", 1, fruits.size());
}
@Test
public void givenAFruitList_whenContainsFruit_thenFruitIsInTheList(){
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
assertTrue("Apple should be in the fruit list", fruits.contains("Apple"));
assertFalse("Banana should not be in the fruit list", fruits.contains("Banana"));
}
@Test
public void givenAnEmptyFruitList_whenEmptyCheck_thenListIsEmpty(){
List<String> fruits = new ArrayList<>();
assertTrue("Fruit list should be empty", fruits.isEmpty());
fruits.add("Apple");
assertFalse("Fruit list should not be empty", fruits.isEmpty());
}
@Test
public void givenAFruitList_whenIterateOverIt_thenFruitsAreInOrder(){
List<String> fruits = new ArrayList<>();
fruits.add("Apple"); // fruit at index 0
fruits.add("Orange");// fruit at index 1
fruits.add("Banana");// fruit at index 2
int index = 0;
for (Iterator<String> it = fruits.listIterator(); it.hasNext(); ) {
String fruit = it.next();
assertEquals("Fruits should be in order", fruits.get(index++), fruit);
}
}
@Test
public void givenAFruitList_whenRemoveFruit_thenFruitIsRemoved(){
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Orange");
assertEquals("Unexpected number of fruits in the list, should have been 2", 2, fruits.size());
fruits.remove("Apple");
assertEquals("Unexpected number of fruits in the list, should have been 1", 1, fruits.size());
}
@Test
public void givenAFruitList_whenSetFruit_thenFruitIsUpdated(){
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Orange");
fruits.set(0, "Banana");
assertEquals("Fruit at index 0 should be Banana", "Banana", fruits.get(0));
}
@Test
public void givenAFruitList_whenSort_thenFruitsAreSorted(){
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Orange");
fruits.add("Banana");
fruits.sort(Comparator.naturalOrder());
assertEquals("Fruit at index 0 should be Apple", "Apple", fruits.get(0));
assertEquals("Fruit at index 1 should be Banana", "Banana", fruits.get(1));
assertEquals("Fruit at index 2 should be Orange", "Orange", fruits.get(2));
}
@Test
public void givenAFruitList_whenSublist_thenWeGetASublist(){
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Orange");
fruits.add("Banana");
List<String> fruitsSublist = fruits.subList(0, 2);
assertEquals("Unexpected number of fruits in the sublist, should have been 2", 2, fruitsSublist.size());
assertEquals("Fruit at index 0 should be Apple", "Apple", fruitsSublist.get(0));
assertEquals("Fruit at index 1 should be Orange", "Orange", fruitsSublist.get(1));
}
@Test
public void givenAFruitList_whenToArray_thenWeGetAnArray(){
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Orange");
fruits.add("Banana");
String[] fruitsArray = fruits.toArray(new String[0]);
assertEquals("Unexpected number of fruits in the array, should have been 3", 3, fruitsArray.length);
assertEquals("Fruit at index 0 should be Apple", "Apple", fruitsArray[0]);
assertEquals("Fruit at index 1 should be Orange", "Orange", fruitsArray[1]);
assertEquals("Fruit at index 2 should be Banana", "Banana", fruitsArray[2]);
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.exception.noenumconst;
public enum Priority {
HIGH("High"), MEDIUM("Medium"), LOW("Low");
private String name;
Priority(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.exception.noenumconst;
public class PriorityUtils {
public static Priority getByName(String name) {
return Priority.valueOf(name);
}
public static Priority getByUpperCaseName(String name) {
if (name == null || name.isEmpty()) {
return null;
}
return Priority.valueOf(name.toUpperCase());
}
public static void main(String[] args) {
System.out.println(getByName("Low"));
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.exception.noenumconst;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class PriorityUtilsUnitTest {
@Test
void givenCustomName_whenUsingGetByName_thenThrowIllegalArgumentException() {
assertThrows(IllegalArgumentException.class, () -> PriorityUtils.getByName("Low"));
}
@Test
void givenCustomName_whenUsingGetByUpperCaseName_thenReturnEnumConstant() {
assertEquals(Priority.HIGH, PriorityUtils.getByUpperCaseName("High"));
}
@Test
void givenInvalidCustomName_whenUsingGetByUpperCaseName_thenThrowIllegalArgumentException() {
assertThrows(IllegalArgumentException.class, () -> PriorityUtils.getByUpperCaseName("invalid"));
}
@Test
void givenEmptyName_whenUsingGetByUpperCaseName_thenReturnNull() {
assertNull(PriorityUtils.getByUpperCaseName(""));
}
@Test
void givenNull_whenUsingGetByUpperCaseName_thenReturnNull() {
assertNull(PriorityUtils.getByUpperCaseName(null));
}
}

View File

@ -5,4 +5,5 @@ This module contains articles about working with the Java Virtual Machine (JVM).
### Relevant Articles:
- [Difference Between Class.getResource() and ClassLoader.getResource()](https://www.baeldung.com/java-class-vs-classloader-getresource)
- [Compiling and Executing Code From a String in Java](https://www.baeldung.com/java-string-compile-execute-code)
- More articles: [[<-- prev]](/core-java-modules/core-java-jvm-2)

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

@ -6,3 +6,4 @@ This module contains articles about Object Oriented Programming (OOP) in Java
- [Object-Oriented-Programming Concepts in Java](https://www.baeldung.com/java-oop)
- [Static and Dynamic Binding in Java](https://www.baeldung.com/java-static-dynamic-binding)
- [Pass-By-Value as a Parameter Passing Mechanism in Java](https://www.baeldung.com/java-pass-by-value-or-pass-by-reference)
- [Check If All the Variables of an Object Are Null](https://www.baeldung.com/java-check-all-variables-object-null)

View File

@ -5,3 +5,4 @@
- [Filter Java Stream to 1 and Only 1 Element](https://www.baeldung.com/java-filter-stream-unique-element)
- [Java 8 Streams: Multiple Filters vs. Complex Condition](https://www.baeldung.com/java-streams-multiple-filters-vs-condition)
- [Finding Max Date in List Using Streams](https://www.baeldung.com/java-max-date-list-streams)
- [Batch Processing of Stream Data in Java](https://www.baeldung.com/java-stream-batch-processing)

View File

@ -9,3 +9,4 @@
- [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
- [Illegal Character Compilation Error](https://www.baeldung.com/java-illegal-character-error)
- [Lambda Expression vs. Anonymous Inner Class](https://www.baeldung.com/java-lambdas-vs-anonymous-class)

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

@ -8,3 +8,4 @@ This module contains articles about Jackson annotations.
- [Jackson Bidirectional Relationships](https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion)
- [Jackson JSON Views](https://www.baeldung.com/jackson-json-view-annotation)
- [Deduction-Based Polymorphism in Jackson 2.12](https://www.baeldung.com/jackson-deduction-based-polymorphism)
- [@JsonIgnore vs @Transient](https://www.baeldung.com/java-jsonignore-vs-transient)

View File

@ -2,3 +2,4 @@
- [Trigger Another Job from a Jenkins Pipeline](https://www.baeldung.com/ops/jenkins-pipeline-trigger-new-job)
- [Fixing the “No Such DSL method” Error in Jenkins Pipeline](https://www.baeldung.com/ops/jenkins-pipeline-no-such-dsl-method-error)
- [Jenkins Pipeline Change to Another Folder](https://www.baeldung.com/ops/jenkins-pipeline-change-to-another-folder)
- [How to Stop a Zombie Job on Jenkins Without Restarting the Server?](https://www.baeldung.com/ops/stop-zombie-job-on-jenkins-without-restarting-the-server)

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

@ -54,4 +54,4 @@ Enjoy it :)
- [Configure Jenkins to Run and Show JMeter Tests](https://www.baeldung.com/ops/jenkins-and-jmeter)
- [Write Extracted Data to a File Using JMeter](https://www.baeldung.com/jmeter-write-to-file)
- [Basic Authentication in JMeter](https://www.baeldung.com/jmeter-basic-auth)
- [JMeter: Latency vs. Load Time](https://www.baeldung.com/java-jmeter-latency-vs-load-time/)
- [JMeter: Latency vs. Load Time](https://www.baeldung.com/java-jmeter-latency-vs-load-time)

View File

@ -0,0 +1,2 @@
## Relevant Articles
- [Lightweight Logging With tinylog 2](https://www.baeldung.com/java-logging-tinylog-guide)

View File

@ -2,4 +2,5 @@
This module contains articles about RestExpress.
### Relevant articles
### Relevant articles
- [RESTful Microservices With RestExpress](https://www.baeldung.com/java-restexpress-guide)

View File

@ -2,3 +2,4 @@
- [Database Migrations with Flyway](http://www.baeldung.com/database-migrations-with-flyway)
- [A Guide to Flyway Callbacks](http://www.baeldung.com/flyway-callbacks)
- [Rolling Back Migrations with Flyway](https://www.baeldung.com/flyway-roll-back)
- [Flyway Out of Order Migrations](https://www.baeldung.com/flyway-migrations)

View File

@ -0,0 +1,85 @@
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.examples.scylladb</groupId>
<artifactId>scylladb</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>scylladb</name>
<description>Sample ScyllaDB Project</description>
<properties>
<testcontainers.version>1.17.6</testcontainers.version>
</properties>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.scylladb</groupId>
<artifactId>java-driver-core</artifactId>
<version>4.14.1.0</version>
</dependency>
<dependency>
<groupId>com.scylladb</groupId>
<artifactId>java-driver-query-builder</artifactId>
<version>4.14.1.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-bom</artifactId>
<version>${testcontainers.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,89 @@
package com.baeldung.scylladb;
import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.insertInto;
import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.literal;
import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.selectFrom;
import static com.datastax.oss.driver.api.querybuilder.SchemaBuilder.createKeyspace;
import static com.datastax.oss.driver.api.querybuilder.SchemaBuilder.createTable;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.scylladb.model.User;
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.Row;
import com.datastax.oss.driver.api.core.cql.SimpleStatement;
import com.datastax.oss.driver.api.core.type.DataTypes;
import com.datastax.oss.driver.api.querybuilder.insert.InsertInto;
import com.datastax.oss.driver.api.querybuilder.schema.CreateKeyspaceStart;
import com.datastax.oss.driver.api.querybuilder.schema.CreateTableStart;
import com.datastax.oss.driver.api.querybuilder.select.Select;
public class ScylladbApplication {
private String keySpaceName;
private String tableName;
public ScylladbApplication(String keySpaceName, String tableName) {
this.keySpaceName = keySpaceName;
this.tableName = tableName;
CreateKeyspaceStart createKeyspace = createKeyspace(keySpaceName);
SimpleStatement keypaceStatement = createKeyspace.ifNotExists()
.withSimpleStrategy(3)
.build();
CreateTableStart createTable = createTable(keySpaceName, tableName);
SimpleStatement tableStatement = createTable.ifNotExists()
.withPartitionKey("id", DataTypes.BIGINT)
.withColumn("name", DataTypes.TEXT)
.build();
try (CqlSession session = CqlSession.builder().build()) {
ResultSet rs = session.execute(keypaceStatement);
if (null == rs.getExecutionInfo().getErrors() || rs.getExecutionInfo().getErrors().isEmpty()) {
rs = session.execute(tableStatement);
}
}
}
public List<String> getAllUserNames() {
List<String> userNames = new ArrayList<>();
try (CqlSession session = CqlSession.builder().build()) {
String query = String.format("select * from %s.%s",keySpaceName,tableName);
ResultSet rs = session.execute(query);
for (Row r : rs.all())
userNames.add(r.getString("name"));
}
return userNames;
}
public List<User> getUsersByUserName(String userName) {
List<User> userList = new ArrayList<>();
try (CqlSession session = CqlSession.builder().build()) {
Select query = selectFrom(keySpaceName, tableName).all()
.whereColumn("name")
.isEqualTo(literal(userName))
.allowFiltering();
SimpleStatement statement = query.build();
ResultSet rs = session.execute(statement);
for (Row r : rs)
userList.add(new User(r.getLong("id"), r.getString("name")));
}
return userList;
}
public boolean addNewUser(User user) {
boolean response = false;
try (CqlSession session = CqlSession.builder().build()) {
InsertInto insert = insertInto(keySpaceName, tableName);
SimpleStatement statement = insert.value("id", literal(user.getId()))
.value("name", literal(user.getName()))
.build();
ResultSet rs = session.execute(statement);
response = null == rs.getExecutionInfo().getErrors() || rs.getExecutionInfo().getErrors().isEmpty();
}
return response;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.scylladb.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class User {
private long id;
private String name;
}

View File

@ -0,0 +1,3 @@
datastax-java-driver:
basic:
contact-points: 127.0.0.1:9042

View File

@ -0,0 +1,68 @@
package com.baeldung.scylladb;
import static org.junit.Assert.assertEquals;
import java.util.List;
import java.util.function.Consumer;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;
import com.baeldung.scylladb.model.User;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.model.ExposedPort;
import com.github.dockerjava.api.model.PortBinding;
import com.github.dockerjava.api.model.Ports;
@Testcontainers
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class ScyllaDBApplicationLiveTest {
private static final String IMAGE_NAME = "scylladb/scylla";
private static final int hostPort = 9042;
private static final int containerExposedPort = 9042;
private static Consumer<CreateContainerCmd> cmd = e -> e.withPortBindings(new PortBinding(Ports.Binding.bindPort(hostPort),
new ExposedPort(containerExposedPort)));
@Container
private static final GenericContainer scyllaDbContainer = new GenericContainer(DockerImageName.parse(IMAGE_NAME))
.withExposedPorts(containerExposedPort)
.withCreateContainerCmdModifier(cmd);
private ScylladbApplication scylladbApplication;
@BeforeAll
void setUp() {
scylladbApplication = new ScylladbApplication("baeldung", "User");
}
@Test
public void givenKeySpaceAndTable_whenInsertData_thenShouldBeAbleToFindData() {
User user = new User(10, "John");
scylladbApplication.addNewUser(user);
List<User> userList = scylladbApplication.getUsersByUserName("John");
assertEquals(1, userList.size());
assertEquals("John", userList.get(0).getName());
assertEquals(10, userList.get(0).getId());
}
@Test
public void givenKeySpaceAndTable_whenInsertData_thenRowCountIncreases() {
int initialCount = scylladbApplication.getAllUserNames().size();
User user = new User(11, "Doe");
scylladbApplication.addNewUser(user);
int expectedCount = initialCount+1;
int updatedCount = scylladbApplication.getAllUserNames().size();
assertEquals(expectedCount, updatedCount);
}
}

View File

@ -0,0 +1,3 @@
datastax-java-driver:
basic:
contact-points: 127.0.0.1:9042

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

@ -7,4 +7,5 @@
- [LIKE Queries in Spring JPA Repositories](https://www.baeldung.com/spring-jpa-like-queries)
- [How to Access EntityManager with Spring Data](https://www.baeldung.com/spring-data-entitymanager)
- [Difference Between JPA and Spring Data JPA](https://www.baeldung.com/spring-data-jpa-vs-jpa)
- [Differences Between Spring Data JPA findFirst() and findTop()](https://www.baeldung.com/spring-data-jpa-findfirst-vs-findtop)
- More articles: [[<-- prev]](../spring-data-jpa-repo)

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

@ -4,4 +4,4 @@ This module contains articles about Spring with Kafka
### Relevant articles
- [Implementing Retry In Kafka Consumer]
- [Implementing Retry In Kafka Consumer](https://www.baeldung.com/spring-retry-kafka-consumer)

View File

@ -23,6 +23,7 @@
<module>spring-5-reactive-3</module>
<module>spring-5-reactive-client</module>
<module>spring-5-reactive-client-2</module>
<module>spring-5-reactive-filters</module>
<module>spring-5-reactive-oauth</module>
<module>spring-5-reactive-security</module>
<module>spring-reactive</module>

View File

@ -0,0 +1,12 @@
#folders#
.idea
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -0,0 +1,15 @@
## Spring 5 Reactive Project
This module contains articles about reactive Spring 5
### The Course
The "REST With Spring" Classes: https://bit.ly/restwithspring
### Relevant Articles
- [Exploring the Spring 5 WebFlux URL Matching](https://www.baeldung.com/spring-5-mvc-url-matching)
- [Reactive WebSockets with Spring 5](https://www.baeldung.com/spring-5-reactive-websockets)
- [Spring WebFlux Filters](https://www.baeldung.com/spring-webflux-filters)
- [How to Set a Header on a Response with Spring 5](https://www.baeldung.com/spring-response-header)
- [A Guide to Spring Session Reactive Support: WebSession](https://www.baeldung.com/spring-session-reactive)
- More articles: [[next -->]](../spring-5-reactive-2)

View File

@ -0,0 +1,68 @@
<?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-5-reactive-filters</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-5-reactive-filters</name>
<packaging>jar</packaging>
<description>spring 5 sample project about new features</description>
<parent>
<groupId>com.baeldung.spring.reactive</groupId>
<artifactId>spring-reactive-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<!-- runtime and test scoped -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Fix ERROR i.n.r.d.DnsServerAddressStreamProviders - Unable to load io.netty.resolver.dns.macos.MacOSDnsServerAddressStreamProvider -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.baeldung.reactive.Spring5ReactiveFiltersApplication</mainClass>
<layout>JAR</layout>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

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

View File

@ -0,0 +1 @@
logging.level.root=INFO

View File

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

View File

@ -0,0 +1,17 @@
package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.reactive.Spring5ReactiveFiltersApplication;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Spring5ReactiveFiltersApplication.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

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

@ -23,6 +23,7 @@
<module>spring-mvc-basics-4</module>
<module>spring-mvc-basics-5</module>
<module>spring-mvc-crash</module>
<module>spring-mvc-file</module>
<module>spring-mvc-forms-jsp</module>
<module>spring-mvc-forms-thymeleaf</module>
<module>spring-mvc-java</module>

View File

@ -0,0 +1,9 @@
*.class
#folders#
/target
# Packaged files #
*.jar
*.war
*.ear

View File

@ -0,0 +1,9 @@
## Spring MVC File
### The Course
### Relevant Articles:

View File

@ -0,0 +1,50 @@
<?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-mvc-file</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-mvc-file</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
</dependencies>
<build>
<finalName>spring-mvc-file</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.baeldung.Application</mainClass>
<layout>JAR</layout>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

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

View File

@ -0,0 +1,60 @@
package com.baeldung.file;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.web.multipart.MultipartFile;
public class CustomMultipartFile implements MultipartFile {
private byte[] input;
public CustomMultipartFile(byte[] input) {
this.input = input;
}
@Override
public String getName() {
return null;
}
@Override
public String getOriginalFilename() {
return null;
}
@Override
public String getContentType() {
return null;
}
@Override
public boolean isEmpty() {
return input == null || input.length == 0;
}
@Override
public long getSize() {
return input.length;
}
@Override
public byte[] getBytes() throws IOException {
return input;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(input);
}
@Override
public void transferTo(File destination) throws IOException, IllegalStateException {
try(FileOutputStream fos = new FileOutputStream(destination)) {
fos.write(input);
}
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.file;
import java.io.IOException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockMultipartFile;
class CustomMultipartFileUnitTest {
@Test
void whenProvidingByteArray_thenMultipartFileCreated() throws IOException {
byte[] inputArray = "Test String".getBytes();
CustomMultipartFile customMultipartFile = new CustomMultipartFile(inputArray);
Assertions.assertFalse(customMultipartFile.isEmpty());
Assertions.assertArrayEquals(inputArray, customMultipartFile.getBytes());
Assertions.assertEquals(inputArray.length, customMultipartFile.getSize());
}
@Test
void whenProvidingEmptyByteArray_thenMockMultipartFileIsEmpty() throws IOException {
byte[] inputArray = "".getBytes();
MockMultipartFile mockMultipartFile = new MockMultipartFile("tempFileName", inputArray);
Assertions.assertTrue(mockMultipartFile.isEmpty());
}
@Test
void whenProvidingNullByteArray_thenMockMultipartFileIsEmpty() throws IOException {
byte[] inputArray = null;
MockMultipartFile mockMultipartFile = new MockMultipartFile("tempFileName", inputArray);
Assertions.assertTrue(mockMultipartFile.isEmpty());
}
@Test
void whenProvidingByteArray_thenMultipartFileInputSizeMatches() throws IOException {
byte[] inputArray = "Testing String".getBytes();
CustomMultipartFile customMultipartFile = new CustomMultipartFile(inputArray);
Assertions.assertEquals(inputArray.length, customMultipartFile.getSize());
}
@Test
void whenProvidingByteArray_thenMockMultipartFileCreated() throws IOException {
byte[] inputArray = "Test String".getBytes();
MockMultipartFile mockMultipartFile = new MockMultipartFile("tempFileName", inputArray);
Assertions.assertFalse(mockMultipartFile.isEmpty());
Assertions.assertArrayEquals(inputArray, mockMultipartFile.getBytes());
Assertions.assertEquals(inputArray.length, mockMultipartFile.getSize());
}
}

View File

@ -6,3 +6,4 @@ This module contains articles about Spring MVC
- [Using a Slash Character in Spring URLs](https://www.baeldung.com/spring-slash-character-in-url)
- [Excluding URLs for a Filter in a Spring Web Application](https://www.baeldung.com/spring-exclude-filter)
- [Handling URL Encoded Form Data in Spring REST](https://www.baeldung.com/spring-url-encoded-form-data)
- [Spring MVC Mapping the Root URL to a Page](https://www.baeldung.com/spring-mvc-map-root-url)

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());
}
}