Merge branch 'eugenp:master' into master

This commit is contained in:
Alexandru Borza
2023-02-06 21:23:03 +02:00
committed by GitHub
142 changed files with 2905 additions and 856 deletions
+4 -1
View File
@@ -33,7 +33,9 @@ Next, they are segregated further on the basis of the tests that we want to exec
Additionally, there are 2 profiles dedicated for JDK9 and above builds. Additionally, there are 2 profiles dedicated for JDK9 and above builds.
Therefore, we have a total of 8 profiles: We also have a parents profile to build only parent modules.
Therefore, we have a total of 9 profiles:
| Profile | Includes | Type of test enabled | | Profile | Includes | Type of test enabled |
| -------------------------- | --------------------------- | -------------------- | | -------------------------- | --------------------------- | -------------------- |
@@ -45,6 +47,7 @@ Therefore, we have a total of 8 profiles:
| integration-heavy | Heavy/long running projects | *IntegrationTest | | integration-heavy | Heavy/long running projects | *IntegrationTest |
| default-jdk9-and-above | JDK9 and above projects | *UnitTest | | default-jdk9-and-above | JDK9 and above projects | *UnitTest |
| integration-jdk9-and-above | JDK9 and above projects | *IntegrationTest | | integration-jdk9-and-above | JDK9 and above projects | *IntegrationTest |
| parents | Set of parent modules | None |
Building the project Building the project
==================== ====================
+1
View File
@@ -36,6 +36,7 @@
</dependency> </dependency>
</dependencies> </dependencies>
<properties> <properties>
<akka.http.version>10.0.11</akka.http.version> <akka.http.version>10.0.11</akka.http.version>
<akka.stream.version>2.5.11</akka.stream.version> <akka.stream.version>2.5.11</akka.stream.version>
@@ -21,6 +21,7 @@
</dependency> </dependency>
</dependencies> </dependencies>
<properties> <properties>
<auto-service.version>1.0-rc2</auto-service.version> <auto-service.version>1.0-rc2</auto-service.version>
</properties> </properties>
+40
View File
@@ -54,6 +54,42 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency>
<groupId>org.apache.httpcomponents.core5</groupId>
<artifactId>httpcore5</artifactId>
<version>${httpcore5.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</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>
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>${httpclient5.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency> <dependency>
<groupId>com.github.tomakehurst</groupId> <groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId> <artifactId>wiremock</artifactId>
@@ -78,6 +114,10 @@
<!-- testing --> <!-- testing -->
<wiremock.version>2.5.1</wiremock.version> <wiremock.version>2.5.1</wiremock.version>
<httpclient.version>4.5.8</httpclient.version> <!-- 4.3.6 --> <!-- 4.4-beta1 --> <httpclient.version>4.5.8</httpclient.version> <!-- 4.3.6 --> <!-- 4.4-beta1 -->
<!-- http client & core 5 -->
<httpcore5.version>5.2</httpcore5.version>
<httpclient5.version>5.2</httpclient5.version>
<httpclient5-fluent.version>5.2</httpclient5-fluent.version>
</properties> </properties>
</project> </project>
@@ -1,19 +1,24 @@
package com.baeldung.httpclient; package com.baeldung.httpclient;
import org.apache.http.HttpEntity; import static org.hamcrest.MatcherAssert.assertThat;
import org.apache.http.HttpStatus; import static org.hamcrest.Matchers.equalTo;
import org.apache.http.client.methods.CloseableHttpResponse; import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType; import org.junit.jupiter.api.BeforeEach;
import org.apache.http.entity.mime.HttpMultipartMode; import org.junit.jupiter.api.Test;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody; import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.http.entity.mime.content.StringBody; import org.apache.hc.client5.http.entity.mime.FileBody;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.hc.client5.http.entity.mime.HttpMultipartMode;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.junit.After; import org.apache.hc.client5.http.entity.mime.StringBody;
import org.junit.Before; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.junit.Test; import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpStatus;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
@@ -22,14 +27,10 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.URL; import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.hamcrest.Matchers.equalTo; import com.baeldung.httpclient.handler.CustomHttpClientResponseHandler;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class HttpClientMultipartLiveTest { class HttpClientMultipartLiveTest {
// No longer available // No longer available
// private static final String SERVER = "http://echo.200please.com"; // private static final String SERVER = "http://echo.200please.com";
@@ -38,41 +39,16 @@ public class HttpClientMultipartLiveTest {
private static final String TEXTFILENAME = "temp.txt"; private static final String TEXTFILENAME = "temp.txt";
private static final String IMAGEFILENAME = "image.jpg"; private static final String IMAGEFILENAME = "image.jpg";
private static final String ZIPFILENAME = "zipFile.zip"; private static final String ZIPFILENAME = "zipFile.zip";
private static final Logger LOGGER = Logger.getLogger("com.baeldung.httpclient.HttpClientMultipartLiveTest");
private CloseableHttpClient client;
private HttpPost post; private HttpPost post;
private BufferedReader rd; private BufferedReader rd;
private CloseableHttpResponse response;
@Before @BeforeEach
public final void before() { public void before() {
client = HttpClientBuilder.create()
.build();
post = new HttpPost(SERVER); post = new HttpPost(SERVER);
} }
@After
public final void after() throws IllegalStateException, IOException {
post.completed();
try {
client.close();
} catch (final IOException e1) {
LOGGER.log(Level.SEVERE, e1.getMessage(), e1);
throw e1;
}
try {
rd.close();
} catch (final IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
throw e;
}
ResponseUtil.closeResponse(response);
}
// tests
@Test @Test
public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException { void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException {
final URL url = Thread.currentThread() final URL url = Thread.currentThread()
.getContextClassLoader() .getContextClassLoader()
.getResource("uploads/" + TEXTFILENAME); .getResource("uploads/" + TEXTFILENAME);
@@ -83,53 +59,61 @@ public class HttpClientMultipartLiveTest {
final StringBody stringBody2 = new StringBody("This is message 2", ContentType.MULTIPART_FORM_DATA); final StringBody stringBody2 = new StringBody("This is message 2", ContentType.MULTIPART_FORM_DATA);
// //
final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.setMode(HttpMultipartMode.LEGACY);
builder.addPart("file", fileBody); builder.addPart("file", fileBody);
builder.addPart("text1", stringBody1); builder.addPart("text1", stringBody1);
builder.addPart("text2", stringBody2); builder.addPart("text2", stringBody2);
final HttpEntity entity = builder.build(); final HttpEntity entity = builder.build();
//
post.setEntity(entity);
response = client.execute(post);
final int statusCode = response.getStatusLine() post.setEntity(entity);
.getStatusCode(); try(CloseableHttpClient client = HttpClientBuilder.create()
final String responseString = getContent(); .build();
final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK)); CloseableHttpResponse response = (CloseableHttpResponse) client
// assertTrue(responseString.contains("Content-Type: multipart/form-data;")); .execute(post, new CustomHttpClientResponseHandler())){
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); final int statusCode = response.getCode();
System.out.println(responseString); final String responseString = getContent(response.getEntity());
System.out.println("POST Content Type: " + contentTypeInHeader); final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
System.out.println(responseString);
System.out.println("POST Content Type: " + contentTypeInHeader);
}
} }
@Test @Test
public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException { void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException {
final URL url = Thread.currentThread() final URL url = Thread.currentThread()
.getContextClassLoader() .getContextClassLoader()
.getResource("uploads/" + TEXTFILENAME); .getResource("uploads/" + TEXTFILENAME);
final File file = new File(url.getPath()); final File file = new File(url.getPath());
final String message = "This is a multipart post"; final String message = "This is a multipart post";
final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.setMode(HttpMultipartMode.LEGACY);
builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, TEXTFILENAME); builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, TEXTFILENAME);
builder.addTextBody("text", message, ContentType.DEFAULT_BINARY); builder.addTextBody("text", message, ContentType.DEFAULT_BINARY);
final HttpEntity entity = builder.build(); final HttpEntity entity = builder.build();
post.setEntity(entity); post.setEntity(entity);
response = client.execute(post);
final int statusCode = response.getStatusLine() try(CloseableHttpClient client = HttpClientBuilder.create()
.getStatusCode(); .build();
final String responseString = getContent();
final String contentTypeInHeader = getContentTypeHeader(); CloseableHttpResponse response = (CloseableHttpResponse) client
assertThat(statusCode, equalTo(HttpStatus.SC_OK)); .execute(post, new CustomHttpClientResponseHandler())){
// assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); final int statusCode = response.getCode();
System.out.println(responseString); final String responseString = getContent(response.getEntity());
System.out.println("POST Content Type: " + contentTypeInHeader); final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
System.out.println(responseString);
System.out.println("POST Content Type: " + contentTypeInHeader);
}
} }
@Test @Test
public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
final URL url = Thread.currentThread() final URL url = Thread.currentThread()
.getContextClassLoader() .getContextClassLoader()
.getResource("uploads/" + ZIPFILENAME); .getResource("uploads/" + ZIPFILENAME);
@@ -140,64 +124,75 @@ public class HttpClientMultipartLiveTest {
final File file = new File(url2.getPath()); final File file = new File(url2.getPath());
final String message = "This is a multipart post"; final String message = "This is a multipart post";
final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.setMode(HttpMultipartMode.STRICT);
builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, IMAGEFILENAME); builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, IMAGEFILENAME);
builder.addBinaryBody("upstream", inputStream, ContentType.create("application/zip"), ZIPFILENAME); builder.addBinaryBody("upstream", inputStream, ContentType.create("application/zip"), ZIPFILENAME);
builder.addTextBody("text", message, ContentType.TEXT_PLAIN); builder.addTextBody("text", message, ContentType.TEXT_PLAIN);
final HttpEntity entity = builder.build(); final HttpEntity entity = builder.build();
post.setEntity(entity); post.setEntity(entity);
response = client.execute(post);
final int statusCode = response.getStatusLine() try(CloseableHttpClient client = HttpClientBuilder.create()
.getStatusCode(); .build();
final String responseString = getContent();
final String contentTypeInHeader = getContentTypeHeader(); CloseableHttpResponse response = (CloseableHttpResponse) client
assertThat(statusCode, equalTo(HttpStatus.SC_OK)); .execute(post, new CustomHttpClientResponseHandler())){
// assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); final int statusCode = response.getCode();
System.out.println(responseString); final String responseString = getContent(response.getEntity());
System.out.println("POST Content Type: " + contentTypeInHeader); final String contentTypeInHeader = getContentTypeHeader();
inputStream.close(); assertThat(statusCode, equalTo(HttpStatus.SC_OK));
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
System.out.println(responseString);
System.out.println("POST Content Type: " + contentTypeInHeader);
inputStream.close();
}
} }
@Test @Test
public final void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
final String message = "This is a multipart post"; final String message = "This is a multipart post";
final byte[] bytes = "binary code".getBytes(); final byte[] bytes = "binary code".getBytes();
final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.setMode(HttpMultipartMode.STRICT);
builder.addBinaryBody("file", bytes, ContentType.DEFAULT_BINARY, TEXTFILENAME); builder.addBinaryBody("file", bytes, ContentType.DEFAULT_BINARY, TEXTFILENAME);
builder.addTextBody("text", message, ContentType.TEXT_PLAIN); builder.addTextBody("text", message, ContentType.TEXT_PLAIN);
final HttpEntity entity = builder.build(); final HttpEntity entity = builder.build();
post.setEntity(entity); post.setEntity(entity);
response = client.execute(post);
final int statusCode = response.getStatusLine() try(CloseableHttpClient client = HttpClientBuilder.create()
.getStatusCode(); .build();
final String responseString = getContent();
final String contentTypeInHeader = getContentTypeHeader(); CloseableHttpResponse response = (CloseableHttpResponse) client
assertThat(statusCode, equalTo(HttpStatus.SC_OK)); .execute(post, new CustomHttpClientResponseHandler())){
// assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); final int statusCode = response.getCode();
System.out.println(responseString); final String responseString = getContent(response.getEntity());
System.out.println("POST Content Type: " + contentTypeInHeader); final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
System.out.println(responseString);
System.out.println("POST Content Type: " + contentTypeInHeader);
}
} }
// UTIL // UTIL
private String getContent() throws IOException { private String getContent(HttpEntity httpEntity) throws IOException {
rd = new BufferedReader(new InputStreamReader(response.getEntity() rd = new BufferedReader(new InputStreamReader(httpEntity.getContent()));
.getContent()));
String body = ""; String body = "";
StringBuilder content = new StringBuilder(); StringBuilder content = new StringBuilder();
while ((body = rd.readLine()) != null) { while ((body = rd.readLine()) != null) {
content.append(body).append("\n"); content.append(body)
.append("\n");
} }
return content.toString().trim(); return content.toString()
.trim();
} }
private String getContentTypeHeader() throws IOException { private String getContentTypeHeader() {
return post.getEntity() return post.getEntity()
.getContentType() .getContentType();
.toString();
} }
} }
@@ -0,0 +1,11 @@
package com.baeldung.httpclient.handler;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
public class CustomHttpClientResponseHandler implements HttpClientResponseHandler<ClassicHttpResponse> {
@Override
public ClassicHttpResponse handleResponse(ClassicHttpResponse response) {
return response;
}
}
@@ -27,7 +27,8 @@ import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest(classes = OrderApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @SpringBootTest(classes = OrderApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class OrderRestEndpointIntegrationTest { //marked as manual as the test is unstable on Jenkins due to low resources
class OrderRestEndpointManualTest {
@LocalServerPort @LocalServerPort
private int port; private int port;
@@ -5,3 +5,4 @@ This module contains articles about Java 11 core features
### Relevant articles ### Relevant articles
- [Adding Parameters to Java HttpClient Requests](https://www.baeldung.com/java-httpclient-request-parameters) - [Adding Parameters to Java HttpClient Requests](https://www.baeldung.com/java-httpclient-request-parameters)
- [Writing a List of Strings Into a Text File](https://www.baeldung.com/java-list-to-text-file) - [Writing a List of Strings Into a Text File](https://www.baeldung.com/java-list-to-text-file)
- [Java HttpClient – Map JSON Response to Java Class](https://www.baeldung.com/java-httpclient-map-json-response)
+1
View File
@@ -1,2 +1,3 @@
## Relevant Articles ## Relevant Articles
- [Record Patterns in Java 19](https://www.baeldung.com/java-19-record-patterns) - [Record Patterns in Java 19](https://www.baeldung.com/java-19-record-patterns)
- [Structured Concurrency in Java 19](https://www.baeldung.com/java-structured-concurrency)
@@ -0,0 +1,63 @@
package com.baeldung.array.conversions;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
public class StringArrayToIntArrayUnitTest {
private final String[] stringArray = new String[] { "1", "2", "3", "4", "5", "6", "42" };
private final int[] expected = new int[] { 1, 2, 3, 4, 5, 6, 42 };
private final String[] stringArrayWithInvalidNum = new String[] { "1", "2", "hello", "4", "world", "6", "42" };
private final int[] expectedWithInvalidInput = new int[] { 1, 2, Integer.MIN_VALUE, 4, Integer.MIN_VALUE, 6, 42 };
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Test
void givenStringArray_whenUseStreamApi_shouldGetExpectedIntArray() {
int[] result = Arrays.stream(stringArray).mapToInt(Integer::parseInt).toArray();
assertArrayEquals(expected, result);
}
@Test
void givenStringArrayWithInvalidNum_whenUseStreamApi_shouldGetExpectedIntArray() {
int[] result = Arrays.stream(stringArrayWithInvalidNum).mapToInt(s -> {
try {
return Integer.parseInt(s);
} catch (NumberFormatException ex) {
logger.warn("Invalid number format detected: {}, use Int.MinValue as the fallback", s);
return Integer.MIN_VALUE;
}
}).toArray();
assertArrayEquals(expectedWithInvalidInput, result);
}
@Test
void givenStringArray_whenConvertInLoop_shouldGetExpectedIntArray() {
int[] result = new int[stringArray.length];
for (int i = 0; i < stringArray.length; i++) {
result[i] = Integer.parseInt(stringArray[i]);
}
assertArrayEquals(expected, result);
}
@Test
void givenStringArrayWithInvalidNum_whenConvertInLoop_shouldGetExpectedIntArray() {
int[] result = new int[stringArrayWithInvalidNum.length];
for (int i = 0; i < stringArrayWithInvalidNum.length; i++) {
try {
result[i] = Integer.parseInt(stringArrayWithInvalidNum[i]);
} catch (NumberFormatException exception) {
logger.warn("Invalid number format detected: [{}], use Int.MinValue as the fallback", stringArrayWithInvalidNum[i]);
result[i] = Integer.MIN_VALUE;
}
}
assertArrayEquals(expectedWithInvalidInput, result);
}
}
@@ -6,8 +6,7 @@ import com.baeldung.callbackfunctions.EventListener;
import com.baeldung.callbackfunctions.asynchronous.AsynchronousEventConsumer; import com.baeldung.callbackfunctions.asynchronous.AsynchronousEventConsumer;
import com.baeldung.callbackfunctions.asynchronous.AsynchronousEventListenerImpl; import com.baeldung.callbackfunctions.asynchronous.AsynchronousEventListenerImpl;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.*;
import static org.mockito.Mockito.verify;
public class AsynchronousCallbackUnitTest { public class AsynchronousCallbackUnitTest {
@@ -17,6 +16,6 @@ public class AsynchronousCallbackUnitTest {
AsynchronousEventConsumer asynchronousEventListenerConsumer = new AsynchronousEventConsumer(listener); AsynchronousEventConsumer asynchronousEventListenerConsumer = new AsynchronousEventConsumer(listener);
asynchronousEventListenerConsumer.doAsynchronousOperation(); asynchronousEventListenerConsumer.doAsynchronousOperation();
verify(listener, times(1)).onTrigger(); verify(listener, timeout(1000).times(1)).onTrigger();
} }
} }
@@ -3,18 +3,25 @@ package com.baeldung.callbackfunctions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import com.baeldung.callbackfunctions.ConsumerCallback; import com.baeldung.callbackfunctions.ConsumerCallback;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
public class ConsumerCallbackUnitTest { public class ConsumerCallbackUnitTest {
@Test @Test
public void whenIncreasingInitialAgeByGivenValueThroughCallback_shouldIncreaseAge(){ void whenIncreasingInitialAgeByGivenValueThroughCallback_shouldIncreaseAge(){
ConsumerCallback consumerCallback = new ConsumerCallback(); ConsumerCallback consumerCallback = new ConsumerCallback();
consumerCallback.getAge(20, (initialAge) -> { int ageDifference = 10;
int ageDifference = 10; AtomicInteger newAge1 = new AtomicInteger();
int initialAge = 20;
consumerCallback.getAge(initialAge, (initialAge1) -> {
consumerCallback.increaseAge(initialAge, ageDifference, (newAge) -> { consumerCallback.increaseAge(initialAge, ageDifference, (newAge) -> {
assertEquals(initialAge + ageDifference, newAge); System.out.printf("New age ==> %s", newAge);
newAge1.set(newAge);
}); });
}); });
assertEquals(initialAge + ageDifference, newAge1.get());
} }
} }
@@ -14,3 +14,4 @@ This module contains articles about core features in the Java language
- [Convert Between int and char in Java](https://www.baeldung.com/java-convert-int-char) - [Convert Between int and char in Java](https://www.baeldung.com/java-convert-int-char)
- [Converting a Number from One Base to Another in Java](https://www.baeldung.com/java-converting-a-number-from-one-base-to-another) - [Converting a Number from One Base to Another in Java](https://www.baeldung.com/java-converting-a-number-from-one-base-to-another)
- [Check if Command-Line Arguments Are Null in Java](https://www.baeldung.com/java-check-command-line-args) - [Check if Command-Line Arguments Are Null in Java](https://www.baeldung.com/java-check-command-line-args)
- [Determine if a Class Implements an Interface in Java](https://www.baeldung.com/java-check-class-implements-interface)
@@ -14,6 +14,12 @@
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
</parent> </parent>
<properties>
<commons-lang3.version>3.12.0</commons-lang3.version>
<reflections.version>0.10.2</reflections.version>
</properties>
<build> <build>
<finalName>core-java-lang-5</finalName> <finalName>core-java-lang-5</finalName>
<resources> <resources>
@@ -24,4 +30,18 @@
</resources> </resources>
</build> </build>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>${reflections.version}</version>
</dependency>
</dependencies>
</project> </project>
@@ -0,0 +1,5 @@
package com.baeldung.checkinterface;
public class ChildClass1 implements ChildInterface1 {
}
@@ -0,0 +1,5 @@
package com.baeldung.checkinterface;
public class ChildClass2 implements ChildInterface2 {
}
@@ -0,0 +1,5 @@
package com.baeldung.checkinterface;
public interface ChildInterface1 extends MasterInterface {
}
@@ -0,0 +1,5 @@
package com.baeldung.checkinterface;
public interface ChildInterface2 extends MasterInterface {
}
@@ -0,0 +1,5 @@
package com.baeldung.checkinterface;
public class MasterClass implements MasterInterface {
}
@@ -0,0 +1,5 @@
package com.baeldung.checkinterface;
public interface MasterInterface {
}
@@ -0,0 +1,154 @@
package com.baeldung.checkinterface;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.ClassUtils;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.reflections.ReflectionUtils;
import org.reflections.Reflections;
public class CheckInterfaceUnitTest {
protected static Reflections reflections;
@BeforeAll
public static void initializeReflectionsLibrary() {
reflections = new Reflections("com.baeldung.checkinterface");
}
@Test
public void whenUsingReflectionGetInterfaces_thenDirectlyImplementedInterfaceIsFound() {
ChildClass2 childClass2 = new ChildClass2();
List<Class<?>> interfaces = Arrays.asList(childClass2.getClass().getInterfaces());
assertEquals(1, interfaces.size());
assertTrue(interfaces.contains(ChildInterface2.class));
}
@Test
public void whenUsingReflectionGetInterfaces_thenParentInterfaceIsNotFound() {
ChildClass2 childClass2 = new ChildClass2();
List<Class<?>> interfaces = Arrays.asList(childClass2.getClass().getInterfaces());
assertFalse(interfaces.contains(MasterInterface.class));
}
@Test
public void whenUsingReflectionGetInterfacesRecursively_thenParentInterfaceIsFound() {
Set<Class<?>> interfaces = getAllExtendedOrImplementedInterfacesRecursively(ChildClass2.class);
assertTrue(interfaces.contains(ChildInterface2.class));
assertTrue(interfaces.contains(MasterInterface.class));
}
@Test
public void whenUsingReflectionIsAssignableFrom_thenDirectlyImplementedInterfaceIsFound() {
ChildClass2 childClass2 = new ChildClass2();
assertTrue(ChildInterface2.class.isAssignableFrom(childClass2.getClass()));
}
@Test
public void whenUsingReflectionIsAssignableFrom_thenParentInterfaceIsFound() {
ChildClass2 childClass2 = new ChildClass2();
assertTrue(MasterInterface.class.isAssignableFrom(childClass2.getClass()));
}
@Test
public void whenUsingReflectionIsInstance_thenDirectlyImplementedInterfaceIsFound() {
ChildClass2 childClass2 = new ChildClass2();
assertTrue(ChildInterface2.class.isInstance(childClass2));
}
@Test
public void whenUsingReflectionIsInstance_thenParentInterfaceIsFound() {
ChildClass2 childClass2 = new ChildClass2();
assertTrue(MasterInterface.class.isInstance(childClass2));
}
@Test
public void whenUsingReflectionInstanceOf_thenDirectlyImplementedInterfaceIsFound() {
ChildClass2 childClass2 = new ChildClass2();
assertTrue(childClass2 instanceof ChildInterface2);
}
@Test
public void whenUsingReflectionInstanceOf_thenParentInterfaceIsFound() {
ChildClass2 childClass2 = new ChildClass2();
assertTrue(childClass2 instanceof MasterInterface);
}
@Test
public void whenUsingCommons_thenDirectlyImplementedInterfaceIsFound() {
ChildClass2 childClass2 = new ChildClass2();
List<Class<?>> interfaces = ClassUtils.getAllInterfaces(childClass2.getClass());
assertTrue(interfaces.contains(ChildInterface2.class));
}
@Test
public void whenUsingCommons_thenParentInterfaceIsFound() {
ChildClass2 childClass2 = new ChildClass2();
List<Class<?>> interfaces = ClassUtils.getAllInterfaces(childClass2.getClass());
assertTrue(interfaces.contains(MasterInterface.class));
}
@Test
public void whenUsingReflections_thenDirectlyImplementedInterfaceIsFound() {
ChildClass2 childClass2 = new ChildClass2();
Set<Class<?>> interfaces = reflections.get(ReflectionUtils.Interfaces.of(childClass2.getClass()));
assertTrue(interfaces.contains(ChildInterface2.class));
}
@Test
public void whenUsingReflections_thenParentInterfaceIsFound() {
ChildClass2 childClass2 = new ChildClass2();
Set<Class<?>> interfaces = reflections.get(ReflectionUtils.Interfaces.of(childClass2.getClass()));
assertTrue(interfaces.contains(MasterInterface.class));
}
static Set<Class<?>> getAllExtendedOrImplementedInterfacesRecursively(Class<?> clazz) {
Set<Class<?>> res = new HashSet<Class<?>>();
Class<?>[] interfaces = clazz.getInterfaces();
if (interfaces.length > 0) {
res.addAll(Arrays.asList(interfaces));
for (Class<?> interfaze : interfaces) {
res.addAll(getAllExtendedOrImplementedInterfacesRecursively(interfaze));
}
}
return res;
}
}
@@ -8,3 +8,4 @@ This module contains articles about types in Java
- [Check if an Enum Value Exists in Java](https://www.baeldung.com/java-search-enum-values) - [Check if an Enum Value Exists in Java](https://www.baeldung.com/java-search-enum-values)
- [Generate a Random Value From an Enum](https://www.baeldung.com/java-enum-random-value) - [Generate a Random Value From an Enum](https://www.baeldung.com/java-enum-random-value)
- [Filling a List With All Enum Values in Java](https://www.baeldung.com/java-enum-values-to-list) - [Filling a List With All Enum Values in Java](https://www.baeldung.com/java-enum-values-to-list)
- [Comparing a String to an Enum Value in Java](https://www.baeldung.com/java-comparing-string-to-enum)
@@ -1,55 +1,67 @@
package com.baeldung.keyword; package com.baeldung.keyword;
import org.junit.Assert;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import com.baeldung.keyword.Circle; import java.util.List;
import com.baeldung.keyword.Ring; import java.util.stream.Collectors;
import com.baeldung.keyword.Round; import java.util.stream.Stream;
import com.baeldung.keyword.Shape;
import com.baeldung.keyword.Triangle; import static org.junit.jupiter.api.Assertions.*;
public class InstanceOfUnitTest { public class InstanceOfUnitTest {
@Test @Test
public void giveWhenInstanceIsCorrect_thenReturnTrue() { void giveWhenInstanceIsCorrect_thenReturnTrue() {
Ring ring = new Ring(); Ring ring = new Ring();
Assert.assertTrue("ring is instance of Round ", ring instanceof Round); assertTrue(ring instanceof Round);
} }
@Test @Test
public void giveWhenObjectIsInstanceOfType_thenReturnTrue() { void giveWhenObjectIsInstanceOfType_thenReturnTrue() {
Circle circle = new Circle(); Circle circle = new Circle();
Assert.assertTrue("circle is instance of Circle ", circle instanceof Circle); assertTrue(circle instanceof Circle);
} }
@Test @Test
public void giveWhenInstanceIsOfSubtype_thenReturnTrue() { void giveWhenInstanceIsOfSubtype_thenReturnTrue() {
Circle circle = new Circle(); Circle circle = new Circle();
Assert.assertTrue("circle is instance of Round", circle instanceof Round); assertTrue(circle instanceof Round);
} }
@Test @Test
public void giveWhenTypeIsInterface_thenReturnTrue() { void giveWhenTypeIsInterface_thenReturnTrue() {
Circle circle = new Circle(); Circle circle = new Circle();
Assert.assertTrue("circle is instance of Shape", circle instanceof Shape); assertTrue(circle instanceof Shape);
} }
@Test @Test
public void giveWhenTypeIsOfObjectType_thenReturnTrue() { void giveWhenTypeIsOfObjectType_thenReturnTrue() {
Thread thread = new Thread(); Thread thread = new Thread();
Assert.assertTrue("thread is instance of Object", thread instanceof Object); assertTrue(thread instanceof Object);
} }
@Test @Test
public void giveWhenInstanceValueIsNull_thenReturnFalse() { void giveWhenInstanceValueIsNull_thenReturnFalse() {
Circle circle = null; Circle circle = null;
Assert.assertFalse("circle is instance of Round", circle instanceof Round); assertFalse(circle instanceof Round);
} }
@Test @Test
public void giveWhenComparingClassInDiffHierarchy_thenCompilationError() { void giveWhenComparingClassInDiffHierarchy_thenCompilationError() {
// Assert.assertFalse("circle is instance of Triangle", circle instanceof Triangle); //assertFalse( circle instanceof Triangle);
}
@Test
void giveWhenStream_whenCastWithoutInstanceOfChk_thenGetException() {
Stream<Round> roundStream = Stream.of(new Ring(), new Ring(), new Circle());
assertThrows(ClassCastException.class, () -> roundStream.map(it -> (Ring) it).collect(Collectors.toList()));
}
@Test
void giveWhenStream_whenCastAfterInstanceOfChk_thenGetExpectedResult() {
Stream<Round> roundStream = Stream.of(new Ring(), new Ring(), new Circle());
List<Ring> ringList = roundStream.filter(it -> it instanceof Ring).map(it -> (Ring) it).collect(Collectors.toList());
assertEquals(2, ringList.size());
} }
} }
@@ -25,15 +25,20 @@
<version>${commons-lang3.version}</version> <version>${commons-lang3.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>javax.mail</groupId> <groupId>org.eclipse.angus</groupId>
<artifactId>mail</artifactId> <artifactId>angus-mail</artifactId>
<version>${javax.mail.version}</version> <version>${angus.mail.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.asynchttpclient</groupId> <groupId>org.asynchttpclient</groupId>
<artifactId>async-http-client</artifactId> <artifactId>async-http-client</artifactId>
<version>${async-http-client.version}</version> <version>${async-http-client.version}</version>
</dependency> </dependency>
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>${jakarta.bind.version}</version>
</dependency>
<dependency> <dependency>
<groupId>com.icegreen</groupId> <groupId>com.icegreen</groupId>
<artifactId>greenmail</artifactId> <artifactId>greenmail</artifactId>
@@ -48,9 +53,10 @@
<properties> <properties>
<httpclient.version>4.5.9</httpclient.version> <httpclient.version>4.5.9</httpclient.version>
<javax.mail.version>1.5.0-b01</javax.mail.version> <angus.mail.version>2.0.1</angus.mail.version>
<async-http-client.version>2.4.5</async-http-client.version> <async-http-client.version>2.4.5</async-http-client.version>
<greenmail.version>1.5.8</greenmail.version> <jakarta.bind.version>2.3.3</jakarta.bind.version>
<greenmail.version>2.0.0-alpha-3</greenmail.version>
</properties> </properties>
</project> </project>
@@ -1,19 +1,20 @@
package com.baeldung.mail; package com.baeldung.mail;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File; import java.io.File;
import java.net.URI; import java.net.URI;
import java.util.Properties; import java.util.Properties;
import jakarta.mail.Authenticator;
import jakarta.mail.Message;
import jakarta.mail.Multipart;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeBodyPart;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;
public class EmailService { public class EmailService {
private String username; private String username;
@@ -1,21 +1,23 @@
package com.baeldung.mail.mailwithattachment; package com.baeldung.mail.mailwithattachment;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.util.Properties; import java.util.Properties;
import jakarta.mail.Authenticator;
import jakarta.mail.BodyPart;
import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.Multipart;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeBodyPart;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;
public class MailWithAttachmentService { public class MailWithAttachmentService {
private final String username; private final String username;
@@ -37,7 +39,7 @@ public class MailWithAttachmentService {
props.put("mail.smtp.host", this.host); props.put("mail.smtp.host", this.host);
props.put("mail.smtp.port", this.port); props.put("mail.smtp.port", this.port);
return Session.getInstance(props, new javax.mail.Authenticator() { return Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() { protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password); return new PasswordAuthentication(username, password);
} }
@@ -1,10 +1,7 @@
package com.baeldung.download; package com.baeldung.download;
import org.junit.After; import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.xml.bind.DatatypeConverter;
import java.io.IOException; import java.io.IOException;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.nio.file.Files; import java.nio.file.Files;
@@ -13,7 +10,11 @@ import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import static org.junit.Assert.assertTrue; import javax.xml.bind.DatatypeConverter;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
public class FileDownloadIntegrationTest { public class FileDownloadIntegrationTest {
@@ -1,17 +1,19 @@
package com.baeldung.mail; package com.baeldung.mail;
import com.icegreen.greenmail.junit.GreenMailRule; import static org.junit.Assert.assertEquals;
import com.icegreen.greenmail.util.ServerSetupTest;
import java.io.IOException;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import javax.mail.MessagingException; import com.icegreen.greenmail.junit.GreenMailRule;
import javax.mail.internet.MimeMessage; import com.icegreen.greenmail.util.ServerSetupTest;
import javax.mail.internet.MimeMultipart;
import java.io.IOException;
import static org.junit.Assert.assertEquals; import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;
public class EmailServiceLiveTest { public class EmailServiceLiveTest {
@@ -1,20 +1,20 @@
package com.baeldung.mail.mailwithattachment; package com.baeldung.mail.mailwithattachment;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import com.icegreen.greenmail.configuration.GreenMailConfiguration; import com.icegreen.greenmail.configuration.GreenMailConfiguration;
import com.icegreen.greenmail.junit.GreenMailRule; import com.icegreen.greenmail.junit.GreenMailRule;
import com.icegreen.greenmail.util.GreenMailUtil; import com.icegreen.greenmail.util.GreenMailUtil;
import com.icegreen.greenmail.util.ServerSetupTest; import com.icegreen.greenmail.util.ServerSetupTest;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import javax.annotation.Resource; import jakarta.mail.MessagingException;
import javax.mail.MessagingException; import jakarta.mail.Session;
import javax.mail.Session; import jakarta.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage; import jakarta.mail.internet.MimeMultipart;
import javax.mail.internet.MimeMultipart;
import static org.junit.Assert.assertEquals;
public class MailWithAttachmentServiceLiveTest { public class MailWithAttachmentServiceLiveTest {
@@ -29,7 +29,6 @@ public class MailWithAttachmentServiceLiveTest {
.withUser(USERNAME, PASSWORD) .withUser(USERNAME, PASSWORD)
); );
@Resource
private MailWithAttachmentService emailService; private MailWithAttachmentService emailService;
@Before @Before
@@ -73,5 +72,4 @@ public class MailWithAttachmentServiceLiveTest {
return GreenMailUtil.getBody(((MimeMultipart) receivedMessage.getContent()) return GreenMailUtil.getBody(((MimeMultipart) receivedMessage.getContent())
.getBodyPart(2)); .getBodyPart(2));
} }
} }
@@ -30,9 +30,9 @@
<version>${tomcat.embeded.version}</version> <version>${tomcat.embeded.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.sun.mail</groupId> <groupId>org.eclipse.angus</groupId>
<artifactId>javax.mail</artifactId> <artifactId>angus-mail</artifactId>
<version>${javax.mail.version}</version> <version>${angus.mail.version}</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/com.github.seancfoley/ipaddress --> <!-- https://mvnrepository.com/artifact/com.github.seancfoley/ipaddress -->
<dependency> <dependency>
@@ -95,7 +95,7 @@
<seancfoley.ipaddress.version>5.3.3</seancfoley.ipaddress.version> <seancfoley.ipaddress.version>5.3.3</seancfoley.ipaddress.version>
<jgonian.commons-ip-math.version>1.32</jgonian.commons-ip-math.version> <jgonian.commons-ip-math.version>1.32</jgonian.commons-ip-math.version>
<googlecode.ipv6.version>0.17</googlecode.ipv6.version> <googlecode.ipv6.version>0.17</googlecode.ipv6.version>
<javax.mail.version>1.6.2</javax.mail.version> <angus.mail.version>2.0.1</angus.mail.version>
<apache.commons-validator.version>1.7</apache.commons-validator.version> <apache.commons-validator.version>1.7</apache.commons-validator.version>
</properties> </properties>

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