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:
@@ -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)
|
||||
|
||||
+65
@@ -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;
|
||||
}
|
||||
}
|
||||
+30
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
+104
@@ -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>
|
||||
+33
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+16
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
+42
@@ -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"));
|
||||
}
|
||||
|
||||
}
|
||||
+18
@@ -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) {}
|
||||
+37
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+17
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
+41
@@ -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"));
|
||||
}
|
||||
|
||||
}
|
||||
+23
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
+44
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.scopedvalues.scoped.inheriting;
|
||||
|
||||
public class ExternalService {
|
||||
|
||||
public String getData() {
|
||||
return "External data";
|
||||
}
|
||||
|
||||
}
|
||||
+17
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
+17
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
+41
@@ -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"));
|
||||
}
|
||||
|
||||
}
|
||||
+52
@@ -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("");
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user