Merge branch 'eugenp:master' into JAVA-24001

This commit is contained in:
anuragkumawat 2023-08-26 12:45:55 +05:30 committed by GitHub
commit dd7101873d
233 changed files with 7920 additions and 1480 deletions

5
.gitignore vendored
View File

@ -124,4 +124,7 @@ devDb*.db
*.xjb
#neo4j
persistence-modules/neo4j/data/**
persistence-modules/neo4j/data/**
/deep-shallow-copy/.mvn/wrapper
/deep-shallow-copy/mvnw
/deep-shallow-copy/mvnw.cmd

View File

@ -5,7 +5,7 @@ import org.slf4j.LoggerFactory;
public class KadaneAlgorithm {
private Logger logger = LoggerFactory.getLogger(BruteForceAlgorithm.class.getName());
private Logger logger = LoggerFactory.getLogger(KadaneAlgorithm.class.getName());
public int maxSubArraySum(int[] arr) {
@ -14,15 +14,15 @@ public class KadaneAlgorithm {
int end = 0;
int maxSoFar = arr[0], maxEndingHere = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > maxEndingHere + arr[i]) {
start = i;
maxEndingHere = maxEndingHere + arr[i];
if (arr[i] > maxEndingHere) {
maxEndingHere = arr[i];
} else {
maxEndingHere = maxEndingHere + arr[i];
if (maxSoFar < maxEndingHere) {
start = i;
}
}
if (maxSoFar < maxEndingHere) {
maxSoFar = maxEndingHere;
end = i;

View File

@ -7,7 +7,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
class KadaneAlgorithmUnitTest {
@Test
void givenArrayWithNegativeNumberWhenMaximumSubarrayThenReturns6() {
void givenArrayWithNegativeNumberWhenMaximumSubarrayThenReturnsExpectedResult() {
//given
int[] arr = new int[] { -3, 1, -8, 4, -1, 2, 1, -5, 5 };
//when
@ -27,7 +27,7 @@ class KadaneAlgorithmUnitTest {
//then
assertEquals(-1, maxSum);
}
@Test
void givenArrayWithAllPosiitveNumbersWhenMaximumSubarrayThenReturnsExpectedResult() {
//given
@ -39,4 +39,15 @@ class KadaneAlgorithmUnitTest {
assertEquals(10, maxSum);
}
@Test
void givenArrayToTestStartIndexWhenMaximumSubarrayThenReturnsExpectedResult() {
//given
int[] arr = new int[] { 1, 2, -1, 3, -6, -2 };
//when
KadaneAlgorithm algorithm = new KadaneAlgorithm();
int maxSum = algorithm.maxSubArraySum(arr);
//then
assertEquals(5, maxSum);
}
}

View File

@ -3,4 +3,5 @@
- [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)
- [Calculate Distance Between Two Coordinates in Java](https://www.baeldung.com/java-find-distance-between-points)
- More articles: [[<-- prev]](/algorithms-miscellaneous-6)

View File

@ -0,0 +1,19 @@
package com.baeldung.algorithms.latlondistance;
public class EquirectangularApproximation {
private static final int EARTH_RADIUS = 6371; // Approx Earth radius in KM
public static double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
double lat1Rad = Math.toRadians(lat1);
double lat2Rad = Math.toRadians(lat2);
double lon1Rad = Math.toRadians(lon1);
double lon2Rad = Math.toRadians(lon2);
double x = (lon2Rad - lon1Rad) * Math.cos((lat1Rad + lat2Rad) / 2);
double y = (lat2Rad - lat1Rad);
double distance = Math.sqrt(x * x + y * y) * EARTH_RADIUS;
return distance;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.algorithms.latlondistance;
public class HaversineDistance {
private static final int EARTH_RADIUS = 6371; // Approx Earth radius in KM
public static double calculateDistance(double startLat, double startLong,
double endLat, double endLong) {
double dLat = Math.toRadians((endLat - startLat));
double dLong = Math.toRadians((endLong - startLong));
startLat = Math.toRadians(startLat);
endLat = Math.toRadians(endLat);
double a = haversine(dLat) + Math.cos(startLat) * Math.cos(endLat) * haversine(dLong);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return EARTH_RADIUS * c;
}
public static double haversine(double val) {
return Math.pow(Math.sin(val / 2), 2);
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.algorithms.latlondistance;
public class VincentyDistance {
// Constants for WGS84 ellipsoid model of Earth
private static final double SEMI_MAJOR_AXIS_MT = 6378137;
private static final double SEMI_MINOR_AXIS_MT = 6356752.314245;
private static final double FLATTENING = 1 / 298.257223563;
private static final double ERROR_TOLERANCE = 1e-12;
public static double calculateDistance(double latitude1, double longitude1, double latitude2, double longitude2) {
double U1 = Math.atan((1 - FLATTENING) * Math.tan(Math.toRadians(latitude1)));
double U2 = Math.atan((1 - FLATTENING) * Math.tan(Math.toRadians(latitude2)));
double sinU1 = Math.sin(U1);
double cosU1 = Math.cos(U1);
double sinU2 = Math.sin(U2);
double cosU2 = Math.cos(U2);
double longitudeDifference = Math.toRadians(longitude2 - longitude1);
double previousLongitudeDifference;
double sinSigma, cosSigma, sigma, sinAlpha, cosSqAlpha, cos2SigmaM;
do {
sinSigma = Math.sqrt(Math.pow(cosU2 * Math.sin(longitudeDifference), 2) +
Math.pow(cosU1 * sinU2 - sinU1 * cosU2 * Math.cos(longitudeDifference), 2));
cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * Math.cos(longitudeDifference);
sigma = Math.atan2(sinSigma, cosSigma);
sinAlpha = cosU1 * cosU2 * Math.sin(longitudeDifference) / sinSigma;
cosSqAlpha = 1 - Math.pow(sinAlpha, 2);
cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha;
if (Double.isNaN(cos2SigmaM)) {
cos2SigmaM = 0;
}
previousLongitudeDifference = longitudeDifference;
double C = FLATTENING / 16 * cosSqAlpha * (4 + FLATTENING * (4 - 3 * cosSqAlpha));
longitudeDifference = Math.toRadians(longitude2 - longitude1) + (1 - C) * FLATTENING * sinAlpha *
(sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * Math.pow(cos2SigmaM, 2))));
} while (Math.abs(longitudeDifference - previousLongitudeDifference) > ERROR_TOLERANCE);
double uSq = cosSqAlpha * (Math.pow(SEMI_MAJOR_AXIS_MT, 2) - Math.pow(SEMI_MINOR_AXIS_MT, 2)) / Math.pow(SEMI_MINOR_AXIS_MT, 2);
double A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
double B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));
double deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * Math.pow(cos2SigmaM, 2)) -
B / 6 * cos2SigmaM * (-3 + 4 * Math.pow(sinSigma, 2)) * (-3 + 4 * Math.pow(cos2SigmaM, 2))));
double distanceMt = SEMI_MINOR_AXIS_MT * A * (sigma - deltaSigma);
return distanceMt / 1000;
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.algorithms.latlondistance;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
class GeoDistanceUnitTest {
@Test
public void testCalculateDistance() {
double lat1 = 40.714268; // New York
double lon1 = -74.005974;
double lat2 = 34.0522; // Los Angeles
double lon2 = -118.2437;
double equirectangularDistance = EquirectangularApproximation.calculateDistance(lat1, lon1, lat2, lon2);
double haversineDistance = HaversineDistance.calculateDistance(lat1, lon1, lat2, lon2);
double vincentyDistance = VincentyDistance.calculateDistance(lat1, lon1, lat2, lon2);
double expectedDistance = 3944;
assertTrue(Math.abs(equirectangularDistance - expectedDistance) < 100);
assertTrue(Math.abs(haversineDistance - expectedDistance) < 10);
assertTrue(Math.abs(vincentyDistance - expectedDistance) < 0.5);
}
}

View File

@ -1,36 +1,43 @@
package com.baeldung.tlsversion;
import javax.net.ssl.SSLSocket;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import javax.net.ssl.SSLSocket;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.TlsConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.ssl.TLS;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.util.Timeout;
public class ClientTlsVersionExamples {
public static CloseableHttpClient setViaSocketFactory() {
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
SSLContexts.createDefault(),
new String[] { "TLSv1.2", "TLSv1.3" },
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
.setDefaultTlsConfig(TlsConfig.custom()
.setHandshakeTimeout(Timeout.ofSeconds(30))
.setSupportedProtocols(TLS.V_1_2, TLS.V_1_3)
.build())
.build();
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
return HttpClients.custom()
.setConnectionManager(cm)
.build();
}
public static CloseableHttpClient setTlsVersionPerConnection() {
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(SSLContexts.createDefault()) {
@Override
protected void prepareSocket(SSLSocket socket) {
String hostname = socket.getInetAddress().getHostName();
String hostname = socket.getInetAddress()
.getHostName();
if (hostname.endsWith("internal.system.com")) {
socket.setEnabledProtocols(new String[] { "TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3" });
} else {
@ -39,7 +46,14 @@ public class ClientTlsVersionExamples {
}
};
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
HttpClientConnectionManager connManager = PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(sslsf)
.build();
return HttpClients.custom()
.setConnectionManager(connManager)
.build();
}
// To configure the TLS versions for the client, set the https.protocols system property during runtime.
@ -47,15 +61,11 @@ public class ClientTlsVersionExamples {
public static CloseableHttpClient setViaSystemProperties() {
return HttpClients.createSystem();
// Alternatively:
// return HttpClients.custom().useSystemProperties().build();
//return HttpClients.custom().useSystemProperties().build();
}
public static void main(String[] args) throws IOException {
// Alternatively:
// CloseableHttpClient httpClient = setTlsVersionPerConnection();
// CloseableHttpClient httpClient = setViaSystemProperties();
try (CloseableHttpClient httpClient = setViaSocketFactory();
CloseableHttpResponse response = httpClient.execute(new HttpGet("https://httpbin.org/"))) {
try (CloseableHttpClient httpClient = setViaSocketFactory(); CloseableHttpResponse response = httpClient.execute(new HttpGet("https://httpbin.org/"))) {
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);

View File

@ -1,29 +1,5 @@
package com.baeldung.httpclient.advancedconfig;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.junit.Rule;
import org.junit.Test;
import java.io.IOException;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
@ -34,6 +10,30 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.apache.hc.client5.http.auth.AuthCache;
import org.apache.hc.client5.http.auth.AuthScope;
import org.apache.hc.client5.http.auth.CredentialsProvider;
import org.apache.hc.client5.http.auth.StandardAuthScheme;
import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.auth.BasicAuthCache;
import org.apache.hc.client5.http.impl.auth.BasicScheme;
import org.apache.hc.client5.http.impl.auth.CredentialsProviderBuilder;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.junit.Rule;
import org.junit.Test;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
public class HttpClientAdvancedConfigurationIntegrationTest {
@Rule
@ -59,7 +59,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
HttpResponse response = httpClient.execute(httpGet);
//then
assertEquals(response.getStatusLine().getStatusCode(), 200);
assertEquals(response.getCode(), 200);
}
@Test
@ -82,7 +82,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
HttpResponse response = httpClient.execute(httpPost);
//then
assertEquals(response.getStatusLine().getStatusCode(), 200);
assertEquals(response.getCode(), 200);
}
@ -107,7 +107,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
HttpResponse response = httpclient.execute(httpGet);
//then
assertEquals(response.getStatusLine().getStatusCode(), 200);
assertEquals(response.getCode(), 200);
proxyMock.verify(getRequestedFor(urlEqualTo("/private")));
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
}
@ -125,14 +125,12 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
// Client credentials
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(proxy),
new UsernamePasswordCredentials("username_admin", "secret_password"));
CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create()
.add(new AuthScope(proxy), "username_admin", "secret_password".toCharArray())
.build();
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(proxy, basicAuth);
@ -149,10 +147,11 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
//when
final HttpGet httpGet = new HttpGet("http://localhost:8089/private");
httpGet.setHeader("Authorization", StandardAuthScheme.BASIC);
HttpResponse response = httpclient.execute(httpGet, context);
//then
assertEquals(response.getStatusLine().getStatusCode(), 200);
assertEquals(response.getCode(), 200);
proxyMock.verify(getRequestedFor(urlEqualTo("/private")).withHeader("Authorization", containing("Basic")));
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
}

View File

@ -1,69 +1,71 @@
package com.baeldung.httpclient.conn;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Iterator;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.ConnectionRequest;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.util.EntityUtils;
import org.junit.Ignore;
import org.apache.hc.client5.http.ConnectionKeepAliveStrategy;
import org.apache.hc.client5.http.HttpRoute;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.ConnectionConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.BasicHttpClientConnectionManager;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.io.ConnectionEndpoint;
import org.apache.hc.client5.http.io.LeaseRequest;
import org.apache.hc.core5.http.HeaderElement;
import org.apache.hc.core5.http.HeaderElements;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.MessageSupport;
import org.apache.hc.core5.http.message.StatusLine;
import org.apache.hc.core5.http.protocol.BasicHttpContext;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.pool.PoolStats;
import org.apache.hc.core5.util.Args;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
import org.junit.Assert;
import org.junit.Test;
public class HttpClientConnectionManagementLiveTest {
// Example 2.1. Getting a Connection Request for a Low Level Connection (HttpClientConnection)
@Test
public final void whenLowLevelConnectionIsEstablished_thenNoExceptions() throws ConnectionPoolTimeoutException, InterruptedException, ExecutionException {
try (BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager()) {
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 80));
final ConnectionRequest connRequest = connManager.requestConnection(route, null);
assertNotNull(connRequest.get(1000, TimeUnit.SECONDS));
}
public final void whenLowLevelConnectionIsEstablished_thenNoExceptions() throws ExecutionException, InterruptedException, TimeoutException {
BasicHttpClientConnectionManager connMgr = new BasicHttpClientConnectionManager();
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 443));
final LeaseRequest connRequest = connMgr.lease("some-id", route, null);
assertNotNull(connRequest.get(Timeout.ZERO_MILLISECONDS));
connMgr.close();
}
// Example 3.1. Setting the PoolingHttpClientConnectionManager on a HttpClient
@Test
public final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExceptions() throws ClientProtocolException, IOException {
public final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExceptions() throws IOException {
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(poolingConnManager)
.build();
client.execute(new HttpGet("https://www.baeldung.com"));
assertTrue(poolingConnManager.getTotalStats()
.getLeased() == 1);
client.close();
poolingConnManager.close();
}
// Example 3.2. Using Two HttpClients to Connect to One Target Host Each
@Test
public final void whenTwoConnectionsForTwoRequests_thenNoExceptions() throws InterruptedException {
public final void whenTwoConnectionsForTwoRequests_thenNoExceptions() throws InterruptedException, IOException {
HttpGet get1 = new HttpGet("https://www.baeldung.com");
HttpGet get2 = new HttpGet("https://www.google.com");
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
@ -81,38 +83,52 @@ public class HttpClientConnectionManagementLiveTest {
thread1.join();
thread2.join();
assertTrue(connManager.getTotalStats()
Assert.assertTrue(connManager.getTotalStats()
.getLeased() == 0);
client1.close();
client2.close();
connManager.close();
}
// Example 4.1. Increasing the Number of Connections that Can be Open and Managed Beyond the default Limits
@Test
public final void whenIncreasingConnectionPool_thenNoEceptions() {
try (PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager()) {
connManager.setMaxTotal(5);
connManager.setDefaultMaxPerRoute(4);
HttpHost host = new HttpHost("www.baeldung.com", 80);
connManager.setMaxPerRoute(new HttpRoute(host), 5);
}
public final void whenIncreasingConnectionPool_thenNoExceptions() {
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(5);
connManager.setDefaultMaxPerRoute(4);
HttpHost host = new HttpHost("www.baeldung.com", 80);
connManager.setMaxPerRoute(new HttpRoute(host), 5);
connManager.close();
}
// Example 4.2. Using Threads to Execute Connections
@Test
public final void whenExecutingSameRequestsInDifferentThreads_thenExecuteReuqest() throws InterruptedException {
public final void whenExecutingSameRequestsInDifferentThreads_thenExecuteRequest() throws InterruptedException, IOException {
HttpGet get = new HttpGet("http://www.baeldung.com");
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(connManager)
.build();
MultiHttpClientConnThread thread1 = new MultiHttpClientConnThread(client, get);
MultiHttpClientConnThread thread2 = new MultiHttpClientConnThread(client, get);
MultiHttpClientConnThread thread3 = new MultiHttpClientConnThread(client, get);
MultiHttpClientConnThread thread1 = new MultiHttpClientConnThread(client, get, connManager);
MultiHttpClientConnThread thread2 = new MultiHttpClientConnThread(client, get, connManager);
MultiHttpClientConnThread thread3 = new MultiHttpClientConnThread(client, get, connManager);
MultiHttpClientConnThread thread4 = new MultiHttpClientConnThread(client, get, connManager);
MultiHttpClientConnThread thread5 = new MultiHttpClientConnThread(client, get, connManager);
MultiHttpClientConnThread thread6 = new MultiHttpClientConnThread(client, get, connManager);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
thread6.start();
thread1.join();
thread2.join();
thread3.join();
thread4.join();
thread5.join();
thread6.join();
client.close();
connManager.close();
}
// Example 5.1. A Custom Keep Alive Strategy
@ -120,22 +136,19 @@ public class HttpClientConnectionManagementLiveTest {
public final void whenCustomizingKeepAliveStrategy_thenNoExceptions() {
final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(final HttpResponse myResponse, final HttpContext myContext) {
final HeaderElementIterator it = new BasicHeaderElementIterator(myResponse.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
final HeaderElement he = it.nextElement();
final String param = he.getName();
final String value = he.getValue();
if ((value != null) && param.equalsIgnoreCase("timeout")) {
return Long.parseLong(value) * 1000;
public TimeValue getKeepAliveDuration(HttpResponse response, HttpContext context) {
Args.notNull(response, "HTTP response");
final Iterator<HeaderElement> it = MessageSupport.iterate(response, HeaderElements.KEEP_ALIVE);
final HeaderElement he = it.next();
final String param = he.getName();
final String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
try {
return TimeValue.ofSeconds(Long.parseLong(value));
} catch (final NumberFormatException ignore) {
}
}
final HttpHost target = (HttpHost) myContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
if ("localhost".equalsIgnoreCase(target.getHostName())) {
return 10 * 1000;
} else {
return 5 * 1000;
}
return TimeValue.ofSeconds(5);
}
};
@ -144,42 +157,38 @@ public class HttpClientConnectionManagementLiveTest {
.setKeepAliveStrategy(myStrategy)
.setConnectionManager(connManager)
.build();
connManager.close();
}
// Example 6.1. BasicHttpClientConnectionManager Connection Reuse
//Example 6.1. BasicHttpClientConnectionManager Connection Reuse
@Test
public final void givenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws IOException, HttpException, InterruptedException, ExecutionException {
BasicHttpClientConnectionManager basicConnManager = new BasicHttpClientConnectionManager();
HttpClientContext context = HttpClientContext.create();
// low level
public final void givenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws InterruptedException, ExecutionException, TimeoutException, IOException, URISyntaxException {
BasicHttpClientConnectionManager connMgr = new BasicHttpClientConnectionManager();
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 443));
ConnectionRequest connRequest = basicConnManager.requestConnection(route, null);
HttpClientConnection conn = connRequest.get(10, TimeUnit.SECONDS);
basicConnManager.connect(conn, route, 1000, context);
basicConnManager.routeComplete(conn, route, context);
final HttpContext context = new BasicHttpContext();
HttpRequestExecutor exeRequest = new HttpRequestExecutor();
context.setTargetHost((new HttpHost("www.baeldung.com", 80)));
HttpGet get = new HttpGet("http://www.baeldung.com");
exeRequest.execute(get, conn, context);
final LeaseRequest connRequest = connMgr.lease("some-id", route, null);
final ConnectionEndpoint endpoint = connRequest.get(Timeout.ZERO_MILLISECONDS);
connMgr.connect(endpoint, Timeout.ZERO_MILLISECONDS, context);
basicConnManager.releaseConnection(conn, null, 1, TimeUnit.SECONDS);
connMgr.release(endpoint, null, TimeValue.ZERO_MILLISECONDS);
// high level
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(basicConnManager)
.setConnectionManager(connMgr)
.build();
client.execute(get);
HttpGet httpGet = new HttpGet("https://www.example.com");
client.execute(httpGet, context, response -> response);
client.close();
connMgr.close();
}
// Example 6.2. PoolingHttpClientConnectionManager: Re-Using Connections with Threads
@Test
public final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException {
HttpGet get = new HttpGet("http://echo.200please.com");
public final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException, IOException {
HttpGet get = new HttpGet("http://www.baeldung.com");
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setDefaultMaxPerRoute(5);
connManager.setMaxTotal(5);
connManager.setDefaultMaxPerRoute(6);
connManager.setMaxTotal(6);
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(connManager)
.build();
@ -193,48 +202,71 @@ public class HttpClientConnectionManagementLiveTest {
for (MultiHttpClientConnThread thread : threads) {
thread.join(1000);
}
client.close();
connManager.close();
}
// Example 7.1. Setting Socket Timeout to 5 Seconds
@Test
public final void whenConfiguringTimeOut_thenNoExceptions() {
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 80));
try (PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager()) {
connManager.setSocketConfig(route.getTargetHost(), SocketConfig.custom()
.setSoTimeout(5000)
.build());
assertTrue(connManager.getSocketConfig(route.getTargetHost())
.getSoTimeout() == 5000);
}
public final void whenConfiguringTimeOut_thenNoExceptions() throws ExecutionException, InterruptedException, TimeoutException, IOException {
final HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 80));
final HttpContext context = new BasicHttpContext();
final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
final ConnectionConfig connConfig = ConnectionConfig.custom()
.setSocketTimeout(5, TimeUnit.SECONDS)
.build();
connManager.setDefaultConnectionConfig(connConfig);
final LeaseRequest leaseRequest = connManager.lease("id1", route, null);
final ConnectionEndpoint endpoint = leaseRequest.get(Timeout.ZERO_MILLISECONDS);
connManager.connect(endpoint, null, context);
connManager.close();
}
// Example 8.1. Setting the HttpClient to Check for Stale Connections
@Test
public final void whenHttpClientChecksStaleConns_thenNoExceptions() {
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setStaleConnectionCheckEnabled(true)
.build())
public final void whenEvictIdealConn_thenNoExceptions() throws InterruptedException, IOException {
final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(100);
try (final CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(connManager)
.build();
}
.evictExpiredConnections()
.evictIdleConnections(TimeValue.ofSeconds(2))
.build()) {
// create an array of URIs to perform GETs on
final String[] urisToGet = { "http://hc.apache.org/", "http://hc.apache.org/httpcomponents-core-ga/"};
// Example 8.2. Using a Stale Connection Monitor Thread
@Test
public final void whenCustomizedIdleConnMonitor_thenNoExceptions() throws InterruptedException {
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
HttpClients.custom()
.setConnectionManager(connManager)
.build();
IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(connManager);
staleMonitor.start();
staleMonitor.join(1000);
for (final String requestURI : urisToGet) {
final HttpGet request = new HttpGet(requestURI);
System.out.println("Executing request " + request.getMethod() + " " + request.getRequestUri());
httpclient.execute(request, response -> {
System.out.println("----------------------------------------");
System.out.println(request + "->" + new StatusLine(response));
EntityUtils.consume(response.getEntity());
return null;
});
}
final PoolStats stats1 = connManager.getTotalStats();
System.out.println("Connections kept alive: " + stats1.getAvailable());
// Sleep 10 sec and let the connection evict or do its job
Thread.sleep(4000);
final PoolStats stats2 = connManager.getTotalStats();
System.out.println("Connections kept alive: " + stats2.getAvailable());
connManager.close();
}
}
// Example 9.1. Closing Connection and Releasing Resources
@Test(expected = IllegalStateException.class)
public final void whenClosingConnectionsandManager_thenCloseWithNoExceptions1() throws InterruptedException, ExecutionException, IOException, HttpException {
@Test
public final void whenClosingConnectionsandManager_thenCloseWithNoExceptions1() throws IOException {
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(connManager)
@ -246,16 +278,11 @@ public class HttpClientConnectionManagementLiveTest {
response.close();
client.close();
connManager.close();
connManager.shutdown();
client.execute(get);
assertTrue(response.getEntity() == null);
}
@Test
// Example 3.2. TESTER VERSION
public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException {
public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException, IOException {
HttpGet get1 = new HttpGet("https://www.baeldung.com");
HttpGet get2 = new HttpGet("https://www.google.com");
@ -273,77 +300,11 @@ public class HttpClientConnectionManagementLiveTest {
thread2.start();
thread1.join();
thread2.join(1000);
assertTrue(poolingConnManager.getTotalStats()
Assert.assertTrue(poolingConnManager.getTotalStats()
.getLeased() == 2);
}
@Test
// Example 4.2 Tester Version
public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException {
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(poolingConnManager)
.build();
final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager);
final TesterVersion_MultiHttpClientConnThread thread2 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager);
final TesterVersion_MultiHttpClientConnThread thread3 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager);
thread1.start();
thread2.start();
thread3.start();
thread1.join(10000);
thread2.join(10000);
thread3.join(10000);
}
@Test
// 6.2 TESTER VERSION
public final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException {
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
poolingConnManager.setDefaultMaxPerRoute(5);
poolingConnManager.setMaxTotal(5);
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(poolingConnManager)
.build();
final MultiHttpClientConnThread[] threads = new MultiHttpClientConnThread[10];
int countConnMade = 0;
for (int i = 0; i < threads.length; i++) {
threads[i] = new MultiHttpClientConnThread(client, new HttpGet("http://www.baeldung.com/"), poolingConnManager);
}
for (final MultiHttpClientConnThread thread : threads) {
thread.start();
}
for (final MultiHttpClientConnThread thread : threads) {
thread.join(10000);
countConnMade++;
if (countConnMade == 0) {
assertTrue(thread.getLeasedConn() == 5);
}
}
}
@Test
@Ignore("Very Long Running")
// 8.2 TESTER VERSION
public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException {
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(poolingConnManager)
.build();
final IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(poolingConnManager);
final HttpGet get = new HttpGet("http://google.com");
final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager);
final TesterVersion_MultiHttpClientConnThread thread2 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager);
final TesterVersion_MultiHttpClientConnThread thread3 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager);
staleMonitor.start();
thread1.start();
thread1.join();
thread2.start();
thread2.join();
thread3.start();
assertTrue(poolingConnManager.getTotalStats()
.getAvailable() == 1);
thread3.join(32000);
assertTrue(poolingConnManager.getTotalStats()
.getAvailable() == 0);
client1.close();
client2.close();
poolingConnManager.close();
}
}

View File

@ -2,12 +2,12 @@ package com.baeldung.httpclient.conn;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
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.io.PoolingHttpClientConnectionManager;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -45,22 +45,21 @@ public class MultiHttpClientConnThread extends Thread {
try {
logger.debug("Thread Running: " + getName());
logger.debug("Thread Running: " + getName());
if (connManager != null) {
logger.info("Before - Leased Connections = " + connManager.getTotalStats().getLeased());
logger.info("Before - Available Connections = " + connManager.getTotalStats().getAvailable());
}
final HttpResponse response = client.execute(get);
HttpEntity entity = client.execute(get).getEntity();
if (connManager != null) {
leasedConn = connManager.getTotalStats().getLeased();
logger.info("After - Leased Connections = " + connManager.getTotalStats().getLeased());
logger.info("After - Available Connections = " + connManager.getTotalStats().getAvailable());
}
EntityUtils.consume(entity);
EntityUtils.consume(response.getEntity());
} catch (final IOException ex) {
logger.error("", ex);
}

View File

@ -2,10 +2,9 @@ package com.baeldung.httpclient.conn;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
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.io.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -0,0 +1,64 @@
package com.baeldung.tlsversion;
import javax.net.ssl.SSLSocket;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class ClientTlsVersionExamples {
public static CloseableHttpClient setViaSocketFactory() {
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
SSLContexts.createDefault(),
new String[] { "TLSv1.2", "TLSv1.3" },
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}
public static CloseableHttpClient setTlsVersionPerConnection() {
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(SSLContexts.createDefault()) {
@Override
protected void prepareSocket(SSLSocket socket) {
String hostname = socket.getInetAddress().getHostName();
if (hostname.endsWith("internal.system.com")) {
socket.setEnabledProtocols(new String[] { "TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3" });
} else {
socket.setEnabledProtocols(new String[] { "TLSv1.3" });
}
}
};
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}
// To configure the TLS versions for the client, set the https.protocols system property during runtime.
// For example: java -Dhttps.protocols=TLSv1.1,TLSv1.2,TLSv1.3 -jar webClient.jar
public static CloseableHttpClient setViaSystemProperties() {
return HttpClients.createSystem();
// Alternatively:
// return HttpClients.custom().useSystemProperties().build();
}
public static void main(String[] args) throws IOException {
// Alternatively:
// CloseableHttpClient httpClient = setTlsVersionPerConnection();
// CloseableHttpClient httpClient = setViaSystemProperties();
try (CloseableHttpClient httpClient = setViaSocketFactory();
CloseableHttpResponse response = httpClient.execute(new HttpGet("https://httpbin.org/"))) {
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
}
}
}

View File

@ -0,0 +1,161 @@
package com.baeldung.httpclient.advancedconfig;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.junit.Rule;
import org.junit.Test;
import java.io.IOException;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static org.junit.Assert.assertEquals;
public class HttpClientAdvancedConfigurationIntegrationTest {
@Rule
public WireMockRule serviceMock = new WireMockRule(8089);
@Rule
public WireMockRule proxyMock = new WireMockRule(8090);
@Test
public void givenClientWithCustomUserAgentHeader_whenExecuteRequest_shouldReturn200() throws IOException {
//given
String userAgent = "BaeldungAgent/1.0";
serviceMock.stubFor(get(urlEqualTo("/detail"))
.withHeader("User-Agent", equalTo(userAgent))
.willReturn(aResponse()
.withStatus(200)));
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://localhost:8089/detail");
httpGet.setHeader(HttpHeaders.USER_AGENT, userAgent);
//when
HttpResponse response = httpClient.execute(httpGet);
//then
assertEquals(response.getStatusLine().getStatusCode(), 200);
}
@Test
public void givenClientThatSendDataInBody_whenSendXmlInBody_shouldReturn200() throws IOException {
//given
String xmlBody = "<xml><id>1</id></xml>";
serviceMock.stubFor(post(urlEqualTo("/person"))
.withHeader("Content-Type", equalTo("application/xml"))
.withRequestBody(equalTo(xmlBody))
.willReturn(aResponse()
.withStatus(200)));
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://localhost:8089/person");
httpPost.setHeader("Content-Type", "application/xml");
StringEntity xmlEntity = new StringEntity(xmlBody);
httpPost.setEntity(xmlEntity);
//when
HttpResponse response = httpClient.execute(httpPost);
//then
assertEquals(response.getStatusLine().getStatusCode(), 200);
}
@Test
public void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException {
//given
proxyMock.stubFor(get(urlMatching(".*"))
.willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
serviceMock.stubFor(get(urlEqualTo("/private"))
.willReturn(aResponse().withStatus(200)));
HttpHost proxy = new HttpHost("localhost", 8090);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
HttpClient httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner)
.build();
//when
final HttpGet httpGet = new HttpGet("http://localhost:8089/private");
HttpResponse response = httpclient.execute(httpGet);
//then
assertEquals(response.getStatusLine().getStatusCode(), 200);
proxyMock.verify(getRequestedFor(urlEqualTo("/private")));
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
}
@Test
public void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException {
//given
proxyMock.stubFor(get(urlMatching("/private"))
.willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
serviceMock.stubFor(get(urlEqualTo("/private"))
.willReturn(aResponse().withStatus(200)));
HttpHost proxy = new HttpHost("localhost", 8090);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
// Client credentials
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(proxy),
new UsernamePasswordCredentials("username_admin", "secret_password"));
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(proxy, basicAuth);
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credentialsProvider);
context.setAuthCache(authCache);
HttpClient httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner)
.setDefaultCredentialsProvider(credentialsProvider)
.build();
//when
final HttpGet httpGet = new HttpGet("http://localhost:8089/private");
HttpResponse response = httpclient.execute(httpGet, context);
//then
assertEquals(response.getStatusLine().getStatusCode(), 200);
proxyMock.verify(getRequestedFor(urlEqualTo("/private")).withHeader("Authorization", containing("Basic")));
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
}
}

View File

@ -0,0 +1,349 @@
package com.baeldung.httpclient.httpclient.conn;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.ConnectionRequest;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.util.EntityUtils;
import org.junit.Ignore;
import org.junit.Test;
public class HttpClientConnectionManagementLiveTest {
// Example 2.1. Getting a Connection Request for a Low Level Connection (HttpClientConnection)
@Test
public final void whenLowLevelConnectionIsEstablished_thenNoExceptions() throws ConnectionPoolTimeoutException, InterruptedException, ExecutionException {
try (BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager()) {
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 80));
final ConnectionRequest connRequest = connManager.requestConnection(route, null);
assertNotNull(connRequest.get(1000, TimeUnit.SECONDS));
}
}
// Example 3.1. Setting the PoolingHttpClientConnectionManager on a HttpClient
@Test
public final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExceptions() throws ClientProtocolException, IOException {
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(poolingConnManager)
.build();
client.execute(new HttpGet("https://www.baeldung.com"));
assertTrue(poolingConnManager.getTotalStats()
.getLeased() == 1);
}
// Example 3.2. Using Two HttpClients to Connect to One Target Host Each
@Test
public final void whenTwoConnectionsForTwoRequests_thenNoExceptions() throws InterruptedException {
HttpGet get1 = new HttpGet("https://www.baeldung.com");
HttpGet get2 = new HttpGet("https://www.google.com");
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client1 = HttpClients.custom()
.setConnectionManager(connManager)
.build();
CloseableHttpClient client2 = HttpClients.custom()
.setConnectionManager(connManager)
.build();
MultiHttpClientConnThread thread1 = new MultiHttpClientConnThread(client1, get1);
MultiHttpClientConnThread thread2 = new MultiHttpClientConnThread(client2, get2);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
assertTrue(connManager.getTotalStats()
.getLeased() == 0);
}
// Example 4.1. Increasing the Number of Connections that Can be Open and Managed Beyond the default Limits
@Test
public final void whenIncreasingConnectionPool_thenNoEceptions() {
try (PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager()) {
connManager.setMaxTotal(5);
connManager.setDefaultMaxPerRoute(4);
HttpHost host = new HttpHost("www.baeldung.com", 80);
connManager.setMaxPerRoute(new HttpRoute(host), 5);
}
}
// Example 4.2. Using Threads to Execute Connections
@Test
public final void whenExecutingSameRequestsInDifferentThreads_thenExecuteReuqest() throws InterruptedException {
HttpGet get = new HttpGet("http://www.baeldung.com");
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(connManager)
.build();
MultiHttpClientConnThread thread1 = new MultiHttpClientConnThread(client, get);
MultiHttpClientConnThread thread2 = new MultiHttpClientConnThread(client, get);
MultiHttpClientConnThread thread3 = new MultiHttpClientConnThread(client, get);
thread1.start();
thread2.start();
thread3.start();
thread1.join();
thread2.join();
thread3.join();
}
// Example 5.1. A Custom Keep Alive Strategy
@Test
public final void whenCustomizingKeepAliveStrategy_thenNoExceptions() {
final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(final HttpResponse myResponse, final HttpContext myContext) {
final HeaderElementIterator it = new BasicHeaderElementIterator(myResponse.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
final HeaderElement he = it.nextElement();
final String param = he.getName();
final String value = he.getValue();
if ((value != null) && param.equalsIgnoreCase("timeout")) {
return Long.parseLong(value) * 1000;
}
}
final HttpHost target = (HttpHost) myContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
if ("localhost".equalsIgnoreCase(target.getHostName())) {
return 10 * 1000;
} else {
return 5 * 1000;
}
}
};
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
HttpClients.custom()
.setKeepAliveStrategy(myStrategy)
.setConnectionManager(connManager)
.build();
}
// Example 6.1. BasicHttpClientConnectionManager Connection Reuse
@Test
public final void givenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws IOException, HttpException, InterruptedException, ExecutionException {
BasicHttpClientConnectionManager basicConnManager = new BasicHttpClientConnectionManager();
HttpClientContext context = HttpClientContext.create();
// low level
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 443));
ConnectionRequest connRequest = basicConnManager.requestConnection(route, null);
HttpClientConnection conn = connRequest.get(10, TimeUnit.SECONDS);
basicConnManager.connect(conn, route, 1000, context);
basicConnManager.routeComplete(conn, route, context);
HttpRequestExecutor exeRequest = new HttpRequestExecutor();
context.setTargetHost((new HttpHost("www.baeldung.com", 80)));
HttpGet get = new HttpGet("http://www.baeldung.com");
exeRequest.execute(get, conn, context);
basicConnManager.releaseConnection(conn, null, 1, TimeUnit.SECONDS);
// high level
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(basicConnManager)
.build();
client.execute(get);
}
// Example 6.2. PoolingHttpClientConnectionManager: Re-Using Connections with Threads
@Test
public final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException {
HttpGet get = new HttpGet("http://echo.200please.com");
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setDefaultMaxPerRoute(5);
connManager.setMaxTotal(5);
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(connManager)
.build();
MultiHttpClientConnThread[] threads = new MultiHttpClientConnThread[10];
for (int i = 0; i < threads.length; i++) {
threads[i] = new MultiHttpClientConnThread(client, get, connManager);
}
for (MultiHttpClientConnThread thread : threads) {
thread.start();
}
for (MultiHttpClientConnThread thread : threads) {
thread.join(1000);
}
}
// Example 7.1. Setting Socket Timeout to 5 Seconds
@Test
public final void whenConfiguringTimeOut_thenNoExceptions() {
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 80));
try (PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager()) {
connManager.setSocketConfig(route.getTargetHost(), SocketConfig.custom()
.setSoTimeout(5000)
.build());
assertTrue(connManager.getSocketConfig(route.getTargetHost())
.getSoTimeout() == 5000);
}
}
// Example 8.1. Setting the HttpClient to Check for Stale Connections
@Test
public final void whenHttpClientChecksStaleConns_thenNoExceptions() {
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setStaleConnectionCheckEnabled(true)
.build())
.setConnectionManager(connManager)
.build();
}
// Example 8.2. Using a Stale Connection Monitor Thread
@Test
public final void whenCustomizedIdleConnMonitor_thenNoExceptions() throws InterruptedException {
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
HttpClients.custom()
.setConnectionManager(connManager)
.build();
IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(connManager);
staleMonitor.start();
staleMonitor.join(1000);
}
// Example 9.1. Closing Connection and Releasing Resources
@Test(expected = IllegalStateException.class)
public final void whenClosingConnectionsandManager_thenCloseWithNoExceptions1() throws InterruptedException, ExecutionException, IOException, HttpException {
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(connManager)
.build();
final HttpGet get = new HttpGet("http://google.com");
CloseableHttpResponse response = client.execute(get);
EntityUtils.consume(response.getEntity());
response.close();
client.close();
connManager.close();
connManager.shutdown();
client.execute(get);
assertTrue(response.getEntity() == null);
}
@Test
// Example 3.2. TESTER VERSION
public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException {
HttpGet get1 = new HttpGet("https://www.baeldung.com");
HttpGet get2 = new HttpGet("https://www.google.com");
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
final CloseableHttpClient client1 = HttpClients.custom()
.setConnectionManager(poolingConnManager)
.build();
final CloseableHttpClient client2 = HttpClients.custom()
.setConnectionManager(poolingConnManager)
.build();
final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client1, get1, poolingConnManager);
final TesterVersion_MultiHttpClientConnThread thread2 = new TesterVersion_MultiHttpClientConnThread(client2, get2, poolingConnManager);
thread1.start();
thread2.start();
thread1.join();
thread2.join(1000);
assertTrue(poolingConnManager.getTotalStats()
.getLeased() == 2);
}
@Test
// Example 4.2 Tester Version
public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException {
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(poolingConnManager)
.build();
final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager);
final TesterVersion_MultiHttpClientConnThread thread2 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager);
final TesterVersion_MultiHttpClientConnThread thread3 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager);
thread1.start();
thread2.start();
thread3.start();
thread1.join(10000);
thread2.join(10000);
thread3.join(10000);
}
@Test
// 6.2 TESTER VERSION
public final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException {
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
poolingConnManager.setDefaultMaxPerRoute(5);
poolingConnManager.setMaxTotal(5);
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(poolingConnManager)
.build();
final MultiHttpClientConnThread[] threads = new MultiHttpClientConnThread[10];
int countConnMade = 0;
for (int i = 0; i < threads.length; i++) {
threads[i] = new MultiHttpClientConnThread(client, new HttpGet("http://www.baeldung.com/"), poolingConnManager);
}
for (final MultiHttpClientConnThread thread : threads) {
thread.start();
}
for (final MultiHttpClientConnThread thread : threads) {
thread.join(10000);
countConnMade++;
if (countConnMade == 0) {
assertTrue(thread.getLeasedConn() == 5);
}
}
}
@Test
@Ignore("Very Long Running")
// 8.2 TESTER VERSION
public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException {
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(poolingConnManager)
.build();
final IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(poolingConnManager);
final HttpGet get = new HttpGet("http://google.com");
final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager);
final TesterVersion_MultiHttpClientConnThread thread2 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager);
final TesterVersion_MultiHttpClientConnThread thread3 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager);
staleMonitor.start();
thread1.start();
thread1.join();
thread2.start();
thread2.join();
thread3.start();
assertTrue(poolingConnManager.getTotalStats()
.getAvailable() == 1);
thread3.join(32000);
assertTrue(poolingConnManager.getTotalStats()
.getAvailable() == 0);
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.httpclient.httpclient.conn;
import java.util.concurrent.TimeUnit;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
public class IdleConnectionMonitorThread extends Thread {
private final HttpClientConnectionManager connMgr;
private volatile boolean shutdown;
IdleConnectionMonitorThread(final PoolingHttpClientConnectionManager connMgr) {
super();
this.connMgr = connMgr;
}
// API
@Override
public final void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(1000);
connMgr.closeExpiredConnections();
connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
}
}
} catch (final InterruptedException ex) {
shutdown();
}
}
private void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}

View File

@ -0,0 +1,69 @@
package com.baeldung.httpclient.httpclient.conn;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MultiHttpClientConnThread extends Thread {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final CloseableHttpClient client;
private final HttpGet get;
private PoolingHttpClientConnectionManager connManager;
private int leasedConn;
MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) {
this.client = client;
this.get = get;
this.connManager = connManager;
leasedConn = 0;
}
MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get) {
this.client = client;
this.get = get;
}
// API
final int getLeasedConn() {
return leasedConn;
}
//
@Override
public final void run() {
try {
logger.debug("Thread Running: " + getName());
logger.debug("Thread Running: " + getName());
if (connManager != null) {
logger.info("Before - Leased Connections = " + connManager.getTotalStats().getLeased());
logger.info("Before - Available Connections = " + connManager.getTotalStats().getAvailable());
}
final HttpResponse response = client.execute(get);
if (connManager != null) {
leasedConn = connManager.getTotalStats().getLeased();
logger.info("After - Leased Connections = " + connManager.getTotalStats().getLeased());
logger.info("After - Available Connections = " + connManager.getTotalStats().getAvailable());
}
EntityUtils.consume(response.getEntity());
} catch (final IOException ex) {
logger.error("", ex);
}
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.httpclient.httpclient.conn;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
public class TesterVersion_MultiHttpClientConnThread extends Thread {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final CloseableHttpClient client;
private final HttpGet get;
private PoolingHttpClientConnectionManager connManager;
TesterVersion_MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) {
this.client = client;
this.get = get;
this.connManager = Preconditions.checkNotNull(connManager);
}
//
@Override
public final void run() {
try {
logger.debug("Thread Running: " + getName());
logger.info("Before - Leased Connections = " + connManager.getTotalStats().getLeased());
logger.info("Before - Available Connections = " + connManager.getTotalStats().getAvailable());
client.execute(get);
logger.info("After - Leased Connections = " + connManager.getTotalStats().getLeased());
logger.info("After - Available Connections = " + connManager.getTotalStats().getAvailable());
} catch (final IOException ex) {
logger.error("", ex);
}
}
}

View File

@ -12,3 +12,4 @@ You can build the project from the command line using: *mvn clean install*, or i
- [Is a Key Required as Part of Sending Messages to Kafka?](https://www.baeldung.com/java-kafka-message-key)
- [Read Data From the Beginning Using Kafka Consumer API](https://www.baeldung.com/java-kafka-consumer-api-read)
- [Get Partition Count for a Topic in Kafka](https://www.baeldung.com/java-kafka-partition-count-topic)
- [bootstrap-server in Kafka Configuration](https://www.baeldung.com/java-kafka-bootstrap-server)

View File

@ -0,0 +1,39 @@
package com.baeldung.kafka.consumer;
import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.serialization.LongDeserializer;
import org.apache.kafka.common.serialization.StringDeserializer;
import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;
public class SimpleConsumerWithBootStrapServers {
public static void main(String[] args) {
try(final Consumer<Long, String> consumer = createConsumer()) {
ConsumerRecords<Long, String> records = consumer.poll(Duration.ofMinutes(1));
for(ConsumerRecord<Long, String> record : records) {
System.out.println(record.value());
}
}
}
private static Consumer<Long, String> createConsumer() {
final Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
"localhost:9092,another-host.com:29092");
props.put(ConsumerConfig.GROUP_ID_CONFIG,
"MySampleConsumer");
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
LongDeserializer.class.getName());
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
StringDeserializer.class.getName());
// Create the consumer using props.
final Consumer<Long, String> consumer = new KafkaConsumer<Long, String>(props);
// Subscribe to the topic.
consumer.subscribe(Arrays.asList("samples"));
return consumer;
}
}

View File

View File

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>apache-libraries-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apache-libraries-2</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>${javax.validation.validation-api.version}</version>
</dependency>
</dependencies>
<properties>
<javax.validation.validation-api.version>2.0.1.Final</javax.validation.validation-api.version>
</properties>
</project>

View File

@ -0,0 +1,18 @@
package com.baeldung.xslt;
import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
public class XSLTProcessor {
public static void transformXMLUsingXSLT(String inputXMLPath, String xsltPath, String outputHTMLPath) throws TransformerException {
Source xmlSource = new StreamSource(new File(inputXMLPath));
Source xsltSource = new StreamSource(new File(xsltPath));
Result output = new StreamResult(new File(outputHTMLPath));
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer(xsltSource);
transformer.transform(xmlSource, output);
}
}

View File

@ -0,0 +1,47 @@
{
"type":"record",
"name":"AvroHttpRequest",
"namespace":"com.baeldung.avro.model",
"fields":[
{
"name":"requestTime",
"type":"long"
},
{
"name":"clientIdentifier",
"type":{
"type":"record",
"name":"ClientIdentifier",
"fields":[
{
"name":"hostName",
"type":"string"
},
{
"name":"ipAddress",
"type":"string"
}
]
}
},
{
"name":"employeeNames",
"type":{
"type":"array",
"items":"string"
},
"default":null
},
{
"name":"active",
"type":{
"type":"enum",
"name":"Active",
"symbols":[
"YES",
"NO"
]
}
}
]
}

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Logger name="org.apache.meecrowave" level="warn">
<AppenderRef ref="Console"/>
</Logger>
<Root level="info">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>

View File

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

View File

@ -0,0 +1,29 @@
package com.baeldung.xslt;
import org.junit.jupiter.api.Test;
import javax.xml.transform.TransformerException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class XSLTProcessorUnitTest {
@Test
public void givenValidInputAndStylesheet_whenTransformingXML_thenOutputHTMLCreated() throws TransformerException, IOException {
// Given
String inputXMLPath = "src/test/resources/input.xml";
String xsltPath = "src/test/resources/stylesheet.xslt";
String outputHTMLPath = "src/test/resources/output.html";
XSLTProcessor.transformXMLUsingXSLT(inputXMLPath, xsltPath, outputHTMLPath);
Path outputFile = Paths.get(outputHTMLPath);
assertTrue(Files.exists(outputFile));
}
}

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<root>
<person gender="male">
<name>John Doe</name>
<age>30</age>
</person>
<person gender="female">
<name>Jane Smith</name>
<age>25</age>
</person>
</root>

View File

@ -0,0 +1,3 @@
<?xml version="1.0" encoding="UTF-8"?>
<p>Male person: John Doe, Age: 30</p>
<p>Female person: Jane Smith, Age: 25</p>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="person[@gender='male']">
<xsl:element name="p">
<xsl:text>Male person: </xsl:text>
<xsl:value-of select="name"/>
<xsl:text>, Age: </xsl:text>
<xsl:value-of select="age"/>
</xsl:element>
</xsl:template>
<xsl:template match="person[@gender='female']">
<xsl:element name="p">
<xsl:text>Female person: </xsl:text>
<xsl:value-of select="name"/>
<xsl:text>, Age: </xsl:text>
<xsl:value-of select="age"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>

View File

@ -13,4 +13,5 @@ This module contains articles about Apache POI.
- [Setting Formulas in Excel with Apache POI](https://www.baeldung.com/java-apache-poi-set-formulas)
- [Set the Date Format Using Apache POI](https://www.baeldung.com/java-apache-poi-date-format)
- [Replacing Variables in a Document Template with Java](https://www.baeldung.com/java-replace-pattern-word-document-doc-docx)
- [Lock Header Rows With Apache POI](https://www.baeldung.com/java-apache-poi-lock-header-rows)
- More articles: [[<-- prev]](../apache-poi)

View File

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>aws-s3-update-object</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>aws-s3-update-object</name>
<description>Project demonstrating overwriting of S3 objects</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>${aws-java-sdk-version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<properties>
<aws-java-sdk-version>1.12.523</aws-java-sdk-version>
</properties>
</project>

View File

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

View File

@ -0,0 +1,24 @@
package com.baeldung.awss3updateobject.controller;
import com.baeldung.awss3updateobject.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("api/v1/file")
public class FileController {
@Autowired
FileService fileService;
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile multipartFile) throws Exception {
return this.fileService.uploadFile(multipartFile);
}
@PostMapping("/update")
public String updateFile(@RequestParam("file") MultipartFile multipartFile, @RequestParam("filePath") String exitingFilePath) throws Exception {
return this.fileService.updateFile(multipartFile, exitingFilePath);
}
}

View File

@ -0,0 +1,80 @@
package com.baeldung.awss3updateobject.service;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
@Service
public class FileService {
private static final Logger logger = LoggerFactory.getLogger(FileService.class);
public AmazonS3 amazonS3;
@Value("${aws.s3bucket}")
public String awsS3Bucket;
@PostConstruct
private void init(){
AWSCredentials credentials = new BasicAWSCredentials(
"AWS AccessKey",
"AWS secretKey"
);
this.amazonS3 = AmazonS3ClientBuilder.standard()
.withRegion(Regions.fromName("us-east-1"))
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.build();
}
public String uploadFile(MultipartFile multipartFile) throws Exception {
String key = "/documents/" + multipartFile.getOriginalFilename();
return this.uploadDocument(this.awsS3Bucket, key, multipartFile);
}
public String updateFile(MultipartFile multipartFile, String key) throws Exception {
return this.uploadDocument(this.awsS3Bucket, key, multipartFile);
}
private String uploadDocument(String s3bucket, String key, MultipartFile multipartFile) throws Exception {
try {
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType(multipartFile.getContentType());
Map<String, String> attributes = new HashMap<>();
attributes.put("document-content-size", String.valueOf(multipartFile.getSize()));
metadata.setUserMetadata(attributes);
InputStream documentStream = multipartFile.getInputStream();
PutObjectResult putObjectResult = this.amazonS3.putObject(new PutObjectRequest(s3bucket, key, documentStream, metadata));
S3Object s3Object = this.amazonS3.getObject(s3bucket, key);
logger.info("Last Modified: " + s3Object.getObjectMetadata().getLastModified());
return key;
} catch (AmazonS3Exception ex) {
if (ex.getErrorCode().equalsIgnoreCase("NoSuchBucket")) {
String msg = String.format("No bucket found with name %s", s3bucket);
throw new Exception(msg);
} else if (ex.getErrorCode().equalsIgnoreCase("AccessDenied")) {
String msg = String.format("Access denied to S3 bucket %s", s3bucket);
throw new Exception(msg);
}
throw ex;
} catch (IOException ex) {
String msg = String.format("Error saving file %s to AWS S3 bucket %s", key, s3bucket);
throw new Exception(msg);
}
}
}

View File

@ -0,0 +1 @@
aws.s3bucket=baeldung-documents;

View File

@ -0,0 +1,62 @@
package com.baeldung.awss3updateobject.controller;
import com.baeldung.awss3updateobject.service.FileService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.multipart.MultipartFile;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
public class FileControllerUnitTest {
private MockMvc mockMvc;
@Mock
private FileService fileService;
@InjectMocks
private FileController fileController;
@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(fileController).build();
}
@Test
public void givenValidMultipartFile_whenUploadedViaEndpoint_thenCorrectPathIsReturned() throws Exception {
MockMultipartFile multipartFile = new MockMultipartFile("file", "test.txt", "text/plain", "sample file content".getBytes());
String expectedResult = "File Uploaded Successfully";
when(fileService.uploadFile(multipartFile)).thenReturn(expectedResult);
mockMvc.perform(multipart("/api/v1/file/upload").file(multipartFile))
.andExpect(status().isOk())
.andExpect(content().string(expectedResult));
}
@Test
public void givenValidMultipartFileAndExistingPath_whenUpdatedViaEndpoint_thenSamePathIsReturned() throws Exception {
MockMultipartFile multipartFile = new MockMultipartFile("file", "test.txt", "text/plain", "updated file content".getBytes());
String filePath = "some/path/to/file";
String expectedResult = "File Updated Successfully";
when(fileService.updateFile(multipartFile, filePath)).thenReturn(expectedResult);
mockMvc.perform(multipart("/api/v1/file/update")
.file(multipartFile)
.param("filePath", filePath))
.andExpect(status().isOk())
.andExpect(content().string(expectedResult));
}
}

View File

@ -0,0 +1,99 @@
package com.baeldung.awss3updateobject.service;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
public class FileServiceUnitTest {
@Mock
private AmazonS3 amazonS3;
@Mock
private MultipartFile multipartFile;
@InjectMocks
private FileService fileService;
@BeforeEach
public void setup() {
MockitoAnnotations.openMocks(this);
fileService = new FileService();
fileService.awsS3Bucket = "test-bucket";
fileService.amazonS3 = amazonS3;
}
@Test
public void givenValidFile_whenUploaded_thenKeyMatchesDocumentPath() throws Exception {
when(multipartFile.getName()).thenReturn("testFile");
when(multipartFile.getOriginalFilename()).thenReturn("testFile");
when(multipartFile.getContentType()).thenReturn("application/pdf");
when(multipartFile.getSize()).thenReturn(1024L);
when(multipartFile.getInputStream()).thenReturn(mock(InputStream.class));
S3Object s3Object = new S3Object();
when(amazonS3.putObject(any())).thenReturn(null);
when(amazonS3.getObject(anyString(), anyString())).thenReturn(s3Object);
String key = fileService.uploadFile(multipartFile);
assertEquals("/documents/testFile", key);
}
@Test
public void givenValidFile_whenUploadFailsDueToNoBucket_thenExceptionIsThrown() throws Exception {
when(multipartFile.getName()).thenReturn("testFile");
when(multipartFile.getOriginalFilename()).thenReturn("testFile");
when(multipartFile.getContentType()).thenReturn("application/pdf");
when(multipartFile.getSize()).thenReturn(1024L);
when(multipartFile.getInputStream()).thenReturn(mock(InputStream.class));
AmazonS3Exception exception = new AmazonS3Exception("Test exception");
exception.setErrorCode("NoSuchBucket");
when(amazonS3.putObject(any(PutObjectRequest.class))).thenThrow(exception);
assertThrows(Exception.class, () -> fileService.uploadFile(multipartFile));
}
@Test
public void givenExistingFile_whenUpdated_thenSameKeyIsReturned() throws Exception {
when(multipartFile.getName()).thenReturn("testFile");
when(multipartFile.getContentType()).thenReturn("application/pdf");
when(multipartFile.getSize()).thenReturn(1024L);
when(multipartFile.getInputStream()).thenReturn(mock(InputStream.class));
S3Object s3Object = new S3Object();
when(amazonS3.putObject(any(PutObjectRequest.class))).thenReturn(null);
when(amazonS3.getObject(anyString(), anyString())).thenReturn(s3Object);
String key = "/documents/existingFile";
String resultKey = fileService.updateFile(multipartFile, key);
assertEquals(key, resultKey);
}
@Test
public void givenFileWithIOException_whenUpdated_thenExceptionIsThrown() throws Exception {
when(multipartFile.getName()).thenReturn("testFile");
when(multipartFile.getContentType()).thenReturn("application/pdf");
when(multipartFile.getSize()).thenReturn(1024L);
when(multipartFile.getInputStream()).thenThrow(new IOException("Test IO Exception"));
assertThrows(Exception.class, () -> fileService.updateFile(multipartFile, "/documents/existingFile"));
}
}

View File

@ -8,4 +8,5 @@ This module contains articles about Simple Storage Service (S3) on AWS
- [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)
- [Check if a Specified Key Exists in a Given S3 Bucket Using Java](https://www.baeldung.com/java-aws-s3-check-specified-key-exists)
- [Listing All AWS S3 Objects in a Bucket Using Java](https://www.baeldung.com/java-aws-s3-list-bucket-objects)
- [Listing All AWS S3 Objects in a Bucket Using Java](https://www.baeldung.com/java-aws-s3-list-bucket-objects)
- [Update an Existing Amazon S3 Object Using Java](https://www.baeldung.com/java-update-amazon-s3-object)

View File

@ -0,0 +1,79 @@
package com.baeldung.s3;
import java.util.List;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.CopyObjectRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
import software.amazon.awssdk.services.s3.model.S3Object;
public class RenameObjectService {
private S3Client s3Client;
public RenameObjectService(S3Client s3Client) {
this.s3Client = s3Client;
}
public RenameObjectService() {
init();
}
public void init() {
this.s3Client = S3Client.builder()
.region(Region.US_EAST_1)
.credentialsProvider(ProfileCredentialsProvider.create("default"))
.build();
}
public void renameFile(String bucketName, String keyName, String destinationKeyName) {
CopyObjectRequest copyObjRequest = CopyObjectRequest.builder()
.sourceBucket(bucketName)
.sourceKey(keyName)
.destinationBucket(destinationKeyName)
.destinationKey(bucketName)
.build();
s3Client.copyObject(copyObjRequest);
DeleteObjectRequest deleteRequest = DeleteObjectRequest.builder()
.bucket(bucketName)
.key(keyName)
.build();
s3Client.deleteObject(deleteRequest);
}
public void renameFolder(String bucketName, String sourceFolderKey, String destinationFolderKey) {
ListObjectsV2Request listRequest = ListObjectsV2Request.builder()
.bucket(bucketName)
.prefix(sourceFolderKey)
.build();
ListObjectsV2Response listResponse = s3Client.listObjectsV2(listRequest);
List<S3Object> objects = listResponse.contents();
for (S3Object s3Object : objects) {
String newKey = destinationFolderKey + s3Object.key()
.substring(sourceFolderKey.length());
// Copy object to destination folder
CopyObjectRequest copyRequest = CopyObjectRequest.builder()
.sourceBucket(bucketName)
.sourceKey(s3Object.key())
.destinationBucket(bucketName)
.destinationKey(newKey)
.build();
s3Client.copyObject(copyRequest);
// Delete object from source folder
DeleteObjectRequest deleteRequest = DeleteObjectRequest.builder()
.bucket(bucketName)
.key(s3Object.key())
.build();
s3Client.deleteObject(deleteRequest);
}
}
}

View File

@ -19,6 +19,7 @@
<module>aws-miscellaneous</module>
<module>aws-reactive</module>
<module>aws-s3</module>
<module>aws-s3-update-object</module>
</modules>
<properties>

View File

@ -9,3 +9,4 @@ This module contains articles about arrays conversion in Java
- [Converting a String Array Into an int Array in Java](https://www.baeldung.com/java-convert-string-array-to-int-array)
- [Convert Java Array to Iterable](https://www.baeldung.com/java-array-convert-to-iterable)
- [Converting an int[] to HashSet in Java](https://www.baeldung.com/java-converting-int-array-to-hashset)
- [Convert an ArrayList of String to a String Array in Java](https://www.baeldung.com/java-convert-string-arraylist-array)

View File

@ -20,5 +20,4 @@
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -13,3 +13,4 @@ This module contains articles about advanced operations on arrays in Java. They
- [Performance of System.arraycopy() vs. Arrays.copyOf()](https://www.baeldung.com/java-system-arraycopy-arrays-copyof-performance)
- [Slicing Arrays in Java](https://www.baeldung.com/java-slicing-arrays)
- [Combining Two or More Byte Arrays](https://www.baeldung.com/java-concatenate-byte-arrays)
- [Calculating the Sum of Two Arrays in Java](https://www.baeldung.com/java-sum-arrays-element-wise)

View File

@ -0,0 +1,14 @@
package com.baeldung.arraysums;
public class SumArraysUsingForEach {
public static int[] sumOfTwoArrays(int[] arr1, int[] arr2) {
int[] arr3 = new int[arr1.length];
int counter = 0;
for (int num1 : arr1) {
arr3[counter] = num1 + arr2[counter];
counter++;
}
return arr3;
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.arraysums;
public class SumArraysUsingForLoop {
public static int[] sumOfTwoArrays(int[] arr1, int[] arr2) {
int[] arr3 = new int[arr1.length];
for (int i = 0; i < arr1.length; i++) {
arr3[i] = arr1[i] + arr2[i];
}
return arr3;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.arraysums;
import java.util.Arrays;
import java.util.stream.IntStream;
public class SumArraysUsingStreams {
public static int[] sumOfTwoArrays(int[] arr1, int[] arr2) {
IntStream range = IntStream.range(0, Math.min(arr1.length, arr2.length));
IntStream stream3 = range.map(i -> arr1[i] + arr2[i]);
int[] arr3 = stream3.toArray();
return arr3;
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.arraysums;
import com.baeldung.arraysums.SumArraysUsingForEach;
import org.junit.Test;
import static org.junit.Assert.*;
public class SumArraysUsingForEachUnitTest {
@Test
public void sumOfTwoArraysUsingForEach_GivenTwoEqualSizedIntArrays_ReturnsCorrectSumArray() {
int[] arr1 = { 4, 5, 1, 6, 4, 15 };
int[] arr2 = { 3, 5, 6, 1, 9, 6 };
int[] expected = { 7, 10, 7, 7, 13, 21 };
assertArrayEquals(expected, SumArraysUsingForEach.sumOfTwoArrays(arr1, arr2));
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.arraysums;
import com.baeldung.arraysums.SumArraysUsingForLoop;
import org.junit.Test;
import static org.junit.Assert.*;
public class SumArraysUsingForLoopUnitTest {
@Test
public void sumOfTwoArrays_GivenTwoEqualSizedIntArrays_ReturnsCorrectSumArray() {
int[] arr1 = {4, 5, 1, 6, 4, 15};
int[] arr2 = {3, 5, 6, 1, 9, 6};
int[] expected = {7, 10, 7, 7, 13, 21};
assertArrayEquals(expected, SumArraysUsingForLoop.sumOfTwoArrays(arr1, arr2));
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.arraysums;
import com.baeldung.arraysums.SumArraysUsingStreams;
import org.junit.Test;
import static org.junit.Assert.*;
public class SumArraysUsingStreamsUnitTest {
@Test
public void sumOfTwoArraysUsingStreams_GivenTwoEqualSizedIntArrays_ReturnsCorrectSumArray() {
int[] arr1 = {4, 5, 1, 6, 4, 15};
int[] arr2 = {3, 5, 6, 1, 9, 6};
int[] expected = {7, 10, 7, 7, 13, 21};
assertArrayEquals(expected, SumArraysUsingStreams.sumOfTwoArrays(arr1, arr2));
}
}

View File

@ -12,4 +12,6 @@ This module contains articles about conversions among Collection types and array
- [Convert a List of Integers to a List of Strings](https://www.baeldung.com/java-convert-list-integers-to-list-strings)
- [Combining Two Lists Into a Map in Java](https://www.baeldung.com/java-combine-two-lists-into-map)
- [Convert a List of Strings to a List of Integers](https://www.baeldung.com/java-convert-list-strings-to-integers)
- [Convert List to Long[] Array in Java](https://www.baeldung.com/java-convert-list-object-to-long-array)
- [Get the First n Elements of a List Into an Array](https://www.baeldung.com/java-take-start-elements-list-array)
- More articles: [[<-- prev]](../core-java-collections-conversions)

View File

@ -43,6 +43,7 @@
<properties>
<vavr.version>0.10.3</vavr.version>
<java.version>11</java.version>
<modelmapper.version>3.1.1</modelmapper.version>
</properties>
</project>

View File

@ -0,0 +1,46 @@
package com.baeldung.arrayconversion;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.util.List;
import org.junit.jupiter.api.Test;
import com.google.common.collect.Lists;
public class ArrayListToArrayUnitTest {
private static final List<String> INPUT_LIST = Lists.newArrayList("Michael Bolton", "Michael Jackson", "Guns and Roses", "Bryan Adams", "Air Supply");
private static final String[] EXPECTED_ARRAY = new String[] { "Michael Bolton", "Michael Jackson", "Guns and Roses", "Bryan Adams", "Air Supply" };
@Test
void whenUsingForLoop_thenGetExpectedResult() {
String[] result = new String[INPUT_LIST.size()];
for (int i = 0; i < INPUT_LIST.size(); i++) {
result[i] = INPUT_LIST.get(i);
}
assertArrayEquals(EXPECTED_ARRAY, result);
}
@Test
void whenUsingListToArray_thenGetExpectedResult() {
String[] result = new String[INPUT_LIST.size()];
INPUT_LIST.toArray(result);
assertArrayEquals(EXPECTED_ARRAY, result);
String[] result2 = INPUT_LIST.toArray(new String[0]);
assertArrayEquals(EXPECTED_ARRAY, result2);
}
@Test
void whenUsingStreamApi_thenGetExpectedResult() {
String[] result = INPUT_LIST.stream()
.toArray(String[]::new);
assertArrayEquals(EXPECTED_ARRAY, result);
}
@Test
void whenUsingListToArrayInJava11_thenGetExpectedResult() {
String[] result = INPUT_LIST.toArray(String[]::new);
assertArrayEquals(EXPECTED_ARRAY, result);
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.arrayconversion;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.util.Iterator;
import java.util.List;
import org.junit.jupiter.api.Test;
import com.google.common.collect.Lists;
public class ListToArrayFirstNElementsUnitTest {
private static final List<String> INPUT_LIST = Lists.newArrayList("one", "two", "three", "four", "five", "six", "seven");
private static final int n = 5;
@Test
void whenUsingForLoop_thenGetExpectedArray() {
String[] result = new String[n];
for (int i = 0; i < n; i++) {
result[i] = INPUT_LIST.get(i);
}
assertArrayEquals(new String[] { "one", "two", "three", "four", "five" }, result);
String[] result2 = new String[n];
Iterator<String> iterator = INPUT_LIST.iterator();
for (int i = 0; i < n && iterator.hasNext(); i++) {
result2[i] = iterator.next();
}
assertArrayEquals(new String[] { "one", "two", "three", "four", "five" }, result2);
}
@Test
void whenUsingSubList_thenGetExpectedArray() {
String[] result = new String[n];
INPUT_LIST.subList(0, n)
.toArray(result);
assertArrayEquals(new String[] { "one", "two", "three", "four", "five" }, result);
String[] result2 = INPUT_LIST.subList(0, n)
.toArray(new String[0]);
assertArrayEquals(new String[] { "one", "two", "three", "four", "five" }, result2);
// available only for java 11+
String[] result3 = INPUT_LIST.subList(0, n)
.toArray(String[]::new);
assertArrayEquals(new String[] { "one", "two", "three", "four", "five" }, result3);
}
@Test
void whenUsingStream_thenGetExpectedArray() {
String[] result = INPUT_LIST.stream()
.limit(n)
.toArray(String[]::new);
assertArrayEquals(new String[] { "one", "two", "three", "four", "five" }, result);
}
}

View File

@ -9,4 +9,5 @@ This module contains articles about Map data structures in Java.
- [Collections.synchronizedMap vs. ConcurrentHashMap](https://www.baeldung.com/java-synchronizedmap-vs-concurrenthashmap)
- [Java HashMap Load Factor](https://www.baeldung.com/java-hashmap-load-factor)
- [Converting Java Properties to HashMap](https://www.baeldung.com/java-convert-properties-to-hashmap)
- [Get Values and Keys as ArrayList From a HashMap](https://www.baeldung.com/java-values-keys-arraylists-hashmap)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-2)

View File

@ -0,0 +1,72 @@
package com.baeldung.map.hashmap.kvtolist;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
public class MapKeysValuesToListUnitTest {
private static final HashMap<String, String> DEV_MAP;
static {
DEV_MAP = new HashMap<>();
DEV_MAP.put("Kent", "Linux");
DEV_MAP.put("Eric", "MacOS");
DEV_MAP.put("Kevin", "Windows");
DEV_MAP.put("Michal", "MacOS");
DEV_MAP.put("Saajan", "Linux");
}
@Test
void whenUsingKeySet_thenGetExpectedResult() {
List<String> keyList = new ArrayList<>(DEV_MAP.keySet());
// this assertion may fail, since hashMap doesn't preserve the insertion order
// assertEquals(Lists.newArrayList("Kent", "Eric", "Kevin", "Michal", "Saajan"), keyList);
assertThat(keyList).containsExactlyInAnyOrder("Kent", "Eric", "Kevin", "Michal", "Saajan");
}
@Test
void whenUsingValues_thenGetExpectedResult() {
List<String> valueList = new ArrayList<>(DEV_MAP.values());
assertThat(valueList).containsExactlyInAnyOrder("Linux", "MacOS", "Windows", "MacOS", "Linux");
}
@Test
void whenLoopingEntries_thenGetExpectedResult() {
List<String> keyList = new ArrayList<>();
List<String> valueList = new ArrayList<>();
for (Map.Entry<String, String> entry : DEV_MAP.entrySet()) {
keyList.add(entry.getKey());
valueList.add(entry.getValue());
}
assertKeyAndValueList(keyList, valueList);
}
@Test
void whenUsingForEach_thenGetExpectedResult() {
List<String> keyList = new ArrayList<>();
List<String> valueList = new ArrayList<>();
DEV_MAP.forEach((k, v) -> {
keyList.add(k);
valueList.add(v);
});
assertKeyAndValueList(keyList, valueList);
}
private void assertKeyAndValueList(List<String> keyList, List<String> valueList) {
assertThat(keyList).containsExactlyInAnyOrder("Kent", "Eric", "Kevin", "Michal", "Saajan");
assertThat(valueList).containsExactlyInAnyOrder("Linux", "MacOS", "Windows", "MacOS", "Linux");
for (int i = 0; i < keyList.size(); i++) {
assertThat(DEV_MAP).containsEntry(keyList.get(i), valueList.get(i));
}
}
}

View File

@ -8,3 +8,4 @@
- [How to Modify a Key in a HashMap?](https://www.baeldung.com/java-hashmap-modify-key)
- [Converting String or String Array to Map in Java](https://www.baeldung.com/java-convert-string-to-map)
- [Remove Duplicate Values From HashMap in Java](https://www.baeldung.com/java-hashmap-delete-duplicates)
- [Sorting Java Map in Descending Order](https://www.baeldung.com/java-sort-map-descending)

View File

@ -20,6 +20,17 @@
<version>${junit-platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>32.1.1-jre</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,75 @@
package com.baeldung.cartesianproduct;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.google.common.collect.Sets;
public class CartesianProduct {
public List<List<Object>> getCartesianProductIterative(List<List<Object>> sets) {
List<List<Object>> result = new ArrayList<>();
if(sets == null || sets.isEmpty()) {
return result;
}
int totalSets = sets.size();
int totalCombinations = 1 << totalSets;
for(int i = 0; i < totalCombinations; i++) {
List<Object> combination = new ArrayList<>();
for(int j = 0; j < totalSets; j++) {
if (((i >> j) & 1) == 1) {
combination.add(sets.get(j).get(0));
} else {
combination.add(sets.get(j).get(1));
}
}
result.add(combination);
}
return result;
}
public List<List<Object>> getCartesianProductRecursive(List<List<Object>> sets) {
List<List<Object>> result = new ArrayList<>();
getCartesianProductRecursiveHelper(sets, 0, new ArrayList<>(), result);
return result;
}
private void getCartesianProductRecursiveHelper(List<List<Object>> sets, int index, List<Object> current, List<List<Object>> result) {
if(index == sets.size()) {
result.add(new ArrayList<>(current));
return;
}
List<Object> currentSet = sets.get(index);
for(Object element: currentSet) {
current.add(element);
getCartesianProductRecursiveHelper(sets, index+1, current, result);
current.remove(current.size() - 1);
}
}
public List<List<Object>> getCartesianProductUsingStreams(List<List<Object>> sets) {
return cartesianProduct(sets,0).collect(Collectors.toList());
}
public Stream<List<Object>> cartesianProduct(List<List<Object>> sets, int index) {
if(index == sets.size()) {
List<Object> emptyList = new ArrayList<>();
return Stream.of(emptyList);
}
List<Object> currentSet = sets.get(index);
return currentSet.stream().flatMap(element -> cartesianProduct(sets, index+1)
.map(list -> {
List<Object> newList = new ArrayList<>(list);
newList.add(0, element); return newList;
}));
}
public List<List<Object>> getCartesianProductUsingGuava(List<Set<Object>> sets) {
Set<List<Object>> cartesianProduct = Sets.cartesianProduct(sets);
List<List<Object>> cartesianList = new ArrayList<>(cartesianProduct);
return cartesianList;
}
}

View File

@ -0,0 +1,93 @@
package com.baeldung.cartesianproduct;
import static org.testng.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.testng.annotations.Test;
public class CartesianProductUnitTest {
private CartesianProduct cp = new CartesianProduct();
List<List<Object>> sets = Arrays.asList(
Arrays.asList(10, 20),
Arrays.asList("John", "Jack"),
Arrays.asList('I', 'J')
);
@Test
public void whenUsingStreams_thenCalculateCartesianProduct() {
List<List<Object>> expected = Arrays.asList(
Arrays.asList(10, "John", 'I'),
Arrays.asList(10, "John", 'J'),
Arrays.asList(10, "Jack", 'I'),
Arrays.asList(10, "Jack", 'J'),
Arrays.asList(20, "John", 'I'),
Arrays.asList(20, "John", 'J'),
Arrays.asList(20, "Jack", 'I'),
Arrays.asList(20, "Jack", 'J')
);
List<List<Object>> cartesianProduct = cp.getCartesianProductUsingStreams(sets);
assertEquals(expected, cartesianProduct);
}
@Test
public void whenUsingRecursion_thenCalculateCartesianProduct() {
List<List<Object>> expected = Arrays.asList(
Arrays.asList(10, "John", 'I'),
Arrays.asList(10, "John", 'J'),
Arrays.asList(10, "Jack", 'I'),
Arrays.asList(10, "Jack", 'J'),
Arrays.asList(20, "John", 'I'),
Arrays.asList(20, "John", 'J'),
Arrays.asList(20, "Jack", 'I'),
Arrays.asList(20, "Jack", 'J')
);
List<List<Object>> cartesianProduct = cp.getCartesianProductRecursive(sets);
assertEquals(expected, cartesianProduct);
}
@Test
public void whenUsingIterativeApproach_thenCalculateCartesianProduct() {
List<List<Object>> expected = Arrays.asList(
Arrays.asList(20, "Jack", 'J'),
Arrays.asList(10, "Jack", 'J'),
Arrays.asList(20, "John", 'J'),
Arrays.asList(10, "John", 'J'),
Arrays.asList(20, "Jack", 'I'),
Arrays.asList(10, "Jack", 'I'),
Arrays.asList(20, "John", 'I'),
Arrays.asList(10, "John", 'I')
);
List<List<Object>> cartesianProduct = cp.getCartesianProductIterative(sets);
assertEquals(expected, cartesianProduct);
}
@Test
public void whenUsingGuava_thenCalculateCartesianProduct() {
List<Set<Object>> sets = new ArrayList<>();
sets.add(new HashSet<>(Arrays.asList(10, 20)));
sets.add(new HashSet<>(Arrays.asList("John", "Jack")));
sets.add(new HashSet<>(Arrays.asList('I', 'J')));
List<List<Object>> expected = Arrays.asList(
Arrays.asList(20, "John", 'I'),
Arrays.asList(20, "John", 'J'),
Arrays.asList(20, "Jack", 'I'),
Arrays.asList(20, "Jack", 'J'),
Arrays.asList(10, "John", 'I'),
Arrays.asList(10, "John", 'J'),
Arrays.asList(10, "Jack", 'I'),
Arrays.asList(10, "Jack", 'J')
);
List<List<Object>> cartesianProduct = cp.getCartesianProductUsingGuava(sets);
assertEquals(expected, cartesianProduct);
}
}

View File

@ -7,31 +7,37 @@ import java.util.concurrent.Phaser;
class LongRunningAction implements Runnable {
private static Logger log = LoggerFactory.getLogger(LongRunningAction.class);
private String threadName;
private Phaser ph;
private static final Logger log = LoggerFactory.getLogger(LongRunningAction.class);
private final String threadName;
private final Phaser ph;
LongRunningAction(String threadName, Phaser ph) {
this.threadName = threadName;
this.ph = ph;
this.randomWait();
ph.register();
log.info("Thread {} registered during phase {}", threadName, ph.getPhase());
}
@Override
public void run() {
log.info("This is phase {}", ph.getPhase());
log.info("Thread {} before long running action", threadName);
log.info("Thread {} BEFORE long running action in phase {}", threadName, ph.getPhase());
ph.arriveAndAwaitAdvance();
randomWait();
log.info("Thread {} AFTER long running action in phase {}", threadName, ph.getPhase());
ph.arriveAndDeregister();
}
// Simulating real work
private void randomWait() {
try {
Thread.sleep(2000);
Thread.sleep((long) (Math.random() * 100));
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("Thread {} action completed and waiting for others", threadName);
ph.arriveAndAwaitAdvance();
log.debug("Thread {} proceeding in phase {}", threadName, ph.getPhase());
ph.arriveAndDeregister();
}
}

View File

@ -7,8 +7,6 @@ import org.junit.runners.MethodSorters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Phaser;
import static junit.framework.TestCase.assertEquals;
@ -16,38 +14,32 @@ import static junit.framework.TestCase.assertEquals;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class PhaserUnitTest {
private static Logger log = LoggerFactory.getLogger(PhaserUnitTest.class);
private static final Logger log = LoggerFactory.getLogger(PhaserUnitTest.class);
@Test
public void givenPhaser_whenCoordinateWorksBetweenThreads_thenShouldCoordinateBetweenMultiplePhases() {
//given
ExecutorService executorService = Executors.newCachedThreadPool();
public void givenPhaser_whenCoordinateWorksBetweenThreads_thenShouldCoordinateBetweenMultiplePhases() throws InterruptedException {
Phaser ph = new Phaser(1);
assertEquals(0, ph.getPhase());
//when
executorService.submit(new LongRunningAction("thread-1", ph));
executorService.submit(new LongRunningAction("thread-2", ph));
executorService.submit(new LongRunningAction("thread-3", ph));
new Thread(new LongRunningAction("thread-1", ph)).start();
new Thread(new LongRunningAction("thread-2", ph)).start();
new Thread(new LongRunningAction("thread-3", ph)).start();
//then
log.debug("Thread {} waiting for others", Thread.currentThread().getName());
log.info("Thread {} waiting for others", Thread.currentThread().getName());
ph.arriveAndAwaitAdvance();
log.debug("Thread {} proceeding in phase {}", Thread.currentThread().getName(), ph.getPhase());
log.info("Thread {} proceeding in phase {}", Thread.currentThread().getName(), ph.getPhase());
assertEquals(1, ph.getPhase());
//and
executorService.submit(new LongRunningAction("thread-4", ph));
executorService.submit(new LongRunningAction("thread-5", ph));
new Thread(new LongRunningAction("thread-4", ph)).start();
new Thread(new LongRunningAction("thread-5", ph)).start();
log.debug("Thread {} waiting for others", Thread.currentThread().getName());
log.info("Thread {} waiting for new phase", Thread.currentThread().getName());
ph.arriveAndAwaitAdvance();
log.debug("Thread {} proceeding in phase {}", Thread.currentThread().getName(), ph.getPhase());
log.info("Thread {} proceeding in phase {}", Thread.currentThread().getName(), ph.getPhase());
assertEquals(2, ph.getPhase());
ph.arriveAndDeregister();
Thread.sleep(1000);
assertEquals(true, ph.isTerminated());
}
}

View File

@ -3,3 +3,4 @@
This module contains articles about Java Conditionals.
### Relevant articles:
- [Guide to the yield Keyword in Java](https://www.baeldung.com/java-yield-switch)

View File

@ -8,3 +8,5 @@ This module contains articles about converting between Java date and time object
- [Convert Date to LocalDate or LocalDateTime and Back](http://www.baeldung.com/java-date-to-localdate-and-localdatetime)
- [Convert Between java.time.Instant and java.sql.Timestamp](https://www.baeldung.com/java-time-instant-to-java-sql-timestamp)
- [Convert Between LocalDateTime and ZonedDateTime](https://www.baeldung.com/java-localdatetime-zoneddatetime)
- [Conversion From 12-Hour Time to 24-Hour Time in Java](https://www.baeldung.com/java-convert-time-format)
- [Convert Epoch Time to LocalDate and LocalDateTime](https://www.baeldung.com/java-convert-epoch-localdate)

View File

@ -0,0 +1,30 @@
package com.baeldung.twelvehourstotwentyhours;
import static org.junit.jupiter.api.Assertions.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;
import org.junit.jupiter.api.Test;
public class TimeConversionUnitTest {
@Test
public void givenTimeInTwelveHours_whenConvertingToTwentyHours_thenConverted() throws ParseException {
SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a");
Date date = parseFormat.parse("06:00 PM");
assertEquals("18:00", displayFormat.format(date));
}
@Test
public void givenTimeInTwelveHours_whenConvertingToTwentyHoursWithDateTimeFormatter_thenConverted() throws ParseException {
String time = LocalTime.parse("06:00 PM", DateTimeFormatter.ofPattern("hh:mm a", Locale.US))
.format(DateTimeFormatter.ofPattern("HH:mm"));
assertEquals("18:00", time);
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.socketexception;
import java.io.IOException;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
public class SslServer {
public static void createSSLSocketWithEnabledProtocols(SSLServerSocketFactory socketFactory, int port, String[] enabledProtocols) {
SSLServerSocket serverSocket = null;
try {
serverSocket = (SSLServerSocket) socketFactory.createServerSocket(port);
// Set the enabled protocols
serverSocket.setEnabledProtocols(enabledProtocols);
System.out.println("Server is running on port " + port);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

View File

@ -1,25 +1,33 @@
package com.baeldung.socketexception;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.net.SocketException;
import java.util.concurrent.Executors;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import org.junit.BeforeClass;
import org.junit.Test;
public class SocketExceptionHandlingUnitTest {
private static final int PORT = 6699;
@BeforeClass
public static void runServer() throws IOException, InterruptedException {
Executors.newSingleThreadExecutor()
.submit(() -> new SocketServer().start(6699));
.submit(() -> new SocketServer().start(PORT));
Thread.sleep(100);
}
@Test
public void givenRunningServer_whenConnectToClosedSocket_thenHandleException() throws IOException {
SocketClient client = new SocketClient();
client.startConnection("127.0.0.1", 6699);
client.startConnection("127.0.0.1", PORT);
try {
client.sendMessage("hi");
client.sendMessage("hi again");
@ -28,4 +36,22 @@ public class SocketExceptionHandlingUnitTest {
}
}
@Test
public void givenRunningServer_whenConnectToSocket_thenHandleConnectionResetException() throws IOException {
// Enable multiple SSL/TLS protocols
String[] enabledProtocols = { "TLSv1.2", "TLSv1.3", "TLSv1.1", "TLSv1", "SSLv3", "SSLv3" };
SSLServerSocketFactory mockFactory = mock(SSLServerSocketFactory.class);
SSLServerSocket mockServerSocket = mock(SSLServerSocket.class);
// Set up the mock factory to return the mock server socket
when(mockFactory.createServerSocket(PORT)).thenReturn(mockServerSocket);
// Call the method being tested
SslServer.createSSLSocketWithEnabledProtocols(mockFactory, PORT, enabledProtocols);
// Verify that setEnabledProtocols and close were called
verify(mockServerSocket).setEnabledProtocols(enabledProtocols);
verify(mockServerSocket).close();
}
}

View File

@ -38,9 +38,9 @@
<version>${fscontext.version}</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1</version>
<groupId>org.eclipse.angus</groupId>
<artifactId>angus-activation</artifactId>
<version>${angus-activation.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
@ -73,10 +73,6 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${maven-javadoc-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<!-- Build an executable JAR -->
@ -131,13 +127,15 @@
<properties>
<!-- maven plugins -->
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<hsqldb.version>2.4.0</hsqldb.version>
<maven-javadoc-plugin.version>3.5.0</maven-javadoc-plugin.version>
<hsqldb.version>2.7.1</hsqldb.version>
<!-- Mime Type Libraries -->
<tika.version>1.18</tika.version>
<tika.version>2.8.0</tika.version>
<jmime-magic.version>0.1.5</jmime-magic.version>
<maven-jar-plugin.version>3.1.0</maven-jar-plugin.version>
<maven-jar-plugin.version>3.3.0</maven-jar-plugin.version>
<fscontext.version>4.4.2</fscontext.version>
<jakarta-activation-api.version>2.1.2</jakarta-activation-api.version>
<angus-activation.version>2.0.1</angus-activation.version>
</properties>
</project>

View File

@ -10,7 +10,7 @@ import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.activation.MimetypesFileTypeMap;
import jakarta.activation.MimetypesFileTypeMap;
import org.apache.tika.Tika;
import org.junit.Test;

View File

@ -3,10 +3,14 @@ package com.baeldung.jar;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import java.util.regex.Pattern;
public class JarAppUnitTest {
@Test
public void findClassTest(){
Assert.assertTrue(JarApp.findObjectMapperClass().endsWith("jackson-databind-2.13.3.jar"));
Pattern databindPattern = Pattern.compile(".*jackson-databind-(\\d)+\\.(\\d)+\\.(\\d)\\.jar$");
Assert.assertTrue(databindPattern.matcher(JarApp.findObjectMapperClass()).matches());
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.randominset;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
public class RandomInSetUtil {
public static <T> T getByRandomClass(Set<T> set) {
if (set == null || set.isEmpty()) {
throw new IllegalArgumentException("The Set cannot be empty.");
}
int randomIndex = new Random().nextInt(set.size());
int i = 0;
for (T element : set) {
if (i == randomIndex) {
return element;
}
i++;
}
throw new IllegalStateException("Something went wrong while picking a random element.");
}
public static <T> T getByThreadLocalRandom(Set<T> set) {
if (set == null || set.isEmpty()) {
throw new IllegalArgumentException("The Set cannot be empty.");
}
int randomIndex = ThreadLocalRandom.current().nextInt(set.size());
int i = 0;
for (T element : set) {
if (i == randomIndex) {
return element;
}
i++;
}
throw new IllegalStateException("Something went wrong while picking a random element.");
}
public static void main(String[] args) {
Set<String> animals = new HashSet<>();
animals.add("Lion");
animals.add("Elephant");
animals.add("Giraffe");
String randomAnimal = getByThreadLocalRandom(animals);
System.out.println("Randomly picked animal: " + randomAnimal);
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.leetcode.magicsquare;
package com.baeldung.magicsquare;
import org.junit.platform.commons.util.StringUtils;
@ -172,7 +172,9 @@ public class MagicSquare {
int value = getCell(x, y);
if (value == 0) {
sb.append(" ");
sb.append(".".repeat(largestNumberLength));
for (int i = 0; i < largestNumberLength; ++i) {
sb.append(".");
}
sb.append(" ");
} else {
sb.append(String.format(formatString, value));

View File

@ -0,0 +1,2 @@
## Relevant Articles
- [Creating a Magic Square in Java](https://www.baeldung.com/java-magic-square)

View File

@ -9,3 +9,4 @@ This module contains articles about generics in Java
- [Super Type Tokens in Java Generics](https://www.baeldung.com/java-super-type-tokens)
- [Java Warning “unchecked conversion”](https://www.baeldung.com/java-unchecked-conversion)
- [Java Warning “Unchecked Cast”](https://www.baeldung.com/java-warning-unchecked-cast)
- [What Does the Holder<T> Class Do in Java?](https://www.baeldung.com/java-holder-class)

View File

@ -12,3 +12,4 @@ This module contains articles about inheritance in Java
- [Guide to Inheritance in Java](https://www.baeldung.com/java-inheritance)
- [Object Type Casting in Java](https://www.baeldung.com/java-type-casting)
- [Variable and Method Hiding in Java](https://www.baeldung.com/java-variable-method-hiding)
- [Inner Classes Vs. Subclasses in Java](https://www.baeldung.com/java-inner-classes-vs-subclasses)

View File

@ -0,0 +1,22 @@
package com.baeldung.subclassinnerclass;
public class EmailNotifier extends Notifier {
@Override
void notify(Message e) {
// connect to the email connector
EmailConnector emailConnector = new EmailConnector();
emailConnector.connect();
// send email
}
// Inner class for email connection
static class EmailConnector {
private String emailHost;
private int emailPort;
// Getter Setters
private void connect() {
// connect to the smtp server
}
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.subclassinnerclass;
public class Message {
private int message;
// getter setter and other atteibutes
}

View File

@ -0,0 +1,17 @@
package com.baeldung.subclassinnerclass;
public class NotificationService {
void notifyMessages() {
// Sending a Text Message
Message textMessage = new Message();
Notifier textNotifier = new TextMessageNotifier();
textNotifier.notify(textMessage);
// Sending an Email Message
Message emailMessage = new Message();
Notifier emailNotifier = new EmailNotifier();
emailNotifier.notify(emailMessage);
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.subclassinnerclass;
public abstract class Notifier {
abstract void notify(Message e);
}

View File

@ -0,0 +1,14 @@
package com.baeldung.subclassinnerclass;
public class TextMessageNotifier extends Notifier {
@Override
void notify(Message e) {
// Provide text message specific implementation here
}
// Inner class for text message connection
private static class SMSConnector {
private String smsHost;
// Getter Setters
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.subclassinnerclass;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import org.junit.Test;
public class InnerClassUnitTest {
@Test
public void givenInnerStaticClassWhenInstantiatedThenOuterClassIsInstantiated() {
Notifier emailNotifier = new EmailNotifier();
EmailNotifier.EmailConnector emailConnector = new EmailNotifier.EmailConnector();
assertThat(emailNotifier).hasSameClassAs(new EmailNotifier());
assertThat(emailConnector).isInstanceOf(EmailNotifier.EmailConnector.class);
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.subclassinnerclass;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import org.junit.Test;
public class SubClassUnitTest {
@Test
public void givenSubclassWhenInstantiatedThenSubclassObjectIsPossible() {
Notifier emailNotifier = new EmailNotifier();
assertThat(emailNotifier).hasSameClassAs(new EmailNotifier());
assertThat(emailNotifier).isExactlyInstanceOf(EmailNotifier.class);
Notifier textMessageNotifier = new TextMessageNotifier();
assertThat(textMessageNotifier).isInstanceOf(Notifier.class);
assertThat(textMessageNotifier).isExactlyInstanceOf(TextMessageNotifier.class);
}
}

View File

@ -1,6 +1,7 @@
package com.baeldung.deepcopyarraylist;
import java.io.Serializable;
import java.util.Objects;
public class Course implements Serializable, Cloneable {
@ -39,4 +40,23 @@ public class Course implements Serializable, Cloneable {
throw new IllegalStateException(e);
}
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Course that = (Course) o;
return Objects.equals(courseId,that.courseId)
&& Objects.equals(courseName,that.courseName);
}
@Override
public int hashCode() {
return Objects.hash(courseId,courseName);
}
}

View File

@ -2,6 +2,7 @@ package com.baeldung.deepcopyarraylist;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.apache.commons.lang3.SerializationUtils;
@ -100,4 +101,23 @@ public class Student implements Serializable, Cloneable {
student.course = this.course.clone();
return student;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Student that = (Student) o;
return Objects.equals(studentId,that.studentId) &&
Objects.equals(studentName, that.studentName) &&
Objects.equals(course, that.course);
}
@Override
public int hashCode() {
return Objects.hash(studentId,studentName,course);
}
}

View File

@ -19,8 +19,10 @@ public class DeepCopyArrayListUnitTest {
List<Student> deepCopy = Student.deepCopyUsingCloneable(students);
Assertions.assertNotEquals(students.get(0), deepCopy.get(0));
Assertions.assertNotEquals(students.get(1), deepCopy.get(1));
Assertions.assertEquals(students.get(0), deepCopy.get(0));
Assertions.assertNotSame(students.get(0),deepCopy.get(0));
Assertions.assertEquals(students.get(1), deepCopy.get(1));
Assertions.assertNotSame(students.get(1),deepCopy.get(1));
}
@ -37,8 +39,10 @@ public class DeepCopyArrayListUnitTest {
List<Student> deepCopy = Student.deepCopyUsingCopyConstructor(students);
Assertions.assertNotEquals(students.get(0), deepCopy.get(0));
Assertions.assertNotEquals(students.get(1), deepCopy.get(1));
Assertions.assertEquals(students.get(0), deepCopy.get(0));
Assertions.assertNotSame(students.get(0),deepCopy.get(0));
Assertions.assertEquals(students.get(1), deepCopy.get(1));
Assertions.assertNotSame(students.get(1),deepCopy.get(1));
}
@Test
@ -54,8 +58,10 @@ public class DeepCopyArrayListUnitTest {
List<Student> deepCopy = Student.deepCopyUsingSerialization(students);
Assertions.assertNotEquals(students.get(0), deepCopy.get(0));
Assertions.assertNotEquals(students.get(1), deepCopy.get(1));
Assertions.assertEquals(students.get(0), deepCopy.get(0));
Assertions.assertNotSame(students.get(0),deepCopy.get(0));
Assertions.assertEquals(students.get(1), deepCopy.get(1));
Assertions.assertNotSame(students.get(1),deepCopy.get(1));
}
@Test
@ -71,7 +77,9 @@ public class DeepCopyArrayListUnitTest {
List<Student> deepCopy = Student.deepCopyUsingJackson(students);
Assertions.assertNotEquals(students.get(0), deepCopy.get(0));
Assertions.assertNotEquals(students.get(1), deepCopy.get(1));
Assertions.assertEquals(students.get(0), deepCopy.get(0));
Assertions.assertNotSame(students.get(0),deepCopy.get(0));
Assertions.assertEquals(students.get(1), deepCopy.get(1));
Assertions.assertNotSame(students.get(1),deepCopy.get(1));
}
}

View File

@ -27,7 +27,7 @@
</dependencies>
<properties>
<commons-codec.version>1.15</commons-codec.version>
<commons-codec.version>1.16.0</commons-codec.version>
</properties>
</project>

View File

@ -1,54 +1,77 @@
package com.baeldung.modulo;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import static org.assertj.core.api.Java6Assertions.*;
public class ModuloUnitTest {
@Test
public void whenIntegerDivision_thenLosesRemainder(){
assertThat(11 / 4).isEqualTo(2);
}
@Test
public void whenDoubleDivision_thenKeepsRemainder(){
assertThat(11 / 4.0).isEqualTo(2.75);
}
@Test
public void whenModulo_thenReturnsRemainder(){
assertThat(11 % 4).isEqualTo(3);
}
@Test(expected = ArithmeticException.class)
public void whenDivisionByZero_thenArithmeticException(){
double result = 1 / 0;
}
@Test(expected = ArithmeticException.class)
public void whenModuloByZero_thenArithmeticException(){
double result = 1 % 0;
}
@Test
public void whenDivisorIsOddAndModulusIs2_thenResultIs1(){
assertThat(3 % 2).isEqualTo(1);
}
@Test
public void whenDivisorIsEvenAndModulusIs2_thenResultIs0(){
assertThat(4 % 2).isEqualTo(0);
}
@Test
public void whenItemsIsAddedToCircularQueue_thenNoArrayIndexOutOfBounds(){
int QUEUE_CAPACITY= 10;
int[] circularQueue = new int[QUEUE_CAPACITY];
int itemsInserted = 0;
for (int value = 0; value < 1000; value++) {
int writeIndex = ++itemsInserted % QUEUE_CAPACITY;
circularQueue[writeIndex] = value;
@Test
public void whenIntegerDivision_thenLosesRemainder() {
assertThat(11 / 4).isEqualTo(2);
}
@Test
public void whenDoubleDivision_thenKeepsRemainder() {
assertThat(11 / 4.0).isEqualTo(2.75);
}
@Test
public void whenModulo_thenReturnsRemainder() {
assertThat(11 % 4).isEqualTo(3);
}
@Test(expected = ArithmeticException.class)
public void whenDivisionByZero_thenArithmeticException() {
double result = 1 / 0;
}
@Test(expected = ArithmeticException.class)
public void whenModuloByZero_thenArithmeticException() {
double result = 1 % 0;
}
@Test
public void whenDivisorIsOddAndModulusIs2_thenResultIs1() {
assertThat(3 % 2).isEqualTo(1);
}
@Test
public void whenDivisorIsEvenAndModulusIs2_thenResultIs0() {
assertThat(4 % 2).isEqualTo(0);
}
@Test
public void whenDividendIsNegativeAndModulusIs2_thenResultIsNegative() {
assertEquals(-1, -9 % 2);
}
@Test
public void whenDividendIsNegativeAndRemainderIsCheckedForNegativeValue_thenResultIsPositive() {
int remainder = -9 % 2;
if (remainder < 0) {
remainder += 2;
}
assertEquals(1, remainder);
}
@Test
public void whenDividendIsNegativeAndUsesMathClass_thenResultIsPositive() {
int remainder = Math.floorMod(-9, 2);
assertEquals(1, remainder);
}
@Test
public void whenItemsIsAddedToCircularQueue_thenNoArrayIndexOutOfBounds() {
int QUEUE_CAPACITY = 10;
int[] circularQueue = new int[QUEUE_CAPACITY];
int itemsInserted = 0;
for (int value = 0; value < 1000; value++) {
int writeIndex = ++itemsInserted % QUEUE_CAPACITY;
circularQueue[writeIndex] = value;
}
}
}
}

View File

@ -30,13 +30,13 @@ public class Java8ComparatorUnitTest {
System.out.println("************** Java 8 Comaparator **************");
Comparator<Player> byRanking = (Player player1, Player player2) -> Integer.compare(player1.getRanking(), player2.getRanking());
System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam, byRanking);
System.out.println("After Sorting : " + footballTeam);
assertEquals(footballTeam.get(0)
.getName(), "Steven");
assertEquals(footballTeam.get(2)
.getRanking(), 67);
assertEquals(footballTeam.get(0).getName(), "Steven");
assertEquals(footballTeam.get(0).getRanking(), 45);
assertEquals(footballTeam.get(1).getName(), "John");
assertEquals(footballTeam.get(1).getRanking(), 59);
assertEquals(footballTeam.get(2).getName(), "Roger");
assertEquals(footballTeam.get(2).getRanking(), 67);
}
@Test
@ -45,24 +45,24 @@ public class Java8ComparatorUnitTest {
System.out.println("********* byRanking *********");
Comparator<Player> byRanking = Comparator.comparing(Player::getRanking);
System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam, byRanking);
System.out.println("After Sorting : " + footballTeam);
assertEquals(footballTeam.get(0)
.getName(), "Steven");
assertEquals(footballTeam.get(2)
.getRanking(), 67);
assertEquals(footballTeam.get(0).getName(), "Steven");
assertEquals(footballTeam.get(0).getRanking(), 45);
assertEquals(footballTeam.get(1).getName(), "John");
assertEquals(footballTeam.get(1).getRanking(), 59);
assertEquals(footballTeam.get(2).getName(), "Roger");
assertEquals(footballTeam.get(2).getRanking(), 67);
System.out.println("********* byAge *********");
Comparator<Player> byAge = Comparator.comparing(Player::getAge);
System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam, byAge);
System.out.println("After Sorting : " + footballTeam);
assertEquals(footballTeam.get(0)
.getName(), "Roger");
assertEquals(footballTeam.get(2)
.getRanking(), 45);
assertEquals(footballTeam.get(0).getName(), "Roger");
assertEquals(footballTeam.get(0).getAge(), 20);
assertEquals(footballTeam.get(1).getName(), "John");
assertEquals(footballTeam.get(1).getAge(), 22);
assertEquals(footballTeam.get(2).getName(), "Steven");
assertEquals(footballTeam.get(2).getAge(), 24);
}
}

View File

@ -1,39 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-leetcode</artifactId>
<name>core-java-leetcode</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<dependencies>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source.version>11</maven.compiler.source.version>
<maven.compiler.target.version>11</maven.compiler.target.version>
</properties>
</project>

View File

@ -0,0 +1,98 @@
package com.baeldung.regex.squarebrackets;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Test;
import com.google.common.collect.Lists;
public class ExtractTextBetweenSquareBracketsUnitTest {
static final String INPUT1 = "some text [THE IMPORTANT MESSAGE] something else";
static final String EXPECTED1 = "THE IMPORTANT MESSAGE";
static final String INPUT2 = "[La La Land], [The last Emperor], and [Life of Pi] are all great movies.";
static final List<String> EXPECTED2 = Lists.newArrayList("La La Land", "The last Emperor", "Life of Pi");
@Test
void whenUsingDotStarOnInput1_thenGetExpectedResult() {
String result = null;
String rePattern = "\\[(.*)]";
Pattern p = Pattern.compile(rePattern);
Matcher m = p.matcher(INPUT1);
if (m.find()) {
result = m.group(1);
}
assertThat(result).isEqualTo(EXPECTED1);
}
@Test
void whenUsingCharClassOnInput1_thenGetExpectedResult() {
String result = null;
String rePattern = "\\[([^]]*)";
Pattern p = Pattern.compile(rePattern);
Matcher m = p.matcher(INPUT1);
if (m.find()) {
result = m.group(1);
}
assertThat(result).isEqualTo(EXPECTED1);
}
@Test
void whenUsingSplitOnInput1_thenGetExpectedResult() {
String[] strArray = INPUT1.split("[\\[\\]]", -1);
String result = strArray.length == 3 ? strArray[1] : null;
assertThat(result).isEqualTo(EXPECTED1);
}
@Test
void whenUsingSplitWithLimit_thenGetExpectedResult() {
String[] strArray = "[THE IMPORTANT MESSAGE]".split("[\\[\\]]");
assertThat(strArray).hasSize(2)
.containsExactly("", "THE IMPORTANT MESSAGE");
strArray = "[THE IMPORTANT MESSAGE]".split("[\\[\\]]", -1);
assertThat(strArray).hasSize(3)
.containsExactly("", "THE IMPORTANT MESSAGE", "");
}
@Test
void whenUsingNonGreedyOnInput2_thenGetExpectedResult() {
List<String> result = new ArrayList<>();
String rePattern = "\\[(.*?)]";
Pattern p = Pattern.compile(rePattern);
Matcher m = p.matcher(INPUT2);
while (m.find()) {
result.add(m.group(1));
}
assertThat(result).isEqualTo(EXPECTED2);
}
@Test
void whenUsingCharClassOnInput2_thenGetExpectedResult() {
List<String> result = new ArrayList<>();
String rePattern = "\\[([^]]*)";
Pattern p = Pattern.compile(rePattern);
Matcher m = p.matcher(INPUT2);
while (m.find()) {
result.add(m.group(1));
}
assertThat(result).isEqualTo(EXPECTED2);
}
@Test
void whenUsingSplitInput2_thenGetExpectedResult() {
List<String> result = new ArrayList<>();
String[] strArray = INPUT2.split("[\\[\\]]", -1);
for (int i = 1; i < strArray.length; i += 2) {
result.add(strArray[i]);
}
assertThat(result).isEqualTo(EXPECTED2);
}
}

View File

@ -28,9 +28,6 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.jupiter.api.Disabled;
@Disabled //fixing in https://team.baeldung.com/browse/JAVA-23897
public class CertificatesUnitTest {
private static final String GODADDY_CA_ALIAS = "godaddyrootg2ca [jdk]";

View File

@ -33,7 +33,7 @@
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${google-guava.version}</version>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
@ -47,7 +47,6 @@
<commons-codec.version>1.15</commons-codec.version>
<jaxb-api.version>2.3.1</jaxb-api.version>
<spring-security-crypto.version>6.0.3</spring-security-crypto.version>
<google-guava.version>31.0.1-jre</google-guava.version>
</properties>
</project>

View File

@ -13,28 +13,4 @@
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>${bouncycastle.version}</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>${jaxb-api.version}</version>
</dependency>
</dependencies>
<properties>
<bouncycastle.version>1.60</bouncycastle.version>
<commons-codec.version>1.11</commons-codec.version>
<jaxb-api.version>2.3.1</jaxb-api.version>
</properties>
</project>

View File

@ -39,7 +39,7 @@
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.23.1</version>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -55,7 +55,7 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
<version>${commons-lang3.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -81,7 +81,7 @@
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${google.guava.version}</version>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>com.oath.cyclops</groupId>
@ -114,6 +114,7 @@
<properties>
<!-- testing -->
<assertj.version>3.23.1</assertj.version>
<maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>
<maven.compiler.source>12</maven.compiler.source>
<maven.compiler.target>12</maven.compiler.target>
@ -123,7 +124,6 @@
<io.varv.version>1.0.0-alpha-4</io.varv.version>
<io.reactor3.version>3.5.1</io.reactor3.version>
<apache.commons.collection4.version>4.4</apache.commons.collection4.version>
<google.guava.version>31.1-jre</google.guava.version>
<cyclops.version>10.4.1</cyclops.version>
</properties>

View File

@ -14,33 +14,6 @@
</parent>
<dependencies>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.codepoetics</groupId>
<artifactId>protonpack</artifactId>
@ -57,17 +30,7 @@
<version>${streamex.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${asspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${asspectj.version}</version>
</dependency>
<dependency>
<groupId>pl.touk</groupId>
<groupId>com.pivovarit</groupId>
<artifactId>throwing-function</artifactId>
<version>${throwing-function.version}</version>
</dependency>
@ -96,15 +59,13 @@
</build>
<properties>
<vavr.version>0.9.0</vavr.version>
<protonpack.version>1.15</protonpack.version>
<streamex.version>0.6.5</streamex.version>
<joda.version>2.10</joda.version>
<throwing-function.version>1.3</throwing-function.version>
<asspectj.version>1.8.9</asspectj.version>
<maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<vavr.version>0.10.4</vavr.version>
<protonpack.version>1.16</protonpack.version>
<streamex.version>0.8.1</streamex.version>
<throwing-function.version>1.5.1</throwing-function.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
</project>

View File

@ -1,8 +1,8 @@
package com.baeldung.stream.filter;
import org.junit.jupiter.api.Test;
import pl.touk.throwing.ThrowingPredicate;
import pl.touk.throwing.exception.WrappedException;
import com.pivovarit.function.ThrowingPredicate;
import com.pivovarit.function.exception.WrappedException;
import java.io.IOException;
import java.util.Arrays;
@ -156,5 +156,4 @@ public class StreamFilterUnitTest {
})
.collect(Collectors.toList())).isInstanceOf(RuntimeException.class);
}
}
}

View File

@ -22,7 +22,7 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons.lang3.version}</version>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>com.ibm.icu</groupId>
@ -42,8 +42,6 @@
</build>
<properties>
<commons.lang3.version>3.12.0</commons.lang3.version>
<guava.version>31.1-jre</guava.version>
<icu4j.version>61.1</icu4j.version>
</properties>

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