Merge branch 'eugenp:master' into string_to_int_encapsulation
This commit is contained in:
commit
acdafe5817
8
.gitignore
vendored
8
.gitignore
vendored
@ -69,6 +69,7 @@ jmeter/src/main/resources/*-Basic*.csv
|
||||
jmeter/src/main/resources/*-JMeter*.csv
|
||||
jmeter/src/main/resources/*ReportsDashboard*.csv
|
||||
jmeter/src/main/resources/dashboard/*ReportsDashboard*.csv
|
||||
jmeter/src/main/resources/*FileExtractionExample.csv
|
||||
|
||||
ninja/devDb.mv.db
|
||||
|
||||
@ -88,6 +89,7 @@ spring-soap/src/main/java/com/baeldung/springsoap/gen/
|
||||
/report-*.json
|
||||
transaction.log
|
||||
*-shell.log
|
||||
customers.xml
|
||||
|
||||
apache-cxf/cxf-aegis/baeldung.xml
|
||||
testing-modules/report-*.json
|
||||
@ -102,6 +104,7 @@ spring-boot-modules/spring-boot-react/frontend/build
|
||||
spring-boot-modules/spring-boot-react/frontend/node
|
||||
spring-boot-modules/spring-boot-react/frontend/yarn.lock
|
||||
spring-boot-modules/spring-boot-properties-3/*.log
|
||||
spring-boot-modules/spring-boot-properties-3/*.gz
|
||||
|
||||
# SDKMan
|
||||
.sdkmanrc
|
||||
@ -114,4 +117,7 @@ libraries-2/employee*
|
||||
libraries-2/src/test/resources/crawler4j/**
|
||||
|
||||
#web-modules/ninja
|
||||
devDb*.db
|
||||
devDb*.db
|
||||
|
||||
#jaxb
|
||||
*.xjb
|
@ -36,7 +36,6 @@
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
<properties>
|
||||
<akka.http.version>10.0.11</akka.http.version>
|
||||
<akka.stream.version>2.5.11</akka.stream.version>
|
||||
|
@ -1,4 +1,6 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [Algorithm to Identify and Validate a Credit Card Number](https://www.baeldung.com/java-validate-cc-number)
|
||||
- [Find the N Most Frequent Elements in a Java Array](https://www.baeldung.com/java-n-most-frequent-elements-array)
|
||||
- [Getting Pixel Array From Image in Java](https://www.baeldung.com/java-getting-pixel-array-from-image)
|
||||
- More articles: [[<-- prev]](/algorithms-miscellaneous-6)
|
||||
|
@ -0,0 +1,65 @@
|
||||
package com.baeldung.algorithms.pixelarray;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.awt.image.DataBufferByte;
|
||||
public class GetPixelArray {
|
||||
|
||||
public static int[][] get2DPixelArraySlow(BufferedImage sampleImage) {
|
||||
int width = sampleImage.getWidth();
|
||||
int height = sampleImage.getHeight();
|
||||
int[][] result = new int[height][width];
|
||||
|
||||
for (int row = 0; row < height; row++) {
|
||||
for (int col = 0; col < width; col++) {
|
||||
result[row][col] = sampleImage.getRGB(col, row);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static int[][] get2DPixelArrayFast(BufferedImage image) {
|
||||
final byte[] pixelData = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
|
||||
final int width = image.getWidth();
|
||||
final int height = image.getHeight();
|
||||
final boolean hasAlphaChannel = image.getAlphaRaster() != null;
|
||||
|
||||
int[][] result = new int[height][width];
|
||||
if (hasAlphaChannel) {
|
||||
final int numberOfValues = 4;
|
||||
for (int valueIndex = 0, row = 0, col = 0; valueIndex + numberOfValues - 1 < pixelData.length; valueIndex += numberOfValues) {
|
||||
// Getting the values for each pixel from the pixelData array.
|
||||
int argb = 0;
|
||||
argb += (((int) pixelData[valueIndex] & 0xff) << 24); // alpha value
|
||||
argb += ((int) pixelData[valueIndex + 1] & 0xff); // blue value
|
||||
argb += (((int) pixelData[valueIndex + 2] & 0xff) << 8); // green value
|
||||
argb += (((int) pixelData[valueIndex + 3] & 0xff) << 16); // red value
|
||||
result[row][col] = argb;
|
||||
|
||||
col++;
|
||||
if (col == width) {
|
||||
col = 0;
|
||||
row++;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
final int numberOfValues = 3;
|
||||
for (int valueIndex = 0, row = 0, col = 0; valueIndex + numberOfValues - 1 < pixelData.length; valueIndex += numberOfValues) {
|
||||
int argb = 0;
|
||||
argb += -16777216; // 255 alpha value (fully opaque)
|
||||
argb += ((int) pixelData[valueIndex] & 0xff); // blue value
|
||||
argb += (((int) pixelData[valueIndex + 1] & 0xff) << 8); // green value
|
||||
argb += (((int) pixelData[valueIndex + 2] & 0xff) << 16); // red value
|
||||
result[row][col] = argb;
|
||||
|
||||
col++;
|
||||
if (col == width) {
|
||||
col = 0;
|
||||
row++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
package com.baeldung.algorithms.pixelarray;
|
||||
|
||||
import static com.baeldung.algorithms.pixelarray.GetPixelArray.get2DPixelArrayFast;
|
||||
import static com.baeldung.algorithms.pixelarray.GetPixelArray.get2DPixelArraySlow;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class GetPixelArrayUnitTest {
|
||||
@Test
|
||||
public void givenImage_whenGetPixelArray_thenBothMethodsReturnEqualValues() {
|
||||
BufferedImage sampleImage = null;
|
||||
try {
|
||||
sampleImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
int[][] firstResult = get2DPixelArraySlow(sampleImage);
|
||||
int[][] secondResult = get2DPixelArrayFast(sampleImage);
|
||||
|
||||
assertTrue(Arrays.deepEquals(firstResult, secondResult));
|
||||
}
|
||||
}
|
@ -21,7 +21,6 @@
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
<properties>
|
||||
<auto-service.version>1.0-rc2</auto-service.version>
|
||||
</properties>
|
||||
|
@ -12,6 +12,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||
- [Reading an HTTP Response Body as a String in Java](https://www.baeldung.com/java-http-response-body-as-string)
|
||||
- [How To Get Cookies From the Apache HttpClient Response](https://www.baeldung.com/java-apache-httpclient-cookies)
|
||||
- [Enabling Logging for Apache HttpClient](https://www.baeldung.com/apache-httpclient-enable-logging)
|
||||
- [Expand Shortened URLs with Apache HttpClient](https://www.baeldung.com/apache-httpclient-expand-url)
|
||||
- [Apache HttpClient vs. CloseableHttpClient](https://www.baeldung.com/apache-httpclient-vs-closeablehttpclient)
|
||||
- [Expand Shortened URLs with Apache HttpClient](https://www.baeldung.com/apache-httpclient-expand-url)
|
||||
- More articles: [[<-- prev]](../apache-httpclient)
|
||||
|
@ -0,0 +1,126 @@
|
||||
package com.baeldung.httpclient.expandUrl;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
import org.apache.commons.lang3.tuple.ImmutablePair;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
|
||||
import org.apache.hc.client5.http.classic.methods.HttpHead;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
||||
|
||||
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.HttpHeaders;
|
||||
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class HttpClientExpandUrlLiveTest {
|
||||
|
||||
private static CloseableHttpClient httpClient;
|
||||
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
httpClient = HttpClientBuilder.create()
|
||||
.disableRedirectHandling()
|
||||
.build();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void tearDown() throws IOException {
|
||||
if (httpClient != null) {
|
||||
httpClient.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenShortenedOnce_whenUrlIsExpanded_thenCorrectResult() throws IOException {
|
||||
final String expectedResult = "https://www.baeldung.com/rest-versioning";
|
||||
final String actualResult = expandSingleLevel("http://bit.ly/3LScTri");
|
||||
assertThat(actualResult, equalTo(expectedResult));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenShortenedMultiple_whenUrlIsExpanded_thenCorrectResult() throws IOException {
|
||||
final String expectedResult = "https://www.baeldung.com/rest-versioning";
|
||||
final String actualResult = expand("http://t.co/e4rDDbnzmk");
|
||||
assertThat(actualResult, equalTo(expectedResult));
|
||||
}
|
||||
|
||||
private String expand(final String urlArg) throws IOException {
|
||||
String originalUrl = urlArg;
|
||||
String newUrl = expandSingleLevel(originalUrl);
|
||||
while (!originalUrl.equals(newUrl)) {
|
||||
originalUrl = newUrl;
|
||||
newUrl = expandSingleLevel(originalUrl);
|
||||
}
|
||||
|
||||
return newUrl;
|
||||
}
|
||||
|
||||
final String expandSafe(final String urlArg) throws IOException {
|
||||
String originalUrl = urlArg;
|
||||
String newUrl = expandSingleLevelSafe(originalUrl).getRight();
|
||||
final List<String> alreadyVisited = Lists.newArrayList(originalUrl, newUrl);
|
||||
while (!originalUrl.equals(newUrl)) {
|
||||
originalUrl = newUrl;
|
||||
final Pair<Integer, String> statusAndUrl = expandSingleLevelSafe(originalUrl);
|
||||
newUrl = statusAndUrl.getRight();
|
||||
final boolean isRedirect = statusAndUrl.getLeft() == 301 || statusAndUrl.getLeft() == 302;
|
||||
if (isRedirect && alreadyVisited.contains(newUrl)) {
|
||||
throw new IllegalStateException("Likely a redirect loop");
|
||||
}
|
||||
alreadyVisited.add(newUrl);
|
||||
}
|
||||
|
||||
return newUrl;
|
||||
}
|
||||
|
||||
private Pair<Integer, String> expandSingleLevelSafe(final String url) throws IOException {
|
||||
try {
|
||||
HttpHead request = new HttpHead(url);
|
||||
Pair<Integer, String> resp = httpClient.execute(request, response -> {
|
||||
final int statusCode = response.getCode();
|
||||
if (statusCode != 301 && statusCode != 302) {
|
||||
return new ImmutablePair<>(statusCode, url);
|
||||
}
|
||||
final Header[] headers = response.getHeaders(HttpHeaders.LOCATION);
|
||||
Preconditions.checkState(headers.length == 1);
|
||||
final String newUrl = headers[0].getValue();
|
||||
|
||||
return new ImmutablePair<>(statusCode, newUrl);
|
||||
});
|
||||
return resp;
|
||||
} catch (final IllegalArgumentException uriEx) {
|
||||
return new ImmutablePair<>(500, url);
|
||||
}
|
||||
}
|
||||
|
||||
private String expandSingleLevel(final String url) throws IOException {
|
||||
try {
|
||||
HttpHead request = new HttpHead(url);
|
||||
String expandedUrl = httpClient.execute(request, response -> {
|
||||
final int statusCode = response.getCode();
|
||||
if (statusCode != 301 && statusCode != 302) {
|
||||
return url;
|
||||
}
|
||||
final Header[] headers = response.getHeaders(HttpHeaders.LOCATION);
|
||||
Preconditions.checkState(headers.length == 1);
|
||||
|
||||
return headers[0].getValue();
|
||||
});
|
||||
return expandedUrl;
|
||||
} catch (final IllegalArgumentException uriEx) {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
package com.baeldung.httpclient;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
||||
import org.apache.hc.client5.http.impl.classic.HttpClients;
|
||||
import org.apache.hc.core5.http.HttpEntity;
|
||||
import org.apache.hc.core5.http.HttpStatus;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class HttpClientCancelRequestLiveTest {
|
||||
|
||||
private static final String SAMPLE_URL = "http://www.github.com";
|
||||
|
||||
@Test
|
||||
void whenRequestIsCanceled_thenCorrect() throws IOException {
|
||||
HttpGet request = new HttpGet(SAMPLE_URL);
|
||||
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
|
||||
httpClient.execute(request, response -> {
|
||||
HttpEntity entity = response.getEntity();
|
||||
|
||||
System.out.println("----------------------------------------");
|
||||
System.out.println(response.getCode());
|
||||
if (entity != null) {
|
||||
System.out.println("Response content length: " + entity.getContentLength());
|
||||
}
|
||||
System.out.println("----------------------------------------");
|
||||
// Do not feel like reading the response body
|
||||
// Call abort on the request object
|
||||
request.abort();
|
||||
|
||||
assertThat(response.getCode()).isEqualTo(HttpStatus.SC_OK);
|
||||
return response;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -1,8 +1,8 @@
|
||||
package com.baeldung.httpclient.base;
|
||||
|
||||
import com.baeldung.httpclient.ResponseUtil;
|
||||
|
||||
import org.apache.http.Header;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpHeaders;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
@ -10,7 +10,6 @@ import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.conn.ConnectTimeoutException;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
@ -73,30 +72,4 @@ public class HttpClientLiveTest {
|
||||
assertThat(headers, not(emptyArray()));
|
||||
}
|
||||
|
||||
// tests - cancel request
|
||||
|
||||
@Test
|
||||
public final void whenRequestIsCanceled_thenCorrect() throws IOException {
|
||||
instance = HttpClients.custom().build();
|
||||
final HttpGet request = new HttpGet(SAMPLE_URL);
|
||||
response = instance.execute(request);
|
||||
|
||||
try {
|
||||
final HttpEntity entity = response.getEntity();
|
||||
|
||||
System.out.println("----------------------------------------");
|
||||
System.out.println(response.getStatusLine());
|
||||
if (entity != null) {
|
||||
System.out.println("Response content length: " + entity.getContentLength());
|
||||
}
|
||||
System.out.println("----------------------------------------");
|
||||
|
||||
// Do not feel like reading the response body
|
||||
// Call abort on the request object
|
||||
request.abort();
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -4,11 +4,13 @@ This module contains articles about Apache HttpClient 4.5
|
||||
|
||||
### Relevant Articles
|
||||
|
||||
- [Apache HttpClient – Cancel Request](https://www.baeldung.com/httpclient-cancel-request)
|
||||
- [Apache HttpClient with SSL](https://www.baeldung.com/httpclient-ssl)
|
||||
- [Apache HttpClient Timeout](https://www.baeldung.com/httpclient-timeout)
|
||||
- [Custom HTTP Header with the Apache HttpClient](https://www.baeldung.com/httpclient-custom-http-header)
|
||||
- [Apache HttpClient vs. CloseableHttpClient](https://www.baeldung.com/apache-httpclient-vs-closeablehttpclient)
|
||||
- [Expand Shortened URLs with Apache HttpClient](https://www.baeldung.com/apache-httpclient-expand-url)
|
||||
- [Retrying Requests using Apache HttpClient](https://www.baeldung.com/java-retrying-requests-using-apache-httpclient)
|
||||
|
||||
### Running the Tests
|
||||
To run the live tests, use the command: mvn clean install -Plive
|
||||
|
@ -1,7 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
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>apache-httpclient4</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
|
@ -0,0 +1,57 @@
|
||||
package com.baeldung.httpclient;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class HttpClientCancelRequestV4LiveTest {
|
||||
|
||||
private static final String SAMPLE_URL = "http://www.github.com";
|
||||
|
||||
private CloseableHttpClient instance;
|
||||
|
||||
private CloseableHttpResponse response;
|
||||
|
||||
@Before
|
||||
public final void before() {
|
||||
instance = HttpClientBuilder.create().build();
|
||||
}
|
||||
|
||||
@After
|
||||
public final void after() throws IllegalStateException, IOException {
|
||||
ResponseUtil.closeResponse(response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenRequestIsCanceled_thenCorrect() throws IOException {
|
||||
instance = HttpClients.custom().build();
|
||||
final HttpGet request = new HttpGet(SAMPLE_URL);
|
||||
response = instance.execute(request);
|
||||
|
||||
try {
|
||||
final HttpEntity entity = response.getEntity();
|
||||
|
||||
System.out.println("----------------------------------------");
|
||||
System.out.println(response.getStatusLine());
|
||||
if (entity != null) {
|
||||
System.out.println("Response content length: " + entity.getContentLength());
|
||||
}
|
||||
System.out.println("----------------------------------------");
|
||||
|
||||
// Do not feel like reading the response body
|
||||
// Call abort on the request object
|
||||
request.abort();
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,168 @@
|
||||
package com.baeldung.httpclient.retry;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.apache.http.HttpRequestInterceptor;
|
||||
import org.apache.http.HttpResponseInterceptor;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpPatch;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.client.methods.HttpPut;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class ApacheHttpClientRetryLiveTest {
|
||||
|
||||
private Integer requestCounter;
|
||||
private CloseableHttpClient httpClient;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
requestCounter = 0;
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws IOException {
|
||||
if (httpClient != null) {
|
||||
httpClient.close();
|
||||
}
|
||||
}
|
||||
|
||||
private void createDefaultApacheHttpClient() {
|
||||
this.httpClient = HttpClientBuilder
|
||||
.create()
|
||||
.addInterceptorFirst((HttpRequestInterceptor) (httpRequest, httpContext) -> {
|
||||
requestCounter++;
|
||||
}).build();
|
||||
}
|
||||
|
||||
private void createFailingHttpClient() {
|
||||
this.httpClient = HttpClientBuilder
|
||||
.create()
|
||||
.addInterceptorFirst((HttpRequestInterceptor) (httpRequest, httpContext) -> requestCounter++)
|
||||
.addInterceptorLast((HttpResponseInterceptor) (httpResponse, httpContext) -> {
|
||||
throw new IOException();
|
||||
})
|
||||
.build();
|
||||
}
|
||||
|
||||
private void createHttpClientWithRetryHandler() {
|
||||
this.httpClient = HttpClientBuilder
|
||||
.create()
|
||||
.addInterceptorFirst((HttpRequestInterceptor) (httpRequest, httpContext) -> requestCounter++)
|
||||
.addInterceptorLast((HttpResponseInterceptor) (httpRequest, httpContext) -> { throw new IOException(); })
|
||||
.setRetryHandler(new DefaultHttpRequestRetryHandler(6, true))
|
||||
.build();
|
||||
}
|
||||
|
||||
private void createHttpClientWithCustomRetryHandler() {
|
||||
this.httpClient = HttpClientBuilder
|
||||
.create()
|
||||
.addInterceptorFirst((HttpRequestInterceptor) (httpRequest, httpContext) -> requestCounter++)
|
||||
.addInterceptorLast((HttpResponseInterceptor) (httpRequest, httpContext) -> { throw new IOException(); })
|
||||
.setRetryHandler((exception, executionCount, context) -> {
|
||||
if (executionCount < 5 && Objects.equals("GET", ((HttpClientContext) context).getRequest().getRequestLine().getMethod())) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})
|
||||
.build();
|
||||
}
|
||||
|
||||
private void createHttpClientWithRetriesDisabled() {
|
||||
this.httpClient = HttpClientBuilder
|
||||
.create()
|
||||
.addInterceptorFirst((HttpRequestInterceptor) (httpRequest, httpContext) -> requestCounter++)
|
||||
.addInterceptorLast((HttpResponseInterceptor) (httpRequest, httpContext) -> { throw new IOException(); })
|
||||
.disableAutomaticRetries()
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDefaultConfiguration_whenReceivedIOException_thenRetriesPerformed() {
|
||||
createFailingHttpClient();
|
||||
assertThrows(IOException.class, () -> httpClient.execute(new HttpGet("https://httpstat.us/200")));
|
||||
assertThat(requestCounter).isEqualTo(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDefaultConfiguration_whenDomainNameNotResolved_thenNoRetryApplied() {
|
||||
createDefaultApacheHttpClient();
|
||||
HttpGet request = new HttpGet(URI.create("http://domain.that.does.not.exist:80/api/v1"));
|
||||
|
||||
assertThrows(UnknownHostException.class, () -> httpClient.execute(request));
|
||||
assertThat(requestCounter).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDefaultConfiguration_whenGotInternalServerError_thenNoRetryLogicApplied() throws IOException {
|
||||
createDefaultApacheHttpClient();
|
||||
HttpGet request = new HttpGet(URI.create("https://httpstat.us/500"));
|
||||
|
||||
CloseableHttpResponse response = assertDoesNotThrow(() -> httpClient.execute(request));
|
||||
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(500);
|
||||
assertThat(requestCounter).isEqualTo(1);
|
||||
response.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDefaultConfiguration_whenHttpPatchRequest_thenRetryIsNotApplied() {
|
||||
createFailingHttpClient();
|
||||
HttpPatch request = new HttpPatch(URI.create("https://httpstat.us/500"));
|
||||
|
||||
assertThrows(IOException.class, () -> httpClient.execute(request));
|
||||
assertThat(requestCounter).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDefaultConfiguration_whenHttpPutRequest_thenRetryIsNotApplied() {
|
||||
createFailingHttpClient();
|
||||
HttpPut request = new HttpPut(URI.create("https://httpstat.us/500"));
|
||||
|
||||
assertThrows(IOException.class, () -> httpClient.execute(request));
|
||||
assertThat(requestCounter).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenConfiguredRetryHandler_whenHttpPostRequest_thenRetriesPerformed() {
|
||||
createHttpClientWithRetryHandler();
|
||||
|
||||
HttpPost request = new HttpPost(URI.create("https://httpstat.us/200"));
|
||||
|
||||
assertThrows(IOException.class, () -> httpClient.execute(request));
|
||||
assertThat(requestCounter).isEqualTo(7);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCustomRetryHandler_whenUnknownHostException_thenRetryAnyway() {
|
||||
createHttpClientWithCustomRetryHandler();
|
||||
|
||||
HttpGet request = new HttpGet(URI.create("https://domain.that.does.not.exist/200"));
|
||||
|
||||
assertThrows(IOException.class, () -> httpClient.execute(request));
|
||||
assertThat(requestCounter).isEqualTo(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDisabledRetries_whenExecutedHttpRequestEndUpWithIOException_thenRetryIsNotApplied() {
|
||||
createHttpClientWithRetriesDisabled();
|
||||
HttpGet request = new HttpGet(URI.create("https://httpstat.us/200"));
|
||||
|
||||
assertThrows(IOException.class, () -> httpClient.execute(request));
|
||||
assertThat(requestCounter).isEqualTo(1);
|
||||
}
|
||||
}
|
@ -7,3 +7,4 @@ You can build the project from the command line using: *mvn clean install*, or i
|
||||
|
||||
### Relevant Articles:
|
||||
- [Guide to Check if Apache Kafka Server Is Running](https://www.baeldung.com/apache-kafka-check-server-is-running)
|
||||
- [Add Custom Headers to a Kafka Message](https://www.baeldung.com/java-kafka-custom-headers)
|
||||
|
@ -0,0 +1,88 @@
|
||||
package com.baeldung.kafka.headers;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.kafka.clients.consumer.ConsumerConfig;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecords;
|
||||
import org.apache.kafka.clients.consumer.KafkaConsumer;
|
||||
import org.apache.kafka.clients.producer.KafkaProducer;
|
||||
import org.apache.kafka.clients.producer.ProducerConfig;
|
||||
import org.apache.kafka.clients.producer.ProducerRecord;
|
||||
import org.apache.kafka.common.header.Header;
|
||||
import org.apache.kafka.common.header.Headers;
|
||||
import org.apache.kafka.common.header.internals.RecordHeader;
|
||||
import org.apache.kafka.common.serialization.StringDeserializer;
|
||||
import org.apache.kafka.common.serialization.StringSerializer;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class KafkaMessageHeaders {
|
||||
|
||||
private static Logger logger = LoggerFactory.getLogger(KafkaMessageHeaders.class);
|
||||
|
||||
private static String TOPIC = "baeldung";
|
||||
private static String MESSAGE_KEY = "message";
|
||||
private static String MESSAGE_VALUE = "Hello World";
|
||||
private static String HEADER_KEY = "website";
|
||||
private static String HEADER_VALUE = "baeldung.com";
|
||||
|
||||
private static KafkaProducer<String, String> producer;
|
||||
private static KafkaConsumer<String, String> consumer;
|
||||
|
||||
public static void main(String[] args) {
|
||||
setup();
|
||||
|
||||
publishMessageWithCustomHeaders();
|
||||
|
||||
consumeMessageWithCustomHeaders();
|
||||
}
|
||||
|
||||
private static void consumeMessageWithCustomHeaders() {
|
||||
consumer.subscribe(Arrays.asList(TOPIC));
|
||||
|
||||
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMinutes(1));
|
||||
for (ConsumerRecord<String, String> record : records) {
|
||||
logger.info(record.key());
|
||||
logger.info(record.value());
|
||||
|
||||
Headers headers = record.headers();
|
||||
for (Header header : headers) {
|
||||
logger.info(header.key());
|
||||
logger.info(new String(header.value()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void publishMessageWithCustomHeaders() {
|
||||
List<Header> headers = new ArrayList<>();
|
||||
headers.add(new RecordHeader(HEADER_KEY, HEADER_VALUE.getBytes()));
|
||||
|
||||
ProducerRecord<String, String> record1 = new ProducerRecord<>(TOPIC, null, MESSAGE_KEY, MESSAGE_VALUE, headers);
|
||||
producer.send(record1);
|
||||
|
||||
ProducerRecord<String, String> record2 = new ProducerRecord<>(TOPIC, null, System.currentTimeMillis(), MESSAGE_KEY, MESSAGE_VALUE, headers);
|
||||
producer.send(record2);
|
||||
}
|
||||
|
||||
private static void setup() {
|
||||
Properties producerProperties = new Properties();
|
||||
producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
|
||||
producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
|
||||
producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
|
||||
|
||||
Properties consumerProperties = new Properties();
|
||||
consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
|
||||
consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
|
||||
consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
|
||||
consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "ConsumerGroup1");
|
||||
|
||||
producer = new KafkaProducer<>(producerProperties);
|
||||
consumer = new KafkaConsumer<>(consumerProperties);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,138 @@
|
||||
package com.baeldung.kafka;
|
||||
|
||||
import org.apache.kafka.clients.consumer.ConsumerConfig;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecords;
|
||||
import org.apache.kafka.clients.consumer.KafkaConsumer;
|
||||
import org.apache.kafka.clients.producer.KafkaProducer;
|
||||
import org.apache.kafka.clients.producer.ProducerConfig;
|
||||
import org.apache.kafka.clients.producer.ProducerRecord;
|
||||
import org.apache.kafka.common.TopicPartition;
|
||||
import org.apache.kafka.common.serialization.StringDeserializer;
|
||||
import org.apache.kafka.common.serialization.StringSerializer;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.testcontainers.containers.KafkaContainer;
|
||||
import org.testcontainers.junit.jupiter.Container;
|
||||
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||
import org.testcontainers.utility.DockerImageName;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@Testcontainers
|
||||
public class KafaConsumeLastNMessages {
|
||||
|
||||
private static String TOPIC1 = "baeldung-github";
|
||||
private static String TOPIC2 = "baeldung-blog";
|
||||
private static String MESSAGE_KEY = "message";
|
||||
private static KafkaProducer<String, String> producer;
|
||||
private static KafkaConsumer<String, String> consumer;
|
||||
private static KafkaProducer<String, String> transactionalProducer;
|
||||
|
||||
@Container
|
||||
private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest"));
|
||||
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
KAFKA_CONTAINER.addExposedPort(9092);
|
||||
|
||||
Properties producerProperties = new Properties();
|
||||
producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
|
||||
producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
|
||||
producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
|
||||
|
||||
Properties consumerProperties = new Properties();
|
||||
consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
|
||||
consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
|
||||
consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
|
||||
consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "ConsumerGroup1");
|
||||
|
||||
Properties transactionalProducerProprieties = new Properties();
|
||||
transactionalProducerProprieties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
|
||||
transactionalProducerProprieties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
|
||||
transactionalProducerProprieties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
|
||||
transactionalProducerProprieties.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, "true");
|
||||
transactionalProducerProprieties.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "prod-0");
|
||||
|
||||
producer = new KafkaProducer<>(producerProperties);
|
||||
consumer = new KafkaConsumer<>(consumerProperties);
|
||||
transactionalProducer = new KafkaProducer<>(transactionalProducerProprieties);
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void destroy() {
|
||||
KAFKA_CONTAINER.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenSeekingKafkaTopicCursorToEnd_consumerRetrievesOnlyDesiredNumberOfMessages() throws ExecutionException, InterruptedException {
|
||||
int messagesInTopic = 100;
|
||||
int messagesToRetrieve = 20;
|
||||
|
||||
for (int i = 0; i < messagesInTopic; i++) {
|
||||
producer.send(new ProducerRecord<>(TOPIC1, null, MESSAGE_KEY, String.valueOf(i)))
|
||||
.get();
|
||||
}
|
||||
|
||||
TopicPartition partition = new TopicPartition(TOPIC1, 0);
|
||||
List<TopicPartition> partitions = new ArrayList<>();
|
||||
partitions.add(partition);
|
||||
consumer.assign(partitions);
|
||||
|
||||
consumer.seekToEnd(partitions);
|
||||
long startIndex = consumer.position(partition) - messagesToRetrieve;
|
||||
consumer.seek(partition, startIndex);
|
||||
|
||||
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMinutes(1));
|
||||
int recordsReceived = 0;
|
||||
for (ConsumerRecord<String, String> record : records) {
|
||||
assertEquals(MESSAGE_KEY, record.key());
|
||||
assertTrue(Integer.parseInt(record.value()) >= (messagesInTopic - messagesToRetrieve));
|
||||
recordsReceived++;
|
||||
}
|
||||
|
||||
assertEquals(messagesToRetrieve, recordsReceived);
|
||||
}
|
||||
|
||||
@Test
|
||||
void havingTransactionalProducer_whenSeekingKafkaTopicCursorToEnd_consumerRetrievesLessMessages() throws ExecutionException, InterruptedException {
|
||||
int messagesInTopic = 100;
|
||||
int messagesToRetrieve = 20;
|
||||
|
||||
transactionalProducer.initTransactions();
|
||||
for (int i = 0; i < messagesInTopic; i++) {
|
||||
transactionalProducer.beginTransaction();
|
||||
transactionalProducer.send(new ProducerRecord<>(TOPIC2, null, MESSAGE_KEY, String.valueOf(i)))
|
||||
.get();
|
||||
transactionalProducer.commitTransaction();
|
||||
}
|
||||
|
||||
TopicPartition partition = new TopicPartition(TOPIC2, 0);
|
||||
List<TopicPartition> partitions = new ArrayList<>();
|
||||
partitions.add(partition);
|
||||
consumer.assign(partitions);
|
||||
|
||||
consumer.seekToEnd(partitions);
|
||||
long startIndex = consumer.position(partition) - messagesToRetrieve;
|
||||
consumer.seek(partition, startIndex);
|
||||
|
||||
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMinutes(1));
|
||||
int recordsReceived = 0;
|
||||
for (ConsumerRecord<String, String> record : records) {
|
||||
assertEquals(MESSAGE_KEY, record.key());
|
||||
assertTrue(Integer.parseInt(record.value()) >= (messagesInTopic - messagesToRetrieve));
|
||||
recordsReceived++;
|
||||
}
|
||||
|
||||
assertTrue(messagesToRetrieve > recordsReceived);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,104 @@
|
||||
package com.baeldung.kafka.headers;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import org.apache.kafka.clients.consumer.ConsumerConfig;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecords;
|
||||
import org.apache.kafka.clients.consumer.KafkaConsumer;
|
||||
import org.apache.kafka.clients.producer.KafkaProducer;
|
||||
import org.apache.kafka.clients.producer.ProducerConfig;
|
||||
import org.apache.kafka.clients.producer.ProducerRecord;
|
||||
import org.apache.kafka.clients.producer.RecordMetadata;
|
||||
import org.apache.kafka.common.header.Header;
|
||||
import org.apache.kafka.common.header.Headers;
|
||||
import org.apache.kafka.common.header.internals.RecordHeader;
|
||||
import org.apache.kafka.common.serialization.StringDeserializer;
|
||||
import org.apache.kafka.common.serialization.StringSerializer;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.testcontainers.containers.KafkaContainer;
|
||||
import org.testcontainers.junit.jupiter.Container;
|
||||
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||
import org.testcontainers.utility.DockerImageName;
|
||||
|
||||
// This live test needs a Docker Daemon running so that a kafka container can be created
|
||||
|
||||
@Testcontainers
|
||||
public class KafkaMessageHeadersLiveTest {
|
||||
|
||||
private static String TOPIC = "baeldung";
|
||||
private static String MESSAGE_KEY = "message";
|
||||
private static String MESSAGE_VALUE = "Hello World";
|
||||
private static String HEADER_KEY = "website";
|
||||
private static String HEADER_VALUE = "baeldung.com";
|
||||
|
||||
private static KafkaProducer<String, String> producer;
|
||||
private static KafkaConsumer<String, String> consumer;
|
||||
|
||||
@Container
|
||||
private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest"));
|
||||
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
KAFKA_CONTAINER.addExposedPort(9092);
|
||||
|
||||
Properties producerProperties = new Properties();
|
||||
producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
|
||||
producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
|
||||
producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
|
||||
|
||||
Properties consumerProperties = new Properties();
|
||||
consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
|
||||
consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
|
||||
consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
|
||||
consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "ConsumerGroup1");
|
||||
|
||||
producer = new KafkaProducer<>(producerProperties);
|
||||
consumer = new KafkaConsumer<>(consumerProperties);
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void destroy() {
|
||||
KAFKA_CONTAINER.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAMessageWithCustomHeaders_whenPublishedToKafkaAndConsumed_thenCheckForCustomHeaders() throws ExecutionException, InterruptedException {
|
||||
List<Header> headers = new ArrayList<>();
|
||||
headers.add(new RecordHeader(HEADER_KEY, HEADER_VALUE.getBytes()));
|
||||
|
||||
ProducerRecord<String, String> record1 = new ProducerRecord<>(TOPIC, null, MESSAGE_KEY, MESSAGE_VALUE, headers);
|
||||
Future<RecordMetadata> future = producer.send(record1);
|
||||
|
||||
RecordMetadata metadata = future.get();
|
||||
|
||||
assertNotNull(metadata);
|
||||
|
||||
consumer.subscribe(Arrays.asList(TOPIC));
|
||||
|
||||
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMinutes(1));
|
||||
for (ConsumerRecord<String, String> record : records) {
|
||||
assertEquals(MESSAGE_KEY, record.key());
|
||||
assertEquals(MESSAGE_VALUE, record.value());
|
||||
|
||||
Headers consumedHeaders = record.headers();
|
||||
assertNotNull(consumedHeaders);
|
||||
|
||||
for (Header header : consumedHeaders) {
|
||||
assertEquals(HEADER_KEY, header.key());
|
||||
assertEquals(HEADER_VALUE, new String(header.value()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -171,7 +171,8 @@
|
||||
<configuration>
|
||||
<argLine>
|
||||
--add-opens java.base/java.time=ALL-UNNAMED
|
||||
--add-opens java.base/java.nio=ALL-UNNAMED
|
||||
--add-opens
|
||||
java.base/java.nio=ALL-UNNAMED
|
||||
--add-opens java.base/java.util=ALL-UNNAMED
|
||||
</argLine>
|
||||
</configuration>
|
||||
@ -179,8 +180,6 @@
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
|
||||
<properties>
|
||||
<kafka.version>3.4.0</kafka.version>
|
||||
<testcontainers-kafka.version>1.15.3</testcontainers-kafka.version>
|
||||
|
@ -7,7 +7,7 @@ import org.junit.Test;
|
||||
|
||||
import com.baeldung.apache.beam.intro.WordCount;
|
||||
|
||||
public class WordCountUnitTest {
|
||||
public class WordCountIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenInputFile_whenWordCountRuns_thenJobFinishWithoutError() {
|
@ -30,6 +30,16 @@
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.dhatim</groupId>
|
||||
<artifactId>fastexcel</artifactId>
|
||||
<version>${fastexcel.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.dhatim</groupId>
|
||||
<artifactId>fastexcel-reader</artifactId>
|
||||
<version>${fastexcel.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@ -52,6 +62,7 @@
|
||||
<properties>
|
||||
<poi.version>5.2.0</poi.version>
|
||||
<jexcel.version>1.0.6</jexcel.version>
|
||||
<fastexcel.version>0.15.3</fastexcel.version>
|
||||
<maven.resources.plugin.version>3.2.0</maven.resources.plugin.version>
|
||||
</properties>
|
||||
|
||||
|
@ -0,0 +1,63 @@
|
||||
package com.baeldung.fastexcel;
|
||||
|
||||
import org.dhatim.fastexcel.Workbook;
|
||||
import org.dhatim.fastexcel.Worksheet;
|
||||
import org.dhatim.fastexcel.reader.Cell;
|
||||
import org.dhatim.fastexcel.reader.ReadableWorkbook;
|
||||
import org.dhatim.fastexcel.reader.Row;
|
||||
import org.dhatim.fastexcel.reader.Sheet;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class FastexcelHelper {
|
||||
|
||||
public Map<Integer, List<String>> readExcel(String fileLocation) throws IOException {
|
||||
Map<Integer, List<String>> data = new HashMap<>();
|
||||
|
||||
try (FileInputStream file = new FileInputStream(fileLocation); ReadableWorkbook wb = new ReadableWorkbook(file)) {
|
||||
Sheet sheet = wb.getFirstSheet();
|
||||
try (Stream<Row> rows = sheet.openStream()) {
|
||||
rows.forEach(r -> {
|
||||
data.put(r.getRowNum(), new ArrayList<>());
|
||||
|
||||
for (Cell cell : r) {
|
||||
data.get(r.getRowNum()).add(cell.getRawValue());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
public void writeExcel() throws IOException {
|
||||
File currDir = new File(".");
|
||||
String path = currDir.getAbsolutePath();
|
||||
String fileLocation = path.substring(0, path.length() - 1) + "fastexcel.xlsx";
|
||||
|
||||
try (OutputStream os = Files.newOutputStream(Paths.get(fileLocation)); Workbook wb = new Workbook(os, "MyApplication", "1.0")) {
|
||||
Worksheet ws = wb.newWorksheet("Sheet 1");
|
||||
|
||||
ws.width(0, 25);
|
||||
ws.width(1, 15);
|
||||
|
||||
ws.range(0, 0, 0, 1).style().fontName("Arial").fontSize(16).bold().fillColor("3366FF").set();
|
||||
ws.value(0, 0, "Name");
|
||||
ws.value(0, 1, "Age");
|
||||
|
||||
ws.range(2, 0, 2, 1).style().wrapText(true).set();
|
||||
ws.value(2, 0, "John Smith");
|
||||
ws.value(2, 1, 20L);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
package com.baeldung.fastexcel;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class FastexcelIntegrationTest {
|
||||
|
||||
private FastexcelHelper fastexcelHelper;
|
||||
private static String FILE_NAME = "fastexcel.xlsx";
|
||||
private String fileLocation;
|
||||
|
||||
@Before
|
||||
public void generateExcelFile() throws IOException {
|
||||
|
||||
File currDir = new File(".");
|
||||
String path = currDir.getAbsolutePath();
|
||||
fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
|
||||
|
||||
fastexcelHelper = new FastexcelHelper();
|
||||
fastexcelHelper.writeExcel();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenParsingExcelFile_thenCorrect() throws IOException {
|
||||
Map<Integer, List<String>> data = fastexcelHelper.readExcel(fileLocation);
|
||||
|
||||
assertEquals("Name", data.get(1).get(0));
|
||||
assertEquals("Age", data.get(1).get(1));
|
||||
|
||||
assertEquals("John Smith", data.get(3).get(0));
|
||||
assertEquals("20", data.get(3).get(1));
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup() {
|
||||
File testFile = new File(fileLocation);
|
||||
if (testFile.exists()) {
|
||||
testFile.delete();
|
||||
}
|
||||
}
|
||||
}
|
@ -7,7 +7,6 @@
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>apache-spark</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
@ -3,14 +3,14 @@
|
||||
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>lambda</artifactId>
|
||||
<artifactId>lambda-function</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>lambda</name>
|
||||
<name>lambda-function</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>aws-lambda</artifactId>
|
||||
<artifactId>aws-lambda-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
@ -3,8 +3,8 @@
|
||||
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>aws-lambda</artifactId>
|
||||
<name>aws-lambda</name>
|
||||
<artifactId>aws-lambda-modules</artifactId>
|
||||
<name>aws-lambda-modules</name>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<parent>
|
||||
@ -14,9 +14,9 @@
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
<module>lambda</module>
|
||||
<module>shipping-tracker/ShippingFunction</module>
|
||||
<module>todo-reminder/ToDoFunction</module>
|
||||
<module>lambda-function</module>
|
||||
<module>shipping-tracker-lambda/ShippingFunction</module>
|
||||
<module>todo-reminder-lambda/ToDoFunction</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
@ -2,7 +2,6 @@
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>ShippingFunction</artifactId>
|
||||
<version>1.0</version>
|
||||
<name>ShippingFunction</name>
|
||||
@ -10,7 +9,7 @@
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>aws-lambda</artifactId>
|
||||
<artifactId>aws-lambda-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
@ -1,6 +1,6 @@
|
||||
<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/maven-v4_0_0.xsd">
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>helloworld</groupId>
|
||||
<artifactId>ToDoFunction</artifactId>
|
||||
@ -8,6 +8,13 @@
|
||||
<name>ToDoFunction</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>aws-lambda-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
@ -21,7 +21,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class AppTest {
|
||||
public class AppUnitTest {
|
||||
|
||||
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
|
||||
private Context mockContext;
|
@ -7,7 +7,7 @@ import uk.org.webcompere.systemstubs.rules.SystemOutRule;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
|
||||
|
||||
public class ToDoReaderServiceTest {
|
||||
public class ToDoReaderServiceUnitTest {
|
||||
|
||||
@Rule
|
||||
public SystemOutRule systemOutRule = new SystemOutRule();
|
@ -6,4 +6,5 @@ This module contains articles about Simple Storage Service (S3) on AWS
|
||||
|
||||
- [AWS S3 with Java](https://www.baeldung.com/aws-s3-java)
|
||||
- [Multipart Uploads in Amazon S3 with Java](https://www.baeldung.com/aws-s3-multipart-upload)
|
||||
- [Using the JetS3t Java Client With Amazon S3](https://www.baeldung.com/jets3t-amazon-s3)
|
||||
- [Using the JetS3t Java Client With Amazon S3](https://www.baeldung.com/jets3t-amazon-s3)
|
||||
- [Check if a Specified Key Exists in a Given S3 Bucket Using Java](https://www.baeldung.com/java-aws-s3-check-specified-key-exists)
|
||||
|
@ -0,0 +1,42 @@
|
||||
package com.baeldung.s3;
|
||||
|
||||
import org.apache.http.HttpStatus;
|
||||
|
||||
import com.amazonaws.AmazonServiceException;
|
||||
import com.amazonaws.services.s3.AmazonS3;
|
||||
|
||||
public class AWSS3ObjectUtils {
|
||||
|
||||
private AmazonS3 s3Client;
|
||||
|
||||
public AWSS3ObjectUtils(AmazonS3 s3client) {
|
||||
this.s3Client = s3client;
|
||||
}
|
||||
|
||||
public boolean doesObjectExistByDefaultMethod(String bucket, String key) {
|
||||
return s3Client.doesObjectExist(bucket, key);
|
||||
}
|
||||
|
||||
public boolean doesObjectExistByListObjects(String bucket, String key) {
|
||||
return s3Client.listObjects(bucket)
|
||||
.getObjectSummaries()
|
||||
.stream()
|
||||
.filter(s3ObjectSummary -> s3ObjectSummary.getKey()
|
||||
.equals(key))
|
||||
.findFirst()
|
||||
.isPresent();
|
||||
}
|
||||
|
||||
public boolean doesObjectExistByMetaData(String bucket, String key) {
|
||||
try {
|
||||
s3Client.getObjectMetadata(bucket, key);
|
||||
return true;
|
||||
} catch (AmazonServiceException e) {
|
||||
if (e.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
|
||||
return false;
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
package com.baeldung.s3;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.amazonaws.auth.EnvironmentVariableCredentialsProvider;
|
||||
import com.amazonaws.regions.Regions;
|
||||
import com.amazonaws.services.s3.AmazonS3;
|
||||
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
|
||||
|
||||
/**
|
||||
* Required defined environment variables AWS_ACCESS_KEY_ID & AWS_ACCESS_KEY to access S3.
|
||||
* Required S3 bucket and key that exist.
|
||||
*/
|
||||
|
||||
public class AWSS3ObjectManualTest {
|
||||
|
||||
private static final String BUCKET = "your-bucket";
|
||||
private static final String KEY_THAT_EXIST = "your-key-that-exist";
|
||||
private AWSS3ObjectUtils s3ObjectUtils;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
AmazonS3 client = AmazonS3ClientBuilder.standard()
|
||||
.withRegion(Regions.DEFAULT_REGION)
|
||||
.withCredentials(new EnvironmentVariableCredentialsProvider())
|
||||
.build();
|
||||
|
||||
s3ObjectUtils = new AWSS3ObjectUtils(client);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVerifyIfObjectExistByDefaultMethod_thenCorrect() {
|
||||
assertTrue(s3ObjectUtils.doesObjectExistByDefaultMethod(BUCKET, KEY_THAT_EXIST), "Key: " + KEY_THAT_EXIST + " doesn't exist");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVerifyIfObjectExistByListObjects_thenCorrect() {
|
||||
assertTrue(s3ObjectUtils.doesObjectExistByListObjects(BUCKET, KEY_THAT_EXIST), "Key: " + KEY_THAT_EXIST + " doesn't exist");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVerifyIfObjectExistByMetaData_thenCorrect() {
|
||||
assertTrue(s3ObjectUtils.doesObjectExistByMetaData(BUCKET, KEY_THAT_EXIST), "Key: " + KEY_THAT_EXIST + " doesn't exist");
|
||||
}
|
||||
}
|
@ -15,7 +15,7 @@
|
||||
|
||||
<modules>
|
||||
<module>aws-app-sync</module>
|
||||
<module>aws-lambda</module>
|
||||
<module>aws-lambda-modules</module>
|
||||
<module>aws-miscellaneous</module>
|
||||
<module>aws-reactive</module>
|
||||
<module>aws-s3</module>
|
||||
|
@ -103,7 +103,8 @@
|
||||
<configuration>
|
||||
<argLine>
|
||||
--add-opens java.base/java.util=ALL-UNNAMED
|
||||
--add-opens java.base/java.util.concurrent=ALL-UNNAMED
|
||||
--add-opens
|
||||
java.base/java.util.concurrent=ALL-UNNAMED
|
||||
</argLine>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
@ -3,11 +3,10 @@
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>checker-plugin</artifactId>
|
||||
<artifactId>checker-framework</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>checker-plugin</name>
|
||||
<name>checker-framework</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
@ -4,7 +4,6 @@
|
||||
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-groovy-2</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>core-groovy-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
@ -153,14 +152,6 @@
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>maven_central</id>
|
||||
<name>Maven Central</name>
|
||||
<url>https://repo.maven.apache.org/maven2/</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<properties>
|
||||
<groovy-wslite.version>1.1.3</groovy-wslite.version>
|
||||
<assembly.plugin.version>3.4.2</assembly.plugin.version>
|
||||
|
@ -4,7 +4,6 @@
|
||||
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-groovy-collections</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>core-groovy-collections</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
@ -111,13 +110,4 @@
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>maven_central</id>
|
||||
<name>Maven Central</name>
|
||||
<url>https://repo.maven.apache.org/maven2/</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
|
||||
</project>
|
||||
|
@ -4,7 +4,6 @@
|
||||
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-groovy-strings</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>core-groovy-strings</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
@ -101,12 +100,4 @@
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>maven_central</id>
|
||||
<name>Maven Central</name>
|
||||
<url>https://repo.maven.apache.org/maven2/</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
</project>
|
||||
|
@ -3,9 +3,7 @@
|
||||
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-groovy</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>core-groovy</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
@ -102,12 +100,4 @@
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>maven_central</id>
|
||||
<name>Maven Central</name>
|
||||
<url>https://repo.maven.apache.org/maven2/</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
</project>
|
||||
|
@ -4,7 +4,6 @@
|
||||
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-10</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-10</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
|
@ -4,7 +4,6 @@
|
||||
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-11-2</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-11-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
|
@ -4,7 +4,6 @@
|
||||
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-11-3</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-11-3</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
@ -14,7 +13,7 @@
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
|
@ -4,10 +4,8 @@
|
||||
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-11</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-11</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
@ -4,10 +4,8 @@
|
||||
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-12</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-12</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
@ -3,12 +3,9 @@
|
||||
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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>core-java-13</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-13</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
@ -6,7 +6,6 @@
|
||||
<artifactId>core-java-14</artifactId>
|
||||
<name>core-java-14</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
@ -6,7 +6,6 @@
|
||||
<artifactId>core-java-15</artifactId>
|
||||
<name>core-java-15</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
@ -4,10 +4,8 @@
|
||||
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-16</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-16</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
@ -4,10 +4,8 @@
|
||||
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-17</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-17</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
@ -1,3 +1,4 @@
|
||||
## Relevant Articles
|
||||
- [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)
|
||||
- [Possible Root Causes for High CPU Usage in Java](https://www.baeldung.com/java-high-cpu-usage-causes)
|
||||
|
@ -1,21 +1,17 @@
|
||||
<?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">
|
||||
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-19</artifactId>
|
||||
<name>core-java-19</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>core-java-19</artifactId>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>19</maven.compiler.source>
|
||||
<maven.compiler.target>19</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
@ -30,4 +26,10 @@
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>19</maven.compiler.source>
|
||||
<maven.compiler.target>19</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.highcpu;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.function.IntUnaryOperator;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class Application {
|
||||
|
||||
static List<Integer> generateList() {
|
||||
return IntStream.range(0, 10000000).parallel().map(IntUnaryOperator.identity()).collect(LinkedList::new, List::add, List::addAll);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
List<Integer> list = generateList();
|
||||
long start = System.nanoTime();
|
||||
int value = list.get(9500000);
|
||||
System.out.printf("Found value %d in %d nanos\n", value, (System.nanoTime() - start));
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user