Merge branch 'master' into master
This commit is contained in:
commit
c55d386498
|
@ -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();
|
||||
}
|
||||
|
|
|
@ -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();
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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());
|
||||
|
|
|
@ -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,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();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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 {
|
||||
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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,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)
|
||||
|
|
|
@ -6,3 +6,4 @@
|
|||
- [Using a Mutex Object in Java](https://www.baeldung.com/java-mutex)
|
||||
- [Testing Multi-Threaded Code in Java](https://www.baeldung.com/java-testing-multithreaded)
|
||||
- [How to Check if All Runnables Are Done](https://www.baeldung.com/java-runnables-check-status)
|
||||
- [Parallelize for Loop in Java](https://www.baeldung.com/java-for-loop-parallel)
|
||||
|
|
|
@ -8,4 +8,5 @@ This module contains articles about basic Java concurrency.
|
|||
- [Thread.sleep() vs Awaitility.await()](https://www.baeldung.com/java-thread-sleep-vs-awaitility-await)
|
||||
- [Is CompletableFuture Non-blocking?](https://www.baeldung.com/java-completablefuture-non-blocking)
|
||||
- [Returning a Value After Finishing Thread’s Job in Java](https://www.baeldung.com/java-return-value-after-thread-finish)
|
||||
- [CompletableFuture and ThreadPool in Java](https://www.baeldung.com/java-completablefuture-threadpool)
|
||||
- [[<-- Prev]](../core-java-concurrency-basic-2)
|
||||
|
|
|
@ -8,4 +8,5 @@ This module contains articles about date operations in Java.
|
|||
- [How to Determine Date of the First Day of the Week Using LocalDate in Java](https://www.baeldung.com/java-first-day-of-the-week)
|
||||
- [Adding One Month to Current Date in Java](https://www.baeldung.com/java-adding-one-month-to-current-date)
|
||||
- [How to Get Last Day of a Month in Java](https://www.baeldung.com/java-last-day-month)
|
||||
- [Getting Yesterday’s Date in Java](https://www.baeldung.com/java-find-yesterdays-date)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-date-operations-2)
|
||||
|
|
|
@ -4,13 +4,5 @@ This module contains articles about core Java input/output(IO) APIs.
|
|||
|
||||
### Relevant Articles:
|
||||
- [Constructing a Relative Path From Two Absolute Paths in Java](https://www.baeldung.com/java-relative-path-absolute)
|
||||
- [Java Scanner Taking a Character Input](https://www.baeldung.com/java-scanner-character-input)
|
||||
- [Get the Desktop Path in Java](https://www.baeldung.com/java-desktop-path)
|
||||
- [Integer.parseInt(scanner.nextLine()) and scanner.nextInt() in Java](https://www.baeldung.com/java-scanner-integer)
|
||||
- [Difference Between FileReader and BufferedReader in Java](https://www.baeldung.com/java-filereader-vs-bufferedreader)
|
||||
- [Java: Read Multiple Inputs on Same Line](https://www.baeldung.com/java-read-multiple-inputs-same-line)
|
||||
- [Storing Java Scanner Input in an Array](https://www.baeldung.com/java-store-scanner-input-in-array)
|
||||
- [How to Take Input as String With Spaces in Java Using Scanner?](https://www.baeldung.com/java-scanner-input-with-spaces)
|
||||
- [Write Console Output to Text File in Java](https://www.baeldung.com/java-write-console-output-file)
|
||||
- [What’s the Difference between Scanner next() and nextLine() Methods?](https://www.baeldung.com/java-scanner-next-vs-nextline)
|
||||
- [Handle NoSuchElementException When Reading a File Through Scanner](https://www.baeldung.com/java-scanner-nosuchelementexception-reading-file)
|
||||
- [Check if a File Is Empty in Java](https://www.baeldung.com/java-check-file-empty)
|
|
@ -92,12 +92,6 @@
|
|||
<version>7.1.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testng</groupId>
|
||||
<artifactId>testng</artifactId>
|
||||
<version>7.5</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<finalName>core-java-io-apis-2</finalName>
|
||||
|
|
|
@ -0,0 +1,71 @@
|
|||
package com.baeldung.emptyfile;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.NoSuchFileException;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class CheckFileIsEmptyUnitTest {
|
||||
@Test
|
||||
void whenTheFileIsEmpty_thenFileLengthIsZero(@TempDir Path tempDir) throws IOException {
|
||||
File emptyFile = tempDir.resolve("an-empty-file.txt")
|
||||
.toFile();
|
||||
emptyFile.createNewFile();
|
||||
assertTrue(emptyFile.exists());
|
||||
assertEquals(0, emptyFile.length());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenFileDoesNotExist_thenFileLengthIsZero(@TempDir Path tempDir) {
|
||||
File aNewFile = tempDir.resolve("a-new-file.txt")
|
||||
.toFile();
|
||||
assertFalse(aNewFile.exists());
|
||||
assertEquals(0, aNewFile.length());
|
||||
}
|
||||
|
||||
boolean isFileEmpty(File file) {
|
||||
if (!file.exists()) {
|
||||
throw new IllegalArgumentException("Cannot check the file length. The file is not found: " + file.getAbsolutePath());
|
||||
}
|
||||
return file.length() == 0;
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTheFileDoesNotExist_thenIsFilesEmptyThrowsException(@TempDir Path tempDir) {
|
||||
File aNewFile = tempDir.resolve("a-new-file.txt")
|
||||
.toFile();
|
||||
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> isFileEmpty(aNewFile));
|
||||
assertEquals(ex.getMessage(), "Cannot check the file length. The file is not found: " + aNewFile.getAbsolutePath());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTheFileIsEmpty_thenIsFilesEmptyReturnsTrue(@TempDir Path tempDir) throws IOException {
|
||||
File emptyFile = tempDir.resolve("an-empty-file.txt")
|
||||
.toFile();
|
||||
emptyFile.createNewFile();
|
||||
assertTrue(isFileEmpty(emptyFile));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTheFileIsEmpty_thenFilesSizeReturnsTrue(@TempDir Path tempDir) throws IOException {
|
||||
Path emptyFilePath = tempDir.resolve("an-empty-file.txt");
|
||||
Files.createFile(emptyFilePath);
|
||||
assertEquals(0, Files.size(emptyFilePath));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTheFileDoesNotExist_thenFilesSizeThrowsException(@TempDir Path tempDir) {
|
||||
Path aNewFilePath = tempDir.resolve("a-new-file.txt");
|
||||
assertThrows(NoSuchFileException.class, () -> Files.size(aNewFilePath));
|
||||
}
|
||||
}
|
|
@ -1,6 +0,0 @@
|
|||
## Core Java IO APIs
|
||||
|
||||
This module contains articles about core Java input/output(IO) APIs.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Read Date in Java Using Scanner](https://www.baeldung.com/java-scanner-read-date)
|
|
@ -1,15 +0,0 @@
|
|||
<?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">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-io-apis-3</artifactId>
|
||||
<name>core-java-io-apis-3</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
</project>
|
|
@ -10,6 +10,6 @@ This module contains articles about core Java input/output(IO) APIs.
|
|||
- [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](https://www.baeldung.com/java-path)
|
||||
- [Quick Use of FilenameFilter](https://www.baeldung.com/java-filename-filter)
|
||||
- [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader)
|
||||
- [Java Scanner](https://www.baeldung.com/java-scanner)
|
||||
- [Scanner nextLine() Method](https://www.baeldung.com/java-scanner-nextline)
|
||||
- [Java Scanner hasNext() vs. hasNextLine()](https://www.baeldung.com/java-scanner-hasnext-vs-hasnextline)
|
||||
- [Difference Between FileReader and BufferedReader in Java](https://www.baeldung.com/java-filereader-vs-bufferedreader)
|
||||
- [Java: Read Multiple Inputs on Same Line](https://www.baeldung.com/java-read-multiple-inputs-same-line)
|
||||
- [Write Console Output to Text File in Java](https://www.baeldung.com/java-write-console-output-file)
|
|
@ -31,6 +31,12 @@
|
|||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testng</groupId>
|
||||
<artifactId>testng</artifactId>
|
||||
<version>7.5</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
|
|
@ -1,36 +1,36 @@
|
|||
package com.baeldung.multinput;
|
||||
|
||||
import java.util.InputMismatchException;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class MultiInputs {
|
||||
public void UsingSpaceDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
System.out.print("Enter two numbers: ");
|
||||
int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2);
|
||||
|
||||
}
|
||||
public void UsingREDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
scanner.useDelimiter("[\\s,]+");
|
||||
System.out.print("Enter two numbers separated by a space or a comma: ");
|
||||
int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2);
|
||||
|
||||
}
|
||||
public void UsingCustomDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
scanner.useDelimiter(";");
|
||||
System.out.print("Enter two numbers separated by a semicolon: ");
|
||||
try { int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2); }
|
||||
catch (InputMismatchException e)
|
||||
{ System.out.println("Invalid input. Please enter two integers separated by a semicolon."); }
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
package com.baeldung.multinput;
|
||||
|
||||
import java.util.InputMismatchException;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class MultiInputs {
|
||||
public void UsingSpaceDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
System.out.print("Enter two numbers: ");
|
||||
int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2);
|
||||
|
||||
}
|
||||
public void UsingREDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
scanner.useDelimiter("[\\s,]+");
|
||||
System.out.print("Enter two numbers separated by a space or a comma: ");
|
||||
int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2);
|
||||
|
||||
}
|
||||
public void UsingCustomDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
scanner.useDelimiter(";");
|
||||
System.out.print("Enter two numbers separated by a semicolon: ");
|
||||
try { int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2); }
|
||||
catch (InputMismatchException e)
|
||||
{ System.out.println("Invalid input. Please enter two integers separated by a semicolon."); }
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -1,36 +1,36 @@
|
|||
package com.baeldung.bufferedreadervsfilereader;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class BufferedReaderUnitTest {
|
||||
|
||||
@Test
|
||||
void whenReadingAFile_thenReadsLineByLine() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
final Path filePath = new File("src/test/resources/sampleText1.txt").toPath();
|
||||
try (BufferedReader br = new BufferedReader(new InputStreamReader(Files.newInputStream(filePath), StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
|
||||
while((line = br.readLine()) != null) {
|
||||
result.append(line);
|
||||
result.append('\n');
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
assertEquals("first line\nsecond line\nthird line\n", result.toString());
|
||||
}
|
||||
|
||||
}
|
||||
package com.baeldung.bufferedreadervsfilereader;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class BufferedReaderUnitTest {
|
||||
|
||||
@Test
|
||||
void whenReadingAFile_thenReadsLineByLine() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
final Path filePath = new File("src/test/resources/sampleText1.txt").toPath();
|
||||
try (BufferedReader br = new BufferedReader(new InputStreamReader(Files.newInputStream(filePath), StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
|
||||
while((line = br.readLine()) != null) {
|
||||
result.append(line);
|
||||
result.append('\n');
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
assertEquals("first line\nsecond line\nthird line\n", result.toString());
|
||||
}
|
||||
|
||||
}
|
|
@ -1,30 +1,30 @@
|
|||
package com.baeldung.bufferedreadervsfilereader;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class FileReaderUnitTest {
|
||||
|
||||
@Test
|
||||
void whenReadingAFile_thenReadsCharByChar() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
try (FileReader fr = new FileReader("src/test/resources/sampleText2.txt")) {
|
||||
int i = fr.read();
|
||||
|
||||
while(i != -1) {
|
||||
result.append((char)i);
|
||||
|
||||
i = fr.read();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
assertEquals("qwerty", result.toString());
|
||||
}
|
||||
}
|
||||
package com.baeldung.bufferedreadervsfilereader;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class FileReaderUnitTest {
|
||||
|
||||
@Test
|
||||
void whenReadingAFile_thenReadsCharByChar() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
try (FileReader fr = new FileReader("src/test/resources/sampleText2.txt")) {
|
||||
int i = fr.read();
|
||||
|
||||
while(i != -1) {
|
||||
result.append((char)i);
|
||||
|
||||
i = fr.read();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
assertEquals("qwerty", result.toString());
|
||||
}
|
||||
}
|
|
@ -1,47 +1,49 @@
|
|||
package com.baeldung.multinput;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.util.InputMismatchException;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.testng.annotations.Test;
|
||||
import com.baeldung.multinput.MultiInputs;
|
||||
public class TestMultipleInputsUnitTest {
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingSpaceDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "10 20\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingSpaceDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingREDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "30, 40\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingREDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingCustomDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "50; 60\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingCustomDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidInput_whenUsingSpaceDelimiter_thenExpectInputMismatchException() {
|
||||
String input = "abc\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
Assertions.assertThrows(InputMismatchException.class, mi::UsingSpaceDelimiter);
|
||||
}
|
||||
}
|
||||
package com.baeldung.multinput;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.util.InputMismatchException;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
public class TestMultipleInputsUnitTest {
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingSpaceDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "10 20\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingSpaceDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingREDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "30, 40\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingREDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingCustomDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "50; 60\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingCustomDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidInput_whenUsingSpaceDelimiter_thenExpectInputMismatchException() {
|
||||
String input = "abc\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
Assertions.assertThrows(InputMismatchException.class, mi::UsingSpaceDelimiter);
|
||||
}
|
||||
}
|
|
@ -4,7 +4,7 @@ This module contains articles about JAR files
|
|||
|
||||
### Relevant Articles:
|
||||
|
||||
- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven)
|
||||
- [How to Create an Executable JAR with Maven](https://www.baeldung.com/executable-jar-with-maven)
|
||||
- [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class)
|
||||
- [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar)
|
||||
- [Get Names of Classes Inside a JAR File](https://www.baeldung.com/jar-file-get-class-names)
|
||||
|
|
|
@ -0,0 +1,7 @@
|
|||
## Core Java Lang (Part 6)
|
||||
|
||||
This module contains articles about core features in the Java language
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Convert One Enum to Another Enum in Java](https://www.baeldung.com/java-convert-enums)
|
|
@ -0,0 +1,52 @@
|
|||
<?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">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>core-java-lang-6</artifactId>
|
||||
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct -->
|
||||
<dependency>
|
||||
<groupId>org.mapstruct</groupId>
|
||||
<artifactId>mapstruct</artifactId>
|
||||
<version>${mapstruct.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.5.1</version>
|
||||
<configuration>
|
||||
<source>17</source>
|
||||
<target>17</target>
|
||||
<annotationProcessorPaths>
|
||||
<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct-processor -->
|
||||
<path>
|
||||
<groupId>org.mapstruct</groupId>
|
||||
<artifactId>mapstruct-processor</artifactId>
|
||||
<version>${mapstruct.version}</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<mapstruct.version>1.5.5.Final</mapstruct.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.enums.mapping;
|
||||
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.MappingConstants;
|
||||
import org.mapstruct.ValueMapping;
|
||||
|
||||
import com.baeldung.enums.mapping.order.CmsOrderStatus;
|
||||
import com.baeldung.enums.mapping.order.OrderStatus;
|
||||
import com.baeldung.enums.mapping.user.ExternalUserStatus;
|
||||
import com.baeldung.enums.mapping.user.UserStatus;
|
||||
|
||||
@Mapper
|
||||
public interface EnumMapper {
|
||||
|
||||
CmsOrderStatus map(OrderStatus orderStatus);
|
||||
|
||||
@ValueMapping(source = "PENDING", target = "INACTIVE")
|
||||
@ValueMapping(source = "BLOCKED", target = "INACTIVE")
|
||||
@ValueMapping(source = "INACTIVATED_BY_SYSTEM", target = "INACTIVE")
|
||||
@ValueMapping(source = "DELETED", target = "INACTIVE")
|
||||
ExternalUserStatus map(UserStatus userStatus);
|
||||
|
||||
@ValueMapping(source = MappingConstants.ANY_REMAINING, target = "INACTIVE")
|
||||
ExternalUserStatus mapDefault(UserStatus userStatus);
|
||||
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.enums.mapping.order;
|
||||
|
||||
public enum CmsOrderStatus {
|
||||
PENDING, APPROVED, PACKED, DELIVERED
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.enums.mapping.order;
|
||||
|
||||
public enum OrderStatus {
|
||||
PENDING, APPROVED, PACKED, DELIVERED;
|
||||
|
||||
public CmsOrderStatus toCmsOrderStatus() {
|
||||
return CmsOrderStatus.valueOf(this.name());
|
||||
}
|
||||
|
||||
public CmsOrderStatus toCmsOrderStatusOrdinal() {
|
||||
return CmsOrderStatus.values()[this.ordinal()];
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.enums.mapping.user;
|
||||
|
||||
public enum ExternalUserStatus {
|
||||
ACTIVE, INACTIVE
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.enums.mapping.user;
|
||||
|
||||
public enum UserStatus {
|
||||
PENDING, ACTIVE, BLOCKED, INACTIVATED_BY_SYSTEM, DELETED;
|
||||
|
||||
public ExternalUserStatus toExternalUserStatusViaSwitchStatement() {
|
||||
return switch (this) {
|
||||
case PENDING, BLOCKED, INACTIVATED_BY_SYSTEM, DELETED -> ExternalUserStatus.INACTIVE;
|
||||
case ACTIVE -> ExternalUserStatus.ACTIVE;
|
||||
};
|
||||
}
|
||||
|
||||
public ExternalUserStatus toExternalUserStatusViaRegularSwitch() {
|
||||
switch (this) {
|
||||
case PENDING:
|
||||
case BLOCKED:
|
||||
case INACTIVATED_BY_SYSTEM:
|
||||
case DELETED:
|
||||
return ExternalUserStatus.INACTIVE;
|
||||
case ACTIVE:
|
||||
return ExternalUserStatus.ACTIVE;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.enums.mapping.user;
|
||||
|
||||
import java.util.EnumMap;
|
||||
|
||||
public class UserStatusMapper {
|
||||
public static EnumMap<UserStatus, ExternalUserStatus> statusesMap;
|
||||
|
||||
static {
|
||||
statusesMap = new EnumMap<>(UserStatus.class);
|
||||
statusesMap.put(UserStatus.PENDING, ExternalUserStatus.INACTIVE);
|
||||
statusesMap.put(UserStatus.BLOCKED, ExternalUserStatus.INACTIVE);
|
||||
statusesMap.put(UserStatus.DELETED, ExternalUserStatus.INACTIVE);
|
||||
statusesMap.put(UserStatus.INACTIVATED_BY_SYSTEM, ExternalUserStatus.INACTIVE);
|
||||
statusesMap.put(UserStatus.ACTIVE, ExternalUserStatus.ACTIVE);
|
||||
}
|
||||
|
||||
public static ExternalUserStatus toExternalUserStatus(UserStatus userStatus) {
|
||||
return statusesMap.get(userStatus);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.enums.mapping.user;
|
||||
|
||||
public enum UserStatusWithFieldVariable {
|
||||
PENDING(ExternalUserStatus.INACTIVE),
|
||||
ACTIVE(ExternalUserStatus.ACTIVE),
|
||||
BLOCKED(ExternalUserStatus.INACTIVE),
|
||||
INACTIVATED_BY_SYSTEM(ExternalUserStatus.INACTIVE),
|
||||
DELETED(ExternalUserStatus.INACTIVE);
|
||||
|
||||
private final ExternalUserStatus externalUserStatus;
|
||||
|
||||
UserStatusWithFieldVariable(ExternalUserStatus externalUserStatus) {
|
||||
this.externalUserStatus = externalUserStatus;
|
||||
}
|
||||
|
||||
public ExternalUserStatus toExternalUserStatus() {
|
||||
return externalUserStatus;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,120 @@
|
|||
package com.baeldung.enums.mapping;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.baeldung.enums.mapping.order.CmsOrderStatus;
|
||||
import com.baeldung.enums.mapping.order.OrderStatus;
|
||||
import com.baeldung.enums.mapping.user.ExternalUserStatus;
|
||||
import com.baeldung.enums.mapping.user.UserStatus;
|
||||
import com.baeldung.enums.mapping.user.UserStatusMapper;
|
||||
import com.baeldung.enums.mapping.user.UserStatusWithFieldVariable;
|
||||
|
||||
public class EnumConversionUnitTest {
|
||||
|
||||
@Test
|
||||
void whenUsingSwitchStatement_thenEnumConverted() {
|
||||
UserStatus userStatusDeleted = UserStatus.DELETED;
|
||||
UserStatus userStatusPending = UserStatus.PENDING;
|
||||
UserStatus userStatusActive = UserStatus.ACTIVE;
|
||||
|
||||
assertEquals(ExternalUserStatus.INACTIVE, userStatusDeleted.toExternalUserStatusViaSwitchStatement());
|
||||
assertEquals(ExternalUserStatus.INACTIVE, userStatusPending.toExternalUserStatusViaSwitchStatement());
|
||||
assertEquals(ExternalUserStatus.ACTIVE, userStatusActive.toExternalUserStatusViaSwitchStatement());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingSwitch_thenEnumConverted() {
|
||||
UserStatus userStatusDeleted = UserStatus.DELETED;
|
||||
UserStatus userStatusPending = UserStatus.PENDING;
|
||||
UserStatus userStatusActive = UserStatus.ACTIVE;
|
||||
|
||||
assertEquals(ExternalUserStatus.INACTIVE, userStatusDeleted.toExternalUserStatusViaRegularSwitch());
|
||||
assertEquals(ExternalUserStatus.INACTIVE, userStatusPending.toExternalUserStatusViaRegularSwitch());
|
||||
assertEquals(ExternalUserStatus.ACTIVE, userStatusActive.toExternalUserStatusViaRegularSwitch());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingFieldVariable_thenEnumConverted() {
|
||||
UserStatusWithFieldVariable userStatusDeleted = UserStatusWithFieldVariable.DELETED;
|
||||
UserStatusWithFieldVariable userStatusPending = UserStatusWithFieldVariable.PENDING;
|
||||
UserStatusWithFieldVariable userStatusActive = UserStatusWithFieldVariable.ACTIVE;
|
||||
|
||||
assertEquals(ExternalUserStatus.INACTIVE, userStatusDeleted.toExternalUserStatus());
|
||||
assertEquals(ExternalUserStatus.INACTIVE, userStatusPending.toExternalUserStatus());
|
||||
assertEquals(ExternalUserStatus.ACTIVE, userStatusActive.toExternalUserStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingEnumMap_thenEnumConverted() {
|
||||
UserStatus userStatusDeleted = UserStatus.DELETED;
|
||||
UserStatus userStatusPending = UserStatus.PENDING;
|
||||
UserStatus userStatusActive = UserStatus.ACTIVE;
|
||||
|
||||
assertEquals(ExternalUserStatus.INACTIVE, UserStatusMapper.toExternalUserStatus(userStatusDeleted));
|
||||
assertEquals(ExternalUserStatus.INACTIVE, UserStatusMapper.toExternalUserStatus(userStatusPending));
|
||||
assertEquals(ExternalUserStatus.ACTIVE, UserStatusMapper.toExternalUserStatus(userStatusActive));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingOrdinalApproach_thenEnumConverted() {
|
||||
OrderStatus orderStatusApproved = OrderStatus.APPROVED;
|
||||
OrderStatus orderStatusDelivered = OrderStatus.DELIVERED;
|
||||
OrderStatus orderStatusPending = OrderStatus.PENDING;
|
||||
|
||||
assertEquals(CmsOrderStatus.APPROVED, orderStatusApproved.toCmsOrderStatusOrdinal());
|
||||
assertEquals(CmsOrderStatus.DELIVERED, orderStatusDelivered.toCmsOrderStatusOrdinal());
|
||||
assertEquals(CmsOrderStatus.PENDING, orderStatusPending.toCmsOrderStatusOrdinal());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingEnumName_thenEnumConverted() {
|
||||
OrderStatus orderStatusApproved = OrderStatus.APPROVED;
|
||||
OrderStatus orderStatusDelivered = OrderStatus.DELIVERED;
|
||||
OrderStatus orderStatusPending = OrderStatus.PENDING;
|
||||
|
||||
assertEquals(CmsOrderStatus.APPROVED, orderStatusApproved.toCmsOrderStatus());
|
||||
assertEquals(CmsOrderStatus.DELIVERED, orderStatusDelivered.toCmsOrderStatus());
|
||||
assertEquals(CmsOrderStatus.PENDING, orderStatusPending.toCmsOrderStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingDefaultMapstruct_thenEnumConverted() {
|
||||
UserStatus userStatusDeleted = UserStatus.DELETED;
|
||||
UserStatus userStatusPending = UserStatus.PENDING;
|
||||
UserStatus userStatusActive = UserStatus.ACTIVE;
|
||||
|
||||
EnumMapper enumMapper = new EnumMapperImpl();
|
||||
|
||||
assertEquals(ExternalUserStatus.INACTIVE, enumMapper.map(userStatusDeleted));
|
||||
assertEquals(ExternalUserStatus.INACTIVE, enumMapper.map(userStatusPending));
|
||||
assertEquals(ExternalUserStatus.ACTIVE, enumMapper.map(userStatusActive));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingConfiguredMapstruct_thenEnumConverted() {
|
||||
OrderStatus orderStatusApproved = OrderStatus.APPROVED;
|
||||
OrderStatus orderStatusDelivered = OrderStatus.DELIVERED;
|
||||
OrderStatus orderStatusPending = OrderStatus.PENDING;
|
||||
|
||||
EnumMapper enumMapper = new EnumMapperImpl();
|
||||
|
||||
assertEquals(CmsOrderStatus.APPROVED, enumMapper.map(orderStatusApproved));
|
||||
assertEquals(CmsOrderStatus.DELIVERED, enumMapper.map(orderStatusDelivered));
|
||||
assertEquals(CmsOrderStatus.PENDING, enumMapper.map(orderStatusPending));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingConfiguredWithRemainingMapstruct_thenEnumConverted() {
|
||||
UserStatus userStatusDeleted = UserStatus.DELETED;
|
||||
UserStatus userStatusPending = UserStatus.PENDING;
|
||||
UserStatus userStatusActive = UserStatus.ACTIVE;
|
||||
|
||||
EnumMapper enumMapper = new EnumMapperImpl();
|
||||
|
||||
assertEquals(ExternalUserStatus.INACTIVE, enumMapper.mapDefault(userStatusDeleted));
|
||||
assertEquals(ExternalUserStatus.INACTIVE, enumMapper.mapDefault(userStatusPending));
|
||||
assertEquals(ExternalUserStatus.ACTIVE, enumMapper.mapDefault(userStatusActive));
|
||||
}
|
||||
}
|
|
@ -9,3 +9,4 @@ This module contains articles about Object-oriented programming (OOP) patterns i
|
|||
- [How to Make a Deep Copy of an Object in Java](https://www.baeldung.com/java-deep-copy)
|
||||
- [Using an Interface vs. Abstract Class in Java](https://www.baeldung.com/java-interface-vs-abstract-class)
|
||||
- [Should We Create an Interface for Only One Implementation?](https://www.baeldung.com/java-interface-single-implementation)
|
||||
- [How to Deep Copy an ArrayList in Java](https://www.baeldung.com/java-arraylist-deep-copy)
|
||||
|
|
|
@ -65,6 +65,7 @@ public class NioVsNio2UnitTest {
|
|||
public void listFilesUsingWalk() throws Exception {
|
||||
Path path = Paths.get("src/test");
|
||||
Stream<Path> walk = Files.walk(path);
|
||||
walk.forEach(System.out::println);
|
||||
|
||||
assertThat(walk.findAny()).isPresent();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +1,6 @@
|
|||
### Relevant Articles:
|
||||
- [Java Program to Estimate Pi](https://www.baeldung.com/java-monte-carlo-compute-pi)
|
||||
- [Convert Integer to Hexadecimal in Java](https://www.baeldung.com/java-convert-int-to-hex)
|
||||
- [Integer.class Vs. Integer.TYPE Vs. int.class](https://www.baeldung.com/java-integer-class-vs-type-vs-int)
|
||||
- [Does Java Read Integers in Little Endian or Big Endian?](https://www.baeldung.com/java-integers-little-big-endian)
|
||||
- More articles: [[<-- prev]](../core-java-numbers-5)
|
||||
|
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.endianness;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
public class Endianness {
|
||||
|
||||
public static void main(String[] args) {
|
||||
int value = 123456789;
|
||||
byte[] bytes = ByteBuffer.allocate(4)
|
||||
.putInt(value)
|
||||
.array();
|
||||
|
||||
for (byte b : bytes) {
|
||||
System.out.format("0x%x ", b);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.integerclassintegertypeintclass;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
|
||||
public class IntegerClassIntegerTYPEIntClassUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenIntegerClass_whenGetName_thenVerifyClassName() {
|
||||
Class<Integer> integerClass = Integer.class;
|
||||
Assertions.assertEquals("java.lang.Integer", integerClass.getName());
|
||||
Assertions.assertEquals(Number.class, integerClass.getSuperclass());
|
||||
Assertions.assertFalse(integerClass.isPrimitive());
|
||||
}
|
||||
|
||||
public int sum(int a, int b) {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
public int sum(Integer a, Integer b) {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
public int sum(int a, Integer b) {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntAndInteger_whenAddingValues_thenVerifySum() {
|
||||
int primitiveValue = 10;
|
||||
Integer wrapperValue = Integer.valueOf(primitiveValue);
|
||||
Assertions.assertEquals(20, sum(primitiveValue, primitiveValue));
|
||||
Assertions.assertEquals(20, sum(primitiveValue, wrapperValue));
|
||||
Assertions.assertEquals(20, sum(wrapperValue, wrapperValue));
|
||||
Assertions.assertEquals(Integer.TYPE.getName(), int.class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntValue_whenUsingIntClass_thenVerifyIntClassProperties() {
|
||||
Class<?> intClass = int.class;
|
||||
Assertions.assertEquals("int", intClass.getName());
|
||||
Assertions.assertTrue(intClass.isPrimitive());
|
||||
Assertions.assertEquals(int.class, intClass);
|
||||
}
|
||||
}
|
|
@ -1,2 +1,3 @@
|
|||
### Relevant Articles:
|
||||
- [Convert a Number to a Letter in Java](https://www.baeldung.com/java-convert-number-to-letter)
|
||||
- [Convert Long to BigDecimal in Java](https://www.baeldung.com/java-convert-long-bigdecimal)
|
||||
|
|
|
@ -0,0 +1,15 @@
|
|||
## Core Java Scanner
|
||||
|
||||
This module contains articles about the Scanner.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Java Scanner](https://www.baeldung.com/java-scanner)
|
||||
- [Scanner nextLine() Method](https://www.baeldung.com/java-scanner-nextline)
|
||||
- [Java Scanner hasNext() vs. hasNextLine()](https://www.baeldung.com/java-scanner-hasnext-vs-hasnextline)
|
||||
- [Read Date in Java Using Scanner](https://www.baeldung.com/java-scanner-read-date)
|
||||
- [Java Scanner Taking a Character Input](https://www.baeldung.com/java-scanner-character-input)
|
||||
- [Integer.parseInt(scanner.nextLine()) and scanner.nextInt() in Java](https://www.baeldung.com/java-scanner-integer)
|
||||
- [Storing Java Scanner Input in an Array](https://www.baeldung.com/java-store-scanner-input-in-array)
|
||||
- [How to Take Input as String With Spaces in Java Using Scanner?](https://www.baeldung.com/java-scanner-input-with-spaces)
|
||||
- [What’s the difference between Scanner next() and nextLine() methods?](https://www.baeldung.com/java-scanner-next-vs-nextline)
|
||||
- [Handle NoSuchElementException When Reading a File Through Scanner](https://www.baeldung.com/java-scanner-nosuchelementexception-reading-file)
|
|
@ -0,0 +1,34 @@
|
|||
<?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">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-scanner</artifactId>
|
||||
<name>core-java-scanner</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
|
@ -1,29 +1,29 @@
|
|||
package com.baeldung.scanner;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Date;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class DateScanner {
|
||||
|
||||
LocalDate scanToLocalDate(String input) {
|
||||
try (Scanner scanner = new Scanner(input)) {
|
||||
String dateString = scanner.next();
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
return LocalDate.parse(dateString, formatter);
|
||||
}
|
||||
}
|
||||
|
||||
Date scanToDate(String input) throws ParseException {
|
||||
try (Scanner scanner = new Scanner(input)) {
|
||||
String dateString = scanner.next();
|
||||
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
|
||||
return formatter.parse(dateString);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
package com.baeldung.scanner;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Date;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class DateScanner {
|
||||
|
||||
LocalDate scanToLocalDate(String input) {
|
||||
try (Scanner scanner = new Scanner(input)) {
|
||||
String dateString = scanner.next();
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
return LocalDate.parse(dateString, formatter);
|
||||
}
|
||||
}
|
||||
|
||||
Date scanToDate(String input) throws ParseException {
|
||||
try (Scanner scanner = new Scanner(input)) {
|
||||
String dateString = scanner.next();
|
||||
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
|
||||
return formatter.parse(dateString);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,26 +1,26 @@
|
|||
package com.baeldung.scanner;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class DateScannerUnitTest {
|
||||
|
||||
@Test
|
||||
void whenScanToLocalDate_ThenCorrectLocalDate() {
|
||||
String dateString = "2018-09-09";
|
||||
assertEquals(LocalDate.parse(dateString, DateTimeFormatter.ofPattern("yyyy-MM-dd")), new DateScanner().scanToLocalDate(dateString));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenScanToDate_ThenCorrectDate() throws ParseException {
|
||||
String dateString = "2018-09-09";
|
||||
assertEquals(new SimpleDateFormat("yyyy-MM-dd").parse(dateString), new DateScanner().scanToDate(dateString));
|
||||
}
|
||||
|
||||
}
|
||||
package com.baeldung.scanner;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class DateScannerUnitTest {
|
||||
|
||||
@Test
|
||||
void whenScanToLocalDate_ThenCorrectLocalDate() {
|
||||
String dateString = "2018-09-09";
|
||||
assertEquals(LocalDate.parse(dateString, DateTimeFormatter.ofPattern("yyyy-MM-dd")), new DateScanner().scanToLocalDate(dateString));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenScanToDate_ThenCorrectDate() throws ParseException {
|
||||
String dateString = "2018-09-09";
|
||||
assertEquals(new SimpleDateFormat("yyyy-MM-dd").parse(dateString), new DateScanner().scanToDate(dateString));
|
||||
}
|
||||
|
||||
}
|
|
@ -1,85 +1,85 @@
|
|||
package com.baeldung.scanner;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import java.util.InputMismatchException;
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class NextLineVsNextIntUnitTest {
|
||||
|
||||
@Test
|
||||
void whenInputLineIsNumber_thenNextLineAndNextIntBothWork() {
|
||||
String input = "42\n";
|
||||
|
||||
//nextLine()
|
||||
Scanner sc1 = new Scanner(input);
|
||||
int num1 = Integer.parseInt(sc1.nextLine());
|
||||
assertEquals(42, num1);
|
||||
|
||||
//nextInt()
|
||||
Scanner sc2 = new Scanner(input);
|
||||
int num2 = sc2.nextInt();
|
||||
assertEquals(42, num2);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenInputIsNotValidNumber_thenNextLineAndNextIntThrowDifferentException() {
|
||||
String input = "Nan\n";
|
||||
|
||||
//nextLine() -> NumberFormatException
|
||||
Scanner sc1 = new Scanner(input);
|
||||
assertThrows(NumberFormatException.class, () -> Integer.parseInt(sc1.nextLine()));
|
||||
|
||||
//nextInt() -> InputMismatchException
|
||||
Scanner sc2 = new Scanner(input);
|
||||
assertThrows(InputMismatchException.class, sc2::nextInt);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingNextInt_thenTheNextTokenAfterItFailsToParseIsNotConsumed() {
|
||||
String input = "42 is a magic number\n";
|
||||
|
||||
//nextInt() to read '42'
|
||||
Scanner sc2 = new Scanner(input);
|
||||
int num2 = sc2.nextInt();
|
||||
assertEquals(42, num2);
|
||||
|
||||
// call nextInt() again on "is"
|
||||
assertThrows(InputMismatchException.class, sc2::nextInt);
|
||||
|
||||
String theNextToken = sc2.next();
|
||||
assertEquals("is", theNextToken);
|
||||
|
||||
theNextToken = sc2.next();
|
||||
assertEquals("a", theNextToken);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenReadingTwoInputLines_thenNextLineAndNextIntBehaveDifferently() {
|
||||
|
||||
String input = new StringBuilder().append("42\n")
|
||||
.append("It is a magic number.\n")
|
||||
.toString();
|
||||
|
||||
//nextLine()
|
||||
Scanner sc1 = new Scanner(input);
|
||||
int num1 = Integer.parseInt(sc1.nextLine());
|
||||
String nextLineText1 = sc1.nextLine();
|
||||
assertEquals(42, num1);
|
||||
assertEquals("It is a magic number.", nextLineText1);
|
||||
|
||||
//nextInt()
|
||||
Scanner sc2 = new Scanner(input);
|
||||
int num2 = sc2.nextInt();
|
||||
assertEquals(42, num2);
|
||||
|
||||
// nextInt() leaves the newline character (\n) behind
|
||||
String nextLineText2 = sc2.nextLine();
|
||||
assertEquals("", nextLineText2);
|
||||
}
|
||||
|
||||
package com.baeldung.scanner;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import java.util.InputMismatchException;
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class NextLineVsNextIntUnitTest {
|
||||
|
||||
@Test
|
||||
void whenInputLineIsNumber_thenNextLineAndNextIntBothWork() {
|
||||
String input = "42\n";
|
||||
|
||||
//nextLine()
|
||||
Scanner sc1 = new Scanner(input);
|
||||
int num1 = Integer.parseInt(sc1.nextLine());
|
||||
assertEquals(42, num1);
|
||||
|
||||
//nextInt()
|
||||
Scanner sc2 = new Scanner(input);
|
||||
int num2 = sc2.nextInt();
|
||||
assertEquals(42, num2);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenInputIsNotValidNumber_thenNextLineAndNextIntThrowDifferentException() {
|
||||
String input = "Nan\n";
|
||||
|
||||
//nextLine() -> NumberFormatException
|
||||
Scanner sc1 = new Scanner(input);
|
||||
assertThrows(NumberFormatException.class, () -> Integer.parseInt(sc1.nextLine()));
|
||||
|
||||
//nextInt() -> InputMismatchException
|
||||
Scanner sc2 = new Scanner(input);
|
||||
assertThrows(InputMismatchException.class, sc2::nextInt);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingNextInt_thenTheNextTokenAfterItFailsToParseIsNotConsumed() {
|
||||
String input = "42 is a magic number\n";
|
||||
|
||||
//nextInt() to read '42'
|
||||
Scanner sc2 = new Scanner(input);
|
||||
int num2 = sc2.nextInt();
|
||||
assertEquals(42, num2);
|
||||
|
||||
// call nextInt() again on "is"
|
||||
assertThrows(InputMismatchException.class, sc2::nextInt);
|
||||
|
||||
String theNextToken = sc2.next();
|
||||
assertEquals("is", theNextToken);
|
||||
|
||||
theNextToken = sc2.next();
|
||||
assertEquals("a", theNextToken);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenReadingTwoInputLines_thenNextLineAndNextIntBehaveDifferently() {
|
||||
|
||||
String input = new StringBuilder().append("42\n")
|
||||
.append("It is a magic number.\n")
|
||||
.toString();
|
||||
|
||||
//nextLine()
|
||||
Scanner sc1 = new Scanner(input);
|
||||
int num1 = Integer.parseInt(sc1.nextLine());
|
||||
String nextLineText1 = sc1.nextLine();
|
||||
assertEquals(42, num1);
|
||||
assertEquals("It is a magic number.", nextLineText1);
|
||||
|
||||
//nextInt()
|
||||
Scanner sc2 = new Scanner(input);
|
||||
int num2 = sc2.nextInt();
|
||||
assertEquals(42, num2);
|
||||
|
||||
// nextInt() leaves the newline character (\n) behind
|
||||
String nextLineText2 = sc2.nextLine();
|
||||
assertEquals("", nextLineText2);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,38 +1,38 @@
|
|||
package com.baeldung.scanner;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class ScanACharacterUnitTest {
|
||||
|
||||
// given - input scanner source, no need to scan from console
|
||||
String input = new StringBuilder().append("abc\n")
|
||||
.append("mno\n")
|
||||
.append("xyz\n")
|
||||
.toString();
|
||||
|
||||
@Test
|
||||
public void givenInputSource_whenScanCharUsingNext_thenOneCharIsRead() {
|
||||
Scanner sc = new Scanner(input);
|
||||
char c = sc.next().charAt(0);
|
||||
assertEquals('a', c);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInputSource_whenScanCharUsingFindInLine_thenOneCharIsRead() {
|
||||
Scanner sc = new Scanner(input);
|
||||
char c = sc.findInLine(".").charAt(0);
|
||||
assertEquals('a', c);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInputSource_whenScanCharUsingUseDelimiter_thenOneCharIsRead() {
|
||||
Scanner sc = new Scanner(input);
|
||||
char c = sc.useDelimiter("").next().charAt(0);
|
||||
assertEquals('a', c);
|
||||
}
|
||||
|
||||
}
|
||||
package com.baeldung.scanner;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class ScanACharacterUnitTest {
|
||||
|
||||
// given - input scanner source, no need to scan from console
|
||||
String input = new StringBuilder().append("abc\n")
|
||||
.append("mno\n")
|
||||
.append("xyz\n")
|
||||
.toString();
|
||||
|
||||
@Test
|
||||
public void givenInputSource_whenScanCharUsingNext_thenOneCharIsRead() {
|
||||
Scanner sc = new Scanner(input);
|
||||
char c = sc.next().charAt(0);
|
||||
assertEquals('a', c);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInputSource_whenScanCharUsingFindInLine_thenOneCharIsRead() {
|
||||
Scanner sc = new Scanner(input);
|
||||
char c = sc.findInLine(".").charAt(0);
|
||||
assertEquals('a', c);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInputSource_whenScanCharUsingUseDelimiter_thenOneCharIsRead() {
|
||||
Scanner sc = new Scanner(input);
|
||||
char c = sc.useDelimiter("").next().charAt(0);
|
||||
assertEquals('a', c);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,11 +1,11 @@
|
|||
package com.baeldung.scannernextline;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Scanner;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ScannerNextLineUnitTest {
|
||||
|
|
@ -1,57 +1,59 @@
|
|||
package com.baeldung.streams;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static java.util.stream.Collectors.*;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class StreamToImmutableUnitTest {
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class StreamToImmutableUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenUsingCollectingToImmutableSet_thenSuccess() {
|
||||
void whenUsingCollectingToImmutableSet_thenSuccess() {
|
||||
List<String> givenList = Arrays.asList("a", "b", "c");
|
||||
List<String> result = givenList.stream()
|
||||
.collect(collectingAndThen(toSet(), ImmutableList::copyOf));
|
||||
|
||||
System.out.println(result.getClass());
|
||||
assertEquals("com.google.common.collect.RegularImmutableList", result.getClass().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCollectingToUnmodifiableList_thenSuccess() {
|
||||
void whenUsingCollectingToUnmodifiableList_thenSuccess() {
|
||||
List<String> givenList = new ArrayList<>(Arrays.asList("a", "b", "c"));
|
||||
List<String> result = givenList.stream()
|
||||
.collect(collectingAndThen(toList(), Collections::unmodifiableList));
|
||||
|
||||
System.out.println(result.getClass());
|
||||
assertEquals("java.util.Collections$UnmodifiableRandomAccessList", result.getClass().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectToImmutableList_thenSuccess() {
|
||||
void whenCollectToImmutableList_thenSuccess() {
|
||||
List<Integer> list = IntStream.range(0, 9)
|
||||
.boxed()
|
||||
.collect(ImmutableList.toImmutableList());
|
||||
|
||||
System.out.println(list.getClass());
|
||||
assertEquals("com.google.common.collect.RegularImmutableList", list.getClass().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectToMyImmutableListCollector_thenSuccess() {
|
||||
void whenCollectToMyImmutableListCollector_thenSuccess() {
|
||||
List<String> givenList = Arrays.asList("a", "b", "c", "d");
|
||||
List<String> result = givenList.stream()
|
||||
.collect(MyImmutableListCollector.toImmutableList());
|
||||
|
||||
System.out.println(result.getClass());
|
||||
assertEquals("java.util.Collections$UnmodifiableRandomAccessList", result.getClass().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPassingSupplier_thenSuccess() {
|
||||
void whenPassingSupplier_thenSuccess() {
|
||||
List<String> givenList = Arrays.asList("a", "b", "c", "d");
|
||||
List<String> result = givenList.stream()
|
||||
.collect(MyImmutableListCollector.toImmutableList(LinkedList::new));
|
||||
|
||||
System.out.println(result.getClass());
|
||||
assertEquals("java.util.Collections$UnmodifiableList", result.getClass().getName());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -5,4 +5,6 @@
|
|||
- [Check if a String Is All Uppercase or Lowercase in Java](https://www.baeldung.com/java-check-string-uppercase-lowercase)
|
||||
- [Java – Generate Random String](https://www.baeldung.com/java-random-string)
|
||||
- [Fixing “constant string too long” Build Error](https://www.baeldung.com/java-constant-string-too-long-error)
|
||||
- [Compact Strings in Java 9](https://www.baeldung.com/java-9-compact-string)
|
||||
- [Compact Strings in Java 9](https://www.baeldung.com/java-9-compact-string)
|
||||
- [Split a String Into Digit and Non-Digit Substrings](https://www.baeldung.com/java-split-string-digits-letters)
|
||||
- [Check if a String Contains Non-Alphanumeric Characters](https://www.baeldung.com/java-string-test-special-characters)
|
||||
|
|
|
@ -0,0 +1,60 @@
|
|||
package com.baeldung.uniquecharcheck;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class UniqueCharChecker {
|
||||
|
||||
public static boolean checkV1(String str) {
|
||||
char[] chars = str.toUpperCase().toCharArray();
|
||||
for (int i = 0; i < chars.length; i++) {
|
||||
for (int j = i + 1; j < chars.length; j++) {
|
||||
if(chars[i] == chars[j]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean checkV2(String str) {
|
||||
char[] chars = str.toUpperCase().toCharArray();
|
||||
Arrays.sort(chars);
|
||||
for (int i = 0; i < chars.length - 1; i++) {
|
||||
if(chars[i] == chars[i+1]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean checkV3(String str) {
|
||||
char[] chars = str.toUpperCase().toCharArray();
|
||||
Set <Character> set = new HashSet <>();
|
||||
for (char c: chars) {
|
||||
set.add(c);
|
||||
}
|
||||
return set.size() == str.length();
|
||||
}
|
||||
|
||||
public static boolean checkV4(String str) {
|
||||
boolean isUnique = str.toUpperCase().chars()
|
||||
.mapToObj(c -> (char)c)
|
||||
.collect(Collectors.toSet())
|
||||
.size() == str.length();
|
||||
return isUnique;
|
||||
}
|
||||
|
||||
public static boolean checkV5(String str) {
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
String curChar = String.valueOf(str.charAt(i));
|
||||
String remainingStr = str.substring(i+1);
|
||||
if(StringUtils.containsIgnoreCase(remainingStr, curChar)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,92 @@
|
|||
package com.baeldung.uniquecharcheck;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
|
||||
public class UniqueCharCheckerUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenMethCheck1_whenUnique_returnTrue() {
|
||||
String[] sampleStrings = new String[]{"Justfewdi123", "$%&Hibusc", "Hibusc%$#", "მშვნიერ"};
|
||||
final String MSG = "Duplicate found";
|
||||
Arrays.stream(sampleStrings)
|
||||
.forEach(sampleStr -> assertTrue(MSG + " in " + sampleStr, UniqueCharChecker.checkV1(sampleStr)));
|
||||
}
|
||||
@Test
|
||||
public void givenMethCheck2_whenUnique_returnTrue() {
|
||||
String[] sampleStrings = new String[]{"Justfewdi123", "$%&Hibusc", "Hibusc%$#", "მშვნიერ"};
|
||||
final String MSG = "Duplicate found";
|
||||
Arrays.stream(sampleStrings)
|
||||
.forEach(sampleStr -> assertTrue(MSG + " in " + sampleStr, UniqueCharChecker.checkV2(sampleStr)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMethCheck3_whenUnique_returnTrue() {
|
||||
String[] sampleStrings = new String[]{"Justfewdi123", "$%&Hibusc", "Hibusc%$#", "მშვნიერ"};
|
||||
final String MSG = "Duplicate found";
|
||||
Arrays.stream(sampleStrings)
|
||||
.forEach(sampleStr -> assertTrue(MSG + " in " + sampleStr, UniqueCharChecker.checkV3(sampleStr)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMethCheck4_whenUnique_returnTrue() {
|
||||
String[] sampleStrings = new String[]{"Justfewdi123", "$%&Hibusc", "Hibusc%$#", "მშვნიერ"};
|
||||
final String MSG = "Duplicate found";
|
||||
Arrays.stream(sampleStrings)
|
||||
.forEach(sampleStr -> assertTrue(MSG + " in " + sampleStr, UniqueCharChecker.checkV1(sampleStr)));
|
||||
}
|
||||
@Test
|
||||
public void givenMethCheck5_whenUnique_returnTrue() {
|
||||
String[] sampleStrings = new String[]{"Justfewdi123", "$%&Hibusc", "Hibusc%$#", "მშვნიერ"};
|
||||
final String MSG = "Duplicate found";
|
||||
Arrays.stream(sampleStrings)
|
||||
.forEach(sampleStr -> assertTrue(MSG + " in " + sampleStr, UniqueCharChecker.checkV5(sampleStr)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMethCheck1_whenNotUnique_returnFalse() {
|
||||
String[] sampleStrings = new String[]{"Justfewdif123", "$%&Hibushc", "Hibusuc%$#", "Hi%busc%$#", "მშვენიერი"};
|
||||
final String MSG = "Duplicate not found";
|
||||
Arrays.stream(sampleStrings)
|
||||
.forEach(sampleStr -> assertFalse(MSG + " in " + sampleStr, UniqueCharChecker.checkV1(sampleStr)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMethCheck2_whenNotUnique_returnFalse() {
|
||||
String[] sampleStrings = new String[]{"Justfewdif123", "$%&Hibushc", "Hibusuc%$#", "Hi%busc%$#", "მშვენიერი"};
|
||||
final String MSG = "Duplicate not found";
|
||||
Arrays.stream(sampleStrings)
|
||||
.forEach(sampleStr -> assertFalse(MSG + " in " + sampleStr, UniqueCharChecker.checkV2(sampleStr)));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMethCheck3_whenNotUnique_returnFalse() {
|
||||
String[] sampleStrings = new String[]{"Justfewdif123", "$%&Hibushc", "Hibusuc%$#", "Hi%busc%$#", "მშვენიერი"};
|
||||
final String MSG = "Duplicate not found";
|
||||
Arrays.stream(sampleStrings)
|
||||
.forEach(sampleStr -> assertFalse(MSG + " in " + sampleStr, UniqueCharChecker.checkV3(sampleStr)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMethCheck4_whenNotUnique_returnFalse() {
|
||||
String[] sampleStrings = new String[]{"Justfewdif123", "$%&Hibushc", "Hibusuc%$#", "Hi%busc%$#", "მშვენიერი"};
|
||||
final String MSG = "Duplicate not found";
|
||||
Arrays.stream(sampleStrings)
|
||||
.forEach(sampleStr -> assertFalse(MSG + " in " + sampleStr, UniqueCharChecker.checkV4(sampleStr)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMethCheck5_whenNotUnique_returnFalse() {
|
||||
String[] sampleStrings = new String[]{"Justfewdif123", "$%&Hibushc", "Hibusuc%$#", "Hi%busc%$#", "მშვენიერი"};
|
||||
final String MSG = "Duplicate not found";
|
||||
Arrays.stream(sampleStrings)
|
||||
.forEach(sampleStr -> assertFalse(MSG + " in " + sampleStr, UniqueCharChecker.checkV5(sampleStr)));
|
||||
}
|
||||
|
||||
}
|
|
@ -81,7 +81,6 @@
|
|||
<module>core-java-io-4</module>
|
||||
<module>core-java-io-apis</module>
|
||||
<module>core-java-io-apis-2</module>
|
||||
<module>core-java-io-apis-3</module>
|
||||
<module>core-java-io-conversions</module>
|
||||
<module>core-java-jar</module>
|
||||
<module>core-java-jndi</module>
|
||||
|
@ -93,6 +92,7 @@
|
|||
<module>core-java-lang-3</module>
|
||||
<module>core-java-lang-4</module>
|
||||
<module>core-java-lang-5</module>
|
||||
<module>core-java-lang-6</module>
|
||||
<module>core-java-lang-math</module>
|
||||
<module>core-java-lang-math-2</module>
|
||||
<module>core-java-lang-oop-constructors</module>
|
||||
|
@ -124,6 +124,7 @@
|
|||
<module>core-java-properties</module>
|
||||
<module>core-java-reflection</module>
|
||||
<module>core-java-reflection-2</module>
|
||||
<module>core-java-scanner</module>
|
||||
<module>core-java-security-2</module>
|
||||
<module>core-java-security-3</module>
|
||||
<module>core-java-security-algorithms</module>
|
||||
|
|
|
@ -6,3 +6,4 @@
|
|||
- [Different Dependency Version Declarations in Gradle](https://www.baeldung.com/gradle-different-dependency-version-declarations)
|
||||
- [Generating Javadoc With Gradle](https://www.baeldung.com/java-gradle-javadoc)
|
||||
- [Generating WSDL Stubs With Gradle](https://www.baeldung.com/java-gradle-create-wsdl-stubs)
|
||||
- [Gradle Toolchains Support for JVM Projects](https://www.baeldung.com/java-gradle-toolchains-jvm-projects)
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
#
|
||||
# https://help.github.com/articles/dealing-with-line-endings/
|
||||
#
|
||||
# Linux start script should use lf
|
||||
/gradlew text eol=lf
|
||||
|
||||
# These are Windows script files and should use crlf
|
||||
*.bat text eol=crlf
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
# Ignore Gradle project-specific cache directory
|
||||
.gradle
|
||||
|
||||
# Ignore Gradle build output directory
|
||||
build
|
|
@ -0,0 +1,49 @@
|
|||
/*
|
||||
* This file was generated by the Gradle 'init' task.
|
||||
*
|
||||
* This is a general purpose Gradle build.
|
||||
* Learn more about Gradle by exploring our samples at https://docs.gradle.org/8.1.1/samples
|
||||
*/
|
||||
plugins {
|
||||
id 'java'
|
||||
}
|
||||
java {
|
||||
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||
targetCompatibility = JavaVersion.VERSION_1_8
|
||||
}
|
||||
|
||||
tasks {
|
||||
compileTestJava {
|
||||
sourceCompatibility = JavaVersion.VERSION_1_7
|
||||
targetCompatibility = JavaVersion.VERSION_1_7
|
||||
}
|
||||
}
|
||||
|
||||
//compileTestJava.getOptions().setFork(true)
|
||||
//compileTestJava.getOptions().getForkOptions().setExecutable('/home/mpolivaha/.jdks/corretto-17.0.4.1/bin/javac')
|
||||
|
||||
//compileJava.getOptions().setFork(true)
|
||||
//compileJava.getOptions().getForkOptions().setExecutable('/home/mpolivaha/.jdks/corretto-17.0.4.1/bin/javac')
|
||||
|
||||
java {
|
||||
toolchain {
|
||||
languageVersion = JavaLanguageVersion.of(17)
|
||||
vendor = JvmVendorSpec.AMAZON
|
||||
implementation = JvmImplementation.VENDOR_SPECIFIC
|
||||
}
|
||||
}
|
||||
|
||||
tasks.named('compileJava').get().configure {
|
||||
javaCompiler = javaToolchains.compilerFor {
|
||||
languageVersion = JavaLanguageVersion.of(17)
|
||||
vendor = JvmVendorSpec.AMAZON
|
||||
implementation = JvmImplementation.VENDOR_SPECIFIC
|
||||
}
|
||||
}
|
||||
tasks.register("testOnAmazonJdk", Test.class, {
|
||||
javaLauncher = javaToolchains.launcherFor {
|
||||
languageVersion = JavaLanguageVersion.of(17)
|
||||
vendor = JvmVendorSpec.AMAZON
|
||||
}
|
||||
})
|
||||
tasks.named("testClasses").get().finalizedBy("testOnAmazonJdk")
|
6
gradle-modules/gradle-7/toolchains-feature/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
6
gradle-modules/gradle-7/toolchains-feature/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
|
@ -0,0 +1,6 @@
|
|||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip
|
||||
networkTimeout=10000
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
|
@ -0,0 +1,245 @@
|
|||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
|
@ -0,0 +1,92 @@
|
|||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
|
@ -0,0 +1,10 @@
|
|||
/*
|
||||
* This file was generated by the Gradle 'init' task.
|
||||
*
|
||||
* The settings file is used to specify which projects to include in your build.
|
||||
*
|
||||
* Detailed information about configuring a multi-project build in Gradle can be found
|
||||
* in the user manual at https://docs.gradle.org/8.1.1/userguide/multi_project_builds.html
|
||||
*/
|
||||
|
||||
rootProject.name = 'toolchains-feature'
|
|
@ -1,96 +0,0 @@
|
|||
package com.baeldung.jacksonjr;
|
||||
|
||||
import com.fasterxml.jackson.jr.annotationsupport.JacksonAnnotationExtension;
|
||||
import com.fasterxml.jackson.jr.ob.JSON;
|
||||
import com.fasterxml.jackson.jr.ob.JacksonJrExtension;
|
||||
import com.fasterxml.jackson.jr.ob.api.ExtensionContext;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public class JacksonJrFeatures {
|
||||
|
||||
public static String jsonObject() throws IOException {
|
||||
return JSON.std
|
||||
.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
|
||||
.asString(new LinkedHashMap<String, Object>() {{
|
||||
put("name", "John Doe");
|
||||
put("age", 30);
|
||||
}});
|
||||
}
|
||||
|
||||
public static String jsonComposer() throws IOException {
|
||||
return JSON.std
|
||||
.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
|
||||
.composeString()
|
||||
.startObject()
|
||||
.startArrayField("objectArray")
|
||||
.startObject()
|
||||
.put("name", "name1")
|
||||
.put("age", 11)
|
||||
.end()
|
||||
.startObject()
|
||||
.put("name", "name2")
|
||||
.put("age", 12)
|
||||
.end()
|
||||
.end()
|
||||
.startArrayField("array")
|
||||
.add(1)
|
||||
.add(2)
|
||||
.add(3)
|
||||
.end()
|
||||
.startObjectField("object")
|
||||
.put("name", "name3")
|
||||
.put("age", 13)
|
||||
.end()
|
||||
.put("last", true)
|
||||
.end()
|
||||
.finish();
|
||||
}
|
||||
|
||||
public static String objectSerialization(Person person) throws IOException {
|
||||
return JSON.std
|
||||
.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
|
||||
.asString(person);
|
||||
}
|
||||
|
||||
public static String objectAnnotationSerialization(Person person) throws IOException {
|
||||
return JSON.builder()
|
||||
.register(JacksonAnnotationExtension.std)
|
||||
.build()
|
||||
.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
|
||||
.asString(person);
|
||||
}
|
||||
|
||||
public static String customObjectSerialization(Person person) throws IOException {
|
||||
return JSON.builder()
|
||||
.register(new JacksonJrExtension() {
|
||||
@Override
|
||||
protected void register (ExtensionContext extensionContext) {
|
||||
extensionContext.insertProvider(new MyHandlerProvider());
|
||||
}
|
||||
})
|
||||
.build()
|
||||
.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
|
||||
.asString(person);
|
||||
}
|
||||
|
||||
public static Person objectDeserialization(String json) throws IOException {
|
||||
return JSON.std
|
||||
.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
|
||||
.beanFrom(Person.class, json);
|
||||
}
|
||||
|
||||
public static Person customObjectDeserialization(String json) throws IOException {
|
||||
return JSON.builder()
|
||||
.register(new JacksonJrExtension() {
|
||||
@Override
|
||||
protected void register (ExtensionContext extensionContext) {
|
||||
extensionContext.insertProvider(new MyHandlerProvider());
|
||||
}
|
||||
})
|
||||
.build()
|
||||
.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
|
||||
.beanFrom(Person.class, json);
|
||||
}
|
||||
}
|
|
@ -1,13 +1,10 @@
|
|||
package com.baeldung.jackson.defaultvalues;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonSetter;
|
||||
|
||||
public class JsonSetterDefaultValue {
|
||||
public class SetterDefaultValue {
|
||||
|
||||
private String required;
|
||||
private String optional = "valueIfMissingEntirely";
|
||||
|
||||
@JsonSetter("optional")
|
||||
public void setOptional(String optional){
|
||||
if(optional == null){
|
||||
this.optional = "valueIfNull";
|
|
@ -17,10 +17,10 @@ public class DefaultValuesUnitTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void givenAClassWithAJsonSetter_whenReadingJsonWithNullOptionalValue_thenExpectDefaultValueInResult() throws JsonProcessingException {
|
||||
public void givenAClassWithASetter_whenReadingJsonWithNullOptionalValue_thenExpectDefaultValueInResult() throws JsonProcessingException {
|
||||
String nullOptionalField = "{\"required\": \"value\", \"optional\": null}";
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
JsonSetterDefaultValue createdObject = objectMapper.readValue(nullOptionalField, JsonSetterDefaultValue.class);
|
||||
SetterDefaultValue createdObject = objectMapper.readValue(nullOptionalField, SetterDefaultValue.class);
|
||||
assert(createdObject.getRequired()).equals("value");
|
||||
assert(createdObject.getOptional()).equals("valueIfNull");
|
||||
}
|
||||
|
|
|
@ -9,9 +9,8 @@
|
|||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<artifactId>jackson-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@ -35,4 +34,14 @@
|
|||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>jackson-jr</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
</project>
|
|
@ -1,22 +1,22 @@
|
|||
package com.baeldung.jacksonjr;
|
||||
|
||||
import com.fasterxml.jackson.jr.ob.api.ValueReader;
|
||||
import com.fasterxml.jackson.jr.ob.impl.JSONReader;
|
||||
import com.fasterxml.jackson.jr.private_.JsonParser;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
import com.fasterxml.jackson.jr.ob.api.ValueReader;
|
||||
import com.fasterxml.jackson.jr.ob.impl.JSONReader;
|
||||
import com.fasterxml.jackson.jr.private_.JsonParser;
|
||||
|
||||
public class CustomDateDeserializer extends ValueReader {
|
||||
private final static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
|
||||
public CustomDateDeserializer () {
|
||||
public CustomDateDeserializer() {
|
||||
super(LocalDate.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object read (JSONReader jsonReader, JsonParser jsonParser) throws IOException {
|
||||
public Object read(JSONReader jsonReader, JsonParser jsonParser) throws IOException {
|
||||
return LocalDate.parse(jsonParser.getText(), dtf);
|
||||
}
|
||||
}
|
|
@ -1,20 +1,20 @@
|
|||
package com.baeldung.jacksonjr;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDate;
|
||||
|
||||
import com.fasterxml.jackson.jr.ob.api.ValueWriter;
|
||||
import com.fasterxml.jackson.jr.ob.impl.JSONWriter;
|
||||
import com.fasterxml.jackson.jr.private_.JsonGenerator;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDate;
|
||||
|
||||
public class CustomDateSerializer implements ValueWriter {
|
||||
@Override
|
||||
public void writeValue (JSONWriter jsonWriter, JsonGenerator jsonGenerator, Object o) throws IOException {
|
||||
public void writeValue(JSONWriter jsonWriter, JsonGenerator jsonGenerator, Object o) throws IOException {
|
||||
jsonGenerator.writeString(o.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<?> valueType () {
|
||||
public Class<?> valueType() {
|
||||
return LocalDate.class;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,92 @@
|
|||
package com.baeldung.jacksonjr;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
import com.fasterxml.jackson.jr.annotationsupport.JacksonAnnotationExtension;
|
||||
import com.fasterxml.jackson.jr.ob.JSON;
|
||||
import com.fasterxml.jackson.jr.ob.JacksonJrExtension;
|
||||
import com.fasterxml.jackson.jr.ob.api.ExtensionContext;
|
||||
|
||||
public class JacksonJrFeatures {
|
||||
|
||||
public static String jsonObject() throws IOException {
|
||||
return JSON.std.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
|
||||
.asString(new LinkedHashMap<String, Object>() {{
|
||||
put("name", "John Doe");
|
||||
put("age", 30);
|
||||
}});
|
||||
}
|
||||
|
||||
public static String jsonComposer() throws IOException {
|
||||
return JSON.std.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
|
||||
.composeString()
|
||||
.startObject()
|
||||
.startArrayField("objectArray")
|
||||
.startObject()
|
||||
.put("name", "name1")
|
||||
.put("age", 11)
|
||||
.end()
|
||||
.startObject()
|
||||
.put("name", "name2")
|
||||
.put("age", 12)
|
||||
.end()
|
||||
.end()
|
||||
.startArrayField("array")
|
||||
.add(1)
|
||||
.add(2)
|
||||
.add(3)
|
||||
.end()
|
||||
.startObjectField("object")
|
||||
.put("name", "name3")
|
||||
.put("age", 13)
|
||||
.end()
|
||||
.put("last", true)
|
||||
.end()
|
||||
.finish();
|
||||
}
|
||||
|
||||
public static String objectSerialization(Person person) throws IOException {
|
||||
return JSON.std.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
|
||||
.asString(person);
|
||||
}
|
||||
|
||||
public static String objectAnnotationSerialization(Person person) throws IOException {
|
||||
return JSON.builder()
|
||||
.register(JacksonAnnotationExtension.std)
|
||||
.build()
|
||||
.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
|
||||
.asString(person);
|
||||
}
|
||||
|
||||
public static String customObjectSerialization(Person person) throws IOException {
|
||||
return JSON.builder()
|
||||
.register(new JacksonJrExtension() {
|
||||
@Override
|
||||
protected void register(ExtensionContext extensionContext) {
|
||||
extensionContext.insertProvider(new MyHandlerProvider());
|
||||
}
|
||||
})
|
||||
.build()
|
||||
.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
|
||||
.asString(person);
|
||||
}
|
||||
|
||||
public static Person objectDeserialization(String json) throws IOException {
|
||||
return JSON.std.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
|
||||
.beanFrom(Person.class, json);
|
||||
}
|
||||
|
||||
public static Person customObjectDeserialization(String json) throws IOException {
|
||||
return JSON.builder()
|
||||
.register(new JacksonJrExtension() {
|
||||
@Override
|
||||
protected void register(ExtensionContext extensionContext) {
|
||||
extensionContext.insertProvider(new MyHandlerProvider());
|
||||
}
|
||||
})
|
||||
.build()
|
||||
.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
|
||||
.beanFrom(Person.class, json);
|
||||
}
|
||||
}
|
|
@ -1,17 +1,17 @@
|
|||
package com.baeldung.jacksonjr;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
import com.fasterxml.jackson.jr.ob.api.ReaderWriterProvider;
|
||||
import com.fasterxml.jackson.jr.ob.api.ValueReader;
|
||||
import com.fasterxml.jackson.jr.ob.api.ValueWriter;
|
||||
import com.fasterxml.jackson.jr.ob.impl.JSONReader;
|
||||
import com.fasterxml.jackson.jr.ob.impl.JSONWriter;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
public class MyHandlerProvider extends ReaderWriterProvider {
|
||||
|
||||
@Override
|
||||
public ValueWriter findValueWriter (JSONWriter writeContext, Class<?> type) {
|
||||
public ValueWriter findValueWriter(JSONWriter writeContext, Class<?> type) {
|
||||
if (type == LocalDate.class) {
|
||||
return new CustomDateSerializer();
|
||||
}
|
||||
|
@ -19,7 +19,7 @@ public class MyHandlerProvider extends ReaderWriterProvider {
|
|||
}
|
||||
|
||||
@Override
|
||||
public ValueReader findValueReader (JSONReader readContext, Class<?> type) {
|
||||
public ValueReader findValueReader(JSONReader readContext, Class<?> type) {
|
||||
if (type.equals(LocalDate.class)) {
|
||||
return new CustomDateDeserializer();
|
||||
}
|
|
@ -1,13 +1,13 @@
|
|||
package com.baeldung.jacksonjr;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import java.time.LocalDate;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
|
@ -1,11 +1,13 @@
|
|||
package com.baeldung.jacksonjr;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDate;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class JacksonJrFeaturesUnitTest {
|
||||
|
|
@ -21,6 +21,7 @@
|
|||
<module>jackson-core</module>
|
||||
<module>jackson-custom-conversions</module>
|
||||
<module>jackson-exceptions</module>
|
||||
<module>jackson-jr</module>
|
||||
</modules>
|
||||
|
||||
<dependencies>
|
||||
|
|
|
@ -0,0 +1,57 @@
|
|||
<?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>jeromq</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>jeromq</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.zeromq</groupId>
|
||||
<artifactId>jeromq</artifactId>
|
||||
<version>0.5.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-engine</artifactId>
|
||||
<version>${junit-platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-console-standalone</artifactId>
|
||||
<version>${junit-platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-migrationsupport</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
<resource>
|
||||
<directory>src/test/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
|
||||
|
|
@ -0,0 +1,256 @@
|
|||
package com.baeldung.jeromq;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.zeromq.SocketType;
|
||||
import org.zeromq.ZContext;
|
||||
import org.zeromq.ZMQ;
|
||||
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class DealerRouterLiveTest {
|
||||
@Test
|
||||
public void single() throws Exception {
|
||||
Thread brokerThread = new Thread(() -> {
|
||||
try (ZContext context = new ZContext()) {
|
||||
|
||||
ZMQ.Socket broker = context.createSocket(SocketType.ROUTER);
|
||||
broker.bind("tcp://*:5555");
|
||||
|
||||
String identity = broker.recvStr();
|
||||
System.out.println(Thread.currentThread().getName() + " - Received identity " + identity);
|
||||
|
||||
broker.recv(0); // Envelope delimiter
|
||||
System.out.println(Thread.currentThread().getName() + " - Received envelope");
|
||||
String message = broker.recvStr(0); // Response from worker
|
||||
System.out.println(Thread.currentThread().getName() + " - Received message " + message);
|
||||
|
||||
broker.sendMore(identity);
|
||||
broker.sendMore("xxx");
|
||||
broker.send("Hello back");
|
||||
}
|
||||
});
|
||||
brokerThread.setName("broker");
|
||||
|
||||
Thread workerThread = new Thread(() -> {
|
||||
try (ZContext context = new ZContext()) {
|
||||
ZMQ.Socket worker = context.createSocket(SocketType.DEALER);
|
||||
worker.setIdentity(Thread.currentThread().getName().getBytes(ZMQ.CHARSET));
|
||||
|
||||
worker.connect("tcp://localhost:5555");
|
||||
System.out.println(Thread.currentThread().getName() + " - Connected");
|
||||
|
||||
worker.sendMore("");
|
||||
worker.send("Hello " + Thread.currentThread().getName());
|
||||
System.out.println(Thread.currentThread().getName() + " - Sent Hello");
|
||||
|
||||
worker.recvStr(); // Envelope delimiter
|
||||
System.out.println(Thread.currentThread().getName() + " - Received Envelope");
|
||||
String workload = worker.recvStr();
|
||||
System.out.println(Thread.currentThread().getName() + " - Received " + workload);
|
||||
}
|
||||
});
|
||||
workerThread.setName("worker");
|
||||
|
||||
brokerThread.start();
|
||||
workerThread.start();
|
||||
|
||||
workerThread.join();
|
||||
brokerThread.join();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void asynchronous() throws Exception {
|
||||
Thread brokerThread = new Thread(() -> {
|
||||
try (ZContext context = new ZContext()) {
|
||||
|
||||
ZMQ.Socket broker = context.createSocket(SocketType.ROUTER);
|
||||
broker.bind("tcp://*:5555");
|
||||
|
||||
while (true) {
|
||||
String identity = broker.recvStr(ZMQ.DONTWAIT);
|
||||
System.out.println(Thread.currentThread().getName() + " - Received identity " + identity);
|
||||
|
||||
if (identity == null) {
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e) {}
|
||||
} else {
|
||||
|
||||
broker.recv(0); // Envelope delimiter
|
||||
System.out.println(Thread.currentThread().getName() + " - Received envelope");
|
||||
String message = broker.recvStr(0); // Response from worker
|
||||
System.out.println(Thread.currentThread().getName() + " - Received message " + message);
|
||||
|
||||
broker.sendMore(identity);
|
||||
broker.sendMore("xxx");
|
||||
broker.send("Hello back");
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
brokerThread.setName("broker");
|
||||
|
||||
Thread workerThread = new Thread(() -> {
|
||||
try (ZContext context = new ZContext()) {
|
||||
ZMQ.Socket worker = context.createSocket(SocketType.DEALER);
|
||||
worker.setIdentity(Thread.currentThread().getName().getBytes(ZMQ.CHARSET));
|
||||
|
||||
worker.connect("tcp://localhost:5555");
|
||||
System.out.println(Thread.currentThread().getName() + " - Connected");
|
||||
|
||||
worker.sendMore("");
|
||||
worker.send("Hello " + Thread.currentThread().getName());
|
||||
System.out.println(Thread.currentThread().getName() + " - Sent Hello");
|
||||
|
||||
worker.recvStr(); // Envelope delimiter
|
||||
System.out.println(Thread.currentThread().getName() + " - Received Envelope");
|
||||
String workload = worker.recvStr();
|
||||
System.out.println(Thread.currentThread().getName() + " - Received " + workload);
|
||||
}
|
||||
});
|
||||
workerThread.setName("worker");
|
||||
|
||||
brokerThread.start();
|
||||
workerThread.start();
|
||||
|
||||
workerThread.join();
|
||||
brokerThread.join();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void many() throws Exception {
|
||||
Thread brokerThread = new Thread(() -> {
|
||||
try (ZContext context = new ZContext()) {
|
||||
|
||||
ZMQ.Socket broker = context.createSocket(SocketType.ROUTER);
|
||||
broker.bind("tcp://*:5555");
|
||||
|
||||
while (!Thread.currentThread().isInterrupted()) {
|
||||
String identity = broker.recvStr();
|
||||
System.out.println(Thread.currentThread().getName() + " - Received identity " + identity);
|
||||
|
||||
broker.recv(0); // Envelope delimiter
|
||||
String message = broker.recvStr(0); // Response from worker
|
||||
System.out.println(Thread.currentThread().getName() + " - Received message " + message);
|
||||
|
||||
broker.sendMore(identity);
|
||||
broker.sendMore("");
|
||||
broker.send("Hello back to " + identity);
|
||||
}
|
||||
}
|
||||
});
|
||||
brokerThread.setName("broker");
|
||||
|
||||
Set<Thread> workers = IntStream.range(0, 10)
|
||||
.mapToObj(index -> {
|
||||
Thread workerThread = new Thread(() -> {
|
||||
try (ZContext context = new ZContext()) {
|
||||
ZMQ.Socket worker = context.createSocket(SocketType.DEALER);
|
||||
worker.setIdentity(Thread.currentThread().getName().getBytes(ZMQ.CHARSET));
|
||||
|
||||
worker.connect("tcp://localhost:5555");
|
||||
System.out.println(Thread.currentThread().getName() + " - Connected");
|
||||
|
||||
worker.sendMore("");
|
||||
worker.send("Hello " + Thread.currentThread().getName());
|
||||
System.out.println(Thread.currentThread().getName() + " - Sent Hello");
|
||||
|
||||
worker.recvStr(); // Envelope delimiter
|
||||
String workload = worker.recvStr();
|
||||
System.out.println(Thread.currentThread().getName() + " - Received " + workload);
|
||||
}
|
||||
});
|
||||
workerThread.setName("worker-" + index);
|
||||
|
||||
return workerThread;
|
||||
})
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
brokerThread.start();
|
||||
workers.forEach(Thread::start);
|
||||
|
||||
for (Thread worker : workers) {
|
||||
worker.join();
|
||||
}
|
||||
brokerThread.interrupt();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void threaded() throws Exception {
|
||||
Thread brokerThread = new Thread(() -> {
|
||||
try (ZContext context = new ZContext()) {
|
||||
|
||||
ZMQ.Socket broker = context.createSocket(SocketType.ROUTER);
|
||||
broker.bind("tcp://*:5555");
|
||||
|
||||
ExecutorService threadPool = Executors.newFixedThreadPool(5);
|
||||
Random rng = new Random();
|
||||
|
||||
while (!Thread.currentThread().isInterrupted()) {
|
||||
String identity = broker.recvStr();
|
||||
System.out.println(Thread.currentThread().getName() + " - Received identity " + identity);
|
||||
|
||||
broker.recv(0); // Envelope delimiter
|
||||
String message = broker.recvStr(0); // Response from worker
|
||||
System.out.println(Thread.currentThread().getName() + " - Received message " + message);
|
||||
|
||||
threadPool.submit(() -> {
|
||||
try {
|
||||
Thread.sleep(rng.nextInt(1000) + 1000 );
|
||||
} catch (Exception e) {}
|
||||
|
||||
synchronized(broker) {
|
||||
broker.sendMore(identity);
|
||||
broker.sendMore("");
|
||||
broker.send("Hello back to " + identity + " from " + Thread.currentThread().getName());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
threadPool.shutdown();
|
||||
}
|
||||
});
|
||||
brokerThread.setName("broker");
|
||||
|
||||
Set<Thread> workers = IntStream.range(0, 10)
|
||||
.mapToObj(index -> {
|
||||
Thread workerThread = new Thread(() -> {
|
||||
try (ZContext context = new ZContext()) {
|
||||
ZMQ.Socket worker = context.createSocket(SocketType.DEALER);
|
||||
worker.setIdentity(Thread.currentThread().getName().getBytes(ZMQ.CHARSET));
|
||||
|
||||
worker.connect("tcp://localhost:5555");
|
||||
System.out.println(Thread.currentThread().getName() + " - Connected");
|
||||
|
||||
worker.sendMore("");
|
||||
worker.send("Hello " + Thread.currentThread().getName());
|
||||
System.out.println(Thread.currentThread().getName() + " - Sent Hello");
|
||||
|
||||
worker.recvStr(); // Envelope delimiter
|
||||
String workload = worker.recvStr();
|
||||
System.out.println(Thread.currentThread().getName() + " - Received " + workload);
|
||||
}
|
||||
});
|
||||
workerThread.setName("worker-" + index);
|
||||
|
||||
return workerThread;
|
||||
})
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
brokerThread.start();
|
||||
workers.forEach(Thread::start);
|
||||
|
||||
for (Thread worker : workers) {
|
||||
worker.join();
|
||||
}
|
||||
brokerThread.interrupt();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,101 @@
|
|||
package com.baeldung.jeromq;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.zeromq.SocketType;
|
||||
import org.zeromq.ZContext;
|
||||
import org.zeromq.ZMQ;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class PubSubLiveTest {
|
||||
@Test
|
||||
public void singleSub() throws Exception {
|
||||
Thread server = new Thread(() -> {
|
||||
try (ZContext context = new ZContext()) {
|
||||
ZMQ.Socket pub = context.createSocket(SocketType.PUB);
|
||||
pub.bind("tcp://*:5555");
|
||||
|
||||
try {
|
||||
Thread.sleep(3000);
|
||||
} catch (InterruptedException e) {}
|
||||
|
||||
System.out.println(Thread.currentThread().getName() + " - Sending");
|
||||
pub.send("Hello");
|
||||
}
|
||||
});
|
||||
server.setName("server");
|
||||
|
||||
Thread client = new Thread(() -> {
|
||||
try (ZContext context = new ZContext()) {
|
||||
ZMQ.Socket sub = context.createSocket(SocketType.SUB);
|
||||
sub.connect("tcp://localhost:5555");
|
||||
System.out.println(Thread.currentThread().getName() + " - Connected");
|
||||
|
||||
sub.subscribe("".getBytes());
|
||||
System.out.println(Thread.currentThread().getName() + " - Subscribed");
|
||||
|
||||
String message = sub.recvStr();
|
||||
System.out.println(Thread.currentThread().getName() + " - " + message);
|
||||
}
|
||||
});
|
||||
client.setName("client");
|
||||
|
||||
server.start();
|
||||
client.start();
|
||||
|
||||
client.join();
|
||||
server.join();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void manySub() throws Exception {
|
||||
Thread server = new Thread(() -> {
|
||||
try (ZContext context = new ZContext()) {
|
||||
ZMQ.Socket pub = context.createSocket(SocketType.PUB);
|
||||
pub.bind("tcp://*:5555");
|
||||
|
||||
try {
|
||||
Thread.sleep(3000);
|
||||
} catch (InterruptedException e) {}
|
||||
|
||||
System.out.println(Thread.currentThread().getName() + " - Sending");
|
||||
pub.send("Hello");
|
||||
}
|
||||
});
|
||||
server.setName("server");
|
||||
|
||||
Set<Thread> clients = IntStream.range(0, 10)
|
||||
.mapToObj(index -> {
|
||||
Thread client = new Thread(() -> {
|
||||
try (ZContext context = new ZContext()) {
|
||||
ZMQ.Socket sub = context.createSocket(SocketType.SUB);
|
||||
sub.connect("tcp://localhost:5555");
|
||||
System.out.println(Thread.currentThread().getName() + " - Connected");
|
||||
|
||||
sub.subscribe("".getBytes());
|
||||
System.out.println(Thread.currentThread().getName() + " - Subscribed");
|
||||
|
||||
String message = sub.recvStr();
|
||||
System.out.println(Thread.currentThread().getName() + " - " + message);
|
||||
}
|
||||
});
|
||||
client.setName("client-" + index);
|
||||
|
||||
return client;
|
||||
})
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
|
||||
server.start();
|
||||
clients.forEach(Thread::start);
|
||||
|
||||
for (Thread client : clients) {
|
||||
client.join();
|
||||
}
|
||||
|
||||
server.join();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,96 @@
|
|||
package com.baeldung.jeromq;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.zeromq.SocketType;
|
||||
import org.zeromq.ZContext;
|
||||
import org.zeromq.ZMQ;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class RequestResponseLiveTest {
|
||||
@Test
|
||||
public void requestResponse() throws Exception {
|
||||
try (ZContext context = new ZContext()) {
|
||||
Thread server = new Thread(() -> {
|
||||
ZMQ.Socket socket = context.createSocket(SocketType.REP);
|
||||
socket.bind("inproc://test");
|
||||
|
||||
while (!Thread.currentThread().isInterrupted()) {
|
||||
byte[] reply = socket.recv(0);
|
||||
System.out.println("Server Received " + ": [" + new String(reply, ZMQ.CHARSET) + "]");
|
||||
|
||||
String response = new String(reply, ZMQ.CHARSET) + ", world";
|
||||
socket.send(response.getBytes(ZMQ.CHARSET), 0);
|
||||
}
|
||||
});
|
||||
|
||||
Thread client = new Thread(() -> {
|
||||
ZMQ.Socket socket = context.createSocket(SocketType.REQ);
|
||||
socket.connect("inproc://test");
|
||||
|
||||
for (int requestNbr = 0; requestNbr != 10; requestNbr++) {
|
||||
String request = "Hello " + requestNbr;
|
||||
System.out.println("Sending " + request);
|
||||
socket.send(request.getBytes(ZMQ.CHARSET), 0);
|
||||
|
||||
byte[] reply = socket.recv(0);
|
||||
System.out.println("Client Received " + new String(reply, ZMQ.CHARSET));
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
server.start();
|
||||
client.start();
|
||||
|
||||
client.join();
|
||||
server.interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void manyRequestResponse() throws Exception {
|
||||
try (ZContext context = new ZContext()) {
|
||||
Thread server = new Thread(() -> {
|
||||
ZMQ.Socket socket = context.createSocket(SocketType.REP);
|
||||
socket.bind("tcp://*:5555");
|
||||
|
||||
while (!Thread.currentThread().isInterrupted()) {
|
||||
byte[] reply = socket.recv(0);
|
||||
System.out.println("Server Received " + ": [" + new String(reply, ZMQ.CHARSET) + "]");
|
||||
|
||||
String response = new String(reply, ZMQ.CHARSET) + ", world";
|
||||
socket.send(response.getBytes(ZMQ.CHARSET), 0);
|
||||
}
|
||||
});
|
||||
|
||||
Set<Thread> clients = IntStream.range(0, 10).mapToObj(index ->
|
||||
new Thread(() -> {
|
||||
ZMQ.Socket socket = context.createSocket(SocketType.REQ);
|
||||
socket.connect("tcp://localhost:5555");
|
||||
|
||||
for (int requestNbr = 0; requestNbr != 10; requestNbr++) {
|
||||
String request = "Hello " + index + " - " + requestNbr;
|
||||
System.out.println("Sending " + request);
|
||||
socket.send(request.getBytes(ZMQ.CHARSET), 0);
|
||||
|
||||
byte[] reply = socket.recv(0);
|
||||
System.out.println("Client " + index + " Received " + new String(reply, ZMQ.CHARSET));
|
||||
}
|
||||
|
||||
})
|
||||
).collect(Collectors.toSet());
|
||||
|
||||
server.start();
|
||||
clients.forEach(Thread::start);
|
||||
|
||||
for (Thread client : clients) {
|
||||
client.join();
|
||||
}
|
||||
|
||||
server.interrupt();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
|
@ -33,7 +33,7 @@ public class PersonSerializerUnitTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void WhenUseCustomGson_ThenDonotSerializeAccountNumAndPassword () {
|
||||
public void whenUseCustomGson_thenDonotSerializeAccountNumAndPassword () {
|
||||
|
||||
String personJson = PersonSerializer.serializeWithConfiguredGson(person);
|
||||
logger.info(personJson);
|
||||
|
@ -42,7 +42,7 @@ public class PersonSerializerUnitTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void WhenUseDefaultGson_ThenSerializeAccountNumAndPassword () {
|
||||
public void whenUseDefaultGson_thenSerializeAccountNumAndPassword () {
|
||||
|
||||
String personJson = PersonSerializer.serializeWithDefaultGson(person);
|
||||
logger.info(personJson);
|
||||
|
@ -51,7 +51,7 @@ public class PersonSerializerUnitTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void whenUseSerializedAnnotation_ThenUseSerializedNameinJsonString() {
|
||||
public void whenUseSerializedAnnotation_thenUseSerializedNameinJsonString() {
|
||||
String countryJson = PersonSerializer.toJsonString(country);
|
||||
logger.info(countryJson);
|
||||
assertFalse("Test failed: No change in the keys", countryJson.contains("countryName"));
|
||||
|
@ -64,7 +64,7 @@ public class PersonSerializerUnitTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void whenJsonStrCreatedWithCustomKeys_ThenCreateObjUsingGson() {
|
||||
public void whenJsonStrCreatedWithCustomKeys_thenCreateObjUsingGson() {
|
||||
String countryJson = PersonSerializer.toJsonString(country);
|
||||
Country country = PersonSerializer.fromJsonString(countryJson);
|
||||
logger.info(country.toString());
|
||||
|
|
|
@ -11,5 +11,6 @@ This module contains articles about JSON.
|
|||
- [A Guide to FastJson](https://www.baeldung.com/fastjson)
|
||||
- [Check Whether a String Is Valid JSON in Java](https://www.baeldung.com/java-validate-json-string)
|
||||
- [Getting a Value in JSONObject](https://www.baeldung.com/java-jsonobject-get-value)
|
||||
- [Pretty-Print a JSON in Java](https://www.baeldung.com/java-json-pretty-print)
|
||||
- More Articles: [[<-- prev]](/json-modules/json)
|
||||
|
||||
|
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.jsonprettyprinter;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
|
||||
|
||||
/*
|
||||
* Class to print string JSON to well-formatted JSON using Jackson and Gson.
|
||||
*/
|
||||
public class JsonPrettyPrinter {
|
||||
private ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
public String prettyPrintJsonUsingDefaultPrettyPrinter(String uglyJsonString) throws JsonProcessingException {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
Object jsonObject = objectMapper.readValue(uglyJsonString, Object.class);
|
||||
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
|
||||
}
|
||||
|
||||
public String prettyPrintUsingGlobalSetting(String uglyJsonString) throws JsonProcessingException {
|
||||
ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
|
||||
Object jsonObject = mapper.readValue(uglyJsonString, Object.class);
|
||||
return mapper.writeValueAsString(jsonObject);
|
||||
}
|
||||
|
||||
public String prettyPrintUsingGson(String uglyJsonString) {
|
||||
Gson gson = new GsonBuilder().setPrettyPrinting().create();
|
||||
Object jsonObject = gson.fromJson(uglyJsonString, Object.class);
|
||||
return gson.toJson(jsonObject);
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue