Merge remote-tracking branch 'upstream/master'

This commit is contained in:
mcasari
2023-09-17 21:05:23 +02:00
501 changed files with 8727 additions and 3175 deletions
@@ -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;
@@ -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);
}
}
@@ -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)
-7
View File
@@ -1,7 +0,0 @@
## Annotations
This module contains articles about Java annotations
### Relevant Articles:
- [Java Annotation Processing and Creating a Builder](https://www.baeldung.com/java-annotation-processing-builder)
-21
View File
@@ -1,21 +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>annotations</artifactId>
<name>annotations</name>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modules>
<module>annotation-processing</module>
<module>annotation-user</module>
</modules>
</project>
+6 -4
View File
@@ -43,19 +43,19 @@
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-ri</artifactId>
<version>2.3.3</version>
<version>${jaxws-ri.version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<version>${javax.servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<version>${jstl.version}</version>
</dependency>
</dependencies>
@@ -117,7 +117,9 @@
<properties>
<spring.version>5.3.25</spring.version>
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
<maven-war-plugin.version>3.3.2</maven-war-plugin.version>
<jstl.version>1.2</jstl.version>
<javax.servlet-api.version>4.0.1</javax.servlet-api.version>
<jaxws-ri.version>2.3.3</jaxws-ri.version>
</properties>
</project>
@@ -14,6 +14,7 @@ import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.cookie.BasicClientCookie;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.http.cookie.ClientCookie;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -51,8 +52,8 @@ class HttpClientGettingCookieValueUnitTest {
private BasicCookieStore createCustomCookieStore() {
BasicCookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("custom_cookie", "test_value");
cookie.setDomain("baeldung.com");
cookie.setAttribute("domain", "true");
cookie.setDomain("github.com");
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "github.com");
cookie.setPath("/");
cookieStore.addCookie(cookie);
return cookieStore;
@@ -16,7 +16,7 @@ public class ApacheHttpClient5UnitTest {
public static final String DUMMY_URL = "https://postman-echo.com/get";
@Test
public void whenUseApacheHttpClient_thenCorrect() throws IOException {
void whenUseApacheHttpClient_thenCorrect() throws IOException {
HttpGet request = new HttpGet(DUMMY_URL);
try (CloseableHttpClient client = HttpClients.createDefault()) {
@@ -1,6 +1,5 @@
package com.baeldung.httpclient.readresponsebodystring;
import org.junit.Test;
import java.io.IOException;
import java.net.URI;
@@ -8,11 +7,13 @@ import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class HttpClientUnitTest {
import org.junit.jupiter.api.Test;
class HttpClientUnitTest {
public static final String DUMMY_URL = "https://postman-echo.com/get";
@Test
public void whenUseHttpClient_thenCorrect() throws IOException, InterruptedException {
void whenUseHttpClient_thenCorrect() throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(DUMMY_URL)).build();
@@ -1,7 +1,7 @@
package com.baeldung.httpclient.readresponsebodystring;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.BufferedReader;
import java.io.IOException;
@@ -10,12 +10,14 @@ import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.junit.jupiter.api.Test;
public class HttpUrlConnectionUnitTest {
public static final String DUMMY_URL = "https://postman-echo.com/get";
@Test
public void whenUseHttpUrlConnection_thenCorrect() throws IOException {
void whenUseHttpUrlConnection_thenCorrect() throws IOException {
HttpURLConnection connection = (HttpURLConnection) new URL(DUMMY_URL).openConnection();
InputStream inputStream = connection.getInputStream();
@@ -28,7 +30,7 @@ public class HttpUrlConnectionUnitTest {
response.append(currentLine);
in.close();
Assert.assertNotNull(response.toString());
assertNotNull(response.toString());
System.out.println("Response -> " + response.toString());
}
}
@@ -1,6 +1,6 @@
package com.baeldung.httpclient.readresponsebodystring;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.web.client.RestTemplate;
public class SpringRestTemplateUnitTest {
@@ -1,6 +1,6 @@
package com.baeldung.httpclient.readresponsebodystring;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
@@ -8,7 +8,7 @@ public class SpringWebClientUnitTest {
public static final String DUMMY_URL = "https://postman-echo.com/get";
@Test
public void whenUseWebClientRetrieve_thenCorrect() {
void whenUseWebClientRetrieve_thenCorrect() {
WebClient webClient = WebClient.create(DUMMY_URL);
Mono<String> body = webClient.get().retrieve().bodyToMono(String.class);
String s = body.block();
@@ -4,6 +4,7 @@
<pattern>%date [%level] %logger - %msg %n</pattern>
</encoder>
</appender>
<logger name="com.baeldung.httpclient.cookies" level="info"/>
<logger name="com.baeldung.httpclient.readresponsebodystring" level="debug"/>
<logger name="org.apache.http" level="debug"/>
-43
View File
@@ -15,45 +15,6 @@
</parent>
<dependencies>
<!-- http client -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>fluent-hc</artifactId>
<version>${httpclient.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>${httpasyncclient.version}</version> <!-- 4.0.2 --> <!-- 4.1-beta1 -->
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents.core5</groupId>
<artifactId>httpcore5</artifactId>
@@ -115,12 +76,8 @@
</build>
<properties>
<!-- util -->
<httpasyncclient.version>4.1.4</httpasyncclient.version>
<!-- testing -->
<mockserver.version>5.6.1</mockserver.version>
<wiremock.version>2.5.1</wiremock.version>
<httpclient.version>4.5.8</httpclient.version> <!-- 4.3.6 --> <!-- 4.4-beta1 -->
<!-- http client & core 5 -->
<httpcore5.version>5.2</httpcore5.version>
<httpclient5.version>5.2</httpclient5.version>
@@ -4,10 +4,10 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.hc.core5.http.ParseException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.mime.FileBody;
import org.apache.hc.client5.http.entity.mime.HttpMultipartMode;
@@ -19,6 +19,7 @@ import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.ParseException;
import java.io.BufferedReader;
import java.io.File;
@@ -30,9 +31,6 @@ import java.net.URL;
class HttpClientMultipartLiveTest extends GetRequestMockServer {
// No longer available
// private static final String SERVER = "http://echo.200please.com";
private static final String SERVER = "http://localhost:8080/spring-mvc-java/stub/multipart";
private static final String TEXTFILENAME = "temp.txt";
private static final String IMAGEFILENAME = "image.jpg";
@@ -1,15 +1,16 @@
package com.baeldung.httpclient;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import org.junit.jupiter.api.Test;
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.DefaultRedirectStrategy;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import java.io.IOException;
@@ -8,7 +8,7 @@ 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;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
@@ -29,21 +29,34 @@ 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;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class HttpClientAdvancedConfigurationIntegrationTest {
import com.github.tomakehurst.wiremock.WireMockServer;
@Rule
public WireMockRule serviceMock = new WireMockRule(8089);
class HttpClientAdvancedConfigurationIntegrationTest {
@Rule
public WireMockRule proxyMock = new WireMockRule(8090);
public WireMockServer serviceMock;
public WireMockServer proxyMock;
@BeforeEach
public void before () {
serviceMock = new WireMockServer(8089);
serviceMock.start();
proxyMock = new WireMockServer(8090);
proxyMock.start();
}
@AfterEach
public void after () {
serviceMock.stop();
proxyMock.stop();
}
@Test
public void givenClientWithCustomUserAgentHeader_whenExecuteRequest_shouldReturn200() throws IOException {
void givenClientWithCustomUserAgentHeader_whenExecuteRequest_shouldReturn200() throws IOException {
//given
String userAgent = "BaeldungAgent/1.0";
serviceMock.stubFor(get(urlEqualTo("/detail"))
@@ -59,11 +72,11 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
HttpResponse response = httpClient.execute(httpGet);
//then
assertEquals(response.getCode(), 200);
assertEquals(200, response.getCode());
}
@Test
public void givenClientThatSendDataInBody_whenSendXmlInBody_shouldReturn200() throws IOException {
void givenClientThatSendDataInBody_whenSendXmlInBody_shouldReturn200() throws IOException {
//given
String xmlBody = "<xml><id>1</id></xml>";
serviceMock.stubFor(post(urlEqualTo("/person"))
@@ -82,12 +95,12 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
HttpResponse response = httpClient.execute(httpPost);
//then
assertEquals(response.getCode(), 200);
assertEquals(200, response.getCode());
}
@Test
public void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException {
void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException {
//given
proxyMock.stubFor(get(urlMatching(".*"))
.willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
@@ -107,7 +120,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
HttpResponse response = httpclient.execute(httpGet);
//then
assertEquals(response.getCode(), 200);
assertEquals(200, response.getCode());
proxyMock.verify(getRequestedFor(urlEqualTo("/private")));
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
}
@@ -151,7 +164,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
HttpResponse response = httpclient.execute(httpGet, context);
//then
assertEquals(response.getCode(), 200);
assertEquals(200, response.getCode());
proxyMock.verify(getRequestedFor(urlEqualTo("/private")).withHeader("Authorization", containing("Basic")));
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
}
@@ -1,59 +0,0 @@
package com.baeldung.httpclient.base;
import com.baeldung.httpclient.ResponseUtil;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
public class HttpClientBasicPostLiveTest {
private static final String SAMPLE_URL = "http://www.github.com";
private CloseableHttpClient instance;
private CloseableHttpResponse response;
@Before
public final void before() {
instance = HttpClientBuilder.create().build();
}
@After
public final void after() throws IllegalStateException, IOException {
ResponseUtil.closeResponse(response);
}
// tests - non-GET
@Test
public final void whenExecutingPostRequest_thenNoExceptions() throws IOException {
instance.execute(new HttpPost(SAMPLE_URL));
}
@Test
public final void whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException {
final HttpPost request = new HttpPost(SAMPLE_URL);
request.setEntity(new StringEntity("in the body of the POST"));
instance.execute(request);
}
@Test
public final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException, AuthenticationException {
final HttpPost request = new HttpPost(SAMPLE_URL);
request.setEntity(new StringEntity("in the body of the POST"));
final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("username", "password");
request.addHeader(new BasicScheme().authenticate(creds, request, null));
instance.execute(request);
}
}
@@ -1,75 +0,0 @@
package com.baeldung.httpclient.base;
import com.baeldung.httpclient.ResponseUtil;
import org.apache.http.Header;
import org.apache.http.HttpHeaders;
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.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.Matchers.emptyArray;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
public class HttpClientLiveTest {
private static final String SAMPLE_URL = "http://www.github.com";
private CloseableHttpClient instance;
private CloseableHttpResponse response;
@Before
public final void before() {
instance = HttpClientBuilder.create().build();
}
@After
public final void after() throws IllegalStateException, IOException {
ResponseUtil.closeResponse(response);
}
// tests
@Test(expected = ConnectTimeoutException.class)
public final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws IOException {
final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5).setConnectTimeout(5).setSocketTimeout(2).build();
final HttpGet request = new HttpGet(SAMPLE_URL);
request.setConfig(requestConfig);
response = instance.execute(request);
}
// tests - configs
@Test
public final void givenHttpClientIsConfiguredWithCustomConnectionManager_whenExecutingRequest_thenNoExceptions() throws IOException {
instance = HttpClientBuilder.create().setConnectionManager(new BasicHttpClientConnectionManager()).build();
response = instance.execute(new HttpGet(SAMPLE_URL));
}
@Test
public final void givenCustomHeaderIsSet_whenSendingRequest_thenNoExceptions() throws IOException {
final HttpGet request = new HttpGet(SAMPLE_URL);
request.addHeader(HttpHeaders.ACCEPT, "application/xml");
response = instance.execute(request);
}
@Test
public final void givenRequestWasSet_whenAnalyzingTheHeadersOfTheResponse_thenCorrect() throws IOException {
response = instance.execute(new HttpGet(SAMPLE_URL));
final Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
assertThat(headers, not(emptyArray()));
}
}
@@ -1,5 +1,6 @@
package com.baeldung.httpclient.conn;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -34,14 +35,13 @@ 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;
import org.junit.jupiter.api.Test;
public class HttpClientConnectionManagementLiveTest {
class HttpClientConnectionManagementLiveTest {
// Example 2.1. Getting a Connection Request for a Low Level Connection (HttpClientConnection)
@Test
public final void whenLowLevelConnectionIsEstablished_thenNoExceptions() throws ExecutionException, InterruptedException, TimeoutException {
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);
@@ -51,7 +51,7 @@ public class HttpClientConnectionManagementLiveTest {
// Example 3.1. Setting the PoolingHttpClientConnectionManager on a HttpClient
@Test
public final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExceptions() throws IOException {
final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExceptions() throws IOException {
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(poolingConnManager)
@@ -65,7 +65,7 @@ public class HttpClientConnectionManagementLiveTest {
// Example 3.2. Using Two HttpClients to Connect to One Target Host Each
@Test
public final void whenTwoConnectionsForTwoRequests_thenNoExceptions() throws InterruptedException, IOException {
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();
@@ -83,8 +83,7 @@ public class HttpClientConnectionManagementLiveTest {
thread1.join();
thread2.join();
Assert.assertTrue(connManager.getTotalStats()
.getLeased() == 0);
assertEquals(0, connManager.getTotalStats().getLeased());
client1.close();
client2.close();
connManager.close();
@@ -92,7 +91,7 @@ public class HttpClientConnectionManagementLiveTest {
// Example 4.1. Increasing the Number of Connections that Can be Open and Managed Beyond the default Limits
@Test
public final void whenIncreasingConnectionPool_thenNoExceptions() {
final void whenIncreasingConnectionPool_thenNoExceptions() {
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(5);
connManager.setDefaultMaxPerRoute(4);
@@ -103,7 +102,7 @@ public class HttpClientConnectionManagementLiveTest {
// Example 4.2. Using Threads to Execute Connections
@Test
public final void whenExecutingSameRequestsInDifferentThreads_thenExecuteRequest() throws InterruptedException, IOException {
final void whenExecutingSameRequestsInDifferentThreads_thenExecuteRequest() throws InterruptedException, IOException {
HttpGet get = new HttpGet("http://www.baeldung.com");
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
@@ -133,7 +132,7 @@ public class HttpClientConnectionManagementLiveTest {
// Example 5.1. A Custom Keep Alive Strategy
@Test
public final void whenCustomizingKeepAliveStrategy_thenNoExceptions() {
final void whenCustomizingKeepAliveStrategy_thenNoExceptions() {
final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
@Override
public TimeValue getKeepAliveDuration(HttpResponse response, HttpContext context) {
@@ -162,7 +161,7 @@ public class HttpClientConnectionManagementLiveTest {
//Example 6.1. BasicHttpClientConnectionManager Connection Reuse
@Test
public final void givenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws InterruptedException, ExecutionException, TimeoutException, IOException, URISyntaxException {
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));
final HttpContext context = new BasicHttpContext();
@@ -184,7 +183,7 @@ public class HttpClientConnectionManagementLiveTest {
// Example 6.2. PoolingHttpClientConnectionManager: Re-Using Connections with Threads
@Test
public final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException, IOException {
final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException, IOException {
HttpGet get = new HttpGet("http://www.baeldung.com");
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setDefaultMaxPerRoute(6);
@@ -208,7 +207,7 @@ public class HttpClientConnectionManagementLiveTest {
// Example 7.1. Setting Socket Timeout to 5 Seconds
@Test
public final void whenConfiguringTimeOut_thenNoExceptions() throws ExecutionException, InterruptedException, TimeoutException, IOException {
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();
@@ -227,7 +226,7 @@ public class HttpClientConnectionManagementLiveTest {
// Example 8.1. Setting the HttpClient to Check for Stale Connections
@Test
public final void whenEvictIdealConn_thenNoExceptions() throws InterruptedException, IOException {
final void whenEvictIdealConn_thenNoExceptions() throws InterruptedException, IOException {
final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(100);
try (final CloseableHttpClient httpclient = HttpClients.custom()
@@ -266,7 +265,7 @@ public class HttpClientConnectionManagementLiveTest {
// Example 9.1. Closing Connection and Releasing Resources
@Test
public final void whenClosingConnectionsandManager_thenCloseWithNoExceptions1() throws IOException {
final void whenClosingConnectionsAndManager_thenCloseWithNoExceptions1() throws IOException {
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(connManager)
@@ -282,7 +281,7 @@ public class HttpClientConnectionManagementLiveTest {
@Test
// Example 3.2. TESTER VERSION
public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException, IOException {
final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException, IOException {
HttpGet get1 = new HttpGet("https://www.baeldung.com");
HttpGet get2 = new HttpGet("https://www.google.com");
@@ -300,8 +299,7 @@ public class HttpClientConnectionManagementLiveTest {
thread2.start();
thread1.join();
thread2.join(1000);
Assert.assertTrue(poolingConnManager.getTotalStats()
.getLeased() == 2);
assertEquals(2, poolingConnManager.getTotalStats().getLeased());
client1.close();
client2.close();
@@ -1,41 +0,0 @@
package com.baeldung.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();
}
}
}
@@ -6,7 +6,6 @@ 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;
-2
View File
@@ -241,8 +241,6 @@
<httpcore.version>4.4.16</httpcore.version>
<httpclient.version>4.5.14</httpclient.version>
<mockserver.version>5.11.2</mockserver.version>
<!-- maven plugins -->
<maven-war-plugin.version>3.3.2</maven-war-plugin.version>
</properties>
</project>
@@ -1,7 +1,7 @@
package com.baeldung.httpclient.base;
package com.baeldung.client;
import java.io.IOException;
import com.baeldung.httpclient.GetRequestMockServer;
import com.baeldung.httpclient.ResponseUtil;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
@@ -12,15 +12,16 @@ import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import com.baeldung.GetRequestMockServer;
import com.baeldung.httpclient.ResponseUtil;
/*
* NOTE : Need module spring-security-rest-basic-auth to be running
*/
public class HttpClientSandboxLiveTest extends GetRequestMockServer {
class HttpClientSandboxLiveTest extends GetRequestMockServer {
@Test
public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException {
final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
final AuthScope authscp = new AuthScope("localhost", 8080);
credentialsProvider.setCredentials(authscp, new UsernamePasswordCredentials("user1", "user1Pass"));
@@ -35,7 +35,7 @@ import org.springframework.web.client.RestTemplate;
* This test requires a localhost server over HTTPS <br>
* It should only be manually run, not part of the automated build
* */
public class RestClientV4LiveManualTest {
class RestClientV4LiveManualTest {
final String urlOverHttps = "http://localhost:8082/httpclient-simple/api/bars/1";
@@ -81,7 +81,7 @@ public class RestClientV4LiveManualTest {
}
@Test
public void whenHttpsUrlIsConsumed_thenException() throws ClientProtocolException, IOException {
void whenHttpsUrlIsConsumed_thenException() throws ClientProtocolException, IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
String urlOverHttps = "https://localhost:8082/httpclient-simple";
HttpGet getMethod = new HttpGet(urlOverHttps);
@@ -2,8 +2,6 @@ package com.baeldung.httpclient;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
public final class ClientUtil {
@@ -1,4 +1,5 @@
package com.baeldung.httpclient;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
@@ -9,11 +9,11 @@ import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class HttpClientCancelRequestV4LiveTest {
class HttpClientCancelRequestV4LiveTest {
private static final String SAMPLE_URL = "http://www.github.com";
@@ -21,18 +21,18 @@ public class HttpClientCancelRequestV4LiveTest {
private CloseableHttpResponse response;
@Before
@BeforeEach
public final void before() {
instance = HttpClientBuilder.create().build();
}
@After
@AfterEach
public final void after() throws IllegalStateException, IOException {
ResponseUtil.closeResponse(response);
}
@Test
public final void whenRequestIsCanceled_thenCorrect() throws IOException {
final void whenRequestIsCanceled_thenCorrect() throws IOException {
instance = HttpClients.custom().build();
final HttpGet request = new HttpGet(SAMPLE_URL);
response = instance.execute(request);
@@ -1,5 +1,9 @@
package com.baeldung.httpclient;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -181,4 +185,20 @@ class HttpClientCookBookV4LiveTest {
}
}
@Test
final void whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException {
final HttpPost request = new HttpPost(SAMPLE_POST_URL);
request.setEntity(new StringEntity("in the body of the POST"));
client.execute(request);
}
@Test
final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException, AuthenticationException {
final HttpPost request = new HttpPost(SAMPLE_POST_URL);
request.setEntity(new StringEntity("in the body of the POST"));
final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("username", "password");
request.addHeader(new BasicScheme().authenticate(creds, request, null));
client.execute(request);
}
}
@@ -1,12 +1,12 @@
package com.baeldung.httpclient;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import java.io.IOException;
import org.apache.http.client.methods.CloseableHttpResponse;

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