@@ -8,7 +8,6 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
||||
- [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique)
|
||||
- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine)
|
||||
- [Converting Between Roman and Arabic Numerals in Java](https://www.baeldung.com/java-convert-roman-arabic)
|
||||
- [Practical Java Examples of the Big O Notation](https://www.baeldung.com/java-algorithm-complexity)
|
||||
- [Checking If a List Is Sorted in Java](https://www.baeldung.com/java-check-if-list-sorted)
|
||||
- [Checking if a Java Graph Has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle)
|
||||
- [A Guide to the Folding Technique in Java](https://www.baeldung.com/folding-hashing-technique)
|
||||
|
||||
@@ -7,7 +7,6 @@ import static org.mockserver.model.HttpResponse.response;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URISyntaxException;
|
||||
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
@@ -18,22 +17,19 @@ import org.mockserver.integration.ClientAndServer;
|
||||
public class GetRequestMockServer {
|
||||
|
||||
public static ClientAndServer mockServer;
|
||||
public static String serviceOneUrl;
|
||||
public static String serviceTwoUrl;
|
||||
|
||||
public static int serverPort;
|
||||
|
||||
public static final String SERVER_ADDRESS = "127.0.0.1";
|
||||
public static final String PATH_ONE = "/test1";
|
||||
public static final String PATH_TWO = "/test2";
|
||||
public static final String METHOD = "GET";
|
||||
|
||||
public static final String SECURITY_PATH = "/spring-security-rest-basic-auth/api/foos/1";
|
||||
|
||||
public static final String UPLOAD_PATH = "/spring-mvc-java/stub/multipart";
|
||||
|
||||
@BeforeAll
|
||||
static void startServer() throws IOException {
|
||||
serverPort = getFreePort();
|
||||
System.out.println("Free port "+serverPort);
|
||||
serviceOneUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_ONE;
|
||||
serviceTwoUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_TWO;
|
||||
System.out.println("Free port " + serverPort);
|
||||
mockServer = startClientAndServer(serverPort);
|
||||
mockGetRequest();
|
||||
}
|
||||
@@ -44,33 +40,36 @@ public class GetRequestMockServer {
|
||||
}
|
||||
|
||||
private static void mockGetRequest() {
|
||||
new MockServerClient(SERVER_ADDRESS, serverPort)
|
||||
.when(
|
||||
request()
|
||||
.withPath(PATH_ONE)
|
||||
.withMethod(METHOD),
|
||||
exactly(5)
|
||||
)
|
||||
.respond(
|
||||
response()
|
||||
.withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}")
|
||||
);
|
||||
new MockServerClient(SERVER_ADDRESS, serverPort)
|
||||
.when(
|
||||
request()
|
||||
.withPath(PATH_TWO)
|
||||
.withMethod(METHOD),
|
||||
exactly(1)
|
||||
)
|
||||
.respond(
|
||||
response()
|
||||
.withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}")
|
||||
);
|
||||
|
||||
MockServerClient client = new MockServerClient(SERVER_ADDRESS, serverPort);
|
||||
|
||||
client.when(
|
||||
request()
|
||||
.withPath(SECURITY_PATH)
|
||||
.withMethod("GET"),
|
||||
exactly(1)
|
||||
)
|
||||
.respond(
|
||||
response()
|
||||
.withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}")
|
||||
);
|
||||
|
||||
client.when(
|
||||
request()
|
||||
.withPath(UPLOAD_PATH)
|
||||
.withMethod("POST"),
|
||||
exactly(4)
|
||||
)
|
||||
.respond(
|
||||
response()
|
||||
.withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}")
|
||||
.withHeader("Content-Type", "multipart/form-data")
|
||||
);
|
||||
}
|
||||
|
||||
private static int getFreePort () throws IOException {
|
||||
private static int getFreePort() throws IOException {
|
||||
try (ServerSocket serverSocket = new ServerSocket(0)) {
|
||||
return serverSocket.getLocalPort();
|
||||
}
|
||||
|
||||
+7
-1
@@ -19,7 +19,7 @@ class HttpClientCancelRequestLiveTest {
|
||||
void whenRequestIsCanceled_thenCorrect() throws IOException {
|
||||
HttpGet request = new HttpGet(SAMPLE_URL);
|
||||
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
|
||||
httpClient.execute(request, response -> {
|
||||
httpClient.execute(request, response -> {
|
||||
HttpEntity entity = response.getEntity();
|
||||
|
||||
System.out.println("----------------------------------------");
|
||||
@@ -28,6 +28,12 @@ class HttpClientCancelRequestLiveTest {
|
||||
System.out.println("Response content length: " + entity.getContentLength());
|
||||
}
|
||||
System.out.println("----------------------------------------");
|
||||
|
||||
if (entity != null) {
|
||||
// Closes this stream and releases any system resources
|
||||
entity.close();
|
||||
}
|
||||
|
||||
// Do not feel like reading the response body
|
||||
// Call abort on the request object
|
||||
request.abort();
|
||||
|
||||
+62
-61
@@ -4,6 +4,7 @@ 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;
|
||||
|
||||
@@ -13,7 +14,6 @@ import org.apache.hc.client5.http.entity.mime.HttpMultipartMode;
|
||||
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
|
||||
import org.apache.hc.client5.http.entity.mime.StringBody;
|
||||
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.HttpClientBuilder;
|
||||
|
||||
import org.apache.hc.core5.http.ContentType;
|
||||
@@ -28,9 +28,7 @@ import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.URL;
|
||||
|
||||
import com.baeldung.httpclient.handler.CustomHttpClientResponseHandler;
|
||||
|
||||
class HttpClientMultipartLiveTest {
|
||||
class HttpClientMultipartLiveTest extends GetRequestMockServer {
|
||||
|
||||
// No longer available
|
||||
// private static final String SERVER = "http://echo.200please.com";
|
||||
@@ -45,13 +43,15 @@ class HttpClientMultipartLiveTest {
|
||||
@BeforeEach
|
||||
public void before() {
|
||||
post = new HttpPost(SERVER);
|
||||
String URL = "http://localhost:" + serverPort + "/spring-mvc-java/stub/multipart";
|
||||
post = new HttpPost(URL);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException {
|
||||
final URL url = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + TEXTFILENAME);
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + TEXTFILENAME);
|
||||
|
||||
final File file = new File(url.getPath());
|
||||
final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
|
||||
@@ -66,27 +66,28 @@ class HttpClientMultipartLiveTest {
|
||||
final HttpEntity entity = builder.build();
|
||||
|
||||
post.setEntity(entity);
|
||||
try(CloseableHttpClient client = HttpClientBuilder.create()
|
||||
.build();
|
||||
try (CloseableHttpClient client = HttpClientBuilder.create()
|
||||
.build()) {
|
||||
|
||||
CloseableHttpResponse response = (CloseableHttpResponse) client
|
||||
.execute(post, new CustomHttpClientResponseHandler())){
|
||||
final int statusCode = response.getCode();
|
||||
final String responseString = getContent(response.getEntity());
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
client.execute(post, response -> {
|
||||
final int statusCode = response.getCode();
|
||||
final String responseString = getContent(response.getEntity());
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(contentTypeInHeader.contains("multipart/form-data"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
return response;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException {
|
||||
final URL url = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + TEXTFILENAME);
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + TEXTFILENAME);
|
||||
final File file = new File(url.getPath());
|
||||
final String message = "This is a multipart post";
|
||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
@@ -96,30 +97,31 @@ class HttpClientMultipartLiveTest {
|
||||
final HttpEntity entity = builder.build();
|
||||
post.setEntity(entity);
|
||||
|
||||
try(CloseableHttpClient client = HttpClientBuilder.create()
|
||||
.build();
|
||||
try (CloseableHttpClient client = HttpClientBuilder.create()
|
||||
.build()) {
|
||||
|
||||
CloseableHttpResponse response = (CloseableHttpResponse) client
|
||||
.execute(post, new CustomHttpClientResponseHandler())){
|
||||
client.execute(post, response -> {
|
||||
|
||||
final int statusCode = response.getCode();
|
||||
final String responseString = getContent(response.getEntity());
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
final int statusCode = response.getCode();
|
||||
final String responseString = getContent(response.getEntity());
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(contentTypeInHeader.contains("multipart/form-data"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
return response;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
|
||||
final URL url = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + ZIPFILENAME);
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + ZIPFILENAME);
|
||||
final URL url2 = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + IMAGEFILENAME);
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + IMAGEFILENAME);
|
||||
final InputStream inputStream = new FileInputStream(url.getPath());
|
||||
final File file = new File(url2.getPath());
|
||||
final String message = "This is a multipart post";
|
||||
@@ -131,25 +133,25 @@ class HttpClientMultipartLiveTest {
|
||||
final HttpEntity entity = builder.build();
|
||||
post.setEntity(entity);
|
||||
|
||||
try(CloseableHttpClient client = HttpClientBuilder.create()
|
||||
.build();
|
||||
try (CloseableHttpClient client = HttpClientBuilder.create()
|
||||
.build()) {
|
||||
|
||||
CloseableHttpResponse response = (CloseableHttpResponse) client
|
||||
.execute(post, new CustomHttpClientResponseHandler())){
|
||||
|
||||
final int statusCode = response.getCode();
|
||||
final String responseString = getContent(response.getEntity());
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
inputStream.close();
|
||||
client.execute(post, response -> {
|
||||
final int statusCode = response.getCode();
|
||||
final String responseString = getContent(response.getEntity());
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(contentTypeInHeader.contains("multipart/form-data;"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
inputStream.close();
|
||||
return response;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
|
||||
void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException, ParseException {
|
||||
final String message = "This is a multipart post";
|
||||
final byte[] bytes = "binary code".getBytes();
|
||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
@@ -159,21 +161,20 @@ class HttpClientMultipartLiveTest {
|
||||
final HttpEntity entity = builder.build();
|
||||
post.setEntity(entity);
|
||||
|
||||
try(CloseableHttpClient client = HttpClientBuilder.create()
|
||||
.build();
|
||||
try (CloseableHttpClient httpClient = HttpClientBuilder.create()
|
||||
.build()) {
|
||||
|
||||
CloseableHttpResponse response = (CloseableHttpResponse) client
|
||||
.execute(post, new CustomHttpClientResponseHandler())){
|
||||
|
||||
final int statusCode = response.getCode();
|
||||
final String responseString = getContent(response.getEntity());
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
httpClient.execute(post, response -> {
|
||||
final int statusCode = response.getCode();
|
||||
final String responseString = getContent(response.getEntity());
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(contentTypeInHeader.contains("multipart/form-data;"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
return response;
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// UTIL
|
||||
|
||||
+1
-1
@@ -43,7 +43,7 @@ public class HttpClientLiveTest {
|
||||
|
||||
@Test(expected = ConnectTimeoutException.class)
|
||||
public final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws IOException {
|
||||
final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(50).setConnectTimeout(50).setSocketTimeout(20).build();
|
||||
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);
|
||||
|
||||
+4
-3
@@ -1,5 +1,6 @@
|
||||
package com.baeldung.httpclient.base;
|
||||
|
||||
import com.baeldung.httpclient.GetRequestMockServer;
|
||||
import com.baeldung.httpclient.ResponseUtil;
|
||||
import org.apache.http.auth.AuthScope;
|
||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||
@@ -9,14 +10,14 @@ import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.impl.client.BasicCredentialsProvider;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/*
|
||||
* NOTE : Need module spring-security-rest-basic-auth to be running
|
||||
*/
|
||||
public class HttpClientSandboxLiveTest {
|
||||
public class HttpClientSandboxLiveTest extends GetRequestMockServer {
|
||||
|
||||
@Test
|
||||
public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException {
|
||||
@@ -26,7 +27,7 @@ public class HttpClientSandboxLiveTest {
|
||||
|
||||
final CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
|
||||
|
||||
final HttpGet httpGet = new HttpGet("http://localhost:8080/spring-security-rest-basic-auth/api/foos/1");
|
||||
final HttpGet httpGet = new HttpGet("http://localhost:" + serverPort + "/spring-security-rest-basic-auth/api/foos/1");
|
||||
final CloseableHttpResponse response = client.execute(httpGet);
|
||||
|
||||
System.out.println(response.getStatusLine());
|
||||
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
package com.baeldung.httpclient.handler;
|
||||
|
||||
import org.apache.hc.core5.http.ClassicHttpResponse;
|
||||
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
|
||||
|
||||
public class CustomHttpClientResponseHandler implements HttpClientResponseHandler<ClassicHttpResponse> {
|
||||
@Override
|
||||
public ClassicHttpResponse handleResponse(ClassicHttpResponse response) {
|
||||
return response;
|
||||
}
|
||||
}
|
||||
@@ -199,33 +199,7 @@
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>${maven-war-plugin.version}</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.cargo</groupId>
|
||||
<artifactId>cargo-maven2-plugin</artifactId>
|
||||
<version>${cargo-maven2-plugin.version}</version>
|
||||
<configuration>
|
||||
<wait>true</wait>
|
||||
<container>
|
||||
<containerId>jetty8x</containerId>
|
||||
<type>embedded</type>
|
||||
<systemProperties>
|
||||
<!-- <provPersistenceTarget>cargo</provPersistenceTarget> -->
|
||||
</systemProperties>
|
||||
</container>
|
||||
<configuration>
|
||||
<properties>
|
||||
<cargo.servlet.port>8082</cargo.servlet.port>
|
||||
</properties>
|
||||
</configuration>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
@@ -233,26 +207,6 @@
|
||||
<id>live</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.cargo</groupId>
|
||||
<artifactId>cargo-maven2-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>start-server</id>
|
||||
<phase>pre-integration-test</phase>
|
||||
<goals>
|
||||
<goal>start</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>stop-server</id>
|
||||
<phase>post-integration-test</phase>
|
||||
<goals>
|
||||
<goal>stop</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
@@ -269,9 +223,6 @@
|
||||
<includes>
|
||||
<include>**/*LiveTest.java</include>
|
||||
</includes>
|
||||
<systemPropertyVariables>
|
||||
<webTarget>cargo</webTarget>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
@@ -291,7 +242,6 @@
|
||||
<httpclient.version>4.5.14</httpclient.version>
|
||||
<mockserver.version>5.11.2</mockserver.version>
|
||||
<!-- maven plugins -->
|
||||
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
|
||||
<maven-war-plugin.version>3.3.2</maven-war-plugin.version>
|
||||
</properties>
|
||||
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.baeldung;
|
||||
|
||||
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
|
||||
import static org.mockserver.model.HttpRequest.request;
|
||||
import static org.mockserver.model.HttpResponse.response;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.mockserver.client.MockServerClient;
|
||||
import org.mockserver.integration.ClientAndServer;
|
||||
|
||||
public class GetRequestMockServer {
|
||||
|
||||
public static ClientAndServer mockServer;
|
||||
public static int serverPort;
|
||||
public static String simplePathUrl;
|
||||
public static final String SERVER_ADDRESS = "127.0.0.1";
|
||||
public static final String SIMPLE_PATH = "/httpclient-simple/api/bars/1";
|
||||
|
||||
@BeforeAll
|
||||
static void startServer() throws IOException {
|
||||
serverPort = getFreePort();
|
||||
System.out.println("Free port " + serverPort);
|
||||
mockServer = startClientAndServer(serverPort);
|
||||
|
||||
simplePathUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + SIMPLE_PATH;
|
||||
|
||||
mockGetRequest();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stopServer() {
|
||||
mockServer.stop();
|
||||
}
|
||||
|
||||
private static void mockGetRequest() {
|
||||
|
||||
MockServerClient client = new MockServerClient(SERVER_ADDRESS, serverPort);
|
||||
|
||||
client.when(request().withPath(SIMPLE_PATH)
|
||||
.withMethod("GET"))
|
||||
.respond(response().withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}"));
|
||||
}
|
||||
|
||||
private static int getFreePort() throws IOException {
|
||||
try (ServerSocket serverSocket = new ServerSocket(0)) {
|
||||
return serverSocket.getLocalPort();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import java.io.IOException;
|
||||
import java.security.GeneralSecurityException;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLPeerUnverifiedException;
|
||||
import javax.net.ssl.SSLHandshakeException;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
@@ -31,10 +31,10 @@ import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import com.baeldung.GetRequestMockServer;
|
||||
|
||||
class ClientLiveTest {
|
||||
class ClientLiveTest extends GetRequestMockServer {
|
||||
|
||||
final String urlOverHttps = "http://localhost:8082/httpclient-simple/api/bars/1";
|
||||
|
||||
@Test
|
||||
void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk_2() throws GeneralSecurityException {
|
||||
@@ -54,13 +54,13 @@ class ClientLiveTest {
|
||||
.build();
|
||||
|
||||
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
|
||||
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
|
||||
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(simplePathUrl, HttpMethod.GET, null, String.class);
|
||||
assertThat(response.getStatusCode().value(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws IOException {
|
||||
final HttpGet getMethod = new HttpGet(urlOverHttps);
|
||||
final HttpGet getMethod = new HttpGet(simplePathUrl);
|
||||
|
||||
try (final CloseableHttpClient httpClient = HttpClients.custom()
|
||||
.setSSLHostnameVerifier(new NoopHostnameVerifier())
|
||||
@@ -80,20 +80,22 @@ class ClientLiveTest {
|
||||
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
|
||||
requestFactory.setHttpClient(httpClient);
|
||||
|
||||
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
|
||||
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(simplePathUrl, HttpMethod.GET, null, String.class);
|
||||
assertThat(response.getStatusCode().value(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenHttpsUrlIsConsumed_thenException() {
|
||||
String urlOverHttps = "https://localhost:8082/httpclient-simple";
|
||||
String urlOverHttps = "https://localhost:"+serverPort+"/httpclient-simple/api/bars/1";
|
||||
HttpGet getMethod = new HttpGet(urlOverHttps);
|
||||
|
||||
assertThrows(SSLPeerUnverifiedException.class, () -> {
|
||||
assertThrows(SSLHandshakeException.class, () -> {
|
||||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||||
HttpResponse response = httpClient.execute(getMethod);
|
||||
assertThat(response.getStatusLine()
|
||||
.getStatusCode(), equalTo(200));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,5 @@
|
||||
package com.baeldung.client;
|
||||
|
||||
import static org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
@@ -89,4 +88,5 @@ public class RestClientV4LiveManualTest {
|
||||
HttpResponse response = httpClient.execute(getMethod);
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
package com.baeldung.httpclient;
|
||||
|
||||
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
|
||||
import static org.mockserver.matchers.Times.exactly;
|
||||
import static org.mockserver.model.HttpRequest.request;
|
||||
import static org.mockserver.model.HttpResponse.response;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URISyntaxException;
|
||||
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.mockserver.client.MockServerClient;
|
||||
import org.mockserver.integration.ClientAndServer;
|
||||
|
||||
public class GetRequestMockServer {
|
||||
|
||||
public static ClientAndServer mockServer;
|
||||
public static String serviceOneUrl;
|
||||
public static String serviceTwoUrl;
|
||||
|
||||
public static int serverPort;
|
||||
|
||||
public static final String SERVER_ADDRESS = "127.0.0.1";
|
||||
public static final String PATH_ONE = "/test1";
|
||||
public static final String PATH_TWO = "/test2";
|
||||
public static final String METHOD = "GET";
|
||||
|
||||
@BeforeAll
|
||||
static void startServer() throws IOException, URISyntaxException {
|
||||
serverPort = getFreePort();
|
||||
serviceOneUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_ONE;
|
||||
serviceTwoUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_TWO;
|
||||
mockServer = startClientAndServer(serverPort);
|
||||
mockGetRequest();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stopServer() {
|
||||
mockServer.stop();
|
||||
}
|
||||
|
||||
private static void mockGetRequest() {
|
||||
new MockServerClient(SERVER_ADDRESS, serverPort)
|
||||
.when(
|
||||
request()
|
||||
.withPath(PATH_ONE)
|
||||
.withMethod(METHOD),
|
||||
exactly(5)
|
||||
)
|
||||
.respond(
|
||||
response()
|
||||
.withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}")
|
||||
);
|
||||
new MockServerClient(SERVER_ADDRESS, serverPort)
|
||||
.when(
|
||||
request()
|
||||
.withPath(PATH_TWO)
|
||||
.withMethod(METHOD),
|
||||
exactly(1)
|
||||
)
|
||||
.respond(
|
||||
response()
|
||||
.withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}")
|
||||
);
|
||||
}
|
||||
|
||||
private static int getFreePort () throws IOException {
|
||||
try (ServerSocket serverSocket = new ServerSocket(0)) {
|
||||
return serverSocket.getLocalPort();
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
@@ -31,6 +31,7 @@ import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.ssl.SSLContexts;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.baeldung.GetRequestMockServer;
|
||||
|
||||
class HttpAsyncClientV4LiveTest extends GetRequestMockServer {
|
||||
|
||||
|
||||
+2
@@ -44,7 +44,9 @@ public class HttpClientCancelRequestV4LiveTest {
|
||||
System.out.println(response.getStatusLine());
|
||||
if (entity != null) {
|
||||
System.out.println("Response content length: " + entity.getContentLength());
|
||||
entity.getContent().close();
|
||||
}
|
||||
|
||||
System.out.println("----------------------------------------");
|
||||
|
||||
// Do not feel like reading the response body
|
||||
|
||||
+4
-2
@@ -21,7 +21,9 @@ import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class HttpClientTimeoutV4LiveTest {
|
||||
import com.baeldung.GetRequestMockServer;
|
||||
|
||||
class HttpClientTimeoutV4LiveTest extends GetRequestMockServer {
|
||||
|
||||
private CloseableHttpResponse response;
|
||||
|
||||
@@ -97,7 +99,7 @@ class HttpClientTimeoutV4LiveTest {
|
||||
int timeout = 20; // seconds
|
||||
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout * 1000)
|
||||
.setConnectTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
|
||||
HttpGet getMethod = new HttpGet("http://localhost:8082/httpclient-simple/api/bars/1");
|
||||
HttpGet getMethod = new HttpGet(simplePathUrl);
|
||||
getMethod.setConfig(requestConfig);
|
||||
|
||||
int hardTimeout = 5; // seconds
|
||||
|
||||
+3
-1
@@ -13,13 +13,15 @@ import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.baeldung.GetRequestMockServer;
|
||||
|
||||
class ApacheHttpClientUnitTest extends GetRequestMockServer {
|
||||
|
||||
|
||||
@Test
|
||||
void givenDeveloperUsedCloseableHttpResponse_whenExecutingGetRequest_thenStatusIsOk() throws IOException {
|
||||
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
|
||||
HttpGet httpGet = new HttpGet(serviceOneUrl);
|
||||
HttpGet httpGet = new HttpGet(simplePathUrl);
|
||||
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
|
||||
HttpEntity entity = response.getEntity();
|
||||
EntityUtils.consume(entity);
|
||||
|
||||
-78
@@ -1,78 +0,0 @@
|
||||
package com.baeldung.httpclient.httpclient;
|
||||
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.mockserver.client.MockServerClient;
|
||||
import org.mockserver.integration.ClientAndServer;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URISyntaxException;
|
||||
|
||||
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
|
||||
import static org.mockserver.matchers.Times.exactly;
|
||||
import static org.mockserver.model.HttpRequest.request;
|
||||
import static org.mockserver.model.HttpResponse.response;
|
||||
|
||||
public class GetRequestMockServer {
|
||||
|
||||
public static ClientAndServer mockServer;
|
||||
public static String serviceOneUrl;
|
||||
public static String serviceTwoUrl;
|
||||
|
||||
private static int serverPort;
|
||||
|
||||
public static final String SERVER_ADDRESS = "127.0.0.1";
|
||||
public static final String PATH_ONE = "/test1";
|
||||
public static final String PATH_TWO = "/test2";
|
||||
public static final String METHOD = "GET";
|
||||
|
||||
@BeforeAll
|
||||
static void startServer() throws IOException, URISyntaxException {
|
||||
serverPort = getFreePort();
|
||||
serviceOneUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_ONE;
|
||||
serviceTwoUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_TWO;
|
||||
mockServer = startClientAndServer(serverPort);
|
||||
mockGetRequest();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stopServer() {
|
||||
mockServer.stop();
|
||||
}
|
||||
|
||||
private static void mockGetRequest() {
|
||||
new MockServerClient(SERVER_ADDRESS, serverPort)
|
||||
.when(
|
||||
request()
|
||||
.withPath(PATH_ONE)
|
||||
.withMethod(METHOD),
|
||||
exactly(5)
|
||||
)
|
||||
.respond(
|
||||
response()
|
||||
.withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}")
|
||||
);
|
||||
new MockServerClient(SERVER_ADDRESS, serverPort)
|
||||
.when(
|
||||
request()
|
||||
.withPath(PATH_TWO)
|
||||
.withMethod(METHOD),
|
||||
exactly(1)
|
||||
)
|
||||
.respond(
|
||||
response()
|
||||
.withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}")
|
||||
);
|
||||
}
|
||||
|
||||
private static int getFreePort () throws IOException {
|
||||
try (ServerSocket serverSocket = new ServerSocket(0)) {
|
||||
return serverSocket.getLocalPort();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
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-poi-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
@@ -100,7 +100,6 @@
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
<properties>
|
||||
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
|
||||
<aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<?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"
|
||||
<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-groovy-2</artifactId>
|
||||
@@ -117,11 +118,11 @@
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.20.1</version>
|
||||
<configuration>
|
||||
<useFile>false</useFile>
|
||||
<includes>
|
||||
<include>**/*Test.java</include>
|
||||
<include>**/*Spec.java</include>
|
||||
</includes>
|
||||
<useFile>false</useFile>
|
||||
<includes>
|
||||
<include>**/*Test.java</include>
|
||||
<include>**/*Spec.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<!-- Maven Assembly Plugin: needed to run the jar through command line -->
|
||||
|
||||
+59
-4
@@ -4,29 +4,84 @@ import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.Socket;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLEngine;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.X509ExtendedTrustManager;
|
||||
|
||||
public class HttpClientSSLBypassUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenHttpsRequest_thenCorrect() throws IOException, InterruptedException {
|
||||
public void givenDisableUsingJVMProperty_whenByPassCertificationVerification_thenSuccessHttpResponse() throws IOException, InterruptedException {
|
||||
final Properties props = System.getProperties();
|
||||
props.setProperty("jdk.internal.httpclient.disableHostnameVerification", Boolean.TRUE.toString());
|
||||
|
||||
HttpClient httpClient = HttpClient.newBuilder()
|
||||
.build();
|
||||
.build();
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create("https://wrong.host.badssl.com/"))
|
||||
.build();
|
||||
.uri(URI.create("https://wrong.host.badssl.com/"))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
props.setProperty("jdk.internal.httpclient.disableHostnameVerification", Boolean.FALSE.toString());
|
||||
|
||||
Assertions.assertEquals(200, response.statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMockTrustManager_whenByPassCertificateVerification_thenSuccessHttpResponse() throws IOException, InterruptedException, NoSuchAlgorithmException, KeyManagementException, URISyntaxException {
|
||||
SSLContext sslContext = SSLContext.getInstance("SSL"); // OR TLS
|
||||
sslContext.init(null, new TrustManager[]{ MOCK_TRUST_MANAGER }, new SecureRandom());
|
||||
HttpClient httpClient = HttpClient.newBuilder().sslContext(sslContext).build();
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://wrong.host.badssl.com/"))
|
||||
.build();
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
Assertions.assertEquals(200, response.statusCode());
|
||||
}
|
||||
|
||||
|
||||
private static final TrustManager MOCK_TRUST_MANAGER = new X509ExtendedTrustManager() {
|
||||
@Override
|
||||
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
|
||||
return new java.security.cert.X509Certificate[0];
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) {
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@
|
||||
<mainClass>org.openjdk.jmh.Main</mainClass>
|
||||
</transformer>
|
||||
<transformer
|
||||
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
|
||||
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
|
||||
</transformers>
|
||||
<filters>
|
||||
<filter>
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
## Relevant Articles
|
||||
- [Scoped Values in Java 20](https://www.baeldung.com/java-20-scoped-values)
|
||||
- [How to Read Zip Files Entries With Java](https://www.baeldung.com/java-read-zip-files)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.convertpaths;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.file.FileSystems;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
public class RelativePathConverter {
|
||||
|
||||
public static String convertToAbsoluteUsePathsClass(String relativePath) {
|
||||
Path absolutePath = Paths.get(relativePath).toAbsolutePath();
|
||||
return absolutePath.toString();
|
||||
}
|
||||
|
||||
public static String convertToAbsoluteUseFileClass(String relativePath) {
|
||||
File file = new File(relativePath);
|
||||
return file.getAbsolutePath();
|
||||
}
|
||||
|
||||
public static String convertToAbsoluteUseFileSystemsClass(String relativePath) {
|
||||
Path absolutePath = FileSystems.getDefault().getPath(relativePath).toAbsolutePath();
|
||||
return absolutePath.toString();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String relativePath = "myFolder/myFile.txt";
|
||||
String absolutePath = convertToAbsoluteUseFileSystemsClass(relativePath);
|
||||
System.out.println("Absolute Path: " + absolutePath);
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.convertpaths;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RelativePathConverterUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenRelativePath_whenConvertingToAbsolutePath_thenPrintOutput() {
|
||||
String relativePath = "data/sample.txt";
|
||||
|
||||
System.out.println(RelativePathConverter.convertToAbsoluteUsePathsClass(relativePath));
|
||||
System.out.println(RelativePathConverter.convertToAbsoluteUseFileClass(relativePath));
|
||||
System.out.println(RelativePathConverter.convertToAbsoluteUseFileSystemsClass(relativePath));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePath_whenConvertingToAbsolutePath_thenPrintOutput() {
|
||||
String absolutePath = "/var/www/index.html";
|
||||
|
||||
System.out.println(RelativePathConverter.convertToAbsoluteUsePathsClass(absolutePath));
|
||||
System.out.println(RelativePathConverter.convertToAbsoluteUseFileClass(absolutePath));
|
||||
System.out.println(RelativePathConverter.convertToAbsoluteUseFileSystemsClass(absolutePath));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyPath_whenConvertingToAbsolutePath_thenPrintOutput() {
|
||||
String emptyPath = "";
|
||||
|
||||
System.out.println(RelativePathConverter.convertToAbsoluteUsePathsClass(emptyPath));
|
||||
System.out.println(RelativePathConverter.convertToAbsoluteUseFileClass(emptyPath));
|
||||
System.out.println(RelativePathConverter.convertToAbsoluteUseFileSystemsClass(emptyPath));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenParentDirectoryPath_whenConvertingToAbsolutePath_thenPrintOutput() {
|
||||
String relativePath = "../data/sample.txt";
|
||||
|
||||
System.out.println(RelativePathConverter.convertToAbsoluteUsePathsClass(relativePath));
|
||||
System.out.println(RelativePathConverter.convertToAbsoluteUseFileClass(relativePath));
|
||||
System.out.println(RelativePathConverter.convertToAbsoluteUseFileSystemsClass(relativePath));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRelativePathContainingDots_whenConvertingToAbsolutePath_thenPrintOutput() {
|
||||
String relativePath = "././data/sample.txt";
|
||||
|
||||
System.out.println(RelativePathConverter.convertToAbsoluteUsePathsClass(relativePath));
|
||||
System.out.println(RelativePathConverter.convertToAbsoluteUseFileClass(relativePath));
|
||||
System.out.println(RelativePathConverter.convertToAbsoluteUseFileSystemsClass(relativePath));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -7,7 +7,7 @@ import java.net.URISyntaxException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
public class ZipEntryReaderTest {
|
||||
public class ZipEntryReaderUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenZipFile_thenReadEntriesAndValidateContent() throws URISyntaxException, IOException {
|
||||
@@ -1,55 +1,55 @@
|
||||
<?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>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>core-java-9-jigsaw</artifactId>
|
||||
<version>0.2-SNAPSHOT</version>
|
||||
</parent>
|
||||
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>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>core-java-9-jigsaw</artifactId>
|
||||
<version>0.2-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>library-core</artifactId>
|
||||
<artifactId>library-core</artifactId>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>19</maven.compiler.source>
|
||||
<maven.compiler.target>19</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
<properties>
|
||||
<maven.compiler.source>19</maven.compiler.source>
|
||||
<maven.compiler.target>19</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>5.9.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>5.9.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>5.9.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>5.9.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<configuration>
|
||||
<release>9</release>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.0.0-M5</version>
|
||||
<configuration>
|
||||
<useModulePath>false</useModulePath>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<configuration>
|
||||
<release>9</release>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.0.0-M5</version>
|
||||
<configuration>
|
||||
<useModulePath>false</useModulePath>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -1,7 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-collections-5</artifactId>
|
||||
<name>core-java-collections-5</name>
|
||||
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package com.baeldung.convertlisttoarray;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.primitives.Longs;
|
||||
|
||||
public class LongListToLongArrayConversionUnitTest {
|
||||
|
||||
private List<Long> list;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
list = Arrays.asList(1L, 2L, 3L, 4L, 5L);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenALongList_whenConvertWithListToArray_thenReturnLongArray() {
|
||||
|
||||
// Init an array with the same size as the list to convert
|
||||
Long[] arrayWithSettedSize = new Long[list.size()];
|
||||
arrayWithSettedSize = list.toArray(arrayWithSettedSize);
|
||||
assertTrue(list.size() == arrayWithSettedSize.length);
|
||||
|
||||
// Init an empty array
|
||||
Long[] arrayWithNoSettedSize = new Long[0];
|
||||
arrayWithNoSettedSize = list.toArray(arrayWithNoSettedSize);
|
||||
assertTrue(list.size() == arrayWithNoSettedSize.length);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenALongList_whenConvertWithLongsToArray_thenReturnLongArray() {
|
||||
// Convertion using Guava library Longs.toArray() method
|
||||
long[] array = Longs.toArray(list);
|
||||
assertTrue(compareListWithArray(list, array));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenALongList_whenConvertWithStreamMapToLong_thenReturnLongArray() {
|
||||
// Using mapToLong() - lambda expression
|
||||
long[] arrayUsingLambda = list.stream()
|
||||
.mapToLong(l -> l)
|
||||
.toArray();
|
||||
assertTrue(compareListWithArray(list, arrayUsingLambda));
|
||||
|
||||
// Using mapToLong() - method reference
|
||||
long[] arrayUsingMethodReference = list.stream()
|
||||
.mapToLong(Long::longValue)
|
||||
.toArray();
|
||||
assertTrue(compareListWithArray(list, arrayUsingMethodReference));
|
||||
}
|
||||
|
||||
public static boolean compareListWithArray(List<Long> list, long[] array) {
|
||||
// Check if the sizes of the array and list are equal
|
||||
if (array.length != list.size()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Compare each element of the array with the corresponding element in the list
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
// Convert Long to long for comparison
|
||||
if (array[i] != list.get(i)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user