Merge branch 'master' into BAEL-6541-convert-relative-path

This commit is contained in:
tienvn 2023-07-08 00:12:28 +07:00
commit b693287519
529 changed files with 8371 additions and 1971 deletions

6
.gitignore vendored
View File

@ -70,6 +70,7 @@ jmeter/src/main/resources/*-JMeter*.csv
jmeter/src/main/resources/*ReportsDashboard*.csv
jmeter/src/main/resources/dashboard/*ReportsDashboard*.csv
jmeter/src/main/resources/*FileExtractionExample.csv
jmeter/src/main/resources/*_Summary-Report.csv
ninja/devDb.mv.db
@ -120,4 +121,7 @@ libraries-2/src/test/resources/crawler4j/**
devDb*.db
#jaxb
*.xjb
*.xjb
#neo4j
persistence-modules/neo4j/data/**

View File

@ -0,0 +1,18 @@
package com.baeldung.httpclient.httpclient;
import java.io.IOException;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
public final class ClientUtil {
private ClientUtil(){}
public static void closeClient(CloseableHttpClient client) throws IOException {
if (client == null) {
return;
}
client.close();
}
}

View File

@ -0,0 +1,211 @@
package com.baeldung.httpclient.httpclient;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.emptyArray;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.config.ConnectionConfig;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.io.BasicHttpClientConnectionManager;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.hc.core5.util.Timeout;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
class HttpClientCookBookLiveTest {
private static final String SAMPLE_GET_URL = "http://www.google.com";
private static final String SAMPLE_POST_URL = "http://www.github.com";
private CloseableHttpClient httpClient;
private CloseableHttpResponse response;
@BeforeEach
public final void before() {
httpClient = HttpClientBuilder.create().build();
}
@AfterEach
public final void after() throws IOException {
ClientUtil.closeClient(httpClient);
}
@Test
void givenGetRequestExecuted_thenCorrectStatusCode() throws IOException {
HttpGet httpGet = new HttpGet(SAMPLE_GET_URL);
httpClient.execute(httpGet,
response -> {
assertThat(response.getCode()).isEqualTo(200);
return response;
}
);
}
@Test
void givenGetRequestExecuted_thenCorrectContentMimeType() throws IOException {
HttpGet httpGet = new HttpGet(SAMPLE_GET_URL);
httpClient.execute(httpGet,
response -> {
final String contentMimeType = ContentType.parse(response.getEntity().getContentType()).getMimeType();
assertThat(contentMimeType).isEqualTo(ContentType.TEXT_HTML.getMimeType());
return response;
}
);
}
@Test
void givenGetRequestExecuted_thenCorrectResponse() throws IOException {
HttpGet httpGet = new HttpGet(SAMPLE_GET_URL);
httpClient.execute(httpGet,
response -> {
String bodyAsString = EntityUtils.toString(response.getEntity());
assertThat(bodyAsString, notNullValue());
return response;
}
);
}
@Test
void whenConfigureTimeoutOnRequest_thenCorrectResponse() throws IOException {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(Timeout.ofMilliseconds(2000L))
.build();
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.build();
HttpGet request = new HttpGet(SAMPLE_GET_URL);
request.setConfig(requestConfig);
httpClient.execute(request,
response -> {
assertThat(response.getCode()).isEqualTo(200);
return response;
}
);
}
@Test
void givenLowSocketTimeOut_whenExecutingRequestWithTimeout_thenException() throws IOException {
ConnectionConfig connConfig = ConnectionConfig.custom()
.setConnectTimeout(1000, TimeUnit.MILLISECONDS)
.setSocketTimeout(20, TimeUnit.MILLISECONDS)
.build();
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(Timeout.ofMilliseconds(2000L))
.build();
BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager();
cm.setConnectionConfig(connConfig);
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(cm)
.build();
HttpGet request = new HttpGet(SAMPLE_GET_URL);
assertThrows(SocketTimeoutException.class, () -> {
httpClient.execute(request, resp -> resp);
});
}
@Test
void whenExecutingPostRequest_thenNoExceptions() throws IOException {
final HttpPost httpPost = new HttpPost(SAMPLE_POST_URL);
httpClient.execute(httpPost,
response -> {
assertThat(response.getCode()).isEqualTo(200);
return response;
}
);
}
@Test
void givenParametersAddedToRequest_thenCorrect() throws IOException {
final HttpPost httpPost = new HttpPost(SAMPLE_POST_URL);
final List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("key1", "value1"));
params.add(new BasicNameValuePair("key2", "value2"));
httpPost.setEntity(new UrlEncodedFormEntity(params, Charset.defaultCharset()));
httpClient.execute(httpPost, response -> {
assertThat(response.getCode()).isEqualTo(200);
return response;
});
}
@Test
void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
CloseableHttpClient client = HttpClientBuilder.create()
.disableRedirectHandling()
.build();
client.execute(new HttpGet("http://t.co/I5YYd9tddw"), response -> {
assertThat(response.getCode()).isEqualTo(301);
return response;
});
}
@Test
void givenHeadersAddedToRequest_thenCorrect() throws IOException {
HttpGet request = new HttpGet(SAMPLE_GET_URL);
request.addHeader(HttpHeaders.ACCEPT, "application/xml");
httpClient.execute(request,
response -> {
assertThat(response.getCode()).isEqualTo(200);
return response;
}
);
}
@Test
void givenRequestWasSet_whenAnalyzingTheHeadersOfTheResponse_thenCorrect() throws IOException {
HttpGet httpGet = new HttpGet(SAMPLE_GET_URL);
httpClient.execute(httpGet,
response -> {
Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
assertThat(headers, not(emptyArray()));
return response;
}
);
}
@Test
void givenAutoClosableClient_thenCorrect() throws IOException {
HttpGet httpGet = new HttpGet(SAMPLE_GET_URL);
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
httpClient.execute(httpGet, resp -> {
assertThat(resp.getCode()).isEqualTo(200);
return resp;
});
}
}
}

View File

@ -9,16 +9,12 @@ import java.util.concurrent.Future;
import javax.net.ssl.SSLContext;
import org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner;
import org.junit.jupiter.api.Test;
import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
import org.apache.hc.client5.http.auth.AuthScope;
import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.cookie.BasicCookieStore;
import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
@ -26,9 +22,9 @@ import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider;
import org.apache.hc.client5.http.impl.cookie.BasicClientCookie;
import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
import org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder;
import org.apache.hc.core5.concurrent.FutureCallback;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
@ -37,6 +33,8 @@ import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.reactor.IOReactorConfig;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.ssl.TrustStrategy;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.junit.jupiter.api.Test;
class HttpAsyncClientLiveTest extends GetRequestMockServer {
@ -56,12 +54,10 @@ class HttpAsyncClientLiveTest extends GetRequestMockServer {
@Test
void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException {
final HttpHost target = new HttpHost(HOST_WITH_COOKIE);
final SimpleHttpRequest request = SimpleRequestBuilder.get()
.setHttpHost(target)
final SimpleHttpRequest request = SimpleRequestBuilder.get(HOST_WITH_COOKIE)
.build();
final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
.build();
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
client.start();
@ -126,6 +122,7 @@ class HttpAsyncClientLiveTest extends GetRequestMockServer {
.build();
final TlsStrategy tlsStrategy = ClientTlsStrategyBuilder.create()
.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
.setSslContext(sslContext)
.build();

View File

@ -0,0 +1,20 @@
package com.baeldung.httpclient;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
public final class ClientUtil {
private ClientUtil(){}
public static void closeClient(CloseableHttpClient client) throws IOException {
if (client == null) {
return;
}
client.close();
}
}

View File

@ -0,0 +1,184 @@
package com.baeldung.httpclient;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.hamcrest.Matchers.emptyArray;
import static org.hamcrest.Matchers.not;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
class HttpClientCookBookV4LiveTest {
private static final String SAMPLE_GET_URL = "http://www.google.com";
private static final String SAMPLE_POST_URL = "http://www.github.com";
private CloseableHttpClient client;
private CloseableHttpResponse response;
@BeforeEach
public final void before() {
client = HttpClientBuilder.create().build();
}
@AfterEach
public final void after() throws IllegalStateException, IOException {
ResponseUtil.closeResponse(response);
ClientUtil.closeClient(client);
}
@Test
void givenGetRequestExecuted_thenCorrectStatusCode() throws IOException {
HttpGet httpGet = new HttpGet(SAMPLE_GET_URL);
response = client.execute(httpGet);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
@Test
void givenGetRequestExecuted_thenCorrectContentMimeType() throws IOException {
CloseableHttpResponse response = client.execute(new HttpGet(SAMPLE_GET_URL));
String contentMimeType = ContentType.getOrDefault(response.getEntity()).getMimeType();
assertThat(contentMimeType, equalTo(ContentType.TEXT_HTML.getMimeType()));
}
@Test
void givenGetRequestExecuted_thenCorrectResponse() throws IOException {
CloseableHttpResponse response = client.execute(new HttpGet(SAMPLE_GET_URL));
String bodyAsString = EntityUtils.toString(response.getEntity());
assertThat(bodyAsString, notNullValue());
}
@Test
void givenLowSocketTimeOut_whenExecutingRequestWithTimeout_thenException() throws IOException {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(1000)
.setConnectTimeout(1000)
.setSocketTimeout(20)
.build();
HttpGet request = new HttpGet(SAMPLE_POST_URL);
request.setConfig(requestConfig);
assertThrows(SocketTimeoutException.class, () -> {
response = client.execute(request);
});
}
@Test
void givenLowSocketTimeOut_whenSettingTimeoutOnTheClient_thenException(){
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(1000)
.setConnectTimeout(1000)
.setSocketTimeout(20).build();
HttpClientBuilder builder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig);
client = builder.build();
HttpGet request = new HttpGet(SAMPLE_GET_URL);
assertThrows(SocketTimeoutException.class, () -> {
response = client.execute(request);
});
}
@Test
void whenExecutingPostRequest_thenNoExceptions() throws IOException {
response = client.execute(new HttpPost(SAMPLE_POST_URL));
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
}
@Test
void givenParametersAddedToRequest_thenCorrect() throws IOException {
final HttpPost httpPost = new HttpPost(SAMPLE_POST_URL);
final List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("key1", "value1"));
params.add(new BasicNameValuePair("key2", "value2"));
httpPost.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
response = client.execute(new HttpPost(SAMPLE_POST_URL));
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
}
@Test
void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
CloseableHttpClient client = HttpClientBuilder.create()
.disableRedirectHandling()
.build();
CloseableHttpResponse response = client.execute(new HttpGet("http://t.co/I5YYd9tddw"));
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
}
@Test
void givenHeadersAddedToRequest_thenCorrect() throws IOException {
HttpGet request = new HttpGet(SAMPLE_GET_URL);
request.addHeader(HttpHeaders.ACCEPT, "application/xml");
response = client.execute(request);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
@Test
void givenRequestWasSet_whenAnalyzingTheHeadersOfTheResponse_thenCorrect() throws IOException {
CloseableHttpResponse response = client.execute(new HttpGet(SAMPLE_GET_URL));
Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
assertThat(headers, not(emptyArray()));
}
@Test
void givenStreamIsClosed_thenCloseResponse() throws IOException {
response = client.execute(new HttpGet(SAMPLE_GET_URL));
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
instream.close();
}
} finally {
response.close();
}
}
@Test
void givenAutoClosableClient_thenCorrect() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet(SAMPLE_GET_URL);
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
// handle response;
HttpEntity entity = response.getEntity();
if (entity != null) {
try (InputStream instream = entity.getContent()) {
// Process the input stream if needed
}
}
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
}
}
}

View File

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

View File

@ -28,7 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@Testcontainers
public class KafaConsumeLastNMessages {
public class KafaConsumeLastNMessagesLiveTest {
private static String TOPIC1 = "baeldung-github";
private static String TOPIC2 = "baeldung-blog";

View File

@ -0,0 +1,83 @@
package com.baeldung.kafka;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.DescribeTopicsResult;
import org.apache.kafka.clients.admin.TopicDescription;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.KafkaFuture;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.serialization.StringSerializer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.KafkaContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ExecutionException;
@Testcontainers
public class KafkaCountPartitionsLiveTest {
@Container
private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest"));
private final static String TOPIC = "baeldung-kafka-github";
private final static Integer PARTITION_NUMBER = 3;
private static KafkaProducer<String, String> producer;
@BeforeAll
static void setup() throws IOException, InterruptedException {
KAFKA_CONTAINER.addExposedPort(9092);
KAFKA_CONTAINER.execInContainer(
"/bin/sh",
"-c",
"/usr/bin/kafka-topics " +
"--bootstrap-server localhost:9092 " +
"--create " +
"--replication-factor 1 " +
"--partitions " + PARTITION_NUMBER + " " +
"--topic " + TOPIC
);
Properties producerProperties = new Properties();
producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
producer = new KafkaProducer<>(producerProperties);
}
@AfterAll
static void destroy() {
KAFKA_CONTAINER.stop();
}
@Test
void testPartitionsForTopic_isEqualToActualNumberAssignedDuringCreation() {
List<PartitionInfo> info = producer.partitionsFor(TOPIC);
Assertions.assertEquals(PARTITION_NUMBER, info.size());
}
@Test
void testTopicPartitionDescription_isEqualToActualNumberAssignedDuringCreation() {
Properties props = new Properties();
props.put("bootstrap.servers", KAFKA_CONTAINER.getBootstrapServers());
props.put("client.id","java-admin-client");
props.put("request.timeout.ms", 3000);
props.put("connections.max.idle.ms", 5000);
try(AdminClient client = AdminClient.create(props)){
DescribeTopicsResult describeTopicsResult = client.describeTopics(Collections.singletonList(TOPIC));
Map<String, KafkaFuture<TopicDescription>> values = describeTopicsResult.values();
KafkaFuture<TopicDescription> topicDescription = values.get(TOPIC);
Assertions.assertEquals(PARTITION_NUMBER, topicDescription.get().partitions().size());
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -0,0 +1,2 @@
## Relevant Articles
- [Listing All AWS S3 Objects in a Bucket Using Java](https://www.baeldung.com/java-aws-s3-list-bucket-objects)

View File

@ -0,0 +1,50 @@
<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>
<groupId>com.baeldung.s3</groupId>
<artifactId>aws-s3-v2</artifactId>
<version>1.0-SNAPSHOT</version>
<name>aws-s3-v2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>aws-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<aws.java.sdk.version>2.20.52</aws.java.sdk.version>
<maven.compiler.plugin.version>3.6.1</maven.compiler.plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>s3</artifactId>
<version>${aws.java.sdk.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,21 @@
package com.baeldung.s3.listobjects;
import java.nio.ByteBuffer;
public class File {
private String name;
private ByteBuffer content;
public File(String name, ByteBuffer content) {
this.name = name;
this.content = content;
}
public String getName() {
return name;
}
public ByteBuffer getContent() {
return content;
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.s3.listobjects;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class FileGenerator {
public static List<File> generateFiles(int fileCount, int fileSize) {
List<File> files = new ArrayList<>();
for (int i = 0; i < fileCount; i++) {
String fileName = "file_" + i + ".txt";
ByteBuffer fileContent = generateRandomBytes(fileSize);
files.add(new File(fileName, fileContent));
}
return files;
}
private static ByteBuffer generateRandomBytes(int size) {
byte[] array = new byte[size];
new Random().nextBytes(array);
return ByteBuffer.wrap(array);
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.s3.listobjects;
import software.amazon.awssdk.regions.Region;
public class Main {
private static String AWS_BUCKET = "baeldung-tutorial-s3";
public static Region AWS_REGION = Region.EU_CENTRAL_1;
public static void main(String[] args) {
S3Service s3Service = new S3Service(AWS_REGION);
s3Service.putObject(AWS_BUCKET, FileGenerator.generateFiles(1000, 1));
s3Service.listBuckets();
s3Service.listObjectsInBucket(AWS_BUCKET);
s3Service.listAllObjectsInBucket(AWS_BUCKET);
s3Service.listAllObjectsInBucketPaginated(AWS_BUCKET, 500);
s3Service.listAllObjectsInBucketPaginatedWithPrefix(AWS_BUCKET, 500, "backup/");
s3Service.cleanup();
}
}

View File

@ -0,0 +1,129 @@
package com.baeldung.s3.listobjects;
import java.util.List;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.*;
import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable;
class S3Service {
private S3Client s3Client;
public S3Service(Region awsRegion) {
init(awsRegion);
}
public S3Service(S3Client s3Client) {
this.s3Client = s3Client;
}
public void init(Region awsRegion) {
this.s3Client = S3Client.builder()
.region(awsRegion)
.credentialsProvider(ProfileCredentialsProvider.create("default"))
.build();
}
public void listObjectsInBucket(String bucketName) {
ListObjectsV2Request listObjectsV2Request = ListObjectsV2Request.builder()
.bucket(bucketName)
.build();
ListObjectsV2Response listObjectsV2Response = s3Client.listObjectsV2(listObjectsV2Request);
List<S3Object> contents = listObjectsV2Response.contents();
System.out.println("Number of objects in the bucket: " + contents.stream().count());
contents.stream().forEach(System.out::println);
}
public void listAllObjectsInBucket(String bucketName) {
String nextContinuationToken = null;
long totalObjects = 0;
do {
ListObjectsV2Request.Builder requestBuilder = ListObjectsV2Request.builder()
.bucket(bucketName)
.continuationToken(nextContinuationToken);
ListObjectsV2Response response = s3Client.listObjectsV2(requestBuilder.build());
nextContinuationToken = response.nextContinuationToken();
totalObjects += response.contents().stream()
.peek(System.out::println)
.reduce(0, (subtotal, element) -> subtotal + 1, Integer::sum);
} while (nextContinuationToken != null);
System.out.println("Number of objects in the bucket: " + totalObjects);
}
public void listAllObjectsInBucketPaginated(String bucketName, int pageSize) {
ListObjectsV2Request listObjectsV2Request = ListObjectsV2Request.builder()
.bucket(bucketName)
.maxKeys(pageSize) // Set the maxKeys parameter to control the page size
.build();
ListObjectsV2Iterable listObjectsV2Iterable = s3Client.listObjectsV2Paginator(listObjectsV2Request);
long totalObjects = 0;
for (ListObjectsV2Response page : listObjectsV2Iterable) {
long retrievedPageSize = page.contents().stream()
.peek(System.out::println)
.reduce(0, (subtotal, element) -> subtotal + 1, Integer::sum);
totalObjects += retrievedPageSize;
System.out.println("Page size: " + retrievedPageSize);
}
System.out.println("Total objects in the bucket: " + totalObjects);
}
public void listAllObjectsInBucketPaginatedWithPrefix(String bucketName, int pageSize, String prefix) {
ListObjectsV2Request listObjectsV2Request = ListObjectsV2Request.builder()
.bucket(bucketName)
.maxKeys(pageSize) // Set the maxKeys parameter to control the page size
.prefix(prefix)
.build();
ListObjectsV2Iterable listObjectsV2Iterable = s3Client.listObjectsV2Paginator(listObjectsV2Request);
long totalObjects = 0;
for (ListObjectsV2Response page : listObjectsV2Iterable) {
long retrievedPageSize = page.contents().stream()
.peek(System.out::println)
.reduce(0, (subtotal, element) -> subtotal + 1, Integer::sum);
totalObjects += retrievedPageSize;
System.out.println("Page size: " + retrievedPageSize);
}
System.out.println("Total objects in the bucket: " + totalObjects);
}
public void listBuckets() {
// List all buckets
ListBucketsResponse listBucketsResponse = s3Client.listBuckets();
// Display the bucket names
List<Bucket> buckets = listBucketsResponse.buckets();
System.out.println("Buckets:");
for (Bucket bucket : buckets) {
System.out.println(bucket.name());
}
}
public void putObject(String bucketName, List<File> files) {
try {
files.stream().forEach(file -> {
s3Client.putObject(PutObjectRequest.builder().bucket(bucketName).key(file.getName()).build(),
RequestBody.fromByteBuffer(file.getContent()));
System.out.println("Uploaded file: " + file.getName());
});
} catch (S3Exception e) {
System.err.println("Upload failed");
e.printStackTrace();
}
}
public void cleanup() {
this.s3Client.close();
}
}

View File

@ -0,0 +1,14 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="info">
<appender-ref ref="STDOUT" />
</root>
<!-- Change the log level for software.amazon.awssdk -->
<logger name="software.amazon.awssdk" level="info" />
</configuration>

View File

@ -0,0 +1,109 @@
package com.baeldung.s3.listobjects;
import com.baeldung.s3.listobjects.S3Service;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.ListBucketsResponse;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
import software.amazon.awssdk.services.s3.model.S3Object;
import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable;
import java.util.Arrays;
import java.util.Collections;
import static org.mockito.Mockito.when;
class S3ServiceLiveTest {
@Mock
private S3Client s3Client;
private S3Service s3Service;
private String AWS_BUCKET = "baeldung-tutorial-s3";
@BeforeEach
public void setup() {
MockitoAnnotations.openMocks(this);
s3Service = new S3Service(s3Client);
}
@AfterEach
public void cleanup() {
s3Service.cleanup();
Mockito.verify(s3Client).close();
}
@Test
public void givenBucketName_whenListObjectsInBucket_thenReturnList() {
ListObjectsV2Request request = ListObjectsV2Request.builder().bucket(AWS_BUCKET).build();
ListObjectsV2Response response = ListObjectsV2Response.builder().contents(Collections.emptyList()).build();
when(s3Client.listObjectsV2(request)).thenReturn(response);
s3Service.listObjectsInBucket(AWS_BUCKET);
Mockito.verify(s3Client).listObjectsV2(request);
}
@Test
public void givenBucketName_whenListAllObjectsInBucket_thenReturnList() {
ListObjectsV2Request request = ListObjectsV2Request.builder().bucket(AWS_BUCKET).build();
ListObjectsV2Response response = ListObjectsV2Response.builder().contents(Collections.emptyList()).build();
when(s3Client.listObjectsV2(request)).thenReturn(response);
s3Service.listAllObjectsInBucket(AWS_BUCKET);
Mockito.verify(s3Client).listObjectsV2(request);
}
@Test
public void givenBucketNameAndPageSize_whenListAllObjectsInBucketPaginated_thenReturnPaginatedList() {
int pageSize = 10;
ListObjectsV2Request request = ListObjectsV2Request.builder().bucket(AWS_BUCKET).maxKeys(pageSize).build();
ListObjectsV2Iterable mockIterable = Mockito.mock(ListObjectsV2Iterable.class);
S3Object s3Object1 = S3Object.builder().key("object1").build();
S3Object s3Object2 = S3Object.builder().key("object2").build();
ListObjectsV2Response response = ListObjectsV2Response.builder().contents(s3Object1, s3Object2).build();
when(s3Client.listObjectsV2Paginator(request)).thenReturn(mockIterable);
when(mockIterable.iterator()).thenReturn(Arrays.asList(response).iterator());
s3Service.listAllObjectsInBucketPaginated(AWS_BUCKET, pageSize);
Mockito.verify(s3Client).listObjectsV2Paginator(request);
}
@Test
public void givenBucketNamePageSizeAndPrefix_whenListAllObjectsInBucketPaginatedWithPrefix_thenReturnPaginatedList() {
int pageSize = 1;
String prefix = "folder/";
ListObjectsV2Request request = ListObjectsV2Request.builder().bucket(AWS_BUCKET).maxKeys(pageSize).prefix(prefix).build();
ListObjectsV2Iterable mockIterable = Mockito.mock(ListObjectsV2Iterable.class);
S3Object s3Object1 = S3Object.builder().key("folder/object1").build();
S3Object s3Object2 = S3Object.builder().key("folder/object2").build();
ListObjectsV2Response response = ListObjectsV2Response.builder().contents(s3Object1, s3Object2).build();
when(s3Client.listObjectsV2Paginator(request)).thenReturn(mockIterable);
when(mockIterable.iterator()).thenReturn(Arrays.asList(response).iterator());
s3Service.listAllObjectsInBucketPaginatedWithPrefix(AWS_BUCKET, pageSize, prefix);
Mockito.verify(s3Client).listObjectsV2Paginator(request);
}
@Test
public void whenListBuckets_thenReturnBucketList() {
when(s3Client.listBuckets()).thenReturn(ListBucketsResponse.builder().buckets(Collections.emptyList()).build());
s3Service.listBuckets();
Mockito.verify(s3Client).listBuckets();
}
}

View File

@ -1,6 +1,7 @@
package com.baeldung.s3;
import java.io.File;
import java.net.URL;
import java.util.List;
import com.amazonaws.services.s3.AmazonS3;
@ -49,6 +50,11 @@ public class AWSS3Service {
public PutObjectResult putObject(String bucketName, String key, File file) {
return s3client.putObject(bucketName, key, file);
}
//uploading object and getting url
public URL getObjectURL(String bucketName, String key, File file) {
s3client.putObject(bucketName, key, file);
return s3client.getUrl(bucketName, key);
}
//listing objects
public ObjectListing listObjects(String bucketName) {

View File

@ -66,6 +66,9 @@ public class S3Application {
new File("/Users/user/Document/hello.txt")
);
//uploading object and getting url
awsService.getObjectURL(bucketName, "Document/hello.txt", new File("/Users/user/Document/hello.txt"));
//listing objects
ObjectListing objectListing = awsService.listObjects(bucketName);
for(S3ObjectSummary os : objectListing.getObjectSummaries()) {

View File

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

View File

@ -2,3 +2,4 @@
- [Record Patterns in Java 19](https://www.baeldung.com/java-19-record-patterns)
- [Structured Concurrency in Java 19](https://www.baeldung.com/java-structured-concurrency)
- [Possible Root Causes for High CPU Usage in Java](https://www.baeldung.com/java-high-cpu-usage-causes)
- [The Vector API in Java 19](https://www.baeldung.com/java-vector-api)

View File

@ -21,6 +21,7 @@
<source>19</source>
<target>19</target>
<compilerArgs>--enable-preview</compilerArgs>
<compilerArgs>--add-modules=jdk.incubator.vector</compilerArgs>
</configuration>
</plugin>
</plugins>

View File

@ -0,0 +1,100 @@
package com.baeldung.vectors;
import jdk.incubator.vector.FloatVector;
import jdk.incubator.vector.IntVector;
import jdk.incubator.vector.VectorOperators;
import jdk.incubator.vector.VectorSpecies;
/**
* This class contains examples of the Vector API in Java, more specifically the fourth incubator to the Vector API.
* There are scalar and vector methods written here and the method names will specify the type.
* Note that, the code is written without any benchmarking done and without any assumption of it being run on
* a SIMD processor, or any specific compiler.
*/
public class VectorAPIExamples {
static final VectorSpecies<Integer> SPECIES = IntVector.SPECIES_PREFERRED;
static final VectorSpecies<Float> PREFERRED_SPECIES = FloatVector.SPECIES_PREFERRED;
public int[] addTwoScalarArrays(int[] arr1, int[] arr2) {
int[] result = new int[arr1.length];
for (int i = 0; i < arr1.length; i++) {
result[i] = arr1[i] + arr2[i];
}
return result;
}
public int[] addTwoVectorArrays(int[] arr1, int[] arr2) {
var v1 = IntVector.fromArray(SPECIES, arr1, 0);
var v2 = IntVector.fromArray(SPECIES, arr2, 0);
var result = v1.add(v2);
return result.toArray();
}
public int[] addTwoVectorsWIthHigherShape(int[] arr1, int[] arr2) {
int[] finalResult = new int[arr1.length];
for (int i = 0; i < arr1.length; i += SPECIES.length()) {
var v1 = IntVector.fromArray(SPECIES, arr1, i);
var v2 = IntVector.fromArray(SPECIES, arr2, i);
var result = v1.add(v2);
result.intoArray(finalResult, i);
}
return finalResult;
}
public int[] addTwoVectorsWithMasks(int[] arr1, int[] arr2) {
int[] finalResult = new int[arr1.length];
int i = 0;
for (; i < SPECIES.loopBound(arr1.length); i += SPECIES.length()) {
var mask = SPECIES.indexInRange(i, arr1.length);
var v1 = IntVector.fromArray(SPECIES, arr1, i, mask);
var v2 = IntVector.fromArray(SPECIES, arr2, i, mask);
var result = v1.add(v2, mask);
result.intoArray(finalResult, i, mask);
}
// tail cleanup loop
for (; i < arr1.length; i++) {
finalResult[i] = arr1[i] + arr2[i];
}
return finalResult;
}
public float[] scalarNormOfTwoArrays(float[] arr1, float[] arr2) {
float[] finalResult = new float[arr1.length];
for (int i = 0; i < arr1.length; i++) {
finalResult[i] = (arr1[i] * arr1[i] + arr2[i] * arr2[i]) * -1.0f;
}
return finalResult;
}
public float[] vectorNormalForm(float[] arr1, float[] arr2) {
float[] finalResult = new float[arr1.length];
int i = 0;
int upperBound = SPECIES.loopBound(arr1.length);
for (; i < upperBound; i += SPECIES.length()) {
var va = FloatVector.fromArray(PREFERRED_SPECIES, arr1, i);
var vb = FloatVector.fromArray(PREFERRED_SPECIES, arr2, i);
var vc = va.mul(va)
.add(vb.mul(vb))
.neg();
vc.intoArray(finalResult, i);
}
// tail cleanup
for (; i < arr1.length; i++) {
finalResult[i] = (arr1[i] * arr1[i] + arr2[i] * arr2[i]) * -1.0f;
}
return finalResult;
}
public double averageOfaVector(int[] arr) {
double sum = 0;
for (int i = 0; i < arr.length; i += SPECIES.length()) {
var mask = SPECIES.indexInRange(i, arr.length);
var V = IntVector.fromArray(SPECIES, arr, i, mask);
sum += V.reduceLanes(VectorOperators.ADD, mask);
}
return sum / arr.length;
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.vectors;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
public class VectorAPIUnitTest {
VectorAPIExamples vector = new VectorAPIExamples();
@Test
public void whenTwoArraysProvided_thenVerifyScalarAdd() {
int[] arr1 = { 1, 2, 3, 4 };
int[] arr2 = { 100, 200, 300, 400 };
int[] result = { 101, 202, 303, 404 };
assertArrayEquals(result, vector.addTwoScalarArrays(arr1, arr2));
}
@Test
public void whenTwoArraysProvided_thenVerifyVectorAdd() {
int[] arr1 = { 1, 2, 3, 4 };
int[] arr2 = { 100, 200, 300, 400 };
int[] result = { 101, 202, 303, 404 };
assertArrayEquals(result, vector.addTwoVectorsWithMasks(arr1, arr2));
}
@Test
public void whenTwoValuesProvided_thenComputeScalarNorm() {
float[] arr1 = { 1, 2.3f };
float[] arr2 = { 1.3f, 2.0f };
float[] result = { -2.6899998f, -9.29f };
Assertions.assertArrayEquals(result, vector.scalarNormOfTwoArrays(arr1, arr2));
}
@Test
public void whenTwoValuesProvided_thenComputeVectorNorm() {
float[] arr1 = { 1, 2.3f };
float[] arr2 = { 1.3f, 2.0f };
float[] result = { -2.6899998f, -9.29f };
Assertions.assertArrayEquals(result, vector.vectorNormalForm(arr1, arr2));
}
@Test
public void whenArrayProvided_thenComputeVectorAverage() {
int[] arr = { 100, 200, 300, 400 };
Assertions.assertEquals(250.0, vector.averageOfaVector(arr));
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.zipentries;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class ZipEntryReader {
public static void readZipEntries(String filePath) throws IOException {
try (ZipFile zipFile = new ZipFile(filePath)) {
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
// Check if entry is a directory
if (!entry.isDirectory()) {
// Read and process the entry contents using the inputStream
try (InputStream inputStream = zipFile.getInputStream(entry);
Scanner scanner = new Scanner(inputStream);) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
}
}
}
}
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.zipentries;
import org.junit.Test;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ZipEntryReaderUnitTest {
@Test
public void givenZipFile_thenReadEntriesAndValidateContent() throws URISyntaxException, IOException {
Path zipFilePath = Paths.get(getClass().getClassLoader().getResource("zipFile.zip").toURI());
ZipEntryReader.readZipEntries(zipFilePath.toString());
}
}

View File

@ -3,4 +3,6 @@
- [Generating Random Dates in Java](https://www.baeldung.com/java-random-dates)
- [Creating a LocalDate with Values in Java](https://www.baeldung.com/java-creating-localdate-with-values)
- [Parsing Date Strings with Varying Formats](https://www.baeldung.com/java-parsing-dates-many-formats)
- [How Many Days Are There in a Particular Month of a Given Year?](https://www.baeldung.com/days-particular-month-given-year)
- [Difference Between Instant and LocalDateTime](https://www.baeldung.com/java-instant-vs-localdatetime)
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)

View File

@ -0,0 +1,41 @@
package com.baeldung.instantvslocaldatetime;
import org.junit.Test;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class InstantAndLocalDateTimeUnitTest {
@Test
public void givenTwoInstants_whenComparing_thenDifferent() {
// Instant arithmetic
Instant.now().plus(12, ChronoUnit.HOURS);
Instant oneWeekAgo = Instant.now().minus(7, ChronoUnit.DAYS);
// Comparing 2 Instants
Instant instant1 = Instant.now();
Instant instant2 = instant1.plus(1, ChronoUnit.SECONDS);
assertTrue(instant1.isBefore(instant2));
assertFalse(instant1.isAfter(instant2));
}
@Test
public void givenTwoLocalDateTimes_whenComparing_thenDifferent() {
// LocalDateTime arithmetic
LocalDateTime tomorrow = LocalDateTime.now().plus(1, ChronoUnit.DAYS);
LocalDateTime oneYearAgo = LocalDateTime.now().minus(1, ChronoUnit.YEARS);
// Comparing 2 LocalDateTimes
LocalDateTime now = LocalDateTime.now();
LocalDateTime y2k = LocalDateTime.of(2000, 1, 1, 0, 0);
assertTrue(now.isAfter(y2k));
assertTrue(y2k.isBefore(now));
}
}

View File

@ -7,3 +7,4 @@ This module contains articles about arrays conversion in Java
- [Converting Between Stream and Array in Java](https://www.baeldung.com/java-stream-to-array)
- [Convert a Byte Array to a Numeric Representation in Java](https://www.baeldung.com/java-byte-array-to-number)
- [Converting a String Array Into an int Array in Java](https://www.baeldung.com/java-convert-string-array-to-int-array)
- [Convert Java Array to Iterable](https://www.baeldung.com/java-array-convert-to-iterable)

View File

@ -0,0 +1,28 @@
package com.baeldung.array.conversions;
import com.google.common.primitives.Ints;
import org.apache.commons.lang3.ArrayUtils;
import java.util.Arrays;
import java.util.stream.Collectors;
public class IntArrayToIterableConversionUtils {
public static Iterable<Integer> convertWithStreamToList(int[] array) {
return Arrays.stream(array).boxed().collect(Collectors.toList());
}
public static Iterable<Integer> convertWithStreamIterator(int[] array) {
return () -> Arrays.stream(array).iterator();
}
public static Iterable<Integer> convertWithApacheCommonsAndJavaAsList(int[] array) {
return Arrays.asList(ArrayUtils.toObject(array));
}
public static Iterable<Integer> convertWithGuava(int[] array) {
return Ints.asList(array);
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.array.conversions;
import org.junit.jupiter.api.Test;
import static com.baeldung.array.conversions.IntArrayToIterableConversionUtils.*;
import static org.junit.Assert.assertTrue;
class IntArrayToIterableConversionUtilsUnitTest {
private int[] ints = new int[]{1, 2, 3, 4, 5};
@Test
void whenConvertWithStreamToList_thenGetIterable() {
Iterable<Integer> integers = convertWithStreamToList(ints);
assertTrue("should be Iterable", integers instanceof Iterable);
}
@Test
void whenConvertWithStreamIterator_thenGetIterable() {
Iterable<Integer> integers = convertWithStreamIterator(ints);
assertTrue("should be Iterable", integers instanceof Iterable);
}
@Test
void whenConvertWithApacheCommonsAndJavaAsList_thenGetIterable() {
Iterable<Integer> integers = convertWithApacheCommonsAndJavaAsList(ints);
assertTrue("should be Iterable", integers instanceof Iterable);
}
@Test
void whenConvertWithGuava_thenGetIterable() {
Iterable<Integer> integers = convertWithGuava(ints);
assertTrue("should be Iterable", integers instanceof Iterable);
}
}

View File

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

View File

@ -4,3 +4,4 @@ This module contains articles about Java Booleans.
### Relevant Articles:
- [Convert Boolean to String in Java](https://www.baeldung.com/java-convert-boolean-to-string)
- [Difference Between Boolean.TRUE and true in Java](https://www.baeldung.com/java-boolean-true-primitive-vs-constant)

View File

@ -0,0 +1,34 @@
package com.baeldung.booleans;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class BooleanTrueVsTrueUnitTest {
@Test
public void given_BooleanValues_whenUsingBooleanTrue_thenTestBooleanEquality() {
assertEquals(Boolean.TRUE, Boolean.valueOf(true));
}
@Test
public void given_BooleanValues_whenUsingBooleanTrue_thenTestBooleanIdentity() {
assertTrue(Boolean.TRUE == Boolean.valueOf(true));
}
@Test
public void given_TrueValue_whenUsingTrue_thenTestPrimitiveEquality() {
assertTrue(true == true);
}
@Test
public void given_TrueStringValue_whenUsingBooleanTrue_thenTestBooleanToString() {
assertEquals("true", Boolean.TRUE.toString());
}
@Test
public void given_PrimitiveValue_whenUsingStringValueOf_thenTestPrimitiveToString() {
assertEquals("true", String.valueOf(true));
}
}

View File

@ -11,4 +11,5 @@ This module contains articles about conversions among Collection types and array
- [Iterate Over a Set in Java](https://www.baeldung.com/java-iterate-set)
- [Convert a List of Integers to a List of Strings](https://www.baeldung.com/java-convert-list-integers-to-list-strings)
- [Combining Two Lists Into a Map in Java](https://www.baeldung.com/java-combine-two-lists-into-map)
- [Convert a List of Strings to a List of Integers](https://www.baeldung.com/java-convert-list-strings-to-integers)
- More articles: [[<-- prev]](../core-java-collections-conversions)

View File

@ -0,0 +1,46 @@
package com.baeldung.strlisttointlist;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
public class StringListToIntListUnitTest {
private final static List<String> STRING_LIST = Arrays.asList("1", "2", "3", "4", "5", "6", "7");
private final static List<Integer> EXPECTED_LIST = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
@Test
void whenUsingStream_thenGetExpectedIntegerList() {
List<Integer> result = STRING_LIST.stream()
.map(Integer::valueOf)
.collect(Collectors.toList());
assertEquals(EXPECTED_LIST, result);
}
@Test
void whenUsingLoop_thenGetExpectedIntegerList() {
List<Integer> result = new ArrayList<>(STRING_LIST.size());
for (String s : STRING_LIST) {
result.add(Integer.valueOf(s));
}
assertEquals(EXPECTED_LIST, result);
}
@Test
void whenUsingGuava_thenGetExpectedIntegerList() {
List<Integer> result = Lists.transform(STRING_LIST, new Function<String, Integer>() {
@Override
public Integer apply(String input) {
return Integer.valueOf(input);
}
});
assertEquals(EXPECTED_LIST, result);
}
}

View File

@ -10,3 +10,4 @@ This module contains articles about the Java List collection
- [Array vs. List Performance in Java](https://www.baeldung.com/java-array-vs-list-performance)
- [Set Default Value for Elements in List](https://www.baeldung.com/java-list-set-default-values)
- [Get Unique Values From an ArrayList In Java](https://www.baeldung.com/java-unique-values-arraylist)
- [Converting a Java List to a Json Array](https://www.baeldung.com/java-converting-list-to-json-array)

View File

@ -0,0 +1,14 @@
package com.baeldung.concurrent.parallel;
import java.io.IOException;
class Benchmark {
public static void main(String[] args) {
try {
org.openjdk.jmh.Main.main(new String[]{"com.baeldung.concurrent.parallel.Processor"});
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -0,0 +1,73 @@
package com.baeldung.concurrent.parallel;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Mode;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public class Processor {
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public void processSerially() throws InterruptedException {
for (int i = 0; i < 100; i++) {
Thread.sleep(10);
}
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public void processParallelyWithExecutorService() throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(10);
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (int i = 0; i < 100; i++) {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, executorService);
futures.add(future);
}
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
executorService.shutdown();
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public void processParallelyWithStream() {
IntStream.range(0, 100)
.parallel()
.forEach(i -> {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public void processParallelyWithStreamSupport() {
Iterable<Integer> iterable = () -> IntStream.range(0, 100).iterator();
Stream<Integer> stream = StreamSupport.stream(iterable.spliterator(), true);
stream.forEach(i -> {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}

View File

@ -17,22 +17,21 @@ public class Consumer implements Runnable {
public void consume() {
while (dataQueue.runFlag) {
synchronized (dataQueue) {
while (dataQueue.isEmpty() && dataQueue.runFlag) {
try {
dataQueue.waitOnEmpty();
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
if (!dataQueue.runFlag) {
while (dataQueue.isEmpty() && dataQueue.runFlag) {
try {
dataQueue.waitOnEmpty();
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
Message message = dataQueue.remove();
dataQueue.notifyAllForFull();
useMessage(message);
}
if (!dataQueue.runFlag) {
break;
}
Message message = dataQueue.remove();
dataQueue.notifyAllForFull();
useMessage(message);
}
log.info("Consumer Stopped");
}
@ -40,7 +39,7 @@ public class Consumer implements Runnable {
private void useMessage(Message message) {
if (message != null) {
log.info(String.format("[%s] Consuming Message. Id: %d, Data: %f%n",
Thread.currentThread().getName(), message.getId(), message.getData()));
Thread.currentThread().getName(), message.getId(), message.getData()));
//Sleeping on random time to make it realistic
ThreadUtil.sleep((long) (message.getData() * 100));

View File

@ -19,22 +19,21 @@ public class Producer implements Runnable {
public void produce() {
while (dataQueue.runFlag) {
synchronized (dataQueue) {
while (dataQueue.isFull() && dataQueue.runFlag) {
try {
dataQueue.waitOnFull();
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
if (!dataQueue.runFlag) {
while (dataQueue.isFull() && dataQueue.runFlag) {
try {
dataQueue.waitOnFull();
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
Message message = generateMessage();
dataQueue.add(message);
dataQueue.notifyAllForEmpty();
}
if (!dataQueue.runFlag) {
break;
}
Message message = generateMessage();
dataQueue.add(message);
dataQueue.notifyAllForEmpty();
}
log.info("Producer Stopped");
}
@ -42,7 +41,7 @@ public class Producer implements Runnable {
private Message generateMessage() {
Message message = new Message(incrementAndGetId(), Math.random());
log.info(String.format("[%s] Generated Message. Id: %d, Data: %f%n",
Thread.currentThread().getName(), message.getId(), message.getData()));
Thread.currentThread().getName(), message.getId(), message.getData()));
//Sleeping on random time to make it realistic
ThreadUtil.sleep((long) (message.getData() * 100));

View File

@ -0,0 +1,28 @@
package com.baeldung.concurrent.completablefuture.threadpool;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.function.Supplier;
public class CustomCompletableFuture<T> extends CompletableFuture<T> {
private static final Executor executor = Executors.newSingleThreadExecutor(runnable -> new Thread(runnable, "Custom-Single-Thread"));
public static <TYPE> CustomCompletableFuture<TYPE> supplyAsync(Supplier<TYPE> supplier) {
CustomCompletableFuture<TYPE> future = new CustomCompletableFuture<>();
executor.execute(() -> {
try {
future.complete(supplier.get());
} catch (Exception ex) {
future.completeExceptionally(ex);
}
});
return future;
}
@Override
public Executor defaultExecutor() {
return executor;
}
}

View File

@ -0,0 +1,88 @@
package com.baeldung.concurrent.completablefuture.threadpool;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.junit.jupiter.api.Test;
public class CompletableFutureThreadPoolUnitTest {
@Test
void whenUsingNonAsync_thenUsesMainThread() throws ExecutionException, InterruptedException {
CompletableFuture<String> name = CompletableFuture.supplyAsync(() -> "Baeldung");
CompletableFuture<Integer> nameLength = name.thenApply(value -> {
printCurrentThread();
return value.length();
});
assertThat(nameLength.get()).isEqualTo(8);
}
@Test
void whenUsingNonAsync_thenUsesCallersThread() throws InterruptedException {
Runnable test = () -> {
CompletableFuture<String> name = CompletableFuture.supplyAsync(() -> "Baeldung");
CompletableFuture<Integer> nameLength = name.thenApply(value -> {
printCurrentThread();
return value.length();
});
try {
assertThat(nameLength.get()).isEqualTo(8);
} catch (Exception e) {
fail(e.getMessage());
}
};
new Thread(test, "test-thread").start();
Thread.sleep(100l);
}
@Test
void whenUsingAsync_thenUsesCommonPool() throws ExecutionException, InterruptedException {
CompletableFuture<String> name = CompletableFuture.supplyAsync(() -> "Baeldung");
CompletableFuture<Integer> nameLength = name.thenApplyAsync(value -> {
printCurrentThread();
return value.length();
});
assertThat(nameLength.get()).isEqualTo(8);
}
@Test
void whenUsingAsync_thenUsesCustomExecutor() throws ExecutionException, InterruptedException {
Executor testExecutor = Executors.newFixedThreadPool(5);
CompletableFuture<String> name = CompletableFuture.supplyAsync(() -> "Baeldung");
CompletableFuture<Integer> nameLength = name.thenApplyAsync(value -> {
printCurrentThread();
return value.length();
}, testExecutor);
assertThat(nameLength.get()).isEqualTo(8);
}
@Test
void whenOverridingDefaultThreadPool_thenUsesCustomExecutor() throws ExecutionException, InterruptedException {
CompletableFuture<String> name = CustomCompletableFuture.supplyAsync(() -> "Baeldung");
CompletableFuture<Integer> nameLength = name.thenApplyAsync(value -> {
printCurrentThread();
return value.length();
});
assertThat(nameLength.get()).isEqualTo(8);
}
private static void printCurrentThread() {
System.out.println(Thread.currentThread().getName());
}
}

View File

@ -0,0 +1,112 @@
package com.baeldung.concurrent.anonymousthread;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class AnonymousThreadUnitTest {
static ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
static PrintStream printStream = new PrintStream(outputStream);
static List<String> expectedNumbers = new ArrayList<>();
@BeforeClass
public static void setupClass() {
for (int i = 1; i <= 10; i++) {
expectedNumbers.add(String.valueOf(i));
}
}
@Before
public void setupMethod() {
System.setOut(printStream);
}
@After
public void cleanUpMethod() {
outputStream.reset();
System.setOut(System.out);
}
@AfterClass
public static void cleanupClass() throws IOException {
expectedNumbers.clear();
outputStream.close();
printStream.close();
}
@Test
public void givenAnonymousThreadSubclassOverridingRunMethod_whenStart_thenRunAsExpected() {
Thread anonymousThread = new Thread() {
@Override
public void run() {
printNumbersFrom1To10();
}
};
anonymousThread.start();
waitForThreadToFinish();
anonymousThread.interrupt();
String[] printedNumbers = getPrintedNumbers();
assertEquals(expectedNumbers, List.of(printedNumbers));
}
@Test
public void givenAnonymousThreadWithLambdaExpression_whenStart_thenRunAsExpected() {
Thread anonymousThread = new Thread(() -> {
printNumbersFrom1To10();
});
anonymousThread.start();
waitForThreadToFinish();
anonymousThread.interrupt();
String[] printedNumbers = getPrintedNumbers();
assertEquals(expectedNumbers, List.of(printedNumbers));
}
@Test
public void givenAnonymousThreadWithRunnableObject_whenStart_thenRunAsExpected() {
Thread anonymousThread = new Thread(new Runnable() {
@Override
public void run() {
printNumbersFrom1To10();
}
});
anonymousThread.start();
waitForThreadToFinish();
anonymousThread.interrupt();
String[] printedNumbers = getPrintedNumbers();
assertEquals(expectedNumbers, List.of(printedNumbers));
}
private void printNumbersFrom1To10() {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
private void waitForThreadToFinish() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// ignore
}
}
private String[] getPrintedNumbers() {
String printedOutput = outputStream.toString()
.trim();
return printedOutput.split(System.lineSeparator());
}
}

View File

@ -19,6 +19,16 @@
<artifactId>jansi</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
@ -70,6 +80,16 @@
<target>${target.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.1.2</version>
<configuration>
<excludeJUnit5Engines>
<engine>junit-vintage-engine</engine>
</excludeJUnit5Engines>
</configuration>
</plugin>
</plugins>
</build>

View File

@ -1,9 +1,10 @@
package com.baeldung.asciiart;
import com.baeldung.asciiart.AsciiArt.Settings;
import org.junit.Test;
import java.awt.Font;
import java.awt.*;
import org.junit.jupiter.api.Test;
import com.baeldung.asciiart.AsciiArt.Settings;
public class AsciiArtIntegrationTest {
@ -12,7 +13,7 @@ public class AsciiArtIntegrationTest {
AsciiArt asciiArt = new AsciiArt();
String text = "BAELDUNG";
Settings settings = asciiArt.new Settings(new Font("SansSerif", Font.BOLD, 24), text.length() * 30, 30); // 30 pixel width per character
asciiArt.drawString(text, "*", settings);
}
}

View File

@ -6,4 +6,6 @@ This module contains articles about date operations in Java.
- [Create Date From Unix Timestamp in Java](https://www.baeldung.com/java-date-unix-timestamp)
- [Convert java.util.Date to java.sql.Date](https://www.baeldung.com/java-convert-util-date-to-sql)
- [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)
- [[<-- Prev]](/core-java-modules/core-java-date-operations-2)

View File

@ -12,5 +12,23 @@
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda-time.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
<properties>
<joda-time.version>2.12.5</joda-time.version>
<commons-lang3.version>3.12.0</commons-lang3.version>
</properties>
</project>

View File

@ -0,0 +1,32 @@
package com.baeldung.lastdaymonth;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
public class LastDayOfMonth {
static int getLastDayOfMonthUsingCalendar(int month) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, month);
return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
}
static int getLastDayOfMonthUsingTemporalAdjusters(LocalDate date) {
return date.with(TemporalAdjusters.lastDayOfMonth())
.getDayOfMonth();
}
static int getLastDayOfMonthUsingYearMonth(YearMonth date) {
return date.atEndOfMonth()
.getDayOfMonth();
}
static int getLastDayOfMonthUsingJodaTime(org.joda.time.LocalDate date) {
return date.dayOfMonth()
.withMaximumValue()
.getDayOfMonth();
}
}

View File

@ -0,0 +1,79 @@
package com.baeldung.date;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.apache.commons.lang3.time.DateUtils;
import org.junit.jupiter.api.Test;
class AddOneMonthToCurrentDateUnitTest {
@Test
void givenCalendarDate_whenAddingOneMonth_thenDateIsChangedCorrectly() {
Calendar calendar = Calendar.getInstance();
// Dummy current date
calendar.set(2023, Calendar.APRIL, 20);
// add one month
calendar.add(Calendar.MONTH, 1);
assertEquals(Calendar.MAY, calendar.get(Calendar.MONTH));
assertEquals(20, calendar.get(Calendar.DAY_OF_MONTH));
assertEquals(2023, calendar.get(Calendar.YEAR));
}
@SuppressWarnings("deprecation")
@Test
void givenDate_whenAddingOneMonth_thenDateIsChangedCorrectly() {
// Dummy current date
Date currentDate = new Date(2023, Calendar.DECEMBER, 20);
// Expected Date
Date expectedDate = new Date(2024, Calendar.JANUARY, 20);
// add one month
currentDate.setMonth(currentDate.getMonth() + 1);
assertEquals(expectedDate, currentDate);
}
@Test
void givenJavaLocalDate_whenAddingOneMonth_thenDateIsChangedCorrectly() {
// Dummy current date
LocalDate localDate = LocalDate.of(2023, 12, 20);
// add one month
localDate = localDate.plusMonths(1);
assertEquals(1, localDate.getMonthValue());
assertEquals(20, localDate.getDayOfMonth());
assertEquals(2024, localDate.getYear());
}
@Test
void givenJodaTimeLocalDate_whenAddingOneMonth_thenDateIsChangedCorrectly() {
// Dummy current date
org.joda.time.LocalDate localDate = new org.joda.time.LocalDate(2023, 12, 20);
// add one month
localDate = localDate.plusMonths(1);
assertEquals(1, localDate.getMonthOfYear());
assertEquals(20, localDate.getDayOfMonth());
assertEquals(2024, localDate.getYear());
}
@Test
void givenApacheCommonsLangDateUtils_whenAddingOneMonth_thenDateIsChangedCorrectly() {
// Dummy current date
Date currentDate = new GregorianCalendar(2023, Calendar.APRIL, 20, 4, 0).getTime();
// Expected Date
Date expectedDate = new GregorianCalendar(2023, Calendar.MAY, 20, 4, 0).getTime();
assertEquals(expectedDate, DateUtils.addMonths(currentDate, 1));
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.lastdaymonth;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.LocalDate;
import java.time.YearMonth;
import org.junit.jupiter.api.Test;
class LastDayOfMonthUnitTest {
@Test
void givenMonth_whenUsingCalendar_thenReturnLastDay() {
assertEquals(31, LastDayOfMonth.getLastDayOfMonthUsingCalendar(0));
assertEquals(30, LastDayOfMonth.getLastDayOfMonthUsingCalendar(3));
assertEquals(31, LastDayOfMonth.getLastDayOfMonthUsingCalendar(9));
}
@Test
void givenMonth_whenUsingTemporalAdjusters_thenReturnLastDay() {
assertEquals(31, LastDayOfMonth.getLastDayOfMonthUsingTemporalAdjusters(LocalDate.of(2023, 1, 1)));
assertEquals(30, LastDayOfMonth.getLastDayOfMonthUsingTemporalAdjusters(LocalDate.of(2023, 4, 1)));
assertEquals(31, LastDayOfMonth.getLastDayOfMonthUsingTemporalAdjusters(LocalDate.of(2023, 10, 1)));
}
@Test
void givenMonth_whenUsingYearMonth_thenReturnLastDay() {
assertEquals(31, LastDayOfMonth.getLastDayOfMonthUsingYearMonth(YearMonth.of(2023, 1)));
assertEquals(30, LastDayOfMonth.getLastDayOfMonthUsingYearMonth(YearMonth.of(2023, 4)));
assertEquals(31, LastDayOfMonth.getLastDayOfMonthUsingYearMonth(YearMonth.of(2023, 10)));
}
@Test
void givenMonth_whenUsingJodaTime_thenReturnLastDay() {
assertEquals(31, LastDayOfMonth.getLastDayOfMonthUsingJodaTime(org.joda.time.LocalDate.parse("2023-1-1")));
assertEquals(30, LastDayOfMonth.getLastDayOfMonthUsingJodaTime(org.joda.time.LocalDate.parse("2023-4-1")));
assertEquals(31, LastDayOfMonth.getLastDayOfMonthUsingJodaTime(org.joda.time.LocalDate.parse("2023-10-1")));
}
}

View File

@ -4,3 +4,4 @@ This module contains articles about parsing and formatting Java date and time ob
### Relevant Articles:
- [Convert String to Instant](https://www.baeldung.com/java-string-to-instant)
- [Sort Date Strings in Java](https://www.baeldung.com/java-sort-date-strings)

View File

@ -3,18 +3,23 @@ package com.baeldung.bufferedreadervsfilereader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.BufferedReader;
import java.io.FileReader;
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.Assertions;
import org.testng.annotations.Test;
public class BufferedReaderUnitTest {
import org.junit.jupiter.api.Test;
class BufferedReaderUnitTest {
@Test
public void whenReadingAFile_thenReadsLineByLine() {
void whenReadingAFile_thenReadsLineByLine() {
StringBuilder result = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader("src/test/resources/sampleText1.txt"))) {
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) {

View File

@ -7,10 +7,10 @@ import java.io.IOException;
import org.junit.jupiter.api.Test;
public class FileReaderUnitTest {
class FileReaderUnitTest {
@Test
public void whenReadingAFile_thenReadsCharByChar() {
void whenReadingAFile_thenReadsCharByChar() {
StringBuilder result = new StringBuilder();
try (FileReader fr = new FileReader("src/test/resources/sampleText2.txt")) {

View File

@ -0,0 +1,6 @@
## 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)

View File

@ -0,0 +1,15 @@
<?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>

View File

@ -0,0 +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);
}
}
}

View File

@ -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;
public 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));
}
}

View File

@ -0,0 +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));
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.deepcopyarraylist;
import java.io.Serializable;
public class Course implements Serializable, Cloneable {
private Integer courseId;
private String courseName;
public Course() {
}
public Course(Integer courseId, String courseName) {
this.courseId = courseId;
this.courseName = courseName;
}
public Integer getCourseId() {
return courseId;
}
public void setCourseId(Integer courseId) {
this.courseId = courseId;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
@Override
public Course clone() {
try {
return (Course) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
}
}

View File

@ -0,0 +1,103 @@
package com.baeldung.deepcopyarraylist;
import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.SerializationUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Student implements Serializable, Cloneable {
private int studentId;
private String studentName;
private Course course;
public Student() {
}
public Student(int studentId, String studentName, Course course) {
this.studentId = studentId;
this.studentName = studentName;
this.course = course;
}
public Student(Student student) {
this.studentId = student.getStudentId();
this.studentName = student.getStudentName();
this.course = new Course(student.getCourse()
.getCourseId(), student.getCourse()
.getCourseName());
}
public static Student createDeepCopy(Student student) {
ObjectMapper objectMapper = new ObjectMapper();
try {
return objectMapper.readValue(objectMapper.writeValueAsString(student), Student.class);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
}
public static List<Student> deepCopyUsingJackson(List<Student> students) {
return students.stream()
.map(Student::createDeepCopy)
.collect(Collectors.toList());
}
public static List<Student> deepCopyUsingCloneable(List<Student> students) {
return students.stream()
.map(Student::clone)
.collect(Collectors.toList());
}
public static List<Student> deepCopyUsingCopyConstructor(List<Student> students) {
return students.stream()
.map(Student::new)
.collect(Collectors.toList());
}
public static List<Student> deepCopyUsingSerialization(List<Student> students) {
return students.stream()
.map(SerializationUtils::clone)
.collect(Collectors.toList());
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
@Override
public Student clone() {
Student student;
try {
student = (Student) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
student.course = this.course.clone();
return student;
}
}

View File

@ -0,0 +1,77 @@
package com.baeldung.deepcopyarraylist;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
public class DeepCopyArrayListUnitTest {
@Test
public void whenCreatingCopyWithCloneable_thenObjectsShouldNotBeSame() {
Course course = new Course(1, "Spring Masterclass");
Student student1 = new Student(1, "John", course);
Student student2 = new Student(2, "David", course);
List<Student> students = new ArrayList<>();
students.add(student1);
students.add(student2);
List<Student> deepCopy = Student.deepCopyUsingCloneable(students);
Assertions.assertNotEquals(students.get(0), deepCopy.get(0));
Assertions.assertNotEquals(students.get(1), deepCopy.get(1));
}
@Test
public void whenCreatingDeepCopyWithCopyConstructor_thenObjectsShouldNotBeSame() {
Course course = new Course(1, "Spring Masterclass");
Student student1 = new Student(1, "John", course);
Student student2 = new Student(2, "David", course);
List<Student> students = new ArrayList<>();
students.add(student1);
students.add(student2);
List<Student> deepCopy = Student.deepCopyUsingCopyConstructor(students);
Assertions.assertNotEquals(students.get(0), deepCopy.get(0));
Assertions.assertNotEquals(students.get(1), deepCopy.get(1));
}
@Test
public void whenCreatingDeepCopyWithSerializationUtils_thenObjectsShouldNotBeSame() {
Course course = new Course(1, "Spring Masterclass");
Student student1 = new Student(1, "John", course);
Student student2 = new Student(2, "David", course);
List<Student> students = new ArrayList<>();
students.add(student1);
students.add(student2);
List<Student> deepCopy = Student.deepCopyUsingSerialization(students);
Assertions.assertNotEquals(students.get(0), deepCopy.get(0));
Assertions.assertNotEquals(students.get(1), deepCopy.get(1));
}
@Test
public void whenCreatingDeepCopyWithJackson_thenObjectsShouldNotBeSame() {
Course course = new Course(1, "Spring Masterclass");
Student student1 = new Student(1, "John", course);
Student student2 = new Student(2, "David", course);
List<Student> students = new ArrayList<>();
students.add(student1);
students.add(student2);
List<Student> deepCopy = Student.deepCopyUsingJackson(students);
Assertions.assertNotEquals(students.get(0), deepCopy.get(0));
Assertions.assertNotEquals(students.get(1), deepCopy.get(1));
}
}

View File

@ -3,4 +3,4 @@
## Core Java Methods
### Relevant Articles:
- [Execute a Method Only Once in Java](https://www.baeldung.com/execute-a-method-only-once-in-java)
- [Execute a Method Only Once in Java](https://www.baeldung.com/java-execute-method-only-once)

View File

@ -13,4 +13,5 @@ This module contains articles about core Java Security
- [Error: “trustAnchors parameter must be non-empty”](https://www.baeldung.com/java-trustanchors-parameter-must-be-non-empty)
- [Common Exceptions of Crypto APIs in Java](https://www.baeldung.com/java-crypto-apis-exceptions)
- [Hashing With Argon2 in Java](https://www.baeldung.com/java-argon2-hashing)
- [Hex Representation of a SHA-1 Digest of a String in Java](https://www.baeldung.com/java-string-sha1-hexadecimal)
- More articles: [[<-- prev]](/core-java-modules/core-java-security-2)

View File

@ -30,6 +30,11 @@
<artifactId>jaxb-api</artifactId>
<version>${jaxb-api.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${google-guava.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
@ -39,9 +44,10 @@
<properties>
<bouncycastle.version>1.70</bouncycastle.version>
<commons-codec.version>1.11</commons-codec.version>
<commons-codec.version>1.15</commons-codec.version>
<jaxb-api.version>2.3.1</jaxb-api.version>
<spring-security-crypto.version>6.0.3</spring-security-crypto.version>
<google-guava.version>31.0.1-jre</google-guava.version>
</properties>
</project>

View File

@ -0,0 +1,42 @@
package com.baeldung.crypto.sha1;
import static org.junit.jupiter.api.Assertions.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.digest.DigestUtils;
import org.junit.jupiter.api.Test;
import com.google.common.hash.Hashing;
public class HexRepresentationSha1DigestUnitTest {
String input = "Hello, World";
String expectedHexValue = "907d14fb3af2b0d4f18c2d46abe8aedce17367bd";
@Test
public void givenMessageDigest_whenUpdatingWithData_thenDigestShouldMatchExpectedValue() throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(input.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
byte[] digest = md.digest();
for (byte b : digest) {
hexString.append(String.format("%02x", b));
}
assertEquals(expectedHexValue, hexString.toString());
}
@Test
public void givenDigestUtils_whenCalculatingSHA1Hex_thenDigestShouldMatchExpectedValue() {
assertEquals(expectedHexValue, DigestUtils.sha1Hex(input));
}
@Test
public void givenHashingLibrary_whenCalculatingSHA1Hash_thenDigestShouldMatchExpectedValue() {
assertEquals(expectedHexValue, Hashing.sha1().hashString(input, StandardCharsets.UTF_8).toString());
}
}

View File

@ -1,47 +1,70 @@
package com.baeldung.readresolvevsreadobject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.junit.After;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class SingletonUnitTest {
private static final String SINGLETON_SER = "singleton.ser";
@After
public void tearDown() {
final File file = new File(SINGLETON_SER);
if (file.exists()) {
file.deleteOnExit();
}
}
@Test
public void testSingletonObj_withNoReadResolve() throws ClassNotFoundException, IOException {
// Serialization
FileOutputStream fos = new FileOutputStream("singleton.ser");
FileOutputStream fos = new FileOutputStream(SINGLETON_SER);
ObjectOutputStream oos = new ObjectOutputStream(fos);
Singleton actualSingletonObject = Singleton.getInstance();
oos.writeObject(actualSingletonObject);
// Deserialization
Singleton deserializedSingletonObject = null;
FileInputStream fis = new FileInputStream("singleton.ser");
FileInputStream fis = new FileInputStream(SINGLETON_SER);
ObjectInputStream ois = new ObjectInputStream(fis);
deserializedSingletonObject = (Singleton) ois.readObject();
// remove readResolve() from Singleton class and uncomment this to test.
//assertNotEquals(actualSingletonObject.hashCode(), deserializedSingletonObject.hashCode());
fos.close();
oos.close();
fis.close();
ois.close();
}
@Test
public void testSingletonObj_withCustomReadResolve()
throws ClassNotFoundException, IOException {
// Serialization
FileOutputStream fos = new FileOutputStream("singleton.ser");
FileOutputStream fos = new FileOutputStream(SINGLETON_SER);
ObjectOutputStream oos = new ObjectOutputStream(fos);
Singleton actualSingletonObject = Singleton.getInstance();
oos.writeObject(actualSingletonObject);
// Deserialization
Singleton deserializedSingletonObject = null;
FileInputStream fis = new FileInputStream("singleton.ser");
Singleton deserializedSingletonObject;
FileInputStream fis = new FileInputStream(SINGLETON_SER);
ObjectInputStream ois = new ObjectInputStream(fis);
deserializedSingletonObject = (Singleton) ois.readObject();
assertEquals(actualSingletonObject.hashCode(), deserializedSingletonObject.hashCode());
fos.close();
oos.close();
fis.close();
ois.close();
}
}

View File

@ -1,52 +1,74 @@
package com.baeldung.readresolvevsreadobject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.junit.After;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class UserUnitTest {
private static final String USER_SER = "user.ser";
@After
public void tearDown() {
final File file = new File(USER_SER);
if (file.exists()) {
file.deleteOnExit();
}
}
@Test
public void testDeserializeObj_withOverriddenReadObject()
throws ClassNotFoundException, IOException {
public void testDeserializeObj_withOverriddenReadObject() throws ClassNotFoundException, IOException {
// Serialization
FileOutputStream fos = new FileOutputStream("user.ser");
FileOutputStream fos = new FileOutputStream(USER_SER);
ObjectOutputStream oos = new ObjectOutputStream(fos);
User acutalObject = new User("Sachin", "Kumar");
oos.writeObject(acutalObject);
// Deserialization
User deserializedUser = null;
FileInputStream fis = new FileInputStream("user.ser");
User deserializedUser;
FileInputStream fis = new FileInputStream(USER_SER);
ObjectInputStream ois = new ObjectInputStream(fis);
deserializedUser = (User) ois.readObject();
assertNotEquals(deserializedUser.hashCode(), acutalObject.hashCode());
assertEquals(deserializedUser.getUserName(), "Sachin");
assertEquals(deserializedUser.getPassword(), "Kumar");
fos.close();
oos.close();
fis.close();
ois.close();
}
@Test
public void testDeserializeObj_withDefaultReadObject()
throws ClassNotFoundException, IOException {
// Serialization
FileOutputStream fos = new FileOutputStream("user.ser");
FileOutputStream fos = new FileOutputStream(USER_SER);
ObjectOutputStream oos = new ObjectOutputStream(fos);
User acutalObject = new User("Sachin", "Kumar");
oos.writeObject(acutalObject);
// Deserialization
User deserializedUser = null;
FileInputStream fis = new FileInputStream("user.ser");
User deserializedUser;
FileInputStream fis = new FileInputStream(USER_SER);
ObjectInputStream ois = new ObjectInputStream(fis);
deserializedUser = (User) ois.readObject();
assertNotEquals(deserializedUser.hashCode(), acutalObject.hashCode());
assertEquals(deserializedUser.getUserName(), "Sachin");
// remove readObject() from User class and uncomment this to test.
//assertEquals(deserializedUser.getPassword(), "xyzKumar");
fos.close();
oos.close();
fis.close();
ois.close();
}
}

View File

@ -3,7 +3,7 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-streams-4</artifactId>
<artifactId>core-java-streams-collect</artifactId>
<name>core-java-streams-collect</name>
<packaging>jar</packaging>

View File

@ -5,3 +5,5 @@ This module contains articles about string APIs.
### Relevant Articles:
- [Retain Only Digits and Decimal Separator in String](https://www.baeldung.com/java-string-retain-digits-decimal)
- [Difference Between null and Empty String in Java](https://www.baeldung.com/java-string-null-vs-empty)
- [Guide to Java String Pool](https://www.baeldung.com/java-string-pool)
- [Java Localization Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting)

View File

@ -24,6 +24,11 @@
<artifactId>commons-lang3</artifactId>
<version>${commons.lang3.version}</version>
</dependency>
<dependency>
<groupId>com.ibm.icu</groupId>
<artifactId>icu4j</artifactId>
<version>${icu4j.version}</version>
</dependency>
</dependencies>
<build>
@ -39,6 +44,7 @@
<properties>
<commons.lang3.version>3.12.0</commons.lang3.version>
<guava.version>31.1-jre</guava.version>
<icu4j.version>61.1</icu4j.version>
</properties>
</project>

View File

@ -29,6 +29,11 @@
<artifactId>commons-lang3</artifactId>
<version>${apache-commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>${apache-commons-text.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
@ -56,6 +61,7 @@
<opencsv.version>4.1</opencsv.version>
<spring-core.version>5.3.13</spring-core.version>
<apache-commons-lang3.version>3.12.0</apache-commons-lang3.version>
<apache-commons-text.version>1.10.0</apache-commons-text.version>
</properties>
</project>

View File

@ -1,6 +1,6 @@
package com.baeldung.namedformatting;
import org.apache.commons.text.StrSubstitutor;
import org.apache.commons.text.StringSubstitutor;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
@ -12,20 +12,20 @@ class NamedFormatterUnitTest {
private static final String TEMPLATE = "Text: [${text}] Number: [${number}] Text again: [${text}]";
@Test
void givenTemplateWithNamedParam_whenCallingCommonsTextStrSubstitutor_shouldGetExpectedResult() {
void givenTemplateWithNamedParam_whenCallingCommonsTextStringSubstitutor_shouldGetExpectedResult() {
Map<String, Object> params = new HashMap<>();
params.put("text", "It's awesome!");
params.put("number", 42);
String result = StrSubstitutor.replace(TEMPLATE, params, "${", "}");
String result = StringSubstitutor.replace(TEMPLATE, params, "${", "}");
assertThat(result).isEqualTo("Text: [It's awesome!] Number: [42] Text again: [It's awesome!]");
}
@Test
void givenTemplateWithNamedParam_whenCallingCommonsTextStrSubstitutorWithParameterNames_shouldNotWorkAsExpected() {
void givenTemplateWithNamedParam_whenCallingCommonsTextStringSubstitutorWithParameterNames_shouldNotWorkAsExpected() {
Map<String, Object> params = new HashMap<>();
params.put("text", "'${number}' is a placeholder.");
params.put("number", 42);
String result = StrSubstitutor.replace(TEMPLATE, params, "${", "}");
String result = StringSubstitutor.replace(TEMPLATE, params, "${", "}");
assertThat(result).isNotEqualTo("Text: ['${number}' is a placeholder.] Number: [42] Text again: ['${number}' is a placeholder.]");

View File

@ -2,3 +2,7 @@
### Relevant Articles:
- [Find the Longest Word in a Given String in Java](https://www.baeldung.com/java-longest-word-string)
- [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)

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-string-operations-6</artifactId>
<name>core-java-string-operations-6</name>
@ -12,6 +12,23 @@
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${apache.commons-lang.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
@ -29,6 +46,8 @@
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<apache.commons-lang.version>3.12.0</apache.commons-lang.version>
<jmh.version>1.36</jmh.version>
</properties>
</project>

View File

@ -0,0 +1,50 @@
package com.baeldung.nonalphanumeric;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NonAlphaNumRegexChecker {
private static final Pattern PATTERN_NON_ALPHNUM_ANYLANG = Pattern.compile("[^\\p{IsAlphabetic}\\p{IsDigit}]");
private static final Pattern PATTERN_NON_ALPHNUM_USASCII = Pattern.compile("[^a-zA-Z0-9]+");
/**
* checks if a non-alphanumeric character is present. this method would return true if
* it comes across a non english or non US-ASCII letter
*
* @param str - String to check for special character
* @return true if special character found else false
*/
public static boolean isNonAlphanumeric(String str) {
// Pattern pattern = Pattern.compile("\\W"); //same as [^a-zA-Z0-9]+
// Pattern pattern = Pattern.compile("[^a-zA-Z0-9||\\s]+"); //ignores space
Matcher matcher = PATTERN_NON_ALPHNUM_USASCII.matcher(str);
return matcher.find();
}
/**
* Checks for non-alphanumeric characters from all language scripts
*
* @param input - String to check for special character
* @return true if special character found else false
*/
public static boolean containsNonAlphanumeric(String input) {
// Pattern pattern = Pattern.compile("[^\\p{Alnum}]", Pattern.UNICODE_CHARACTER_CLASS); //Binary properties
Matcher matcher = PATTERN_NON_ALPHNUM_ANYLANG.matcher(input);
return matcher.find();
}
/**
* checks for non-alphanumeric character. it returns true if it detects any character other than the
* specified script argument. example of script - Character.UnicodeScript.GEORGIAN.name()
*
* @param input - String to check for special character
* @param script - language script
* @return true if special character found else false
*/
public static boolean containsNonAlphanumeric(String input, String script) {
String regexScriptClass = "\\p{" + "Is" + script + "}";
Pattern pattern = Pattern.compile("[^" + regexScriptClass + "\\p{IsDigit}]"); //Binary properties
Matcher matcher = pattern.matcher(input);
return matcher.find();
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.nonalphanumeric;
import org.apache.commons.lang3.StringUtils;
public class NonAlphaNumericChecker {
/**
* Checks for non-alphanumeric characters in any Unicode Script
* @param str - String to check for special characters
* @return true if special character found else false
*/
public static boolean isNonAlphanumericAnyLangScript(String str) {
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (!Character.isLetterOrDigit(c)) {
return true;
}
}
return false;
}
/**
* checks for special characters,returns false if any character
* found other than the script argument
* @param str - String to check for special characters
* @param script - Language script
* @return true if special character found else false
*/
public static boolean isNonAlphanumericInLangScript(String str, String script) {
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
// script e.g., Character.UnicodeScript.of(c).toString().equalsIgnoreCase(Character.UnicodeScript.LATIN.toString())
if (!Character.UnicodeScript.of(c).toString().equalsIgnoreCase(script)
&& !Character.isDigit(c)) {
return true;
}
}
return false;
}
/**
* checks for special characters in any lang
* @param str - String to check for special characters
* @return true if special character found else false
*/
public static boolean isNonAlphanumericAnyLangScriptV2(String str) {
return !StringUtils.isAlphanumeric(str);
}
}

View File

@ -0,0 +1,104 @@
package com.baeldung.checkcase;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
class CaseChecker {
static boolean allUpper1(String input) {
return input.equals(input.toUpperCase());
}
static boolean allLower1(String input) {
return input.equals(input.toLowerCase());
}
static boolean allUpper2(String input) {
for (char c : input.toCharArray()) {
// don't write in this way: if (!Character.isUpperCase(c))
if (Character.isLowerCase(c)) {
return false;
}
}
return true;
}
static boolean allLower2(String input) {
for (char c : input.toCharArray()) {
// don't write in this way: if (!Character.isLowerCase(c))
if (Character.isUpperCase(c)) {
return false;
}
}
return true;
}
static boolean allUpper3(String input) {
return input.chars()
.noneMatch(Character::isLowerCase);
}
static boolean allLower3(String input) {
return input.chars()
.noneMatch(Character::isUpperCase);
}
}
public class StringAllUpperOrLowercaseUnitTest {
private static final String UPPER_INPUT = "1: COOL!";
private static final String LOWER_INPUT = "2: cool!";
private static final String MIXED_INPUT = "3: Cool";
@Test
void whenComparingToConvertedString_thenGetExpectedResult() {
assertTrue(CaseChecker.allLower1(LOWER_INPUT));
assertFalse(CaseChecker.allLower1(UPPER_INPUT));
assertFalse(CaseChecker.allLower1(MIXED_INPUT));
assertFalse(CaseChecker.allUpper1(LOWER_INPUT));
assertTrue(CaseChecker.allUpper1(UPPER_INPUT));
assertFalse(CaseChecker.allUpper1(MIXED_INPUT));
}
@Test
void whenCheckCharInArray_thenGetExpectedResult() {
assertTrue(CaseChecker.allLower2(LOWER_INPUT));
assertFalse(CaseChecker.allLower2(UPPER_INPUT));
assertFalse(CaseChecker.allLower2(MIXED_INPUT));
assertFalse(CaseChecker.allUpper2(LOWER_INPUT));
assertTrue(CaseChecker.allUpper2(UPPER_INPUT));
assertFalse(CaseChecker.allUpper2(MIXED_INPUT));
}
@Test
void whenUsingStream_thenGetExpectedResult() {
assertTrue(CaseChecker.allLower3(LOWER_INPUT));
assertFalse(CaseChecker.allLower3(UPPER_INPUT));
assertFalse(CaseChecker.allLower3(MIXED_INPUT));
assertFalse(CaseChecker.allUpper3(LOWER_INPUT));
assertTrue(CaseChecker.allUpper3(UPPER_INPUT));
assertFalse(CaseChecker.allUpper3(MIXED_INPUT));
}
@Test
void whenUsingApacheCommons_thenGetExpectedResult() {
assertFalse(StringUtils.isAllLowerCase(LOWER_INPUT));
assertFalse(StringUtils.isAllLowerCase(UPPER_INPUT));
assertFalse(StringUtils.isAllLowerCase(MIXED_INPUT));
assertFalse(StringUtils.isAllLowerCase("a b"));
assertTrue(StringUtils.isAllLowerCase("ab"));
assertFalse(StringUtils.isAllUpperCase(LOWER_INPUT));
assertFalse(StringUtils.isAllUpperCase(UPPER_INPUT));
assertFalse(StringUtils.isAllUpperCase(MIXED_INPUT));
assertFalse(StringUtils.isAllUpperCase("A B"));
assertTrue(StringUtils.isAllUpperCase("AB"));
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.digitsandnondigits;
import static com.baeldung.digitsandnondigits.SplitDigitsAndNondigitsUnitTest.parseString;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
@State(Scope.Benchmark)
@Threads(1)
@BenchmarkMode(Mode.Throughput)
@Fork(warmups = 1, value = 1)
@Warmup(iterations = 2, time = 10, timeUnit = TimeUnit.MILLISECONDS)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class BenchmarkLiveTest {
private static final String INPUT = "01Michael Jackson23Michael Jordan42Michael Bolton999Michael Johnson000";
@Param({ "10000" })
public int iterations;
@Benchmark
public void regexBased(Blackhole blackhole) {
blackhole.consume(INPUT.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"));
}
@Benchmark
public void nonRegexBased(Blackhole blackhole) {
blackhole.consume(parseString(INPUT));
}
@Test
public void benchmark() throws Exception {
String[] argv = {};
org.openjdk.jmh.Main.main(argv);
}
}

View File

@ -0,0 +1,69 @@
package com.baeldung.digitsandnondigits;
import static com.baeldung.digitsandnondigits.SplitDigitsAndNondigitsUnitTest.State.INIT;
import static com.baeldung.digitsandnondigits.SplitDigitsAndNondigitsUnitTest.State.PARSING_DIGIT;
import static com.baeldung.digitsandnondigits.SplitDigitsAndNondigitsUnitTest.State.PARSING_NON_DIGIT;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
public class SplitDigitsAndNondigitsUnitTest {
private static final String INPUT1 = "01Michael Jackson23Michael Jordan42Michael Bolton999Michael Johnson000";
private static final String[] EXPECTED1 = new String[] { "01", "Michael Jackson", "23", "Michael Jordan", "42", "Michael Bolton", "999", "Michael Johnson", "000" };
private static final List<String> EXPECTED_LIST1 = Arrays.asList(EXPECTED1);
private static final String INPUT2 = "Michael Jackson01Michael Jordan23Michael Bolton42Michael Johnson999Great Michaels";
private static final String[] EXPECTED2 = new String[] { "Michael Jackson", "01", "Michael Jordan", "23", "Michael Bolton", "42", "Michael Johnson", "999", "Great Michaels" };
private static final List<String> EXPECTED_LIST2 = Arrays.asList(EXPECTED2);
@Test
void whenUsingLookaroundRegex_thenGetExpectedResult() {
String splitRE = "(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)";
String[] result1 = INPUT1.split(splitRE);
assertArrayEquals(EXPECTED1, result1);
String[] result2 = INPUT2.split(splitRE);
assertArrayEquals(EXPECTED2, result2);
}
enum State {
INIT, PARSING_DIGIT, PARSING_NON_DIGIT
}
static List<String> parseString(String input) {
List<String> result = new ArrayList<>();
int start = 0;
State state = INIT;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) >= '0' && input.charAt(i) <= '9') {
if (state == PARSING_NON_DIGIT) {
result.add(input.substring(start, i));
start = i;
}
state = PARSING_DIGIT;
} else {
if (state == PARSING_DIGIT) {
result.add(input.substring(start, i));
start = i;
}
state = PARSING_NON_DIGIT;
}
}
result.add(input.substring(start));
return result;
}
@Test
void whenCheckEachChar_thenGetExpectedResult() {
List<String> result1 = parseString(INPUT1);
assertEquals(EXPECTED_LIST1, result1);
List<String> result2 = parseString(INPUT2);
assertEquals(EXPECTED_LIST2, result2);
}
}

View File

@ -0,0 +1,117 @@
package com.baeldung.nonalphanumeric;
import org.junit.Test;
import static org.junit.Assert.*;
public class NonAlphaNumRegexCheckerUnitTest {
@Test
public void whenStrLatinOrHasNonAlphaNum_ThenRetTrue() {
//alphabets with special character
String str1 = "W$nder^ful";
//digits with special character
String str2 = "123$%45";
//alphabets and digits with special characters
String str3 = "W@nd$r123$%45";
//Error message
String ERROR_MSG = "Test failed, no alphanumeric char found in ";
assertTrue(ERROR_MSG + str1, NonAlphaNumRegexChecker.isNonAlphanumeric(str1));
assertTrue(ERROR_MSG + str2, NonAlphaNumRegexChecker.isNonAlphanumeric(str2));
assertTrue(ERROR_MSG + str3, NonAlphaNumRegexChecker.isNonAlphanumeric(str3));
}
@Test
public void whenStrLatinOrHasNoNonAlphaNum_ThenRetFalse() {
//only alphabets
String str1 = "Wonderful";
//only digits
String str2 = "12345";
//mix of alphabet and digit
String str3 = "5Won6der1234";
//Error message
String ERROR_MSG = "Test failed, non alphanumeric char found in ";
assertFalse(ERROR_MSG + str1, NonAlphaNumRegexChecker.isNonAlphanumeric(str1));
assertFalse(ERROR_MSG + str2, NonAlphaNumRegexChecker.isNonAlphanumeric(str2));
assertFalse(ERROR_MSG + str3, NonAlphaNumRegexChecker.isNonAlphanumeric(str3));
}
@Test
public void whenStrNonLatinOrHasNonAlphaNum_ThenRetTrue() {
//special character in Georgian text
String str1 = "##მშვენიერი@";
//special character with Turkish text
String str2 = "müthiş#$";
//No special character in Georgian text
String str3 = "მშვენიერი";
//Error message
String ERROR_MSG = "Test failed, no alphanumeric char found in ";
assertTrue(ERROR_MSG + str1, NonAlphaNumRegexChecker.isNonAlphanumeric(str1));
assertTrue(ERROR_MSG + str2, NonAlphaNumRegexChecker.isNonAlphanumeric(str2));
assertTrue(ERROR_MSG + str3, NonAlphaNumRegexChecker.isNonAlphanumeric(str3));
}
@Test
public void whenStrAnyLangOrHasNonAlphaNum_ThenRetTrue() {
//special character in Georgian text
String str1 = "##მშვენიერი@";
//special character with Turkish text
String str2 = "müthiş#$";
//Error message
String ERROR_MSG = "Test failed, no alphanumeric char found in ";
assertTrue(ERROR_MSG + str1, NonAlphaNumRegexChecker.containsNonAlphanumeric(str1));
assertTrue(ERROR_MSG + str2, NonAlphaNumRegexChecker.containsNonAlphanumeric(str2));
}
@Test
public void whenStrAnyLangOrHasNoNonAlphaNum_ThenRetFalse() {
//Georgian text with no special char
String str1 = "მშვენიერი";
//Turkish text with no special char
String str2 = "müthiş";
//Latin text with no special char
String str3 = "Wonderful";
//Error message
String ERROR_MSG = "Test failed, no alphanumeric char found in ";
assertFalse(ERROR_MSG + str1, NonAlphaNumRegexChecker.containsNonAlphanumeric(str1));
assertFalse(ERROR_MSG + str2, NonAlphaNumRegexChecker.containsNonAlphanumeric(str2));
assertFalse(ERROR_MSG + str3, NonAlphaNumRegexChecker.containsNonAlphanumeric(str3));
}
@Test
public void givenLang_whenStrHasDiffLangOrHasNonAlphaNum_ThenRetTrue() {
String script1 = Character.UnicodeScript.MYANMAR.name(); //script used for Burmese Lang
//text in Burmese with special char
String str1 = "အံ့ဩ%စ##ရာ";
//special character and english char in Burmese
String str2 = "အံ့ADFဩစ%ရာ*^";
//English character in Burmese
String str3 = "အံ့ဩစTရာWon";
//Error message
String ERROR_MSG = "Test failed, no alphanumeric char found in ";
assertTrue(ERROR_MSG + str1, NonAlphaNumRegexChecker.containsNonAlphanumeric(str1, script1));
assertTrue(ERROR_MSG + str2, NonAlphaNumRegexChecker.containsNonAlphanumeric(str2, script1));
assertTrue(ERROR_MSG + str3, NonAlphaNumRegexChecker.containsNonAlphanumeric(str3, script1));
}
@Test
public void givenLang_whenStrHasSameLangOrHasNoNonAlphaNum_ThenRetFalse() {
String script1 = Character.UnicodeScript.MYANMAR.name(); //script used for Burmese Lang
String script2 = Character.UnicodeScript.GREEK.name();
//text in Burmese
String str1 = "အံ့ဩစရာ";
//text in Greek
String str2 = "Εκπληκτικός";
//Error message
String ERROR_MSG = "Test failed, alphanumeric char found in ";
assertFalse(ERROR_MSG + str1, NonAlphaNumRegexChecker.containsNonAlphanumeric(str1, script1));
assertFalse(ERROR_MSG + str2, NonAlphaNumRegexChecker.containsNonAlphanumeric(str2, script2));
}
}

View File

@ -0,0 +1,159 @@
package com.baeldung.nonalphanumeric;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class NonAlphaNumericCheckerUnitTest {
@Test
public void whenStrLatinOrHasNonAlphaNum_ThenRetTrue() {
String latin = Character.UnicodeScript.LATIN.name();
//alphabets with special character
String str1 = "W$nder^ful";
//digits with special character
String str2 = "123$%45";
//alphabets and digits with special characters
String str3 = "W@nd$r123$%45";
//Error message
String ERROR_MSG = "Test failed, no alphanumeric char found in ";
assertTrue(ERROR_MSG + str1, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str1, latin));
assertTrue(ERROR_MSG + str2, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str2, latin));
assertTrue(ERROR_MSG + str3, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str3, latin));
}
@Test
public void whenStrLatinOrHasNoNonAlphaNum_ThenRetFalse() {
String latin = Character.UnicodeScript.LATIN.name();
//only alphabets
String str1 = "Wonderful";
//only digits
String str2 = "12345";
//mix of alphabet and digit
String str3 = "5Won6der1234";
//Error message
String ERROR_MSG = "Test failed, non alphanumeric char found in ";
assertFalse(ERROR_MSG + str1, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str1, latin));
assertFalse(ERROR_MSG + str2, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str2, latin));
assertFalse(ERROR_MSG + str3, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str3, latin));
}
@Test
public void whenStrNonLatinOrHasNonAlphaNum_ThenRetTrue() {
String latin = Character.UnicodeScript.LATIN.name();
//special character in Georgian text
String str1 = "##მშვენიერი@";
//special character with Turkish text
String str2 = "müthiş#$";
//No special character in Georgian text
String str3 = "მშვენიერი";
//Error message
String ERROR_MSG = "Test failed, no alphanumeric char found in ";
assertTrue(ERROR_MSG + str1, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str1, latin));
assertTrue(ERROR_MSG + str2, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str2, latin));
assertTrue(ERROR_MSG + str3, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str3, latin));
}
@Test
public void whenStrAnyLangOrHasNonAlphaNum_ThenRetTrue() {
//special character in Georgian text
String str1 = "##მშვენიერი@";
//special character with Turkish text
String str2 = "müthiş#$";
//Error message
String ERROR_MSG = "Test failed, no alphanumeric char found in ";
assertTrue(ERROR_MSG + str1, NonAlphaNumericChecker.isNonAlphanumericAnyLangScript(str1));
assertTrue(ERROR_MSG + str2, NonAlphaNumericChecker.isNonAlphanumericAnyLangScript(str2));
}
@Test
public void whenStrAnyLangOrHasNoNonAlphaNum_ThenRetFalse() {
//Georgian text with no special char
String str1 = "მშვენიერი";
//Turkish text with no special char
String str2 = "müthiş";
//Latin text with no special char
String str3 = "Wonderful";
//Error message
String ERROR_MSG = "Test failed, no alphanumeric char found in ";
assertFalse(ERROR_MSG + str1, NonAlphaNumericChecker.isNonAlphanumericAnyLangScript(str1));
assertFalse(ERROR_MSG + str2, NonAlphaNumericChecker.isNonAlphanumericAnyLangScript(str2));
assertFalse(ERROR_MSG + str3, NonAlphaNumericChecker.isNonAlphanumericAnyLangScript(str3));
}
@Test
public void givenLang_whenStrHasDiffLangOrHasNonAlphaNum_ThenRetTrue() {
String script1 = Character.UnicodeScript.MYANMAR.name(); //script used for Burmese Lang
//text in Burmese with special char
String str1 = "အံ့ဩ%စ##ရာ";
//special character and english char in Burmese
String str2 = "အံ့ADFဩစ%ရာ*^";
//English character in Burmese
String str3 = "အံ့ဩစTရာWon";
//Error message
String ERROR_MSG = "Test failed, no alphanumeric char found in ";
assertTrue(ERROR_MSG + str1, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str1, script1));
assertTrue(ERROR_MSG + str2, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str2, script1));
assertTrue(ERROR_MSG + str3, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str3, script1));
}
@Test
public void givenLang_whenStrHasSameLangOrHasNoNonAlphaNum_ThenRetFalse() {
String script1 = Character.UnicodeScript.MYANMAR.name(); //script used for Burmese Lang
String script2 = Character.UnicodeScript.GREEK.name();
//text in Burmese
String str1 = "အံ့ဩစရာ";
//text in Greek
String str2 = "Εκπληκτικός";
//Error message
String ERROR_MSG = "Test failed, alphanumeric char found in ";
assertFalse(ERROR_MSG + str1, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str1, script1));
assertFalse(ERROR_MSG + str2, NonAlphaNumericChecker.isNonAlphanumericInLangScript(str2, script2));
}
@Test
public void givenComLangImpl_whenStrAnyLangOrHasNonAlphaNum_ThenRetTrue() {
//special character in Georgian text
String str1 = "##მშვენიერი@";
//special character with Turkish text
String str2 = "müthiş#$";
//Error message
String ERROR_MSG = "Test failed, no alphanumeric char found in ";
assertTrue(ERROR_MSG + str1, NonAlphaNumericChecker.isNonAlphanumericAnyLangScriptV2(str1));
assertTrue(ERROR_MSG + str2, NonAlphaNumericChecker.isNonAlphanumericAnyLangScriptV2(str2));
}
@Test
public void givenComLangImpl_whenStrAnyLangOrHasNoNonAlphaNum_ThenRetFalse() {
//Georgian text with no special char
String str1 = "მშვენიერი";
//Turkish text with no special char
String str2 = "müthiş";
//Latin text with no special char
String str3 = "Wonderful";
//Burmese in Myanmar script
// String str4 = "အံ့ဩစရာ";
//only digits
String str5 = "3465";
//Error message
String ERROR_MSG = "Test failed, alphanumeric char found in ";
assertFalse(ERROR_MSG + str1, NonAlphaNumericChecker.isNonAlphanumericAnyLangScriptV2(str1));
assertFalse(ERROR_MSG + str2, NonAlphaNumericChecker.isNonAlphanumericAnyLangScriptV2(str2));
assertFalse(ERROR_MSG + str3, NonAlphaNumericChecker.isNonAlphanumericAnyLangScriptV2(str3));
//StringUtils.isAlphanumeric is unable to support supplementary unicode character and hence fails
//assertFalse(ERROR_MSG + str4, NonAlphaNumericChecker.isNonAlphanumericAnyLangScriptV2(str4));
assertFalse(ERROR_MSG + str5, NonAlphaNumericChecker.isNonAlphanumericAnyLangScriptV2(str5));
}
}

View File

@ -1,103 +1,103 @@
package com.baeldung.randomstrings;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.Charset;
import java.util.Random;
public class RandomStringsUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(RandomStringsUnitTest.class);
@Test
public void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() {
byte[] array = new byte[7]; // length is bounded by 7
new Random().nextBytes(array);
String generatedString = new String(array, Charset.forName("UTF-8"));
LOG.debug(generatedString);
}
@Test
public void givenUsingPlainJava_whenGeneratingRandomStringBounded_thenCorrect() {
int leftLimit = 97; // letter 'a'
int rightLimit = 122; // letter 'z'
int targetStringLength = 10;
Random random = new Random();
StringBuilder buffer = new StringBuilder(targetStringLength);
for (int i = 0; i < targetStringLength; i++) {
int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1));
buffer.append((char) randomLimitedInt);
}
String generatedString = buffer.toString();
LOG.debug(generatedString);
}
@Test
public void givenUsingJava8_whenGeneratingRandomAlphabeticString_thenCorrect() {
int leftLimit = 97; // letter 'a'
int rightLimit = 122; // letter 'z'
int targetStringLength = 10;
Random random = new Random();
String generatedString = random.ints(leftLimit, rightLimit + 1)
.limit(targetStringLength)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
LOG.debug(generatedString);
}
@Test
public void givenUsingJava8_whenGeneratingRandomAlphanumericString_thenCorrect() {
int leftLimit = 48; // numeral '0'
int rightLimit = 122; // letter 'z'
int targetStringLength = 10;
Random random = new Random();
String generatedString = random.ints(leftLimit, rightLimit + 1)
.filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97))
.limit(targetStringLength)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
LOG.debug(generatedString);
}
@Test
public void givenUsingApache_whenGeneratingRandomString_thenCorrect() {
String generatedString = RandomStringUtils.random(10);
LOG.debug(generatedString);
}
@Test
public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() {
String generatedString = RandomStringUtils.randomAlphabetic(10);
LOG.debug(generatedString);
}
@Test
public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() {
String generatedString = RandomStringUtils.randomAlphanumeric(10);
LOG.debug(generatedString);
}
@Test
public void givenUsingApache_whenGeneratingRandomStringBounded_thenCorrect() {
int length = 10;
boolean useLetters = true;
boolean useNumbers = false;
String generatedString = RandomStringUtils.random(length, useLetters, useNumbers);
LOG.debug(generatedString);
}
}
package com.baeldung.randomstrings;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.Charset;
import java.util.Random;
public class RandomStringsUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(RandomStringsUnitTest.class);
@Test
public void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() {
byte[] array = new byte[7]; // length is bounded by 7
new Random().nextBytes(array);
String generatedString = new String(array, Charset.forName("UTF-8"));
LOG.debug(generatedString);
}
@Test
public void givenUsingPlainJava_whenGeneratingRandomStringBounded_thenCorrect() {
int leftLimit = 97; // letter 'a'
int rightLimit = 122; // letter 'z'
int targetStringLength = 10;
Random random = new Random();
StringBuilder buffer = new StringBuilder(targetStringLength);
for (int i = 0; i < targetStringLength; i++) {
int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1));
buffer.append((char) randomLimitedInt);
}
String generatedString = buffer.toString();
LOG.debug(generatedString);
}
@Test
public void givenUsingJava8_whenGeneratingRandomAlphabeticString_thenCorrect() {
int leftLimit = 97; // letter 'a'
int rightLimit = 122; // letter 'z'
int targetStringLength = 10;
Random random = new Random();
String generatedString = random.ints(leftLimit, rightLimit + 1)
.limit(targetStringLength)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
LOG.debug(generatedString);
}
@Test
public void givenUsingJava8_whenGeneratingRandomAlphanumericString_thenCorrect() {
int leftLimit = 48; // numeral '0'
int rightLimit = 122; // letter 'z'
int targetStringLength = 10;
Random random = new Random();
String generatedString = random.ints(leftLimit, rightLimit + 1)
.filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97))
.limit(targetStringLength)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
LOG.debug(generatedString);
}
@Test
public void givenUsingApache_whenGeneratingRandomString_thenCorrect() {
String generatedString = RandomStringUtils.random(10);
LOG.debug(generatedString);
}
@Test
public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() {
String generatedString = RandomStringUtils.randomAlphabetic(10);
LOG.debug(generatedString);
}
@Test
public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() {
String generatedString = RandomStringUtils.randomAlphanumeric(10);
LOG.debug(generatedString);
}
@Test
public void givenUsingApache_whenGeneratingRandomStringBounded_thenCorrect() {
int length = 10;
boolean useLetters = true;
boolean useNumbers = false;
String generatedString = RandomStringUtils.random(length, useLetters, useNumbers);
LOG.debug(generatedString);
}
}

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