Merge branch 'master' of https://github.com/eugenp/tutorials into
task/JAVA-13721 # Conflicts: # testing-modules/mockito-simple/pom.xml
This commit is contained in:
commit
c3767c3a91
|
@ -2,4 +2,5 @@
|
|||
|
||||
- [Algorithm to Identify and Validate a Credit Card Number](https://www.baeldung.com/java-validate-cc-number)
|
||||
- [Find the N Most Frequent Elements in a Java Array](https://www.baeldung.com/java-n-most-frequent-elements-array)
|
||||
- [Getting Pixel Array From Image in Java](https://www.baeldung.com/java-getting-pixel-array-from-image)
|
||||
- More articles: [[<-- prev]](/algorithms-miscellaneous-6)
|
||||
|
|
|
@ -0,0 +1,65 @@
|
|||
package com.baeldung.algorithms.pixelarray;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.awt.image.DataBufferByte;
|
||||
public class GetPixelArray {
|
||||
|
||||
public static int[][] get2DPixelArraySlow(BufferedImage sampleImage) {
|
||||
int width = sampleImage.getWidth();
|
||||
int height = sampleImage.getHeight();
|
||||
int[][] result = new int[height][width];
|
||||
|
||||
for (int row = 0; row < height; row++) {
|
||||
for (int col = 0; col < width; col++) {
|
||||
result[row][col] = sampleImage.getRGB(col, row);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static int[][] get2DPixelArrayFast(BufferedImage image) {
|
||||
final byte[] pixelData = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
|
||||
final int width = image.getWidth();
|
||||
final int height = image.getHeight();
|
||||
final boolean hasAlphaChannel = image.getAlphaRaster() != null;
|
||||
|
||||
int[][] result = new int[height][width];
|
||||
if (hasAlphaChannel) {
|
||||
final int numberOfValues = 4;
|
||||
for (int valueIndex = 0, row = 0, col = 0; valueIndex + numberOfValues - 1 < pixelData.length; valueIndex += numberOfValues) {
|
||||
// Getting the values for each pixel from the pixelData array.
|
||||
int argb = 0;
|
||||
argb += (((int) pixelData[valueIndex] & 0xff) << 24); // alpha value
|
||||
argb += ((int) pixelData[valueIndex + 1] & 0xff); // blue value
|
||||
argb += (((int) pixelData[valueIndex + 2] & 0xff) << 8); // green value
|
||||
argb += (((int) pixelData[valueIndex + 3] & 0xff) << 16); // red value
|
||||
result[row][col] = argb;
|
||||
|
||||
col++;
|
||||
if (col == width) {
|
||||
col = 0;
|
||||
row++;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
final int numberOfValues = 3;
|
||||
for (int valueIndex = 0, row = 0, col = 0; valueIndex + numberOfValues - 1 < pixelData.length; valueIndex += numberOfValues) {
|
||||
int argb = 0;
|
||||
argb += -16777216; // 255 alpha value (fully opaque)
|
||||
argb += ((int) pixelData[valueIndex] & 0xff); // blue value
|
||||
argb += (((int) pixelData[valueIndex + 1] & 0xff) << 8); // green value
|
||||
argb += (((int) pixelData[valueIndex + 2] & 0xff) << 16); // red value
|
||||
result[row][col] = argb;
|
||||
|
||||
col++;
|
||||
if (col == width) {
|
||||
col = 0;
|
||||
row++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package com.baeldung.algorithms.pixelarray;
|
||||
|
||||
import static com.baeldung.algorithms.pixelarray.GetPixelArray.get2DPixelArrayFast;
|
||||
import static com.baeldung.algorithms.pixelarray.GetPixelArray.get2DPixelArraySlow;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class GetPixelArrayUnitTest {
|
||||
@Test
|
||||
public void givenImage_whenGetPixelArray_thenBothMethodsReturnEqualValues() {
|
||||
BufferedImage sampleImage = null;
|
||||
try {
|
||||
sampleImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
int[][] firstResult = get2DPixelArraySlow(sampleImage);
|
||||
int[][] secondResult = get2DPixelArrayFast(sampleImage);
|
||||
|
||||
assertTrue(Arrays.deepEquals(firstResult, secondResult));
|
||||
}
|
||||
}
|
|
@ -7,3 +7,4 @@ You can build the project from the command line using: *mvn clean install*, or i
|
|||
|
||||
### Relevant Articles:
|
||||
- [Guide to Check if Apache Kafka Server Is Running](https://www.baeldung.com/apache-kafka-check-server-is-running)
|
||||
- [Add Custom Headers to a Kafka Message](https://www.baeldung.com/java-kafka-custom-headers)
|
||||
|
|
|
@ -0,0 +1,88 @@
|
|||
package com.baeldung.kafka.headers;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.kafka.clients.consumer.ConsumerConfig;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecords;
|
||||
import org.apache.kafka.clients.consumer.KafkaConsumer;
|
||||
import org.apache.kafka.clients.producer.KafkaProducer;
|
||||
import org.apache.kafka.clients.producer.ProducerConfig;
|
||||
import org.apache.kafka.clients.producer.ProducerRecord;
|
||||
import org.apache.kafka.common.header.Header;
|
||||
import org.apache.kafka.common.header.Headers;
|
||||
import org.apache.kafka.common.header.internals.RecordHeader;
|
||||
import org.apache.kafka.common.serialization.StringDeserializer;
|
||||
import org.apache.kafka.common.serialization.StringSerializer;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class KafkaMessageHeaders {
|
||||
|
||||
private static Logger logger = LoggerFactory.getLogger(KafkaMessageHeaders.class);
|
||||
|
||||
private static String TOPIC = "baeldung";
|
||||
private static String MESSAGE_KEY = "message";
|
||||
private static String MESSAGE_VALUE = "Hello World";
|
||||
private static String HEADER_KEY = "website";
|
||||
private static String HEADER_VALUE = "baeldung.com";
|
||||
|
||||
private static KafkaProducer<String, String> producer;
|
||||
private static KafkaConsumer<String, String> consumer;
|
||||
|
||||
public static void main(String[] args) {
|
||||
setup();
|
||||
|
||||
publishMessageWithCustomHeaders();
|
||||
|
||||
consumeMessageWithCustomHeaders();
|
||||
}
|
||||
|
||||
private static void consumeMessageWithCustomHeaders() {
|
||||
consumer.subscribe(Arrays.asList(TOPIC));
|
||||
|
||||
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMinutes(1));
|
||||
for (ConsumerRecord<String, String> record : records) {
|
||||
logger.info(record.key());
|
||||
logger.info(record.value());
|
||||
|
||||
Headers headers = record.headers();
|
||||
for (Header header : headers) {
|
||||
logger.info(header.key());
|
||||
logger.info(new String(header.value()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void publishMessageWithCustomHeaders() {
|
||||
List<Header> headers = new ArrayList<>();
|
||||
headers.add(new RecordHeader(HEADER_KEY, HEADER_VALUE.getBytes()));
|
||||
|
||||
ProducerRecord<String, String> record1 = new ProducerRecord<>(TOPIC, null, MESSAGE_KEY, MESSAGE_VALUE, headers);
|
||||
producer.send(record1);
|
||||
|
||||
ProducerRecord<String, String> record2 = new ProducerRecord<>(TOPIC, null, System.currentTimeMillis(), MESSAGE_KEY, MESSAGE_VALUE, headers);
|
||||
producer.send(record2);
|
||||
}
|
||||
|
||||
private static void setup() {
|
||||
Properties producerProperties = new Properties();
|
||||
producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
|
||||
producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
|
||||
producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
|
||||
|
||||
Properties consumerProperties = new Properties();
|
||||
consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
|
||||
consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
|
||||
consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
|
||||
consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "ConsumerGroup1");
|
||||
|
||||
producer = new KafkaProducer<>(producerProperties);
|
||||
consumer = new KafkaConsumer<>(consumerProperties);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,138 @@
|
|||
package com.baeldung.kafka;
|
||||
|
||||
import org.apache.kafka.clients.consumer.ConsumerConfig;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecords;
|
||||
import org.apache.kafka.clients.consumer.KafkaConsumer;
|
||||
import org.apache.kafka.clients.producer.KafkaProducer;
|
||||
import org.apache.kafka.clients.producer.ProducerConfig;
|
||||
import org.apache.kafka.clients.producer.ProducerRecord;
|
||||
import org.apache.kafka.common.TopicPartition;
|
||||
import org.apache.kafka.common.serialization.StringDeserializer;
|
||||
import org.apache.kafka.common.serialization.StringSerializer;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
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.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@Testcontainers
|
||||
public class KafaConsumeLastNMessages {
|
||||
|
||||
private static String TOPIC1 = "baeldung-github";
|
||||
private static String TOPIC2 = "baeldung-blog";
|
||||
private static String MESSAGE_KEY = "message";
|
||||
private static KafkaProducer<String, String> producer;
|
||||
private static KafkaConsumer<String, String> consumer;
|
||||
private static KafkaProducer<String, String> transactionalProducer;
|
||||
|
||||
@Container
|
||||
private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest"));
|
||||
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
KAFKA_CONTAINER.addExposedPort(9092);
|
||||
|
||||
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());
|
||||
|
||||
Properties consumerProperties = new Properties();
|
||||
consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
|
||||
consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
|
||||
consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
|
||||
consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "ConsumerGroup1");
|
||||
|
||||
Properties transactionalProducerProprieties = new Properties();
|
||||
transactionalProducerProprieties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
|
||||
transactionalProducerProprieties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
|
||||
transactionalProducerProprieties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
|
||||
transactionalProducerProprieties.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, "true");
|
||||
transactionalProducerProprieties.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "prod-0");
|
||||
|
||||
producer = new KafkaProducer<>(producerProperties);
|
||||
consumer = new KafkaConsumer<>(consumerProperties);
|
||||
transactionalProducer = new KafkaProducer<>(transactionalProducerProprieties);
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void destroy() {
|
||||
KAFKA_CONTAINER.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenSeekingKafkaTopicCursorToEnd_consumerRetrievesOnlyDesiredNumberOfMessages() throws ExecutionException, InterruptedException {
|
||||
int messagesInTopic = 100;
|
||||
int messagesToRetrieve = 20;
|
||||
|
||||
for (int i = 0; i < messagesInTopic; i++) {
|
||||
producer.send(new ProducerRecord<>(TOPIC1, null, MESSAGE_KEY, String.valueOf(i)))
|
||||
.get();
|
||||
}
|
||||
|
||||
TopicPartition partition = new TopicPartition(TOPIC1, 0);
|
||||
List<TopicPartition> partitions = new ArrayList<>();
|
||||
partitions.add(partition);
|
||||
consumer.assign(partitions);
|
||||
|
||||
consumer.seekToEnd(partitions);
|
||||
long startIndex = consumer.position(partition) - messagesToRetrieve;
|
||||
consumer.seek(partition, startIndex);
|
||||
|
||||
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMinutes(1));
|
||||
int recordsReceived = 0;
|
||||
for (ConsumerRecord<String, String> record : records) {
|
||||
assertEquals(MESSAGE_KEY, record.key());
|
||||
assertTrue(Integer.parseInt(record.value()) >= (messagesInTopic - messagesToRetrieve));
|
||||
recordsReceived++;
|
||||
}
|
||||
|
||||
assertEquals(messagesToRetrieve, recordsReceived);
|
||||
}
|
||||
|
||||
@Test
|
||||
void havingTransactionalProducer_whenSeekingKafkaTopicCursorToEnd_consumerRetrievesLessMessages() throws ExecutionException, InterruptedException {
|
||||
int messagesInTopic = 100;
|
||||
int messagesToRetrieve = 20;
|
||||
|
||||
transactionalProducer.initTransactions();
|
||||
for (int i = 0; i < messagesInTopic; i++) {
|
||||
transactionalProducer.beginTransaction();
|
||||
transactionalProducer.send(new ProducerRecord<>(TOPIC2, null, MESSAGE_KEY, String.valueOf(i)))
|
||||
.get();
|
||||
transactionalProducer.commitTransaction();
|
||||
}
|
||||
|
||||
TopicPartition partition = new TopicPartition(TOPIC2, 0);
|
||||
List<TopicPartition> partitions = new ArrayList<>();
|
||||
partitions.add(partition);
|
||||
consumer.assign(partitions);
|
||||
|
||||
consumer.seekToEnd(partitions);
|
||||
long startIndex = consumer.position(partition) - messagesToRetrieve;
|
||||
consumer.seek(partition, startIndex);
|
||||
|
||||
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMinutes(1));
|
||||
int recordsReceived = 0;
|
||||
for (ConsumerRecord<String, String> record : records) {
|
||||
assertEquals(MESSAGE_KEY, record.key());
|
||||
assertTrue(Integer.parseInt(record.value()) >= (messagesInTopic - messagesToRetrieve));
|
||||
recordsReceived++;
|
||||
}
|
||||
|
||||
assertTrue(messagesToRetrieve > recordsReceived);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,104 @@
|
|||
package com.baeldung.kafka.headers;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import org.apache.kafka.clients.consumer.ConsumerConfig;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecords;
|
||||
import org.apache.kafka.clients.consumer.KafkaConsumer;
|
||||
import org.apache.kafka.clients.producer.KafkaProducer;
|
||||
import org.apache.kafka.clients.producer.ProducerConfig;
|
||||
import org.apache.kafka.clients.producer.ProducerRecord;
|
||||
import org.apache.kafka.clients.producer.RecordMetadata;
|
||||
import org.apache.kafka.common.header.Header;
|
||||
import org.apache.kafka.common.header.Headers;
|
||||
import org.apache.kafka.common.header.internals.RecordHeader;
|
||||
import org.apache.kafka.common.serialization.StringDeserializer;
|
||||
import org.apache.kafka.common.serialization.StringSerializer;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
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;
|
||||
|
||||
// This live test needs a Docker Daemon running so that a kafka container can be created
|
||||
|
||||
@Testcontainers
|
||||
public class KafkaMessageHeadersLiveTest {
|
||||
|
||||
private static String TOPIC = "baeldung";
|
||||
private static String MESSAGE_KEY = "message";
|
||||
private static String MESSAGE_VALUE = "Hello World";
|
||||
private static String HEADER_KEY = "website";
|
||||
private static String HEADER_VALUE = "baeldung.com";
|
||||
|
||||
private static KafkaProducer<String, String> producer;
|
||||
private static KafkaConsumer<String, String> consumer;
|
||||
|
||||
@Container
|
||||
private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest"));
|
||||
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
KAFKA_CONTAINER.addExposedPort(9092);
|
||||
|
||||
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());
|
||||
|
||||
Properties consumerProperties = new Properties();
|
||||
consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
|
||||
consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
|
||||
consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
|
||||
consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "ConsumerGroup1");
|
||||
|
||||
producer = new KafkaProducer<>(producerProperties);
|
||||
consumer = new KafkaConsumer<>(consumerProperties);
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void destroy() {
|
||||
KAFKA_CONTAINER.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAMessageWithCustomHeaders_whenPublishedToKafkaAndConsumed_thenCheckForCustomHeaders() throws ExecutionException, InterruptedException {
|
||||
List<Header> headers = new ArrayList<>();
|
||||
headers.add(new RecordHeader(HEADER_KEY, HEADER_VALUE.getBytes()));
|
||||
|
||||
ProducerRecord<String, String> record1 = new ProducerRecord<>(TOPIC, null, MESSAGE_KEY, MESSAGE_VALUE, headers);
|
||||
Future<RecordMetadata> future = producer.send(record1);
|
||||
|
||||
RecordMetadata metadata = future.get();
|
||||
|
||||
assertNotNull(metadata);
|
||||
|
||||
consumer.subscribe(Arrays.asList(TOPIC));
|
||||
|
||||
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMinutes(1));
|
||||
for (ConsumerRecord<String, String> record : records) {
|
||||
assertEquals(MESSAGE_KEY, record.key());
|
||||
assertEquals(MESSAGE_VALUE, record.value());
|
||||
|
||||
Headers consumedHeaders = record.headers();
|
||||
assertNotNull(consumedHeaders);
|
||||
|
||||
for (Header header : consumedHeaders) {
|
||||
assertEquals(HEADER_KEY, header.key());
|
||||
assertEquals(HEADER_VALUE, new String(header.value()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -30,6 +30,16 @@
|
|||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.dhatim</groupId>
|
||||
<artifactId>fastexcel</artifactId>
|
||||
<version>${fastexcel.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.dhatim</groupId>
|
||||
<artifactId>fastexcel-reader</artifactId>
|
||||
<version>${fastexcel.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -52,6 +62,7 @@
|
|||
<properties>
|
||||
<poi.version>5.2.0</poi.version>
|
||||
<jexcel.version>1.0.6</jexcel.version>
|
||||
<fastexcel.version>0.15.3</fastexcel.version>
|
||||
<maven.resources.plugin.version>3.2.0</maven.resources.plugin.version>
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -0,0 +1,63 @@
|
|||
package com.baeldung.fastexcel;
|
||||
|
||||
import org.dhatim.fastexcel.Workbook;
|
||||
import org.dhatim.fastexcel.Worksheet;
|
||||
import org.dhatim.fastexcel.reader.Cell;
|
||||
import org.dhatim.fastexcel.reader.ReadableWorkbook;
|
||||
import org.dhatim.fastexcel.reader.Row;
|
||||
import org.dhatim.fastexcel.reader.Sheet;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class FastexcelHelper {
|
||||
|
||||
public Map<Integer, List<String>> readExcel(String fileLocation) throws IOException {
|
||||
Map<Integer, List<String>> data = new HashMap<>();
|
||||
|
||||
try (FileInputStream file = new FileInputStream(fileLocation); ReadableWorkbook wb = new ReadableWorkbook(file)) {
|
||||
Sheet sheet = wb.getFirstSheet();
|
||||
try (Stream<Row> rows = sheet.openStream()) {
|
||||
rows.forEach(r -> {
|
||||
data.put(r.getRowNum(), new ArrayList<>());
|
||||
|
||||
for (Cell cell : r) {
|
||||
data.get(r.getRowNum()).add(cell.getRawValue());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
public void writeExcel() throws IOException {
|
||||
File currDir = new File(".");
|
||||
String path = currDir.getAbsolutePath();
|
||||
String fileLocation = path.substring(0, path.length() - 1) + "fastexcel.xlsx";
|
||||
|
||||
try (OutputStream os = Files.newOutputStream(Paths.get(fileLocation)); Workbook wb = new Workbook(os, "MyApplication", "1.0")) {
|
||||
Worksheet ws = wb.newWorksheet("Sheet 1");
|
||||
|
||||
ws.width(0, 25);
|
||||
ws.width(1, 15);
|
||||
|
||||
ws.range(0, 0, 0, 1).style().fontName("Arial").fontSize(16).bold().fillColor("3366FF").set();
|
||||
ws.value(0, 0, "Name");
|
||||
ws.value(0, 1, "Age");
|
||||
|
||||
ws.range(2, 0, 2, 1).style().wrapText(true).set();
|
||||
ws.value(2, 0, "John Smith");
|
||||
ws.value(2, 1, 20L);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
package com.baeldung.fastexcel;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class FastexcelIntegrationTest {
|
||||
|
||||
private FastexcelHelper fastexcelHelper;
|
||||
private static String FILE_NAME = "fastexcel.xlsx";
|
||||
private String fileLocation;
|
||||
|
||||
@Before
|
||||
public void generateExcelFile() throws IOException {
|
||||
|
||||
File currDir = new File(".");
|
||||
String path = currDir.getAbsolutePath();
|
||||
fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
|
||||
|
||||
fastexcelHelper = new FastexcelHelper();
|
||||
fastexcelHelper.writeExcel();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenParsingExcelFile_thenCorrect() throws IOException {
|
||||
Map<Integer, List<String>> data = fastexcelHelper.readExcel(fileLocation);
|
||||
|
||||
assertEquals("Name", data.get(1).get(0));
|
||||
assertEquals("Age", data.get(1).get(1));
|
||||
|
||||
assertEquals("John Smith", data.get(3).get(0));
|
||||
assertEquals("20", data.get(3).get(1));
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup() {
|
||||
File testFile = new File(fileLocation);
|
||||
if (testFile.exists()) {
|
||||
testFile.delete();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.s3;
|
||||
|
||||
import org.apache.http.HttpStatus;
|
||||
|
||||
import com.amazonaws.AmazonServiceException;
|
||||
import com.amazonaws.services.s3.AmazonS3;
|
||||
|
||||
public class AWSS3ObjectUtils {
|
||||
|
||||
private AmazonS3 s3Client;
|
||||
|
||||
public AWSS3ObjectUtils(AmazonS3 s3client) {
|
||||
this.s3Client = s3client;
|
||||
}
|
||||
|
||||
public boolean doesObjectExistByDefaultMethod(String bucket, String key) {
|
||||
return s3Client.doesObjectExist(bucket, key);
|
||||
}
|
||||
|
||||
public boolean doesObjectExistByListObjects(String bucket, String key) {
|
||||
return s3Client.listObjects(bucket)
|
||||
.getObjectSummaries()
|
||||
.stream()
|
||||
.filter(s3ObjectSummary -> s3ObjectSummary.getKey()
|
||||
.equals(key))
|
||||
.findFirst()
|
||||
.isPresent();
|
||||
}
|
||||
|
||||
public boolean doesObjectExistByMetaData(String bucket, String key) {
|
||||
try {
|
||||
s3Client.getObjectMetadata(bucket, key);
|
||||
return true;
|
||||
} catch (AmazonServiceException e) {
|
||||
if (e.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
|
||||
return false;
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
package com.baeldung.s3;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.amazonaws.auth.EnvironmentVariableCredentialsProvider;
|
||||
import com.amazonaws.regions.Regions;
|
||||
import com.amazonaws.services.s3.AmazonS3;
|
||||
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
|
||||
|
||||
public class AWSS3ObjectIntegrationTest {
|
||||
|
||||
private static final String BUCKET = "your-bucket";
|
||||
private static final String KEY_THAT_EXIST = "your-key-that-exist";
|
||||
private AWSS3ObjectUtils s3ObjectUtils;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
AmazonS3 client = AmazonS3ClientBuilder.standard()
|
||||
.withRegion(Regions.DEFAULT_REGION)
|
||||
.withCredentials(new EnvironmentVariableCredentialsProvider())
|
||||
.build();
|
||||
|
||||
s3ObjectUtils = new AWSS3ObjectUtils(client);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVerifyIfObjectExistByDefaultMethod_thenCorrect() {
|
||||
assertTrue(s3ObjectUtils.doesObjectExistByDefaultMethod(BUCKET, KEY_THAT_EXIST), "Key: " + KEY_THAT_EXIST + " doesn't exist");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVerifyIfObjectExistByListObjects_thenCorrect() {
|
||||
assertTrue(s3ObjectUtils.doesObjectExistByListObjects(BUCKET, KEY_THAT_EXIST), "Key: " + KEY_THAT_EXIST + " doesn't exist");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVerifyIfObjectExistByMetaData_thenCorrect() {
|
||||
assertTrue(s3ObjectUtils.doesObjectExistByMetaData(BUCKET, KEY_THAT_EXIST), "Key: " + KEY_THAT_EXIST + " doesn't exist");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
## Relevant Articles
|
||||
- [Scoped Values in Java 20](https://www.baeldung.com/java-20-scoped-values)
|
|
@ -0,0 +1,65 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>core-java-20</artifactId>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>20</maven.compiler.source>
|
||||
<maven.compiler.target>20</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>20</source>
|
||||
<target>20</target>
|
||||
<compilerArgs>
|
||||
<arg>--enable-preview</arg>
|
||||
<arg>--add-modules=jdk.incubator.concurrent</arg>
|
||||
</compilerArgs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<argLine>--enable-preview --add-modules=jdk.incubator.concurrent</argLine>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>jakarta.servlet</groupId>
|
||||
<artifactId>jakarta.servlet-api</artifactId>
|
||||
<version>6.0.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.24.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-junit-jupiter</artifactId>
|
||||
<version>5.2.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.scopedvalues.classic;
|
||||
|
||||
import com.baeldung.scopedvalues.data.Data;
|
||||
import com.baeldung.scopedvalues.data.User;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.util.Optional;
|
||||
|
||||
public class Controller {
|
||||
|
||||
private final Service service = new Service();
|
||||
|
||||
public void processRequest(HttpServletRequest request, HttpServletResponse response, User loggedInUser) {
|
||||
Optional<Data> data = service.getData(request, loggedInUser);
|
||||
if (data.isPresent()) {
|
||||
try {
|
||||
PrintWriter out = response.getWriter();
|
||||
response.setContentType("application/json");
|
||||
out.print(data.get());
|
||||
out.flush();
|
||||
response.setStatus(200);
|
||||
} catch (IOException e) {
|
||||
response.setStatus(500);
|
||||
}
|
||||
} else {
|
||||
response.setStatus(400);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.scopedvalues.classic;
|
||||
|
||||
import com.baeldung.scopedvalues.data.Data;
|
||||
import com.baeldung.scopedvalues.data.User;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class Repository {
|
||||
|
||||
public Optional<Data> getData(String id, User user) {
|
||||
return user.isAdmin()
|
||||
? Optional.of(new Data(id, "Title 1", "Description 1"))
|
||||
: Optional.empty();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.scopedvalues.classic;
|
||||
|
||||
import com.baeldung.scopedvalues.data.User;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
public class Server {
|
||||
|
||||
private static final List<User> AUTHENTICATED_USERS = List.of(
|
||||
new User("1", "admin", "123456", true),
|
||||
new User("2", "user", "123456", false)
|
||||
);
|
||||
private final Controller controller = new Controller();
|
||||
private final ExecutorService executor = Executors.newFixedThreadPool(5);
|
||||
|
||||
public void serve(HttpServletRequest request, HttpServletResponse response) throws InterruptedException, ExecutionException {
|
||||
Optional<User> user = authenticateUser(request);
|
||||
if (user.isPresent()) {
|
||||
Future<?> future = executor.submit(() ->
|
||||
controller.processRequest(request, response, user.get()));
|
||||
future.get();
|
||||
} else {
|
||||
response.setStatus(401);
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<User> authenticateUser(HttpServletRequest request) {
|
||||
return AUTHENTICATED_USERS.stream()
|
||||
.filter(user -> checkUserPassword(user, request))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
private boolean checkUserPassword(User user, HttpServletRequest request) {
|
||||
return user.name().equals(request.getParameter("user_name"))
|
||||
&& user.password().equals(request.getParameter("user_pw"));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.scopedvalues.classic;
|
||||
|
||||
import com.baeldung.scopedvalues.data.Data;
|
||||
import com.baeldung.scopedvalues.data.User;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class Service {
|
||||
|
||||
private final Repository repository = new Repository();
|
||||
|
||||
public Optional<Data> getData(HttpServletRequest request, User loggedInUser) {
|
||||
String id = request.getParameter("data_id");
|
||||
return repository.getData(id, loggedInUser);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
package com.baeldung.scopedvalues.data;
|
||||
|
||||
public record Data(String id, String title, String description) {}
|
|
@ -0,0 +1,3 @@
|
|||
package com.baeldung.scopedvalues.data;
|
||||
|
||||
public record User(String id, String name, String password, boolean isAdmin) {}
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung.scopedvalues.scoped;
|
||||
|
||||
import com.baeldung.scopedvalues.data.Data;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jdk.incubator.concurrent.ScopedValue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.util.Optional;
|
||||
|
||||
public class Controller {
|
||||
|
||||
private final Service internalService = new Service();
|
||||
|
||||
public void processRequest(HttpServletRequest request, HttpServletResponse response) {
|
||||
Optional<Data> data = internalService.getData(request);
|
||||
|
||||
ScopedValue.where(Server.LOGGED_IN_USER, null)
|
||||
.run(internalService::extractData);
|
||||
|
||||
if (data.isPresent()) {
|
||||
try {
|
||||
PrintWriter out = response.getWriter();
|
||||
response.setContentType("application/json");
|
||||
out.print(data.get());
|
||||
out.flush();
|
||||
response.setStatus(200);
|
||||
} catch (IOException e) {
|
||||
response.setStatus(500);
|
||||
}
|
||||
} else {
|
||||
response.setStatus(400);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.scopedvalues.scoped;
|
||||
|
||||
import com.baeldung.scopedvalues.data.Data;
|
||||
import com.baeldung.scopedvalues.data.User;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class Repository {
|
||||
|
||||
public Optional<Data> getData(String id) {
|
||||
User loggedInUser = Server.LOGGED_IN_USER.get();
|
||||
return loggedInUser.isAdmin()
|
||||
? Optional.of(new Data(id, "Title 1", "Description 1"))
|
||||
: Optional.empty();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.scopedvalues.scoped;
|
||||
|
||||
import com.baeldung.scopedvalues.data.User;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jdk.incubator.concurrent.ScopedValue;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public class Server {
|
||||
|
||||
private static final List<User> AUTHENTICATED_USERS = List.of(
|
||||
new User("1", "admin", "123456", true),
|
||||
new User("2", "user", "123456", false)
|
||||
);
|
||||
public final static ScopedValue<User> LOGGED_IN_USER = ScopedValue.newInstance();
|
||||
private final Controller controller = new Controller();
|
||||
|
||||
public void serve(HttpServletRequest request, HttpServletResponse response) {
|
||||
Optional<User> user = authenticateUser(request);
|
||||
if (user.isPresent()) {
|
||||
ScopedValue.where(LOGGED_IN_USER, user.get())
|
||||
.run(() -> controller.processRequest(request, response));
|
||||
} else {
|
||||
response.setStatus(401);
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<User> authenticateUser(HttpServletRequest request) {
|
||||
return AUTHENTICATED_USERS.stream()
|
||||
.filter(user -> checkUserPassword(user, request))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
private boolean checkUserPassword(User user, HttpServletRequest request) {
|
||||
return user.name().equals(request.getParameter("user_name"))
|
||||
&& user.password().equals(request.getParameter("user_pw"));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.scopedvalues.scoped;
|
||||
|
||||
import com.baeldung.scopedvalues.data.Data;
|
||||
import com.baeldung.scopedvalues.data.User;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class Service {
|
||||
|
||||
private final Repository repository = new Repository();
|
||||
|
||||
public Optional<Data> getData(HttpServletRequest request) {
|
||||
String id = request.getParameter("data_id");
|
||||
return repository.getData(id);
|
||||
}
|
||||
|
||||
public void extractData() {
|
||||
User loggedInUser = Server.LOGGED_IN_USER.get();
|
||||
assert loggedInUser == null;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
package com.baeldung.scopedvalues.scoped.inheriting;
|
||||
|
||||
import com.baeldung.scopedvalues.data.Data;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jdk.incubator.concurrent.StructuredTaskScope;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
public class Controller {
|
||||
|
||||
private final InternalService internalService = new InternalService();
|
||||
private final ExternalService externalService = new ExternalService();
|
||||
|
||||
public void processRequest(HttpServletRequest request, HttpServletResponse response) {
|
||||
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
|
||||
Future<Optional<Data>> internalData = scope.fork(() -> internalService.getData(request));
|
||||
Future<String> externalData = scope.fork(externalService::getData);
|
||||
try {
|
||||
scope.join();
|
||||
scope.throwIfFailed();
|
||||
|
||||
Optional<Data> data = internalData.resultNow();
|
||||
if (data.isPresent()) {
|
||||
PrintWriter out = response.getWriter();
|
||||
response.setContentType("application/json");
|
||||
out.println(data.get());
|
||||
out.print(externalData.resultNow());
|
||||
out.flush();
|
||||
response.setStatus(200);
|
||||
} else {
|
||||
response.setStatus(400);
|
||||
}
|
||||
} catch (InterruptedException | ExecutionException | IOException e) {
|
||||
response.setStatus(500);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.scopedvalues.scoped.inheriting;
|
||||
|
||||
public class ExternalService {
|
||||
|
||||
public String getData() {
|
||||
return "External data";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.scopedvalues.scoped.inheriting;
|
||||
|
||||
import com.baeldung.scopedvalues.data.Data;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class InternalService {
|
||||
|
||||
private final Repository repository = new Repository();
|
||||
|
||||
public Optional<Data> getData(HttpServletRequest request) {
|
||||
String id = request.getParameter("data_id");
|
||||
return repository.getData(id);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.scopedvalues.scoped.inheriting;
|
||||
|
||||
import com.baeldung.scopedvalues.data.Data;
|
||||
import com.baeldung.scopedvalues.data.User;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class Repository {
|
||||
|
||||
public Optional<Data> getData(String id) {
|
||||
User loggedInUser = Server.LOGGED_IN_USER.get();
|
||||
return loggedInUser.isAdmin()
|
||||
? Optional.of(new Data(id, "Title 1", "Description 1"))
|
||||
: Optional.empty();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.scopedvalues.scoped.inheriting;
|
||||
|
||||
import com.baeldung.scopedvalues.data.User;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jdk.incubator.concurrent.ScopedValue;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public class Server {
|
||||
|
||||
private static final List<User> AUTHENTICATED_USERS = List.of(
|
||||
new User("1", "admin", "123456", true),
|
||||
new User("2", "user", "123456", false)
|
||||
);
|
||||
public final static ScopedValue<User> LOGGED_IN_USER = ScopedValue.newInstance();
|
||||
private final Controller controller = new Controller();
|
||||
|
||||
public void serve(HttpServletRequest request, HttpServletResponse response) {
|
||||
Optional<User> user = authenticateUser(request);
|
||||
if (user.isPresent()) {
|
||||
ScopedValue.where(LOGGED_IN_USER, user.get())
|
||||
.run(() -> controller.processRequest(request, response));
|
||||
} else {
|
||||
response.setStatus(401);
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<User> authenticateUser(HttpServletRequest request) {
|
||||
return AUTHENTICATED_USERS.stream()
|
||||
.filter(user -> checkUserPassword(user, request))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
private boolean checkUserPassword(User user, HttpServletRequest request) {
|
||||
return user.name().equals(request.getParameter("user_name"))
|
||||
&& user.password().equals(request.getParameter("user_pw"));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
package com.baeldung.scopedvalues.classic;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
public class ServerUnitTest {
|
||||
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
|
||||
@Mock
|
||||
private HttpServletResponse response;
|
||||
|
||||
private final StringWriter writer = new StringWriter();
|
||||
|
||||
private final Server server = new Server();
|
||||
|
||||
@Test
|
||||
void givenMockedRequestWithAdminCredentials_whenServeMethodIsCalled_thenDataIsReturned() throws InterruptedException, IOException, ExecutionException {
|
||||
when(request.getParameter("user_name")).thenReturn("admin");
|
||||
when(request.getParameter("user_pw")).thenReturn("123456");
|
||||
when(request.getParameter("data_id")).thenReturn("1");
|
||||
when(response.getWriter()).thenReturn(new PrintWriter(writer));
|
||||
|
||||
server.serve(request, response);
|
||||
|
||||
assertThat(writer.toString()).isEqualTo("Data[id=1, title=Title 1, description=Description 1]");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMockedRequestWithUserCredentials_whenServeMethodIsCalled_thenNoDataIsReturned() throws InterruptedException, ExecutionException {
|
||||
when(request.getParameter("user_name")).thenReturn("user");
|
||||
when(request.getParameter("user_pw")).thenReturn("123456");
|
||||
|
||||
server.serve(request, response);
|
||||
|
||||
assertThat(writer.toString()).isEqualTo("");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
package com.baeldung.scopedvalues.scoped;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
public class ServerUnitTest {
|
||||
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
|
||||
@Mock
|
||||
private HttpServletResponse response;
|
||||
|
||||
private final StringWriter writer = new StringWriter();
|
||||
|
||||
private final Server server = new Server();
|
||||
|
||||
@Test
|
||||
void givenMockedRequestWithAdminCredentials_whenServeMethodIsCalled_thenDataIsReturned() throws IOException {
|
||||
when(request.getParameter("user_name")).thenReturn("admin");
|
||||
when(request.getParameter("user_pw")).thenReturn("123456");
|
||||
when(request.getParameter("data_id")).thenReturn("1");
|
||||
when(response.getWriter()).thenReturn(new PrintWriter(writer));
|
||||
|
||||
server.serve(request, response);
|
||||
|
||||
assertThat(writer.toString()).isEqualTo("Data[id=1, title=Title 1, description=Description 1]");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMockedRequestWithUserCredentials_whenServeMethodIsCalled_thenNoDataIsReturned() throws IOException {
|
||||
when(request.getParameter("user_name")).thenReturn("user");
|
||||
when(request.getParameter("user_pw")).thenReturn("123456");
|
||||
|
||||
server.serve(request, response);
|
||||
|
||||
assertThat(writer.toString()).isEqualTo("");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
package com.baeldung.scopedvalues.scoped.inheriting;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
public class ServerUnitTest {
|
||||
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
|
||||
@Mock
|
||||
private HttpServletResponse response;
|
||||
|
||||
private final StringWriter writer = new StringWriter();
|
||||
|
||||
private final Server server = new Server();
|
||||
|
||||
@Test
|
||||
void givenMockedRequestWithAdminCredentials_whenServeMethodIsCalled_thenDataIsReturned() throws IOException {
|
||||
when(request.getParameter("user_name")).thenReturn("admin");
|
||||
when(request.getParameter("user_pw")).thenReturn("123456");
|
||||
when(request.getParameter("data_id")).thenReturn("1");
|
||||
when(response.getWriter()).thenReturn(new PrintWriter(writer));
|
||||
|
||||
server.serve(request, response);
|
||||
|
||||
assertThat(writer.toString()).isEqualTo("Data[id=1, title=Title 1, description=Description 1]\nExternal data");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMockedRequestWithUserCredentials_whenServeMethodIsCalled_thenNoDataIsReturned() throws IOException {
|
||||
when(request.getParameter("user_name")).thenReturn("user");
|
||||
when(request.getParameter("user_pw")).thenReturn("123456");
|
||||
|
||||
server.serve(request, response);
|
||||
|
||||
assertThat(writer.toString()).isEqualTo("");
|
||||
}
|
||||
|
||||
}
|
|
@ -11,3 +11,5 @@ This module contains articles about Java array fundamentals. They assume no prev
|
|||
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
|
||||
- [Extending an Array’s Length](https://www.baeldung.com/java-array-add-element-at-the-end)
|
||||
- [Initializing a Boolean Array in Java](https://www.baeldung.com/java-initializing-boolean-array)
|
||||
- [Find the Index of an Element in a Java Array](https://www.baeldung.com/java-array-find-index)
|
||||
- [Comparing Two Byte Arrays in Java](https://www.baeldung.com/java-comparing-byte-arrays)
|
||||
|
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.arrayindex;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
class ArrayIndex {
|
||||
static int forLoop(int[] numbers, int target) {
|
||||
for (int index = 0; index < numbers.length; index++) {
|
||||
if (numbers[index] == target) {
|
||||
return index;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
static int listIndexOf(Integer[] numbers, int target) {
|
||||
List<Integer> list = Arrays.asList(numbers);
|
||||
return list.indexOf(target);
|
||||
}
|
||||
|
||||
static int intStream(int[] numbers, int target) {
|
||||
return IntStream.range(0, numbers.length)
|
||||
.filter(i -> numbers[i] == target)
|
||||
.findFirst()
|
||||
.orElse(-1);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package com.baeldung.array.compare;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class CompareByteArraysUnitTest {
|
||||
private final static String INPUT = "I am a magic string.";
|
||||
private final static byte[] ARRAY1 = INPUT.getBytes();
|
||||
private final static byte[] ARRAY2 = INPUT.getBytes();
|
||||
|
||||
@Test
|
||||
void whenUsingEqualsSign_thenTwoArraysAreNotEqual() {
|
||||
assertFalse(ARRAY1 == ARRAY2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingEquals_thenTwoArraysAreNotEqual() {
|
||||
assertFalse(ARRAY1.equals(ARRAY2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingArrayEquals_thenTwoArraysAreEqual() {
|
||||
assertTrue(Arrays.equals(ARRAY1, ARRAY2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenComparingStringArrays_thenGetExpectedResult() {
|
||||
String[] strArray1 = new String[] { "Java", "is", "great" };
|
||||
String[] strArray2 = new String[] { "Java", "is", "great" };
|
||||
|
||||
assertFalse(strArray1 == strArray2);
|
||||
assertFalse(strArray1.equals(strArray2));
|
||||
assertTrue(Arrays.equals(strArray1, strArray2));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,106 @@
|
|||
package com.baeldung.arrayindex;
|
||||
|
||||
import static com.baeldung.arrayindex.ArrayIndex.forLoop;
|
||||
import static com.baeldung.arrayindex.ArrayIndex.intStream;
|
||||
import static com.baeldung.arrayindex.ArrayIndex.listIndexOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.google.common.primitives.Ints;
|
||||
|
||||
class ArrayIndexUnitTest {
|
||||
|
||||
@Test
|
||||
void givenIntegerArray_whenUseForLoop_thenWillGetElementIndex() {
|
||||
int[] numbers = { 10, 20, 30, 40, 50 };
|
||||
assertEquals(2, forLoop(numbers, 30));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIntegerArray_whenUseForLoop_thenWillGetElementMinusOneIndex() {
|
||||
int[] numbers = { 10, 20, 30, 40, 50 };
|
||||
assertEquals(-1, forLoop(numbers, 100));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIntegerArray_whenUseIndexOf_thenWillGetElementIndex() {
|
||||
Integer[] numbers = { 10, 20, 30, 40, 50 };
|
||||
assertEquals(2, listIndexOf(numbers, 30));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIntegerArray_whenUseIndexOf_thenWillGetElementMinusOneIndex() {
|
||||
Integer[] numbers = { 10, 20, 30, 40, 50 };
|
||||
assertEquals(-1, listIndexOf(numbers, 100));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIntegerArray_whenUseIntStream_thenWillGetElementIndex() {
|
||||
int[] numbers = { 10, 20, 30, 40, 50 };
|
||||
assertEquals(2, intStream(numbers, 30));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIntegerArray_whenUseIntStream_thenWillGetElementMinusOneIndex() {
|
||||
int[] numbers = { 10, 20, 30, 40, 50 };
|
||||
assertEquals(-1, intStream(numbers, 100));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIntegerArray_whenUseBinarySearch_thenWillGetElementIndex() {
|
||||
int[] numbers = { 10, 20, 30, 40, 50 };
|
||||
assertEquals(2, Arrays.binarySearch(numbers, 30));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIntegerArray_whenUseBinarySearch_thenWillGetUpperBoundMinusIndex() {
|
||||
int[] numbers = { 10, 20, 30, 40, 50 };
|
||||
assertEquals(-6, Arrays.binarySearch(numbers, 100));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIntegerArray_whenUseBinarySearch_thenWillGetInArrayMinusIndex() {
|
||||
int[] numbers = { 10, 20, 30, 40, 50 };
|
||||
assertEquals(-2, Arrays.binarySearch(numbers, 15));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIntegerArray_whenUseBinarySearch_thenWillGetLowerBoundMinusIndex() {
|
||||
int[] numbers = { 10, 20, 30, 40, 50 };
|
||||
assertEquals(-1, Arrays.binarySearch(numbers, -15));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIntegerArray_whenUseApacheCommons_thenWillGetElementIndex() {
|
||||
int[] numbers = { 10, 20, 30, 40, 50 };
|
||||
assertEquals(2, ArrayUtils.indexOf(numbers, 30));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIntegerArray_whenUseApacheCommonsStartingFromIndex_thenWillGetNegativeIndex() {
|
||||
int[] numbers = { 10, 20, 30, 40, 50 };
|
||||
assertEquals(-1, ArrayUtils.indexOf(numbers, 30, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIntegerArray_whenUseApacheCommons_thenWillGetElementMinusOneIndex() {
|
||||
int[] numbers = { 10, 20, 30, 40, 50 };
|
||||
assertEquals(-1, ArrayUtils.indexOf(numbers, 100));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIntegerArray_whenUseGuavaInts_thenWillGetElementIndex() {
|
||||
int[] numbers = { 10, 20, 30, 40, 50 };
|
||||
assertEquals(2, Ints.indexOf(numbers, 30));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIntegerArray_whenUseGuavaInts_thenWillGetElementMinusOneIndex() {
|
||||
int[] numbers = { 10, 20, 30, 40, 50 };
|
||||
assertEquals(-1, Ints.indexOf(numbers, 100));
|
||||
}
|
||||
}
|
|
@ -4,3 +4,4 @@ This module contains articles about Java Character Class
|
|||
|
||||
### Relevant Articles:
|
||||
- [Character#isAlphabetic vs. Character#isLetter](https://www.baeldung.com/java-character-isletter-isalphabetic)
|
||||
- [Difference Between Java’s “char” and “String”](https://www.baeldung.com/java-char-vs-string)
|
||||
|
|
|
@ -0,0 +1,56 @@
|
|||
package com.baeldung.charandstring;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class DifferenceBetweenCharAndStringUnitTest {
|
||||
|
||||
@Test
|
||||
void whenPlusTwoChars_thenGetSumAsInteger() {
|
||||
char h = 'H'; // the value is 72
|
||||
char i = 'i'; // the value is 105
|
||||
assertEquals(177, h + i);
|
||||
assertInstanceOf(Integer.class, h + i);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenPlusTwoStrings_thenConcatenateThem() {
|
||||
String i = "i";
|
||||
String h = "H";
|
||||
assertEquals("Hi", h + i);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenPlusCharsAndStrings_thenGetExpectedValues() {
|
||||
char c = 'C';
|
||||
assertEquals("C", "" + c);
|
||||
|
||||
char h = 'H'; // the value is 72
|
||||
char i = 'i'; // the value is 105
|
||||
assertEquals("Hi", "" + h + i);
|
||||
assertEquals("Hi", h + "" + i);
|
||||
assertEquals("177", h + i + "");
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenStringChars_thenGetCharArray() {
|
||||
char h = 'h';
|
||||
char e = 'e';
|
||||
char l = 'l';
|
||||
char o = 'o';
|
||||
|
||||
String hello = "hello";
|
||||
assertEquals(h, hello.charAt(0));
|
||||
assertEquals(e, hello.charAt(1));
|
||||
assertEquals(l, hello.charAt(2));
|
||||
assertEquals(l, hello.charAt(3));
|
||||
assertEquals(o, hello.charAt(4));
|
||||
|
||||
char[] chars = new char[] { h, e, l, l, o };
|
||||
char[] charsFromString = hello.toCharArray();
|
||||
assertArrayEquals(chars, charsFromString);
|
||||
}
|
||||
}
|
|
@ -1,34 +1,41 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-collections-list-5</artifactId>
|
||||
<name>core-java-collections-list-5</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>commons-lang</groupId>
|
||||
<artifactId>commons-lang</artifactId>
|
||||
<version>${commons-lang.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<commons-lang.version>2.2</commons-lang.version>
|
||||
<commons-lang3.version>3.12.0</commons-lang3.version>
|
||||
</properties>
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-collections-list-5</artifactId>
|
||||
<name>core-java-collections-list-5</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>1.36</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-lang</groupId>
|
||||
<artifactId>commons-lang</artifactId>
|
||||
<version>${commons-lang.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<jmh.version>1.21</jmh.version>
|
||||
<commons-lang.version>2.2</commons-lang.version>
|
||||
<commons-lang3.version>3.12.0</commons-lang3.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,65 @@
|
|||
package com.baeldung.arrayandlistperformance;
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
import java.util.ArrayList;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
@State(Scope.Benchmark)
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public class ArrayAndArrayListPerformance {
|
||||
|
||||
@Benchmark
|
||||
public void arrayCreation() {
|
||||
int[] array = new int[1000000];
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void arrayListCreation() {
|
||||
ArrayList<Integer> list = new ArrayList<>(1000000);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void arrayItemSetting() {
|
||||
int[] array = new int[1000000];
|
||||
array[0] = 10;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void arrayListItemSetting() {
|
||||
ArrayList<Integer> list = new ArrayList<>(1000000);
|
||||
list.add(0, 10);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void arrayItemRetrieval() {
|
||||
int[] array = new int[1000000];
|
||||
array[0] = 10;
|
||||
int item = array[0];
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void arrayListItemRetrieval() {
|
||||
ArrayList<Integer> list = new ArrayList<>(1000000);
|
||||
list.add(0, 10);
|
||||
int item2 = list.get(0);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void arrayCloning() {
|
||||
int[] array = new int[1000000];
|
||||
int[] newArray = array.clone();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void arrayListCloning() {
|
||||
ArrayList<Integer> list = new ArrayList<>(1000000);
|
||||
ArrayList<Integer> newList = new ArrayList<>(list);
|
||||
}
|
||||
public static void main(String[] args) throws Exception {
|
||||
org.openjdk.jmh.runner.Runner runner = new org.openjdk.jmh.runner.Runner(new OptionsBuilder()
|
||||
.include(ArrayAndArrayListPerformance.class.getSimpleName())
|
||||
.forks(1)
|
||||
.build());
|
||||
runner.run();
|
||||
}
|
||||
}
|
|
@ -1,6 +1,9 @@
|
|||
package com.baeldung.producerconsumer;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class Consumer implements Runnable {
|
||||
private static final Logger log = Logger.getLogger(Consumer.class.getCanonicalName());
|
||||
private final DataQueue dataQueue;
|
||||
|
||||
public Consumer(DataQueue dataQueue) {
|
||||
|
@ -14,7 +17,7 @@ public class Consumer implements Runnable {
|
|||
|
||||
public void consume() {
|
||||
while (dataQueue.runFlag) {
|
||||
synchronized (this) {
|
||||
synchronized (dataQueue) {
|
||||
while (dataQueue.isEmpty() && dataQueue.runFlag) {
|
||||
try {
|
||||
dataQueue.waitOnEmpty();
|
||||
|
@ -31,12 +34,13 @@ public class Consumer implements Runnable {
|
|||
useMessage(message);
|
||||
}
|
||||
}
|
||||
System.out.println("Consumer Stopped");
|
||||
log.info("Consumer Stopped");
|
||||
}
|
||||
|
||||
private void useMessage(Message message) {
|
||||
if (message != null) {
|
||||
System.out.printf("[%s] Consuming Message. Id: %d, Data: %f\n", Thread.currentThread().getName(), message.getId(), message.getData());
|
||||
log.info(String.format("[%s] Consuming Message. Id: %d, Data: %f%n",
|
||||
Thread.currentThread().getName(), message.getId(), message.getData()));
|
||||
|
||||
//Sleeping on random time to make it realistic
|
||||
ThreadUtil.sleep((long) (message.getData() * 100));
|
||||
|
|
|
@ -1,6 +1,9 @@
|
|||
package com.baeldung.producerconsumer;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class Producer implements Runnable {
|
||||
private static final Logger log = Logger.getLogger(Producer.class.getCanonicalName());
|
||||
private final DataQueue dataQueue;
|
||||
|
||||
private static int idSequence = 0;
|
||||
|
@ -16,7 +19,7 @@ public class Producer implements Runnable {
|
|||
|
||||
public void produce() {
|
||||
while (dataQueue.runFlag) {
|
||||
synchronized (this) {
|
||||
synchronized (dataQueue) {
|
||||
while (dataQueue.isFull() && dataQueue.runFlag) {
|
||||
try {
|
||||
dataQueue.waitOnFull();
|
||||
|
@ -33,12 +36,13 @@ public class Producer implements Runnable {
|
|||
dataQueue.notifyAllForEmpty();
|
||||
}
|
||||
}
|
||||
System.out.println("Producer Stopped");
|
||||
log.info("Producer Stopped");
|
||||
}
|
||||
|
||||
private Message generateMessage() {
|
||||
Message message = new Message(++idSequence, Math.random());
|
||||
System.out.printf("[%s] Generated Message. Id: %d, Data: %f\n", Thread.currentThread().getName(), message.getId(), message.getData());
|
||||
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()));
|
||||
|
||||
//Sleeping on random time to make it realistic
|
||||
ThreadUtil.sleep((long) (message.getData() * 100));
|
||||
|
@ -46,6 +50,10 @@ public class Producer implements Runnable {
|
|||
return message;
|
||||
}
|
||||
|
||||
private static int incrementAndGetId() {
|
||||
return ++idSequence;
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
dataQueue.runFlag = false;
|
||||
dataQueue.notifyAllForFull();
|
||||
|
|
|
@ -2,10 +2,12 @@ package com.baeldung.producerconsumer;
|
|||
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.LinkedBlockingDeque;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static com.baeldung.producerconsumer.ThreadUtil.sleep;
|
||||
|
||||
public class SimpleProducerConsumerDemonstrator {
|
||||
private static final Logger log = Logger.getLogger(SimpleProducerConsumerDemonstrator.class.getCanonicalName());
|
||||
BlockingQueue<Double> blockingQueue = new LinkedBlockingDeque<>(5);
|
||||
|
||||
private void produce() {
|
||||
|
@ -17,7 +19,7 @@ public class SimpleProducerConsumerDemonstrator {
|
|||
e.printStackTrace();
|
||||
break;
|
||||
}
|
||||
System.out.printf("[%s] Value produced: %f\n", Thread.currentThread().getName(), value);
|
||||
log.info(String.format("[%s] Value produced: %f%n", Thread.currentThread().getName(), value));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -31,7 +33,7 @@ public class SimpleProducerConsumerDemonstrator {
|
|||
break;
|
||||
}
|
||||
// Consume value
|
||||
System.out.printf("[%s] Value consumed: %f\n", Thread.currentThread().getName(), value);
|
||||
log.info(String.format("[%s] Value consumed: %f%n", Thread.currentThread().getName(), value));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -6,4 +6,5 @@ This module contains articles about basic Java concurrency.
|
|||
|
||||
- [How to Handle InterruptedException in Java](https://www.baeldung.com/java-interrupted-exception)
|
||||
- [Thread.sleep() vs Awaitility.await()](https://www.baeldung.com/java-thread-sleep-vs-awaitility-await)
|
||||
- [Is CompletableFuture Non-blocking?](https://www.baeldung.com/java-completablefuture-non-blocking)
|
||||
- [[<-- Prev]](../core-java-concurrency-basic-2)
|
||||
|
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.concurrent.completablefuture;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public class NonBlockingExample {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(NonBlockingExample.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
CompletableFuture.supplyAsync(() -> "Baeldung")
|
||||
.thenApply(String::length)
|
||||
.thenAccept(s -> logger.info(String.valueOf(s)));
|
||||
}
|
||||
}
|
|
@ -20,7 +20,8 @@ public class RequestProcessorUnitTest {
|
|||
void whenWaitingWithThreadSleep_thenStatusIsDone() throws InterruptedException {
|
||||
String requestId = requestProcessor.processRequest();
|
||||
|
||||
Thread.sleep(2000);
|
||||
//The sleep value should be greater than the maximum time the request takes to complete
|
||||
Thread.sleep(2010);
|
||||
|
||||
assertEquals("DONE", requestProcessor.getStatus(requestId));
|
||||
}
|
||||
|
@ -31,7 +32,8 @@ public class RequestProcessorUnitTest {
|
|||
String requestId = requestProcessor.processRequest();
|
||||
|
||||
Awaitility.await()
|
||||
.atMost(2, TimeUnit.SECONDS)
|
||||
//The timeout value should exceed the maximum time the request takes to complete, for the time amount of a poll (500 ms)
|
||||
.atMost(2501, TimeUnit.MILLISECONDS)
|
||||
.pollDelay(500, TimeUnit.MILLISECONDS)
|
||||
.until(() -> requestProcessor.getStatus(requestId), not(equalTo("PROCESSING")));
|
||||
|
||||
|
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.concurrent.completablefuture;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class BlockingUnitTest {
|
||||
|
||||
@Test
|
||||
void givenCompletableFuture_whenGet_thenReturnResult()
|
||||
throws ExecutionException, InterruptedException {
|
||||
CompletableFuture<String> completableFuture = CompletableFuture
|
||||
.supplyAsync(() -> "Baeldung")
|
||||
.thenApply(String::toUpperCase);
|
||||
|
||||
assertEquals("BAELDUNG", completableFuture.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenCompletableFuture_whenJoin_thenReturnResult() {
|
||||
CompletableFuture<String> completableFuture = CompletableFuture
|
||||
.supplyAsync(() -> "Blocking")
|
||||
.thenApply(s -> s + " Operation")
|
||||
.thenApply(String::toLowerCase);
|
||||
|
||||
assertEquals("blocking operation", completableFuture.join());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.concurrent.queue;
|
||||
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class BlockingQueueUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenArrayBlockingQueue_whenAddedElements_thenReturnQueueRemainingCapacity() {
|
||||
BlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue<>(10);
|
||||
arrayBlockingQueue.add("TestString1");
|
||||
arrayBlockingQueue.add("TestString2");
|
||||
assertEquals(8, arrayBlockingQueue.remainingCapacity());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLinkedBlockingQueue_whenAddedElements_thenReturnQueueRemainingCapacity() {
|
||||
BlockingQueue<String> linkedBlockingQueue = new LinkedBlockingQueue<>(10);
|
||||
linkedBlockingQueue.add("TestString1");
|
||||
assertEquals(9, linkedBlockingQueue.remainingCapacity());
|
||||
}
|
||||
}
|
|
@ -6,4 +6,5 @@ This module contains articles about core Java input/output(IO) APIs.
|
|||
- [Constructing a Relative Path From Two Absolute Paths in Java](https://www.baeldung.com/java-relative-path-absolute)
|
||||
- [Java Scanner Taking a Character Input](https://www.baeldung.com/java-scanner-character-input)
|
||||
- [Get the Desktop Path in Java](https://www.baeldung.com/java-desktop-path)
|
||||
|
||||
- [Integer.parseInt(scanner.nextLine()) and scanner.nextInt() in Java](https://www.baeldung.com/java-scanner-integer)
|
||||
- [Difference Between FileReader and BufferedReader in Java](https://www.baeldung.com/java-filereader-vs-bufferedreader)
|
||||
|
|
|
@ -1,46 +1,115 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-io-apis-2</artifactId>
|
||||
<name>core-java-io-apis-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- logging -->
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-io-apis-2</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-io-apis-2</artifactId>
|
||||
<name>core-java-io-apis-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- logging -->
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>5.7.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
</dependency>
|
||||
<!-- this is all you need to write tests with JUnit Jupiter -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>${junit-jupiter-version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- this dependency is needed to create parameterized tests -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-params</artifactId>
|
||||
<version>${junit-jupiter-version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- contains the engine that actually runs the Jupiter-tests -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>${junit-jupiter-version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testng</groupId>
|
||||
<artifactId>testng</artifactId>
|
||||
<version>7.1.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testng</groupId>
|
||||
<artifactId>testng</artifactId>
|
||||
<version>7.5</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<properties>
|
||||
<junit-jupiter-version>5.2.0</junit-jupiter-version>
|
||||
</properties>
|
||||
<build>
|
||||
<finalName>core-java-io-apis-2</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.multinput;
|
||||
|
||||
import java.util.InputMismatchException;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class MultiInputs {
|
||||
public void UsingSpaceDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
System.out.print("Enter two numbers: ");
|
||||
int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2);
|
||||
|
||||
}
|
||||
public void UsingREDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
scanner.useDelimiter("[\\s,]+");
|
||||
System.out.print("Enter two numbers separated by a space or a comma: ");
|
||||
int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2);
|
||||
|
||||
}
|
||||
public void UsingCustomDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
scanner.useDelimiter(";");
|
||||
System.out.print("Enter two numbers separated by a semicolon: ");
|
||||
try { int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2); }
|
||||
catch (InputMismatchException e)
|
||||
{ System.out.println("Invalid input. Please enter two integers separated by a semicolon."); }
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -1,93 +1,92 @@
|
|||
package com.baeldung.absolutetorelative;
|
||||
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
public class AbsoluteToRelativeUnitTest {
|
||||
|
||||
// given - until using Paths, no need to create physical files
|
||||
private final Path pathOne = Paths.get("/baeldung/bar/one.txt");
|
||||
private final Path pathTwo = Paths.get("/baeldung/bar/two.txt");
|
||||
private final Path pathThree = Paths.get("/baeldung/foo/three.txt");
|
||||
|
||||
private final URI uriOne = pathOne.toUri();
|
||||
private final URI uriTwo = pathTwo.toUri();
|
||||
private final URI uriThree = pathThree.toUri();
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePaths_whenRelativizePathOneToPathTwo_thenRelativeIsReturned() {
|
||||
Path result = pathOne.relativize(pathTwo);
|
||||
|
||||
Assertions.assertThat(result)
|
||||
.isRelative()
|
||||
.isEqualTo(Paths.get("../two.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePaths_whenRelativizePathTwoToPathOne_thenRelativeIsReturned() {
|
||||
Path result = pathTwo.relativize(pathOne);
|
||||
|
||||
Assertions.assertThat(result)
|
||||
.isRelative()
|
||||
.isEqualTo(Paths.get("../one.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePaths_whenRelativizePathOneParentToPathTwo_thenRelativeIsReturned() {
|
||||
Path result = pathOne.getParent().relativize(pathTwo);
|
||||
|
||||
Assertions.assertThat(result)
|
||||
.isRelative()
|
||||
.isEqualTo(Paths.get("two.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePaths_whenRelativizePathOneToPathThree_thenRelativeIsReturned() {
|
||||
Path result = pathOne.relativize(pathThree);
|
||||
|
||||
Assertions.assertThat(result)
|
||||
.isRelative()
|
||||
.isEqualTo(Paths.get("../../foo/three.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePaths_whenRelativizePathThreeToPathOne_thenRelativeIsReturned() {
|
||||
Path result = pathThree.relativize(pathOne);
|
||||
|
||||
Assertions.assertThat(result)
|
||||
.isRelative()
|
||||
.isEqualTo(Paths.get("../../bar/one.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsoluteURIs_whenRelativizeUriOneToUriTwo_thenAbsoluteIsReturned() {
|
||||
URI result = uriOne.relativize(uriTwo);
|
||||
|
||||
Assertions.assertThat(result)
|
||||
.asString()
|
||||
.contains("/baeldung/bar/two.txt");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsoluteURIs_whenRelativizeUriOneParentToUriTwo_thenRelativeIsReturned() {
|
||||
URI result = pathOne.getParent().toUri().relativize(uriTwo);
|
||||
|
||||
Assertions.assertThat(result)
|
||||
.asString()
|
||||
.contains("two.txt");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsoluteURIs_whenRelativizeUriOneParentToUriThree_thenAbsoluteIsReturned() {
|
||||
URI result = pathOne.getParent().toUri().relativize(uriThree);
|
||||
|
||||
Assertions.assertThat(result)
|
||||
.asString()
|
||||
.contains("/baeldung/foo/three.txt");
|
||||
}
|
||||
|
||||
}
|
||||
package com.baeldung.absolutetorelative;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class AbsoluteToRelativeUnitTest {
|
||||
|
||||
// given - until using Paths, no need to create physical files
|
||||
private final Path pathOne = Paths.get("/baeldung/bar/one.txt");
|
||||
private final Path pathTwo = Paths.get("/baeldung/bar/two.txt");
|
||||
private final Path pathThree = Paths.get("/baeldung/foo/three.txt");
|
||||
|
||||
private final URI uriOne = pathOne.toUri();
|
||||
private final URI uriTwo = pathTwo.toUri();
|
||||
private final URI uriThree = pathThree.toUri();
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePaths_whenRelativizePathOneToPathTwo_thenRelativeIsReturned() {
|
||||
Path result = pathOne.relativize(pathTwo);
|
||||
|
||||
org.assertj.core.api.Assertions.assertThat(result)
|
||||
.isRelative()
|
||||
.isEqualTo(Paths.get("../two.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePaths_whenRelativizePathTwoToPathOne_thenRelativeIsReturned() {
|
||||
Path result = pathTwo.relativize(pathOne);
|
||||
|
||||
org.assertj.core.api.Assertions.assertThat(result)
|
||||
.isRelative()
|
||||
.isEqualTo(Paths.get("../one.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePaths_whenRelativizePathOneParentToPathTwo_thenRelativeIsReturned() {
|
||||
Path result = pathOne.getParent().relativize(pathTwo);
|
||||
|
||||
org.assertj.core.api.Assertions.assertThat(result)
|
||||
.isRelative()
|
||||
.isEqualTo(Paths.get("two.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePaths_whenRelativizePathOneToPathThree_thenRelativeIsReturned() {
|
||||
Path result = pathOne.relativize(pathThree);
|
||||
|
||||
org.assertj.core.api.Assertions.assertThat(result)
|
||||
.isRelative()
|
||||
.isEqualTo(Paths.get("../../foo/three.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePaths_whenRelativizePathThreeToPathOne_thenRelativeIsReturned() {
|
||||
Path result = pathThree.relativize(pathOne);
|
||||
|
||||
org.assertj.core.api.Assertions.assertThat(result)
|
||||
.isRelative()
|
||||
.isEqualTo(Paths.get("../../bar/one.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsoluteURIs_whenRelativizeUriOneToUriTwo_thenAbsoluteIsReturned() {
|
||||
URI result = uriOne.relativize(uriTwo);
|
||||
|
||||
org.assertj.core.api.Assertions.assertThat(result)
|
||||
.asString()
|
||||
.contains("/baeldung/bar/two.txt");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsoluteURIs_whenRelativizeUriOneParentToUriTwo_thenRelativeIsReturned() {
|
||||
URI result = pathOne.getParent().toUri().relativize(uriTwo);
|
||||
|
||||
org.assertj.core.api.Assertions.assertThat(result)
|
||||
.asString()
|
||||
.contains("two.txt");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsoluteURIs_whenRelativizeUriOneParentToUriThree_thenAbsoluteIsReturned() {
|
||||
URI result = pathOne.getParent().toUri().relativize(uriThree);
|
||||
|
||||
org.assertj.core.api.Assertions.assertThat(result)
|
||||
.asString()
|
||||
.contains("/baeldung/foo/three.txt");
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.bufferedreadervsfilereader;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.testng.annotations.Test;
|
||||
public class BufferedReaderUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenReadingAFile_thenReadsLineByLine() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
try (BufferedReader br = new BufferedReader(new FileReader("src/test/resources/sampleText1.txt"))) {
|
||||
String line;
|
||||
|
||||
while((line = br.readLine()) != null) {
|
||||
result.append(line);
|
||||
result.append('\n');
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
assertEquals("first line\nsecond line\nthird line\n", result.toString());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package com.baeldung.bufferedreadervsfilereader;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class FileReaderUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenReadingAFile_thenReadsCharByChar() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
try (FileReader fr = new FileReader("src/test/resources/sampleText2.txt")) {
|
||||
int i = fr.read();
|
||||
|
||||
while(i != -1) {
|
||||
result.append((char)i);
|
||||
|
||||
i = fr.read();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
assertEquals("qwerty", result.toString());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,47 @@
|
|||
package com.baeldung.multinput;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.util.InputMismatchException;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.testng.annotations.Test;
|
||||
import com.baeldung.multinput.MultiInputs;
|
||||
public class TestMultipleInputsUnitTest {
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingSpaceDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "10 20\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingSpaceDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingREDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "30, 40\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingREDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingCustomDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "50; 60\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingCustomDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidInput_whenUsingSpaceDelimiter_thenExpectInputMismatchException() {
|
||||
String input = "abc\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
Assertions.assertThrows(InputMismatchException.class, mi::UsingSpaceDelimiter);
|
||||
}
|
||||
}
|
|
@ -1,29 +1,27 @@
|
|||
package com.baeldung.path;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import javax.swing.filechooser.FileSystemView;
|
||||
|
||||
public class DesktopPathUnitTest {
|
||||
// Adapt DESKTOP_PATH variable to your own system path
|
||||
// private static final String DESKTOP_PATH = "C:\\Users\\HRAF\\Desktop";
|
||||
|
||||
@Test
|
||||
public void whenUsingGetUserHomeProperty_thenShouldEqualDesktopPath() {
|
||||
String desktopPath = System.getProperty("user.home") + File.separator + "Desktop";
|
||||
// assertEquals(DESKTOP_PATH, desktopPath);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFileSystemViewGetHomeDirectory_thenShouldEqualDesktopPath() {
|
||||
FileSystemView view = FileSystemView.getFileSystemView();
|
||||
File file = view.getHomeDirectory();
|
||||
String path = file.getPath();
|
||||
// assertEquals(DESKTOP_PATH, path);
|
||||
}
|
||||
|
||||
}
|
||||
package com.baeldung.path;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import javax.swing.filechooser.FileSystemView;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class DesktopPathUnitTest {
|
||||
// Adapt DESKTOP_PATH variable to your own system path
|
||||
// private static final String DESKTOP_PATH = "C:\\Users\\HRAF\\Desktop";
|
||||
|
||||
@Test
|
||||
public void whenUsingGetUserHomeProperty_thenShouldEqualDesktopPath() {
|
||||
String desktopPath = System.getProperty("user.home") + File.separator + "Desktop";
|
||||
// assertEquals(DESKTOP_PATH, desktopPath);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFileSystemViewGetHomeDirectory_thenShouldEqualDesktopPath() {
|
||||
FileSystemView view = FileSystemView.getFileSystemView();
|
||||
File file = view.getHomeDirectory();
|
||||
String path = file.getPath();
|
||||
// assertEquals(DESKTOP_PATH, path);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,85 +1,85 @@
|
|||
package com.baeldung.scanner;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import java.util.InputMismatchException;
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class NextLineVsNextIntUnitTest {
|
||||
|
||||
@Test
|
||||
void whenInputLineIsNumber_thenNextLineAndNextIntBothWork() {
|
||||
String input = "42\n";
|
||||
|
||||
//nextLine()
|
||||
Scanner sc1 = new Scanner(input);
|
||||
int num1 = Integer.parseInt(sc1.nextLine());
|
||||
assertEquals(42, num1);
|
||||
|
||||
//nextInt()
|
||||
Scanner sc2 = new Scanner(input);
|
||||
int num2 = sc2.nextInt();
|
||||
assertEquals(42, num2);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenInputIsNotValidNumber_thenNextLineAndNextIntThrowDifferentException() {
|
||||
String input = "Nan\n";
|
||||
|
||||
//nextLine() -> NumberFormatException
|
||||
Scanner sc1 = new Scanner(input);
|
||||
assertThrows(NumberFormatException.class, () -> Integer.parseInt(sc1.nextLine()));
|
||||
|
||||
//nextInt() -> InputMismatchException
|
||||
Scanner sc2 = new Scanner(input);
|
||||
assertThrows(InputMismatchException.class, sc2::nextInt);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingNextInt_thenTheNextTokenAfterItFailsToParseIsNotConsumed() {
|
||||
String input = "42 is a magic number\n";
|
||||
|
||||
//nextInt() to read '42'
|
||||
Scanner sc2 = new Scanner(input);
|
||||
int num2 = sc2.nextInt();
|
||||
assertEquals(42, num2);
|
||||
|
||||
// call nextInt() again on "is"
|
||||
assertThrows(InputMismatchException.class, sc2::nextInt);
|
||||
|
||||
String theNextToken = sc2.next();
|
||||
assertEquals("is", theNextToken);
|
||||
|
||||
theNextToken = sc2.next();
|
||||
assertEquals("a", theNextToken);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenReadingTwoInputLines_thenNextLineAndNextIntBehaveDifferently() {
|
||||
|
||||
String input = new StringBuilder().append("42\n")
|
||||
.append("It is a magic number.\n")
|
||||
.toString();
|
||||
|
||||
//nextLine()
|
||||
Scanner sc1 = new Scanner(input);
|
||||
int num1 = Integer.parseInt(sc1.nextLine());
|
||||
String nextLineText1 = sc1.nextLine();
|
||||
assertEquals(42, num1);
|
||||
assertEquals("It is a magic number.", nextLineText1);
|
||||
|
||||
//nextInt()
|
||||
Scanner sc2 = new Scanner(input);
|
||||
int num2 = sc2.nextInt();
|
||||
assertEquals(42, num2);
|
||||
|
||||
// nextInt() leaves the newline character (\n) behind
|
||||
String nextLineText2 = sc2.nextLine();
|
||||
assertEquals("", nextLineText2);
|
||||
}
|
||||
|
||||
package com.baeldung.scanner;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import java.util.InputMismatchException;
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class NextLineVsNextIntUnitTest {
|
||||
|
||||
@Test
|
||||
void whenInputLineIsNumber_thenNextLineAndNextIntBothWork() {
|
||||
String input = "42\n";
|
||||
|
||||
//nextLine()
|
||||
Scanner sc1 = new Scanner(input);
|
||||
int num1 = Integer.parseInt(sc1.nextLine());
|
||||
assertEquals(42, num1);
|
||||
|
||||
//nextInt()
|
||||
Scanner sc2 = new Scanner(input);
|
||||
int num2 = sc2.nextInt();
|
||||
assertEquals(42, num2);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenInputIsNotValidNumber_thenNextLineAndNextIntThrowDifferentException() {
|
||||
String input = "Nan\n";
|
||||
|
||||
//nextLine() -> NumberFormatException
|
||||
Scanner sc1 = new Scanner(input);
|
||||
assertThrows(NumberFormatException.class, () -> Integer.parseInt(sc1.nextLine()));
|
||||
|
||||
//nextInt() -> InputMismatchException
|
||||
Scanner sc2 = new Scanner(input);
|
||||
assertThrows(InputMismatchException.class, sc2::nextInt);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingNextInt_thenTheNextTokenAfterItFailsToParseIsNotConsumed() {
|
||||
String input = "42 is a magic number\n";
|
||||
|
||||
//nextInt() to read '42'
|
||||
Scanner sc2 = new Scanner(input);
|
||||
int num2 = sc2.nextInt();
|
||||
assertEquals(42, num2);
|
||||
|
||||
// call nextInt() again on "is"
|
||||
assertThrows(InputMismatchException.class, sc2::nextInt);
|
||||
|
||||
String theNextToken = sc2.next();
|
||||
assertEquals("is", theNextToken);
|
||||
|
||||
theNextToken = sc2.next();
|
||||
assertEquals("a", theNextToken);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenReadingTwoInputLines_thenNextLineAndNextIntBehaveDifferently() {
|
||||
|
||||
String input = new StringBuilder().append("42\n")
|
||||
.append("It is a magic number.\n")
|
||||
.toString();
|
||||
|
||||
//nextLine()
|
||||
Scanner sc1 = new Scanner(input);
|
||||
int num1 = Integer.parseInt(sc1.nextLine());
|
||||
String nextLineText1 = sc1.nextLine();
|
||||
assertEquals(42, num1);
|
||||
assertEquals("It is a magic number.", nextLineText1);
|
||||
|
||||
//nextInt()
|
||||
Scanner sc2 = new Scanner(input);
|
||||
int num2 = sc2.nextInt();
|
||||
assertEquals(42, num2);
|
||||
|
||||
// nextInt() leaves the newline character (\n) behind
|
||||
String nextLineText2 = sc2.nextLine();
|
||||
assertEquals("", nextLineText2);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,38 +1,38 @@
|
|||
package com.baeldung.scanner;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class ScanACharacterUnitTest {
|
||||
|
||||
// given - input scanner source, no need to scan from console
|
||||
String input = new StringBuilder().append("abc\n")
|
||||
.append("mno\n")
|
||||
.append("xyz\n")
|
||||
.toString();
|
||||
|
||||
@Test
|
||||
public void givenInputSource_whenScanCharUsingNext_thenOneCharIsRead() {
|
||||
Scanner sc = new Scanner(input);
|
||||
char c = sc.next().charAt(0);
|
||||
assertEquals('a', c);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInputSource_whenScanCharUsingFindInLine_thenOneCharIsRead() {
|
||||
Scanner sc = new Scanner(input);
|
||||
char c = sc.findInLine(".").charAt(0);
|
||||
assertEquals('a', c);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInputSource_whenScanCharUsingUseDelimiter_thenOneCharIsRead() {
|
||||
Scanner sc = new Scanner(input);
|
||||
char c = sc.useDelimiter("").next().charAt(0);
|
||||
assertEquals('a', c);
|
||||
}
|
||||
|
||||
}
|
||||
package com.baeldung.scanner;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class ScanACharacterUnitTest {
|
||||
|
||||
// given - input scanner source, no need to scan from console
|
||||
String input = new StringBuilder().append("abc\n")
|
||||
.append("mno\n")
|
||||
.append("xyz\n")
|
||||
.toString();
|
||||
|
||||
@Test
|
||||
public void givenInputSource_whenScanCharUsingNext_thenOneCharIsRead() {
|
||||
Scanner sc = new Scanner(input);
|
||||
char c = sc.next().charAt(0);
|
||||
assertEquals('a', c);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInputSource_whenScanCharUsingFindInLine_thenOneCharIsRead() {
|
||||
Scanner sc = new Scanner(input);
|
||||
char c = sc.findInLine(".").charAt(0);
|
||||
assertEquals('a', c);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInputSource_whenScanCharUsingUseDelimiter_thenOneCharIsRead() {
|
||||
Scanner sc = new Scanner(input);
|
||||
char c = sc.useDelimiter("").next().charAt(0);
|
||||
assertEquals('a', c);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,107 @@
|
|||
package com.baeldung.scanner;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.ObjectArrays;
|
||||
|
||||
public class ScannerToArrayUnitTest {
|
||||
|
||||
@Test
|
||||
void whenMultipleElementsInOneLine_thenGetExpectedArray() {
|
||||
String input = "Java Kotlin Ruby Python Go\n";
|
||||
String[] expected = new String[] { "Java", "Kotlin", "Ruby", "Python", "Go" };
|
||||
|
||||
// scanner.next()
|
||||
Scanner scanner1 = new Scanner(input);
|
||||
String[] result1 = new String[5];
|
||||
int i = 0;
|
||||
while (i < result1.length) {
|
||||
result1[i] = scanner1.next();
|
||||
i++;
|
||||
}
|
||||
assertArrayEquals(expected, result1);
|
||||
|
||||
//split()
|
||||
Scanner scanner2 = new Scanner(input);
|
||||
String[] result2 = scanner2.nextLine()
|
||||
.split("\\s+");
|
||||
assertArrayEquals(expected, result2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenOneElementPerLine_thenGetExpectedArray() {
|
||||
String input = new StringBuilder().append("Baeldung Java\n")
|
||||
.append("Baeldung Kotlin\n")
|
||||
.append("Baeldung Linux\n")
|
||||
.toString();
|
||||
|
||||
String[] expected = new String[] { "Baeldung Java", "Baeldung Kotlin", "Baeldung Linux" };
|
||||
|
||||
String[] result = new String[3];
|
||||
Scanner scanner = new Scanner(input);
|
||||
int i = 0;
|
||||
while (i < result.length) {
|
||||
result[i] = scanner.nextLine();
|
||||
i++;
|
||||
}
|
||||
assertArrayEquals(expected, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenOneElementPerLine_thenGetExpectedList() {
|
||||
String input = new StringBuilder().append("Baeldung Java\n")
|
||||
.append("Baeldung Kotlin\n")
|
||||
.append("Baeldung Linux\n")
|
||||
.toString();
|
||||
|
||||
List<String> expected = Lists.newArrayList("Baeldung Java", "Baeldung Kotlin", "Baeldung Linux");
|
||||
|
||||
List<String> result = new ArrayList<>();
|
||||
Scanner scanner = new Scanner(input);
|
||||
while (scanner.hasNextLine()) {
|
||||
result.add(scanner.nextLine());
|
||||
}
|
||||
assertEquals(expected, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenEveryTokenIsAnElement_thenGetExpectedList() {
|
||||
String input = new StringBuilder().append("Linux Windows MacOS\n")
|
||||
.append("Java Kotlin Python Go\n")
|
||||
.toString();
|
||||
|
||||
List<String> expected = Lists.newArrayList("Linux", "Windows", "MacOS", "Java", "Kotlin", "Python", "Go");
|
||||
List<String> result = new ArrayList<>();
|
||||
Scanner scanner = new Scanner(input);
|
||||
while (scanner.hasNext()) {
|
||||
result.add(scanner.next());
|
||||
}
|
||||
assertEquals(expected, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenEveryTokenIsAnElement_thenGetExpectedArray() {
|
||||
String input = new StringBuilder().append("Linux Windows MacOS\n")
|
||||
.append("Java Kotlin Python Go\n")
|
||||
.toString();
|
||||
|
||||
String[] expected = new String[] { "Linux", "Windows", "MacOS", "Java", "Kotlin", "Python", "Go" };
|
||||
String[] result = new String[] {};
|
||||
|
||||
Scanner scanner = new Scanner(input);
|
||||
while (scanner.hasNextLine()) {
|
||||
String[] lineInArray = scanner.nextLine()
|
||||
.split("\\s+");
|
||||
result = ObjectArrays.concat(result, lineInArray, String.class);
|
||||
}
|
||||
assertArrayEquals(expected, result);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
first line
|
||||
second line
|
||||
third line
|
|
@ -0,0 +1 @@
|
|||
qwerty
|
|
@ -0,0 +1,68 @@
|
|||
package com.baeldung.printstreamtostring;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.io.PrintStream;
|
||||
|
||||
public class PrintStreamToStringUtil {
|
||||
|
||||
public static String usingByteArrayOutputStreamClass(String input) throws IOException {
|
||||
if (input == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String output;
|
||||
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(outputStream)) {
|
||||
printStream.print(input);
|
||||
|
||||
output = outputStream.toString();
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
public static String usingApacheCommonsIO(String input) {
|
||||
if (input == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
org.apache.commons.io.output.ByteArrayOutputStream outputStream = new org.apache.commons.io.output.ByteArrayOutputStream();
|
||||
try (PrintStream printStream = new PrintStream(outputStream)) {
|
||||
printStream.print(input);
|
||||
}
|
||||
|
||||
return new String(outputStream.toByteArray());
|
||||
}
|
||||
|
||||
public static String usingCustomOutputStream(String input) throws IOException {
|
||||
if (input == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String output;
|
||||
try (CustomOutputStream outputStream = new CustomOutputStream(); PrintStream printStream = new PrintStream(outputStream)) {
|
||||
printStream.print(input);
|
||||
|
||||
output = outputStream.toString();
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
private static class CustomOutputStream extends OutputStream {
|
||||
|
||||
private StringBuilder stringBuilder = new StringBuilder();
|
||||
|
||||
@Override
|
||||
public void write(int b) throws IOException {
|
||||
this.stringBuilder.append((char) b);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.stringBuilder.toString();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -49,7 +49,7 @@ public class JavaInputStreamToXUnitTest {
|
|||
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
|
||||
|
||||
final StringBuilder textBuilder = new StringBuilder();
|
||||
try (Reader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
|
||||
try (Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
|
||||
int c;
|
||||
while ((c = reader.read()) != -1) {
|
||||
textBuilder.append((char) c);
|
||||
|
@ -63,7 +63,7 @@ public class JavaInputStreamToXUnitTest {
|
|||
final String originalString = randomAlphabetic(DEFAULT_SIZE);
|
||||
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
|
||||
|
||||
final String text = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name())))
|
||||
final String text = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
|
||||
.lines()
|
||||
.collect(Collectors.joining("\n"));
|
||||
|
||||
|
|
|
@ -0,0 +1,53 @@
|
|||
package com.baeldung.outputstreamtoinputstream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.PipedInputStream;
|
||||
import java.io.PipedOutputStream;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class ConvertOutputStreamToInputStreamUnitTest {
|
||||
|
||||
@Test
|
||||
void whenUsingByteArray_thenGetExpectedInputStream() throws IOException {
|
||||
String content = "I'm an important message.";
|
||||
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
|
||||
out.write(content.getBytes());
|
||||
try (ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray())) {
|
||||
String inContent = new String(in.readAllBytes());
|
||||
|
||||
assertEquals(content, inContent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingPipeStream_thenGetExpectedInputStream() throws IOException {
|
||||
String content = "I'm going through the pipe.";
|
||||
|
||||
ByteArrayOutputStream originOut = new ByteArrayOutputStream();
|
||||
originOut.write(content.getBytes());
|
||||
|
||||
//connect the pipe
|
||||
PipedInputStream in = new PipedInputStream();
|
||||
PipedOutputStream out = new PipedOutputStream(in);
|
||||
|
||||
try (in) {
|
||||
new Thread(() -> {
|
||||
try (out) {
|
||||
originOut.writeTo(out);
|
||||
} catch (IOException iox) {
|
||||
// handle IOExceptions
|
||||
}
|
||||
}).start();
|
||||
|
||||
String inContent = new String(in.readAllBytes());
|
||||
assertEquals(content, inContent);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.printstreamtostring;
|
||||
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class PrintStreamToStringUtilUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenUsingByteArrayOutputStreamClass_thenConvert() throws IOException {
|
||||
assertEquals("test", PrintStreamToStringUtil.usingByteArrayOutputStreamClass("test"));
|
||||
assertEquals("", PrintStreamToStringUtil.usingByteArrayOutputStreamClass(""));
|
||||
assertNull(PrintStreamToStringUtil.usingByteArrayOutputStreamClass(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCustomOutputStream_thenConvert() throws IOException {
|
||||
assertEquals("world", PrintStreamToStringUtil.usingCustomOutputStream("world"));
|
||||
assertEquals("", PrintStreamToStringUtil.usingCustomOutputStream(""));
|
||||
assertNull(PrintStreamToStringUtil.usingCustomOutputStream(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingApacheCommonsIO_thenConvert() {
|
||||
assertEquals("hello", PrintStreamToStringUtil.usingApacheCommonsIO("hello"));
|
||||
assertEquals("", PrintStreamToStringUtil.usingApacheCommonsIO(""));
|
||||
assertNull(PrintStreamToStringUtil.usingApacheCommonsIO(null));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
## Core Java Lang OOP - Constructors - Part 2
|
||||
|
||||
This module contains article about constructors in Java
|
||||
|
||||
### Relevant Articles:
|
||||
- [Different Ways to Create an Object in Java](https://www.baeldung.com/java-different-ways-to-create-objects)
|
||||
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-oop-constructors)
|
|
@ -0,0 +1,16 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-lang-oop-constructors-2</artifactId>
|
||||
<name>core-java-lang-oop-constructors-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
</project>
|
|
@ -13,4 +13,4 @@ This module contains article about constructors in Java
|
|||
- [Constructor Specification in Java](https://www.baeldung.com/java-constructor-specification)
|
||||
- [Static vs. Instance Initializer Block in Java](https://www.baeldung.com/java-static-instance-initializer-blocks)
|
||||
- [Accessing Private Constructor in Java](https://www.baeldung.com/java-private-constructor-access)
|
||||
- [Different Ways to Create an Object in Java](https://www.baeldung.com/java-different-ways-to-create-objects)
|
||||
- More articles: [[next -->]](/core-java-modules/core-java-lang-oop-constructors-2)
|
|
@ -11,3 +11,4 @@ This module contains articles about methods in Java
|
|||
- [The Covariant Return Type in Java](https://www.baeldung.com/java-covariant-return-type)
|
||||
- [Does a Method’s Signature Include the Return Type in Java?](https://www.baeldung.com/java-method-signature-return-type)
|
||||
- [Solving the Hide Utility Class Public Constructor Sonar Warning](https://www.baeldung.com/java-sonar-hide-implicit-constructor)
|
||||
- [Best Practices for Passing Many Arguments to a Method in Java](https://www.baeldung.com/java-best-practices-many-parameters-method)
|
||||
|
|
|
@ -0,0 +1,98 @@
|
|||
package com.baeldung.methods;
|
||||
|
||||
public class Car {
|
||||
|
||||
private final String make;
|
||||
private final String model;
|
||||
private final int year;
|
||||
private final String color;
|
||||
private final boolean automatic;
|
||||
private final int numDoors;
|
||||
private final String features;
|
||||
|
||||
private Car(CarBuilder carBuilder) {
|
||||
this.make = carBuilder.make;
|
||||
this.model = carBuilder.model;
|
||||
this.year = carBuilder.year;
|
||||
this.color = carBuilder.color;
|
||||
this.automatic = carBuilder.automatic;
|
||||
this.numDoors = carBuilder.numDoors;
|
||||
this.features = carBuilder.features;
|
||||
}
|
||||
|
||||
public String getMake() {
|
||||
return make;
|
||||
}
|
||||
|
||||
public String getModel() {
|
||||
return model;
|
||||
}
|
||||
|
||||
public int getYear() {
|
||||
return year;
|
||||
}
|
||||
|
||||
public String getColor() {
|
||||
return color;
|
||||
}
|
||||
|
||||
public boolean isAutomatic() {
|
||||
return automatic;
|
||||
}
|
||||
|
||||
public int getNumDoors() {
|
||||
return numDoors;
|
||||
}
|
||||
|
||||
public String getFeatures() {
|
||||
return features;
|
||||
}
|
||||
|
||||
public static class CarBuilder {
|
||||
|
||||
private final String make;
|
||||
private final String model;
|
||||
private final int year;
|
||||
|
||||
private String color = "unknown";
|
||||
private boolean automatic = false;
|
||||
private int numDoors = 4;
|
||||
private String features = "";
|
||||
|
||||
public CarBuilder(String make, String model, int year) {
|
||||
this.make = make;
|
||||
this.model = model;
|
||||
this.year = year;
|
||||
}
|
||||
|
||||
public CarBuilder color(String color) {
|
||||
this.color = color;
|
||||
return this;
|
||||
}
|
||||
|
||||
public CarBuilder automatic(boolean automatic) {
|
||||
this.automatic = automatic;
|
||||
return this;
|
||||
}
|
||||
|
||||
public CarBuilder numDoors(int numDoors) {
|
||||
this.numDoors = numDoors;
|
||||
return this;
|
||||
}
|
||||
|
||||
public CarBuilder features(String features) {
|
||||
this.features = features;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Car build() {
|
||||
return new Car(this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Car [make=" + make + ", model=" + model + ", year=" + year + ", color=" + color + ", automatic=" + automatic + ", numDoors=" + numDoors + ", features=" + features + "]";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
package com.baeldung.methods;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class Motorcycle extends Vehicle implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 5973661295933599929L;
|
||||
|
||||
private int year;
|
||||
private String features = "";
|
||||
|
||||
public Motorcycle() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Motorcycle(String make, String model, String color, int weight, boolean statusNew, int year) {
|
||||
super(make, model, color, weight, statusNew);
|
||||
this.year = year;
|
||||
}
|
||||
|
||||
public Motorcycle(Vehicle vehicle, int year) {
|
||||
super(vehicle);
|
||||
this.year = year;
|
||||
}
|
||||
|
||||
public int getYear() {
|
||||
return year;
|
||||
}
|
||||
|
||||
public void setYear(int year) {
|
||||
this.year = year;
|
||||
}
|
||||
|
||||
public void setFeatures(String features) {
|
||||
this.features = features;
|
||||
}
|
||||
|
||||
public String getFeatures() {
|
||||
return features;
|
||||
}
|
||||
|
||||
public void addMotorcycleFeatures(String... features) {
|
||||
StringBuilder str = new StringBuilder(this.getFeatures());
|
||||
for (String feature : features) {
|
||||
if (!str.toString().isEmpty())
|
||||
str.append(", ");
|
||||
str.append(feature);
|
||||
}
|
||||
this.setFeatures(str.toString());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.methods;
|
||||
|
||||
public class Vehicle {
|
||||
|
||||
static String defaultValue = "DEFAULT";
|
||||
private String make = defaultValue;
|
||||
private String model = defaultValue;
|
||||
private String color = defaultValue;
|
||||
private int weight = 0;
|
||||
private boolean statusNew = true;
|
||||
|
||||
public Vehicle() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Vehicle(String make, String model, String color, int weight, boolean statusNew) {
|
||||
this.make = make;
|
||||
this.model = model;
|
||||
this.color = color;
|
||||
this.weight = weight;
|
||||
this.statusNew = statusNew;
|
||||
}
|
||||
|
||||
public Vehicle(Vehicle vehicle) {
|
||||
this(vehicle.make, vehicle.model, vehicle.color, vehicle.weight, vehicle.statusNew);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Vehicle [make=" + make + ", model=" + model + ", color=" + color + ", weight=" + weight + ", statusNew=" + statusNew + "]";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.methods;
|
||||
|
||||
public class VehicleProcessor {
|
||||
|
||||
Vehicle processVehicle(String make, String model, String color, int weight, boolean status) {
|
||||
return new Vehicle(make, model, color, weight, status);
|
||||
}
|
||||
|
||||
Vehicle processVehicle(Vehicle vehicle) {
|
||||
return new Vehicle(vehicle);
|
||||
}
|
||||
|
||||
Car processCar(Car car) {
|
||||
return new Car.CarBuilder(car.getMake(), car.getModel(), car.getYear()).color(car.getColor())
|
||||
.automatic(car.isAutomatic())
|
||||
.features(car.getFeatures())
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
package com.baeldung.methods;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class VehicleProcessorUnitTest {
|
||||
|
||||
VehicleProcessor vehicleProcessor = new VehicleProcessor();
|
||||
Vehicle vehicle = new Vehicle("Ford", "Focus", "red", 2200, true);
|
||||
|
||||
@Test
|
||||
void givenAllArguments_whenMethodCall_thenVerifyCallIsDoneCorrectly() {
|
||||
Vehicle veh = vehicleProcessor.processVehicle("Ford", "Focus", "red", 2200, true);
|
||||
assertThat(veh.toString()).hasToString(vehicle.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenParameterObject_whenMethodCall_thenVerifyCallIsDoneCorrectly() {
|
||||
Vehicle veh = vehicleProcessor.processVehicle(vehicle);
|
||||
assertThat(veh.toString()).hasToString(vehicle.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenJavaBeanPattern_whenMethodCall_thenVerifyCallIsDoneCorrectly() {
|
||||
Motorcycle motorcycle = new Motorcycle("Ducati", "Monster", "yellow", 235, true, 2023);
|
||||
motorcycle.setFeatures("GPS");
|
||||
|
||||
vehicleProcessor.processVehicle(motorcycle);
|
||||
assertThat(motorcycle.getFeatures()).isEqualToIgnoringCase("GPS");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenJavaVarargs_whenMethodCall_thenAssertTheReturnedConcatenatedString() {
|
||||
Motorcycle motorcycle = new Motorcycle("Ducati", "Monster", "red", 350, true, 2023);
|
||||
motorcycle.addMotorcycleFeatures("abs");
|
||||
assertThat(motorcycle.getFeatures()).isEqualToIgnoringCase("abs");
|
||||
|
||||
motorcycle.addMotorcycleFeatures("navi", "charger");
|
||||
assertThat(motorcycle.getFeatures()).isEqualToIgnoringCase("abs, navi, charger");
|
||||
|
||||
motorcycle.addMotorcycleFeatures("wifi", "phone", "satellite");
|
||||
assertThat(motorcycle.getFeatures()).isEqualToIgnoringCase("abs, navi, charger, wifi, phone, satellite");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenJavaBuilderPattern_whenMethodCall_thenVerifyCallIsDoneCorrectly() {
|
||||
Car car = new Car.CarBuilder("Ford", "Focus", 2023).color("blue")
|
||||
.automatic(true)
|
||||
.features("abs, navi, charger, wifi, phone, satellite")
|
||||
.build();
|
||||
|
||||
Car result = vehicleProcessor.processCar(car);
|
||||
|
||||
assertThat(result.toString()).hasToString(car.toString());
|
||||
}
|
||||
|
||||
}
|
|
@ -23,7 +23,7 @@
|
|||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<h2.version>1.4.197</h2.version> <!-- needs to be specified as it fails with parent's 1.4.200 -->
|
||||
<h2.version>2.1.214</h2.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -42,6 +42,10 @@ public class Car {
|
|||
this.engine = engine;
|
||||
}
|
||||
|
||||
public static String getCarsInformation(Car car) {
|
||||
return car.getName() + "-" + car.getEngine();
|
||||
}
|
||||
|
||||
public static void setNumberOfCars(int numberOfCars) {
|
||||
Car.numberOfCars = numberOfCars;
|
||||
}
|
||||
|
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.staticmethod;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.staticmodifier.Car;
|
||||
|
||||
public class CallNonStaticMethodUnitTest {
|
||||
@AfterClass
|
||||
public static void setUpCarInstance() {
|
||||
Car.setNumberOfCars(0);
|
||||
}
|
||||
@Test
|
||||
public void whenCallingNonStaticMethodInStaticMethodWithInstanceClass_thenSuccess() {
|
||||
Car car = new Car("Jaguar", "V8");
|
||||
assertEquals("Jaguar-V8", Car.getCarsInformation(car));
|
||||
}
|
||||
|
||||
}
|
|
@ -2,9 +2,16 @@ package com.baeldung.staticmodifier;
|
|||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CarUnitTest {
|
||||
|
||||
@AfterClass
|
||||
public static void setUpCarInstance() {
|
||||
Car.setNumberOfCars(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNumberOfCarObjectsInitialized_thenStaticCounterIncreases() {
|
||||
new Car("Jaguar", "V8");
|
||||
|
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.interfacesingleimpl;
|
||||
|
||||
public interface Animal {
|
||||
String makeSound();
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.interfacesingleimpl;
|
||||
|
||||
public class AnimalCare {
|
||||
private Animal animal;
|
||||
|
||||
public AnimalCare(Animal animal) {
|
||||
this.animal = animal;
|
||||
}
|
||||
|
||||
public String animalSound() {
|
||||
return animal.makeSound();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.interfacesingleimpl;
|
||||
|
||||
public class Cat {
|
||||
private String name;
|
||||
|
||||
public Cat(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String makeSound() {
|
||||
return "Meow! My name is " + name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.interfacesingleimpl;
|
||||
|
||||
public class Dog implements Animal {
|
||||
private String name;
|
||||
|
||||
public Dog(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String makeSound() {
|
||||
return "Woof! My name is " + name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
package com.baeldung.interfacesingleimpl;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class InterfaceSingleImplUnitTest {
|
||||
@Test
|
||||
public void whenUsingMockAnimal_thenAnimalSoundIsCorrect() {
|
||||
MockAnimal mockAnimal = new MockAnimal();
|
||||
String expected = "Mock animal sound!";
|
||||
AnimalCare animalCare = new AnimalCare(mockAnimal);
|
||||
assertThat(animalCare.animalSound()).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingDog_thenDogMakesWoofSound() {
|
||||
Dog dog = new Dog("Buddy");
|
||||
String expected = "Woof! My name is Buddy";
|
||||
assertThat(dog.makeSound()).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingCat_thenCatMakesMeowSound() {
|
||||
Cat cat = new Cat("FuzzBall");
|
||||
String expected = "Meow! My name is FuzzBall";
|
||||
assertThat(cat.makeSound()).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingAnimalCareWithDog_thenDogMakesWoofSound() {
|
||||
Animal dog = new Dog("Ham");
|
||||
AnimalCare animalCare = new AnimalCare(dog);
|
||||
String expected = "Woof! My name is Ham";
|
||||
assertThat(animalCare.animalSound()).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingCatCareWithCat_thenCatMakesMeowSound() {
|
||||
Cat cat = new Cat("Grumpy");
|
||||
String expected = "Meow! My name is Grumpy";
|
||||
assertThat(cat.makeSound()).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingMockAnimal_thenMockAnimalMakesMockAnimalSound() {
|
||||
MockAnimal mockAnimal = new MockAnimal();
|
||||
String expected = "Mock animal sound!";
|
||||
assertThat(mockAnimal.makeSound()).isEqualTo(expected);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.interfacesingleimpl;
|
||||
|
||||
public class MockAnimal implements Animal {
|
||||
@Override
|
||||
public String makeSound() {
|
||||
return "Mock animal sound!";
|
||||
}
|
||||
}
|
|
@ -3,3 +3,4 @@
|
|||
- [Validating URL in Java](https://www.baeldung.com/java-validate-url)
|
||||
- [Validating IPv4 Address in Java](https://www.baeldung.com/java-validate-ipv4-address)
|
||||
- [Download a Webpage in Java](https://www.baeldung.com/java-download-webpage)
|
||||
- [URL Query Manipulation in Java](https://www.baeldung.com/java-url-query-manipulation)
|
||||
|
|
|
@ -13,3 +13,5 @@ This module contains articles about performance of Java applications
|
|||
- [Capturing a Java Thread Dump](https://www.baeldung.com/java-thread-dump)
|
||||
- [JMX Ports](https://www.baeldung.com/jmx-ports)
|
||||
- [Calling JMX MBean Method From a Shell Script](https://www.baeldung.com/jmx-mbean-shell-access)
|
||||
- [External Debugging With JMXTerm](https://www.baeldung.com/java-jmxterm-external-debugging)
|
||||
- [Create and Detect Memory Leaks in Java](https://www.baeldung.com/java-create-detect-memory-leaks)
|
||||
|
|
|
@ -0,0 +1,2 @@
|
|||
## Relevant Articles
|
||||
- [Overridding hashCode() And equals() For Records](https://www.baeldung.com/java-override-hashcode-equals-records)
|
|
@ -0,0 +1,32 @@
|
|||
<?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">
|
||||
<parent>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>core-java-records</artifactId>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>16</source>
|
||||
<target>16</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>19</maven.compiler.source>
|
||||
<maven.compiler.target>19</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.equalshashcoderecords;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
record Movie(String name, Integer yearOfRelease, String distributor) {
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (this == other) {
|
||||
return true;
|
||||
}
|
||||
if (other == null) {
|
||||
return false;
|
||||
}
|
||||
Movie movie = (Movie) other;
|
||||
if (movie.name.equals(this.name) && movie.yearOfRelease.equals(this.yearOfRelease)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(name, yearOfRelease);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.equalshashcoderecords;
|
||||
|
||||
public record Person(String firstName, String lastName, String SSN, String dateOfBirth) {
|
||||
};
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
package com.baeldung.equalshashcoderecords;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class CustomRecordEqualsHashCode {
|
||||
@Test
|
||||
public void givenTwoRecords_whenDefaultEquals_thenCompareEquality() {
|
||||
Person robert = new Person("Robert", "Frost", "HDHDB223", "2000-01-02");
|
||||
Person mike = new Person("Mike", "Adams", "ABJDJ2883", "2001-01-02");
|
||||
assertNotEquals(robert, mike);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoRecords_hashCodesShouldBeSame() {
|
||||
Person robert = new Person("Robert", "Frost", "HDHDB223", "2000-01-02");
|
||||
Person robertCopy = new Person("Robert", "Frost", "HDHDB223", "2000-01-02");
|
||||
assertEquals(robert.hashCode(), robertCopy.hashCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoRecords_whenCustomImplementation_thenCompareEquality() {
|
||||
Movie movie1 = new Movie("The Batman", 2022, "WB");
|
||||
Movie movie2 = new Movie("The Batman", 2022, "Dreamworks");
|
||||
assertEquals(movie1, movie2);
|
||||
assertEquals(movie1.hashCode(), movie2.hashCode());
|
||||
}
|
||||
}
|
|
@ -5,4 +5,5 @@
|
|||
- [Converting Camel Case and Title Case to Words in Java](https://www.baeldung.com/java-camel-case-title-case-to-words)
|
||||
- [How to Use Regular Expressions to Replace Tokens in Strings in Java](https://www.baeldung.com/java-regex-token-replacement)
|
||||
- [Creating a Java Array from Regular Expression Matches](https://www.baeldung.com/java-array-regex-matches)
|
||||
- [Getting the Text That Follows After the Regex Match in Java](https://www.baeldung.com/java-regex-text-after-match)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-regex)
|
||||
|
|
|
@ -0,0 +1,35 @@
|
|||
package com.baeldung.regex.z_regexp;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class ZRegularExpressionUnitTest {
|
||||
@Test
|
||||
public void givenCreditCardNumber_thenReturnIfMatched() {
|
||||
String creditCardNumber = "1234567890123456";
|
||||
String pattern = "\\d{16}\\z";
|
||||
Assertions.assertTrue(creditCardNumber.matches(pattern));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLogOutput_thenReturnIfMatched() {
|
||||
String logLine = "2022-05-01 14:30:00,123 INFO Some log message";
|
||||
String pattern = ".*message\\z";
|
||||
Assertions.assertTrue(logLine.matches(pattern));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmailMessage_thenReturnIfMatched() {
|
||||
String myMessage = "Hello HR, I hope i can write to Baeldung\n";
|
||||
String pattern = ".*Baeldung\\s*\\Z";
|
||||
Assertions.assertTrue(myMessage.matches(pattern));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileExtension_thenReturnIfMatched() {
|
||||
String fileName = "image.jpeg";
|
||||
String pattern = ".*\\.jpeg\\Z";
|
||||
Assertions.assertTrue(fileName.matches(pattern));
|
||||
}
|
||||
|
||||
}
|
|
@ -30,12 +30,18 @@
|
|||
<artifactId>jaxb-api</artifactId>
|
||||
<version>${jaxb-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-crypto</artifactId>
|
||||
<version>${spring-security-crypto.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<bouncycastle.version>1.60</bouncycastle.version>
|
||||
<bouncycastle.version>1.70</bouncycastle.version>
|
||||
<commons-codec.version>1.11</commons-codec.version>
|
||||
<jaxb-api.version>2.3.1</jaxb-api.version>
|
||||
<spring-security-crypto.version>6.0.3</spring-security-crypto.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue