Merge branch 'master' of https://github.com/Maiklins/tutorials into JAVA-7244-Review_log_statements_for_projects
Conflicts: algorithms-searching/src/test/java/com/baeldung/algorithms/quadtree/QuadTreeSearchUnitTest.java
This commit is contained in:
commit
e3aebd9c10
@ -50,4 +50,4 @@
|
||||
<commons-codec.version>1.11</commons-codec.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
</project>
|
@ -37,7 +37,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-commons</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<version>${junit-platform.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
@ -53,7 +53,6 @@
|
||||
<commons-codec.version>1.11</commons-codec.version>
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<guava.version>28.1-jre</guava.version>
|
||||
<junit.platform.version>1.6.0</junit.platform.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -1,10 +1,10 @@
|
||||
package com.baeldung.algorithms.prim;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class PrimUnitTest {
|
||||
|
||||
@Test
|
||||
|
@ -22,7 +22,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-commons</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<version>${junit-platform.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
@ -46,7 +46,6 @@
|
||||
<properties>
|
||||
<guava.version>28.1-jre</guava.version>
|
||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||
<junit.platform.version>1.6.0</junit.platform.version>
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
</properties>
|
||||
|
||||
|
@ -29,11 +29,13 @@ public class Graph {
|
||||
stack.push(start);
|
||||
while (!stack.isEmpty()) {
|
||||
int current = stack.pop();
|
||||
isVisited[current] = true;
|
||||
visit(current);
|
||||
for (int dest : adjVertices.get(current)) {
|
||||
if (!isVisited[dest])
|
||||
stack.push(dest);
|
||||
if(!isVisited[current]){
|
||||
isVisited[current] = true;
|
||||
visit(current);
|
||||
for (int dest : adjVertices.get(current)) {
|
||||
if (!isVisited[dest])
|
||||
stack.push(dest);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -8,7 +8,9 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class SuffixTree {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(SuffixTree.class);
|
||||
|
||||
private static final String WORD_TERMINATION = "$";
|
||||
private static final int POSITION_UNDEFINED = -1;
|
||||
private Node root;
|
||||
|
@ -2,7 +2,6 @@ package com.baeldung.algorithms.dfs;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.algorithms.dfs.Graph;
|
||||
import org.junit.Test;
|
||||
|
||||
public class GraphUnitTest {
|
||||
|
@ -10,7 +10,7 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class QuadTreeSearchUnitTest {
|
||||
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(QuadTreeSearchUnitTest.class);
|
||||
|
||||
private static QuadTree quadTree;
|
||||
@ -20,7 +20,7 @@ public class QuadTreeSearchUnitTest {
|
||||
Region area = new Region(0, 0, 400, 400);
|
||||
quadTree = new QuadTree(area);
|
||||
|
||||
float[][] points = new float[][] { { 21, 25 }, { 55, 53 }, { 70, 318 }, { 98, 302 },
|
||||
float[][] points = new float[][] { { 21, 25 }, { 55, 53 }, { 70, 318 }, { 98, 302 },
|
||||
{ 49, 229 }, { 135, 229 }, { 224, 292 }, { 206, 321 }, { 197, 258 }, { 245, 238 } };
|
||||
|
||||
for (int i = 0; i < points.length; i++) {
|
||||
@ -35,26 +35,28 @@ public class QuadTreeSearchUnitTest {
|
||||
public void givenQuadTree_whenSearchingForRange_thenReturn1MatchingItem() {
|
||||
Region searchArea = new Region(200, 200, 250, 250);
|
||||
List<Point> result = quadTree.search(searchArea, null, "");
|
||||
|
||||
LOGGER.debug(result.toString());
|
||||
LOGGER.debug(quadTree.printSearchTraversePath());
|
||||
|
||||
|
||||
Assert.assertEquals(1, result.size());
|
||||
Assert.assertArrayEquals(new float[] { 245, 238 },
|
||||
Assert.assertArrayEquals(new float[] { 245, 238 },
|
||||
new float[]{result.get(0).getX(), result.get(0).getY() }, 0);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenQuadTree_whenSearchingForRange_thenReturn2MatchingItems() {
|
||||
Region searchArea = new Region(0, 0, 100, 100);
|
||||
List<Point> result = quadTree.search(searchArea, null, "");
|
||||
|
||||
LOGGER.debug(result.toString());
|
||||
LOGGER.debug(quadTree.printSearchTraversePath());
|
||||
|
||||
|
||||
Assert.assertEquals(2, result.size());
|
||||
Assert.assertArrayEquals(new float[] { 21, 25 },
|
||||
Assert.assertArrayEquals(new float[] { 21, 25 },
|
||||
new float[]{result.get(0).getX(), result.get(0).getY() }, 0);
|
||||
Assert.assertArrayEquals(new float[] { 55, 53 },
|
||||
Assert.assertArrayEquals(new float[] { 55, 53 },
|
||||
new float[]{result.get(1).getX(), result.get(1).getY() }, 0);
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -32,7 +32,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>${junit-jupiter-api.version}</version>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -47,7 +47,6 @@
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||
<commons-codec.version>1.11</commons-codec.version>
|
||||
<junit-jupiter-api.version>5.3.1</junit-jupiter-api.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -33,7 +33,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>${junit-jupiter-api.version}</version>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -48,7 +48,6 @@
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||
<commons-codec.version>1.11</commons-codec.version>
|
||||
<junit-jupiter-api.version>5.3.1</junit-jupiter-api.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -10,7 +10,6 @@
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<artifactId>annotations</artifactId>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@ -10,7 +10,6 @@
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>annotations</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@ -3,7 +3,7 @@
|
||||
This module contains articles about Apache Kafka.
|
||||
|
||||
### Relevant articles
|
||||
- [Kafka Streams vs Kafka Consumer](https://www.baeldung.com/java-kafka-streams-vs-kafka-consumer)
|
||||
- [Kafka Streams vs. Kafka Consumer](https://www.baeldung.com/java-kafka-streams-vs-kafka-consumer)
|
||||
- [Kafka Topic Creation Using Java](https://www.baeldung.com/kafka-topic-creation)
|
||||
- [Using Kafka MockConsumer](https://www.baeldung.com/kafka-mockconsumer)
|
||||
- [Using Kafka MockProducer](https://www.baeldung.com/kafka-mockproducer)
|
||||
|
@ -161,6 +161,12 @@
|
||||
<artifactId>spark-cassandra-connector-java_2.11</artifactId>
|
||||
<version>${com.datastax.spark.spark-cassandra-connector-java.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
@ -175,6 +181,7 @@
|
||||
<graphframes.version>0.8.1-spark3.0-s_2.12</graphframes.version>
|
||||
<com.datastax.spark.spark-cassandra-connector.version>2.5.2</com.datastax.spark.spark-cassandra-connector.version>
|
||||
<com.datastax.spark.spark-cassandra-connector-java.version>1.6.0-M1</com.datastax.spark.spark-cassandra-connector-java.version>
|
||||
<lombok.version>1.18.20</lombok.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -0,0 +1,15 @@
|
||||
package com.baeldung.kafka.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@Builder
|
||||
public class MessageDto {
|
||||
private String message;
|
||||
private String version;
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
package com.baeldung.kafka.serdes;
|
||||
|
||||
import com.baeldung.kafka.dto.MessageDto;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.apache.kafka.common.errors.SerializationException;
|
||||
import org.apache.kafka.common.serialization.Deserializer;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class CustomDeserializer implements Deserializer<MessageDto> {
|
||||
|
||||
private ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@Override
|
||||
public void configure(Map<String, ?> configs, boolean isKey) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public MessageDto deserialize(String topic, byte[] data) {
|
||||
try {
|
||||
if (data == null){
|
||||
System.out.println("Null received at deserializing");
|
||||
return null;
|
||||
}
|
||||
System.out.println("Deserializing...");
|
||||
return objectMapper.readValue(new String(data, "UTF-8"), MessageDto.class);
|
||||
} catch (Exception e) {
|
||||
throw new SerializationException("Error when deserializing byte[] to MessageDto");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
}
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
package com.baeldung.kafka.serdes;
|
||||
|
||||
import com.baeldung.kafka.dto.MessageDto;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.apache.kafka.common.errors.SerializationException;
|
||||
import org.apache.kafka.common.serialization.Serializer;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class CustomSerializer implements Serializer<MessageDto> {
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@Override
|
||||
public void configure(Map<String, ?> configs, boolean isKey) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] serialize(String topic, MessageDto data) {
|
||||
try {
|
||||
if (data == null){
|
||||
System.out.println("Null received at serializing");
|
||||
return null;
|
||||
}
|
||||
System.out.println("Serializing...");
|
||||
return objectMapper.writeValueAsBytes(data);
|
||||
} catch (Exception e) {
|
||||
throw new SerializationException("Error when serializing MessageDto to byte[]");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
}
|
||||
}
|
@ -12,8 +12,10 @@ import java.util.Properties;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
// This live test needs a running Docker instance so that a kafka container can be created
|
||||
|
||||
@Testcontainers
|
||||
class KafkaTopicApplicationIntegrationTest {
|
||||
class KafkaTopicApplicationLiveTest {
|
||||
|
||||
@Container
|
||||
private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:5.4.3"));
|
@ -0,0 +1,94 @@
|
||||
package com.baeldung.kafka.serdes;
|
||||
|
||||
import com.baeldung.kafka.dto.MessageDto;
|
||||
import org.apache.kafka.clients.consumer.ConsumerConfig;
|
||||
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.junit.Before;
|
||||
import org.junit.ClassRule;
|
||||
import org.junit.Test;
|
||||
import org.testcontainers.containers.KafkaContainer;
|
||||
import org.testcontainers.utility.DockerImageName;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
// This live test needs a Docker instance running so that kafka container can be created
|
||||
|
||||
public class KafkaSerDesLiveTest {
|
||||
private static final String CONSUMER_APP_ID = "consumer_id";
|
||||
private static final String CONSUMER_GROUP_ID = "group_id";
|
||||
|
||||
@ClassRule
|
||||
public static KafkaContainer kafka = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:5.4.3"));
|
||||
private final String TOPIC = "mytopic";
|
||||
|
||||
private static KafkaConsumer<String, MessageDto> createKafkaConsumer() {
|
||||
|
||||
Properties props = new Properties();
|
||||
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafka.getBootstrapServers());
|
||||
props.put(ConsumerConfig.CLIENT_ID_CONFIG, CONSUMER_APP_ID);
|
||||
props.put(ConsumerConfig.GROUP_ID_CONFIG, CONSUMER_GROUP_ID);
|
||||
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
|
||||
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
|
||||
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "com.baeldung.kafka.serdes.CustomDeserializer");
|
||||
|
||||
return new KafkaConsumer<>(props);
|
||||
|
||||
}
|
||||
|
||||
private static KafkaProducer<String, MessageDto> createKafkaProducer() {
|
||||
|
||||
Properties props = new Properties();
|
||||
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafka.getBootstrapServers());
|
||||
props.put(ProducerConfig.CLIENT_ID_CONFIG, CONSUMER_APP_ID);
|
||||
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
|
||||
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "com.baeldung.kafka.serdes.CustomSerializer");
|
||||
|
||||
return new KafkaProducer(props);
|
||||
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenKafkaClientShouldSerializeAndDeserialize() throws InterruptedException {
|
||||
|
||||
MessageDto msgProd = MessageDto.builder().message("test").version("1.0").build();
|
||||
|
||||
KafkaProducer<String, MessageDto> producer = createKafkaProducer();
|
||||
producer.send(new ProducerRecord<String, MessageDto>(TOPIC, "1", msgProd));
|
||||
System.out.println("Message sent " + msgProd);
|
||||
producer.close();
|
||||
|
||||
Thread.sleep(2000);
|
||||
|
||||
AtomicReference<MessageDto> msgCons = new AtomicReference<>();
|
||||
|
||||
KafkaConsumer<String, MessageDto> consumer = createKafkaConsumer();
|
||||
consumer.subscribe(Arrays.asList(TOPIC));
|
||||
|
||||
ConsumerRecords<String, MessageDto> records = consumer.poll(Duration.ofSeconds(1));
|
||||
records.forEach(record -> {
|
||||
msgCons.set(record.value());
|
||||
System.out.println("Message received " + record.value());
|
||||
});
|
||||
|
||||
consumer.close();
|
||||
|
||||
assertEquals(msgProd, msgCons.get());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
@ -44,6 +44,8 @@ import static org.apache.kafka.clients.consumer.ConsumerConfig.BOOTSTRAP_SERVERS
|
||||
import static org.apache.kafka.clients.producer.ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG;
|
||||
import static org.apache.kafka.clients.producer.ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG;
|
||||
|
||||
// This live test needs a Docker instance running so that kafka container can be created
|
||||
|
||||
public class KafkaStreamsLiveTest {
|
||||
private final String LEFT_TOPIC = "left-stream-topic";
|
||||
private final String RIGHT_TOPIC = "right-stream-topic";
|
||||
|
@ -133,6 +133,11 @@
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-annotations</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jayway.awaitility</groupId>
|
||||
<artifactId>awaitility</artifactId>
|
||||
@ -196,7 +201,6 @@
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<avro.version>1.8.2</avro.version>
|
||||
<slf4j.version>1.7.25</slf4j.version>
|
||||
<beam.version>2.19.0</beam.version>
|
||||
<assertj.version>3.9.0</assertj.version>
|
||||
<bval.version>1.1.2</bval.version>
|
||||
|
18
apache-libraries/src/main/resources/log4j2.xml
Normal file
18
apache-libraries/src/main/resources/log4j2.xml
Normal file
@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
<Configuration status="WARN">
|
||||
<Appenders>
|
||||
<Console name="Console" target="SYSTEM_OUT">
|
||||
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
|
||||
</Console>
|
||||
</Appenders>
|
||||
<Loggers>
|
||||
<Logger name="org.apache.meecrowave" level="warn">
|
||||
<AppenderRef ref="Console"/>
|
||||
</Logger>
|
||||
|
||||
<Root level="info">
|
||||
<AppenderRef ref="Console"/>
|
||||
</Root>
|
||||
</Loggers>
|
||||
</Configuration>
|
@ -10,7 +10,6 @@ import com.baeldung.apache.beam.intro.WordCount;
|
||||
public class WordCountUnitTest {
|
||||
|
||||
@Test
|
||||
// @Ignore
|
||||
public void givenInputFile_whenWordCountRuns_thenJobFinishWithoutError() {
|
||||
boolean jobDone = WordCount.wordCount("src/test/resources/wordcount.txt", "target/output");
|
||||
assertTrue(jobDone);
|
||||
|
@ -0,0 +1,18 @@
|
||||
package com.baeldung.poi.excel.multilinetext;
|
||||
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.CellStyle;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
|
||||
public class MultilineText {
|
||||
public void formatMultilineText(Cell cell, int cellNumber) {
|
||||
cell.getRow()
|
||||
.setHeightInPoints(cell.getSheet()
|
||||
.getDefaultRowHeightInPoints() * 2);
|
||||
CellStyle cellStyle = cell.getSheet()
|
||||
.getWorkbook()
|
||||
.createCellStyle();
|
||||
cellStyle.setWrapText(true);
|
||||
cell.setCellStyle(cellStyle);
|
||||
}
|
||||
}
|
Binary file not shown.
@ -0,0 +1,69 @@
|
||||
package com.baeldung.poi.excel.multilinetext;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.DataFormatter;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class MultilineTextUnitTest {
|
||||
private static String FILE_NAME = "com/baeldung/poi/excel/multilinetext/MultilineTextTest.xlsx";
|
||||
private static final String NEW_FILE_NAME = "MultilineTextTest_output.xlsx";
|
||||
private static final int STRING_ROW_INDEX = 1;
|
||||
private static final int STRING_CELL_INDEX = 0;
|
||||
|
||||
private String fileLocation;
|
||||
|
||||
@Before
|
||||
public void setup() throws IOException, URISyntaxException {
|
||||
fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME)
|
||||
.toURI())
|
||||
.toString();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultilineTextCell_whenFormated_thenMultilineTextVisible() throws IOException {
|
||||
Workbook workbook = new XSSFWorkbook(fileLocation);
|
||||
Sheet sheet = workbook.getSheetAt(0);
|
||||
sheet.createRow(STRING_ROW_INDEX);
|
||||
Row row = sheet.getRow(STRING_ROW_INDEX);
|
||||
Cell cell = row.createCell(STRING_CELL_INDEX);
|
||||
|
||||
cell.setCellValue("Hello \n world!");
|
||||
MultilineText multilineText = new MultilineText();
|
||||
multilineText.formatMultilineText(cell, STRING_CELL_INDEX);
|
||||
|
||||
FileOutputStream outputStream = new FileOutputStream(NEW_FILE_NAME);
|
||||
workbook.write(outputStream);
|
||||
outputStream.close();
|
||||
|
||||
File file = new File(NEW_FILE_NAME);
|
||||
FileInputStream fileInputStream = new FileInputStream(file);
|
||||
Workbook testWorkbook = new XSSFWorkbook(fileInputStream);
|
||||
assertTrue(row.getHeightInPoints() == testWorkbook.getSheetAt(0)
|
||||
.getRow(STRING_ROW_INDEX)
|
||||
.getHeightInPoints());
|
||||
DataFormatter formatter = new DataFormatter();
|
||||
assertEquals("Hello \n world!", formatter.formatCellValue(testWorkbook.getSheetAt(0)
|
||||
.getRow(STRING_ROW_INDEX)
|
||||
.getCell(STRING_CELL_INDEX)));
|
||||
testWorkbook.close();
|
||||
fileInputStream.close();
|
||||
file.delete();
|
||||
|
||||
workbook.close();
|
||||
}
|
||||
}
|
@ -39,10 +39,6 @@
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<!-- spring-sec -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
|
42
apache-spark/src/main/resources/log4j.properties
Normal file
42
apache-spark/src/main/resources/log4j.properties
Normal file
@ -0,0 +1,42 @@
|
||||
#
|
||||
# Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
# contributor license agreements. See the NOTICE file distributed with
|
||||
# this work for additional information regarding copyright ownership.
|
||||
# The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
# (the "License"); you may not use this file except in compliance with
|
||||
# the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
# Set everything to be logged to the console
|
||||
log4j.rootCategory=WARN, console
|
||||
log4j.appender.console=org.apache.log4j.ConsoleAppender
|
||||
log4j.appender.console.target=System.err
|
||||
log4j.appender.console.layout=org.apache.log4j.PatternLayout
|
||||
log4j.appender.console.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c{1}: %m%n
|
||||
|
||||
# Set the default spark-shell log level to WARN. When running the spark-shell, the
|
||||
# log level for this class is used to overwrite the root logger's log level, so that
|
||||
# the user can have different defaults for the shell and regular Spark apps.
|
||||
log4j.logger.org.apache.spark.repl.Main=WARN
|
||||
|
||||
# Settings to quiet third party logs that are too verbose
|
||||
log4j.logger.org.spark_project.jetty=WARN
|
||||
log4j.logger.org.spark_project.jetty.util.component.AbstractLifeCycle=ERROR
|
||||
log4j.logger.org.apache.spark.repl.SparkIMain$exprTyper=INFO
|
||||
log4j.logger.org.apache.spark.repl.SparkILoop$SparkILoopInterpreter=INFO
|
||||
|
||||
# SPARK-9183: Settings to avoid annoying messages when looking up nonexistent UDFs in SparkSQL with Hive support
|
||||
log4j.logger.org.apache.hadoop.hive.metastore.RetryingHMSHandler=FATAL
|
||||
log4j.logger.org.apache.hadoop.hive.ql.exec.FunctionRegistry=ERROR
|
||||
|
||||
# Parquet related logging
|
||||
log4j.logger.org.apache.parquet.CorruptStatistics=ERROR
|
||||
log4j.logger.parquet.CorruptStatistics=ERROR
|
@ -32,7 +32,6 @@
|
||||
<!-- Uncomment this to add support for file uploads: -->
|
||||
<!-- <dependency> <groupId>org.apache.tapestry</groupId> <artifactId>tapestry-upload</artifactId>
|
||||
<version>${tapestry-release-version}</version> </dependency> -->
|
||||
|
||||
<!-- A dependency on either JUnit or TestNG is required, or the surefire plugin (which runs the
|
||||
tests) will fail, preventing Maven from packaging the WAR. Tapestry includes a large number of testing
|
||||
facilities designed for use with TestNG (http://testng.org/), so it's recommended. -->
|
||||
@ -110,8 +109,6 @@
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<reporting />
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>jboss</id>
|
||||
|
@ -29,7 +29,7 @@
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-simple</artifactId>
|
||||
<version>${org.slf4j.slf4j-simple.version}</version>
|
||||
<version>${org.slf4j.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
@ -61,7 +61,6 @@
|
||||
<properties>
|
||||
<thrift.version>0.10.0</thrift.version>
|
||||
<maven-thrift.version>0.1.11</maven-thrift.version>
|
||||
<org.slf4j.slf4j-simple.version>1.7.12</org.slf4j.slf4j-simple.version>
|
||||
<build-helper-maven-plugin.version>3.0.0</build-helper-maven-plugin.version>
|
||||
</properties>
|
||||
|
||||
|
@ -72,9 +72,9 @@
|
||||
<version>${derby.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- the JTA API -->
|
||||
|
@ -62,6 +62,13 @@
|
||||
<groupId>com.googlecode.json-simple</groupId>
|
||||
<artifactId>json-simple</artifactId>
|
||||
<version>${json-simple.version}</version>
|
||||
<exclusions>
|
||||
<!-- junit4 dependency is excluded as it should to be resolved from junit-vintage-engine included in parent-modules. -->
|
||||
<exclusion>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
@ -12,23 +12,17 @@
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-lambda-java-core</artifactId>
|
||||
<version>1.2.0</version>
|
||||
<version>${aws-lambda-java-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-lambda-java-events</artifactId>
|
||||
<version>3.1.0</version>
|
||||
<version>${aws-lambda-java-events.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>2.11.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
<version>${jackson-databind.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
@ -43,7 +37,7 @@
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<version>42.2.16</version>
|
||||
<version>${postgresql.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
@ -71,6 +65,10 @@
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<hibernate.version>5.4.21.Final</hibernate.version>
|
||||
<aws-lambda-java-core.version>1.2.0</aws-lambda-java-core.version>
|
||||
<aws-lambda-java-events.version>3.1.0</aws-lambda-java-events.version>
|
||||
<jackson-databind.version>2.11.2</jackson-databind.version>
|
||||
<postgresql.version>42.2.16</postgresql.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -12,70 +12,70 @@
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-lambda-java-core</artifactId>
|
||||
<version>1.2.1</version>
|
||||
<version>${aws-lambda-java-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-lambda-java-events</artifactId>
|
||||
<version>3.6.0</version>
|
||||
<version>${aws-lambda-java-events.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>uk.org.webcompere</groupId>
|
||||
<artifactId>lightweight-config</artifactId>
|
||||
<version>1.1.0</version>
|
||||
<version>${lightweight-config.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-lambda-java-log4j2</artifactId>
|
||||
<version>1.2.0</version>
|
||||
<version>${aws-lambda-java-log4j2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-slf4j-impl</artifactId>
|
||||
<version>2.13.2</version>
|
||||
<version>${log4j-slf4j-impl.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.openfeign</groupId>
|
||||
<artifactId>feign-core</artifactId>
|
||||
<version>11.2</version>
|
||||
<version>${feign-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.openfeign</groupId>
|
||||
<artifactId>feign-slf4j</artifactId>
|
||||
<version>11.2</version>
|
||||
<version>${feign-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.openfeign</groupId>
|
||||
<artifactId>feign-gson</artifactId>
|
||||
<version>11.2</version>
|
||||
<version>${feign-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.inject</groupId>
|
||||
<artifactId>guice</artifactId>
|
||||
<version>5.0.1</version>
|
||||
<version>${guice.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.13.1</version>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>uk.org.webcompere</groupId>
|
||||
<artifactId>system-stubs-junit4</artifactId>
|
||||
<version>1.2.0</version>
|
||||
<version>${system-stubs-junit4.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>3.3.0</version>
|
||||
<version>${mockito-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.19.0</version>
|
||||
<version>${assertj-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
@ -103,6 +103,17 @@
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<aws-lambda-java-core.version>1.2.1</aws-lambda-java-core.version>
|
||||
<aws-lambda-java-events.version>3.6.0</aws-lambda-java-events.version>
|
||||
<lightweight-config.version>1.1.0</lightweight-config.version>
|
||||
<aws-lambda-java-log4j2.version>1.2.0</aws-lambda-java-log4j2.version>
|
||||
<log4j-slf4j-impl.version>2.13.2</log4j-slf4j-impl.version>
|
||||
<feign-core.version>11.2</feign-core.version>
|
||||
<guice.version>5.0.1</guice.version>
|
||||
<system-stubs-junit4.version>1.2.0</system-stubs-junit4.version>
|
||||
<mockito-core.version>3.3.0</mockito-core.version>
|
||||
<assertj-core.version>3.19.0</assertj-core.version>
|
||||
<junit-jupiter.version>5.8.1</junit-jupiter.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -93,5 +93,5 @@
|
||||
<spring.version>2.2.1.RELEASE</spring.version>
|
||||
<awssdk.version>2.10.27</awssdk.version>
|
||||
</properties>
|
||||
|
||||
|
||||
</project>
|
@ -6,7 +6,7 @@ This module contains articles about Amazon Web Services (AWS)
|
||||
|
||||
- [AWS Lambda Using DynamoDB With Java](https://www.baeldung.com/aws-lambda-dynamodb-java)
|
||||
- [AWS S3 with Java](https://www.baeldung.com/aws-s3-java)
|
||||
- [AWS Lambda With Java](https://www.baeldung.com/java-aws-lambda)
|
||||
- [A Basic AWS Lambda Example With Java](https://www.baeldung.com/java-aws-lambda)
|
||||
- [Managing EC2 Instances in Java](https://www.baeldung.com/ec2-java)
|
||||
- [Multipart Uploads in Amazon S3 with Java](https://www.baeldung.com/aws-s3-multipart-upload)
|
||||
- [Integration Testing with a Local DynamoDB Instance](https://www.baeldung.com/dynamodb-local-integration-tests)
|
||||
|
@ -6,3 +6,4 @@ This module contains articles about Axon
|
||||
|
||||
- [A Guide to the Axon Framework](https://www.baeldung.com/axon-cqrs-event-sourcing)
|
||||
- [Multi-Entity Aggregates in Axon](https://www.baeldung.com/java-axon-multi-entity-aggregates)
|
||||
- [Snapshotting Aggregates in Axon](https://www.baeldung.com/axon-snapshotting-aggregates)
|
||||
|
@ -0,0 +1,18 @@
|
||||
package com.baeldung.axon;
|
||||
|
||||
import org.axonframework.eventsourcing.EventCountSnapshotTriggerDefinition;
|
||||
import org.axonframework.eventsourcing.SnapshotTriggerDefinition;
|
||||
import org.axonframework.eventsourcing.Snapshotter;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class OrderApplicationConfiguration {
|
||||
|
||||
@Bean
|
||||
public SnapshotTriggerDefinition orderAggregateSnapshotTriggerDefinition(Snapshotter snapshotter,
|
||||
@Value("${axon.aggregate.order.snapshot-threshold:250}") int threshold) {
|
||||
return new EventCountSnapshotTriggerDefinition(snapshotter, threshold);
|
||||
}
|
||||
}
|
@ -23,7 +23,7 @@ import java.util.Map;
|
||||
|
||||
import static org.axonframework.modelling.command.AggregateLifecycle.apply;
|
||||
|
||||
@Aggregate
|
||||
@Aggregate(snapshotTriggerDefinition = "orderAggregateSnapshotTriggerDefinition")
|
||||
public class OrderAggregate {
|
||||
|
||||
@AggregateIdentifier
|
||||
|
@ -70,6 +70,7 @@
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>${maven-failsafe-plugin.version}</version>
|
||||
<configuration>
|
||||
<skipITs>true</skipITs>
|
||||
<includes>
|
||||
<include>**/*LiveTest.java</include>
|
||||
</includes>
|
||||
|
@ -33,7 +33,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<version>${junit-platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -95,7 +95,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-surefire-provider</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<version>${junit-platform-surefire-provider.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<executions>
|
||||
@ -165,7 +165,6 @@
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<junit.platform.version>1.0.0</junit.platform.version>
|
||||
<hsqldb.version>2.4.0</hsqldb.version>
|
||||
<spock-core.version>1.1-groovy-2.4</spock-core.version>
|
||||
<commons-lang3.version>3.9</commons-lang3.version>
|
||||
|
@ -34,7 +34,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<version>${junit-platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -94,7 +94,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-surefire-provider</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<version>${junit-platform-surefire-provider.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<executions>
|
||||
@ -162,11 +162,9 @@
|
||||
</repositories>
|
||||
|
||||
<properties>
|
||||
<junit.platform.version>1.0.0</junit.platform.version>
|
||||
<hsqldb.version>2.4.0</hsqldb.version>
|
||||
<spock-core.version>1.1-groovy-2.4</spock-core.version>
|
||||
<groovy-wslite.version>1.1.3</groovy-wslite.version>
|
||||
<logback.version>1.2.3</logback.version>
|
||||
<groovy.version>2.5.7</groovy.version>
|
||||
<assembly.plugin.version>3.1.0</assembly.plugin.version>
|
||||
<compiler.plugin.version>3.8.0</compiler.plugin.version>
|
||||
|
@ -39,7 +39,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<version>${junit-platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -80,7 +80,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-surefire-provider</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<version>${junit-platform-surefire-provider.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<executions>
|
||||
@ -119,7 +119,6 @@
|
||||
</repositories>
|
||||
|
||||
<properties>
|
||||
<junit.platform.version>1.0.0</junit.platform.version>
|
||||
<groovy.version>2.5.6</groovy.version>
|
||||
<groovy-all.version>2.5.6</groovy-all.version>
|
||||
<groovy-sql.version>2.5.6</groovy-sql.version>
|
||||
|
@ -39,7 +39,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<version>${junit-platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -80,7 +80,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-surefire-provider</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<version>${junit-platform-surefire-provider.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<executions>
|
||||
@ -109,7 +109,6 @@
|
||||
</repositories>
|
||||
|
||||
<properties>
|
||||
<junit.platform.version>1.0.0</junit.platform.version>
|
||||
<groovy.version>2.5.6</groovy.version>
|
||||
<groovy-all.version>2.5.6</groovy-all.version>
|
||||
<groovy-sql.version>2.5.6</groovy-sql.version>
|
||||
|
@ -39,7 +39,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<version>${junit-platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -80,7 +80,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-surefire-provider</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<version>${junit-platform-surefire-provider.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<executions>
|
||||
@ -109,7 +109,6 @@
|
||||
</repositories>
|
||||
|
||||
<properties>
|
||||
<junit.platform.version>1.0.0</junit.platform.version>
|
||||
<groovy.version>2.5.6</groovy.version>
|
||||
<groovy-all.version>2.5.6</groovy-all.version>
|
||||
<groovy-sql.version>2.5.6</groovy-sql.version>
|
||||
|
@ -8,3 +8,4 @@ This module contains articles about Java 11 core features
|
||||
- [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors)
|
||||
- [New Features in Java 11](https://www.baeldung.com/java-11-new-features)
|
||||
- [Getting the Java Version at Runtime](https://www.baeldung.com/get-java-version-runtime)
|
||||
- [Invoking a SOAP Web Service in Java](https://www.baeldung.com/java-soap-web-service)
|
||||
|
@ -35,19 +35,19 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-params</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -106,7 +106,6 @@
|
||||
<maven.compiler.source.version>11</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>11</maven.compiler.target.version>
|
||||
<guava.version>29.0-jre</guava.version>
|
||||
<junit.jupiter.version>5.7.0</junit.jupiter.version>
|
||||
<assertj.version>3.17.2</assertj.version>
|
||||
<mockserver.version>5.11.1</mockserver.version>
|
||||
<commons-lang3.version>3.12.0</commons-lang3.version>
|
||||
|
@ -1,60 +1,60 @@
|
||||
<?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-12</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-12</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
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-12</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-12</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>2.11.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>2.11.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source.version}</source>
|
||||
<target>${maven.compiler.target.version}</target>
|
||||
<compilerArgs>--enable-preview</compilerArgs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<argLine>--enable-preview</argLine>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source.version}</source>
|
||||
<target>${maven.compiler.target.version}</target>
|
||||
<compilerArgs>--enable-preview</compilerArgs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<argLine>--enable-preview</argLine>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source.version>12</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>12</maven.compiler.target.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
</properties>
|
||||
<properties>
|
||||
<maven.compiler.source.version>12</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>12</maven.compiler.target.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -14,7 +14,7 @@
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
@ -35,7 +35,7 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
@ -1,3 +1,7 @@
|
||||
### Relevant articles:
|
||||
|
||||
- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection)
|
||||
- [Guide to mapMulti in Stream API](https://www.baeldung.com/java-mapmulti)
|
||||
- [Collecting Stream Elements into a List in Java](https://www.baeldung.com/java-stream-to-list-collecting)
|
||||
- [New Features in Java 16](https://www.baeldung.com/java-16-new-features)
|
||||
- [Guide to Java 8 groupingBy Collector](https://www.baeldung.com/java-groupingby-collector)
|
||||
|
@ -1,53 +1,86 @@
|
||||
<?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-16</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-16</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
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-16</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-16</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.12.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.12.0</version>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<release>${maven.compiler.release}</release>
|
||||
<compilerArgs>--enable-preview</compilerArgs>
|
||||
<source>${maven.compiler.source.version}</source>
|
||||
<target>${maven.compiler.target.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${surefire.plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source.version}</source>
|
||||
<target>${maven.compiler.target.version}</target>
|
||||
<argLine>--enable-preview</argLine>
|
||||
<forkCount>1</forkCount>
|
||||
</configuration>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.maven.surefire</groupId>
|
||||
<artifactId>surefire-api</artifactId>
|
||||
<version>${surefire.plugin.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source.version>16</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>16</maven.compiler.target.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
</properties>
|
||||
<properties>
|
||||
<maven.compiler.source.version>16</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>16</maven.compiler.target.version>
|
||||
<maven.compiler.release>16</maven.compiler.release>
|
||||
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
|
||||
<surefire.plugin.version>3.0.0-M5</surefire.plugin.version>
|
||||
<assertj.version>3.17.2</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -0,0 +1,7 @@
|
||||
package com.baeldung.features;
|
||||
|
||||
interface HelloWorld {
|
||||
default String hello() {
|
||||
return "world";
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
package com.baeldung.features;
|
||||
|
||||
import com.baeldung.features.record.Book;
|
||||
|
||||
public class OuterClass {
|
||||
class InnerClass {
|
||||
Book book = new Book("Title", "author", "isbn");
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.baeldung.features;
|
||||
|
||||
import jdk.incubator.vector.IntVector;
|
||||
|
||||
public class VectorExample {
|
||||
public int[] scalarComputation(int[] a, int[] b) {
|
||||
var c = new int[a.length];
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
c[i] = a[i] * b[i];
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
public int[] vectorComputation(int[] a, int[] b) {
|
||||
var c = new int[a.length];
|
||||
|
||||
var vectorA = IntVector.fromArray(IntVector.SPECIES_128, a, 0);
|
||||
var vectorB = IntVector.fromArray(IntVector.SPECIES_128, b, 0);
|
||||
var vectorC = vectorA.mul(vectorB);
|
||||
vectorC.intoArray(c, 0);
|
||||
return c;
|
||||
}
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
package com.baeldung.features.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public final class Book {
|
||||
private final String title;
|
||||
private final String author;
|
||||
private final String isbn;
|
||||
|
||||
public Book(String title, String author, String isbn) {
|
||||
this.title = title;
|
||||
this.author = author;
|
||||
this.isbn = isbn;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public String getIsbn() {
|
||||
return isbn;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
Book book = (Book) o;
|
||||
return Objects.equals(title, book.title) && Objects.equals(author, book.author) && Objects.equals(isbn, book.isbn);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(title, author, isbn);
|
||||
}
|
||||
}
|
@ -0,0 +1,4 @@
|
||||
package com.baeldung.features.record;
|
||||
|
||||
public record Book(String title, String author, String isbn) {
|
||||
}
|
@ -0,0 +1,4 @@
|
||||
package com.baeldung.features.sealed;
|
||||
|
||||
public sealed interface JungleAnimal permits Monkey, Snake {
|
||||
}
|
@ -0,0 +1,4 @@
|
||||
package com.baeldung.features.sealed;
|
||||
|
||||
public final class Monkey implements JungleAnimal {
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.features.sealed;
|
||||
|
||||
public class Sealed {
|
||||
public static void main(String... args) {
|
||||
JungleAnimal j = new Monkey();
|
||||
|
||||
if (j instanceof Monkey m) {
|
||||
// do logic
|
||||
} else if (j instanceof Snake s) {
|
||||
// do logic
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,4 @@
|
||||
package com.baeldung.features.sealed;
|
||||
|
||||
public non-sealed class Snake implements JungleAnimal {
|
||||
}
|
@ -0,0 +1,4 @@
|
||||
module core.java {
|
||||
requires jdk.incubator.vector;
|
||||
requires org.apache.commons.lang3;
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.features;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.LocalTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class DayPeriodSupportUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenASpecificTime_whenFormattingUsingTheBSymbol_thenExpectVerbosePeriodOfDay() {
|
||||
LocalTime date = LocalTime.parse("15:25:08.690791");
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h B");
|
||||
assertThat(date.format(formatter)).isEqualTo("3 in the afternoon");
|
||||
|
||||
formatter = DateTimeFormatter.ofPattern("h BBBB");
|
||||
assertThat(date.format(formatter)).isEqualTo("3 in the afternoon");
|
||||
|
||||
formatter = DateTimeFormatter.ofPattern("h BBBBB");
|
||||
assertThat(date.format(formatter)).isEqualTo("3 in the afternoon");
|
||||
}
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package com.baeldung.features;
|
||||
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Proxy;
|
||||
|
||||
import static java.lang.ClassLoader.getSystemClassLoader;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class HelloWorldUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenAnInterfaceWithDefaulMethod_whenCreatingProxyInstance_thenCanInvokeDefaultMethod() throws Exception {
|
||||
Object proxy = Proxy.newProxyInstance(getSystemClassLoader(), new Class<?>[] { HelloWorld.class },
|
||||
(prox, method, args) -> {
|
||||
if (method.isDefault()) {
|
||||
return InvocationHandler.invokeDefault(prox, method, args);
|
||||
}
|
||||
return method.invoke(prox, args);
|
||||
}
|
||||
);
|
||||
Method method = proxy.getClass().getMethod("hello");
|
||||
assertThat(method.invoke(proxy)).isEqualTo("world");
|
||||
}
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package com.baeldung.features;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class InstanceOfPatternMatchingUnitTest {
|
||||
|
||||
@Test
|
||||
void givenTheNewPatternMatchingAbility_whenComparingAgainstTheTradiationalApproach_thenBothVariablesAreEqual() {
|
||||
Object obj = "TEST";
|
||||
|
||||
if (obj instanceof String a) {
|
||||
String b = (String) obj;
|
||||
assertThat(a).isEqualTo(b);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.features;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StreamToListUnitTest {
|
||||
|
||||
@Test
|
||||
void givenAStream_whenCreatingANewListFromStream_thenCollectorsOrInbuiltFunctionAreEquivalent() {
|
||||
List<String> integersAsString = Arrays.asList("1", "2", "3");
|
||||
List<Integer> ints = integersAsString.stream().map(Integer::parseInt).collect(Collectors.toList());
|
||||
List<Integer> intsEquivalent = integersAsString.stream().map(Integer::parseInt).toList();
|
||||
assertThat(ints).isEqualTo(intsEquivalent);
|
||||
}
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package com.baeldung.features;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
|
||||
class VectorExampleUnitTest {
|
||||
|
||||
@Test
|
||||
void givenAScalarComputation_whenCalculatingUsingVectorAPI_thenResultIsSameAsPreviousMethodOfComputation() {
|
||||
VectorExample objectUnderTest = new VectorExample();
|
||||
|
||||
int[] a = {1, 2, 3, 4};
|
||||
int[] b = {5, 6, 7, 8};
|
||||
|
||||
int[] result = objectUnderTest.scalarComputation(a, b);
|
||||
int[] result2 = objectUnderTest.vectorComputation(a, b);
|
||||
|
||||
assertArrayEquals(result, result2);
|
||||
}
|
||||
}
|
@ -0,0 +1,128 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class StreamToListComparisonWithCollectorsToListUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenAddingtoCollectToList_thenSuccess() {
|
||||
|
||||
List<String> result = Stream.of(Locale.getISOCountries())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
Assertions.assertDoesNotThrow(() -> {
|
||||
result.add("test");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSortingtoCollectToList_thenSuccess() {
|
||||
|
||||
List<String> result = Stream.of(Locale.getISOCountries())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
Assertions.assertDoesNotThrow(() -> {
|
||||
result.sort(String::compareToIgnoreCase);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddingCollectUnmodifiableToList_thenException() {
|
||||
|
||||
List<String> result = Stream.of(Locale.getISOCountries())
|
||||
.collect(Collectors.toUnmodifiableList());
|
||||
|
||||
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
|
||||
result.add("test");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSortingCollectUnmodifiableToList_thenSortException() {
|
||||
|
||||
List<String> result = Stream.of(Locale.getISOCountries())
|
||||
.collect(Collectors.toUnmodifiableList());
|
||||
|
||||
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
|
||||
result.sort(String::compareToIgnoreCase);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddingStreamToList_thenException() {
|
||||
|
||||
List<String> result = Stream.of(Locale.getISOCountries())
|
||||
.toList();
|
||||
|
||||
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
|
||||
result.add("test");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSortingStreamToList_thenException() {
|
||||
|
||||
List<String> result = Stream.of(Locale.getISOCountries())
|
||||
.toList();
|
||||
|
||||
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
|
||||
result.sort(String::compareToIgnoreCase);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenComparingStreamToList_withCollectToList_thenEqual() {
|
||||
|
||||
List<String> streamToList = Stream.of(Locale.getISOCountries())
|
||||
.toList();
|
||||
List<String> collectToList = Stream.of(Locale.getISOCountries())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
Assertions.assertEquals(streamToList, collectToList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenComparingStreamToList_withUnmodifiedCollectToList_thenEqual() {
|
||||
|
||||
List<String> streamToList = Stream.of(Locale.getISOCountries())
|
||||
.toList();
|
||||
List<String> collectToUnmodifiableList = Stream.of(Locale.getISOCountries())
|
||||
.collect(Collectors.toUnmodifiableList());
|
||||
|
||||
Assertions.assertEquals(streamToList, collectToUnmodifiableList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNullCollectorsToList_thenSuccess() {
|
||||
|
||||
Assertions.assertDoesNotThrow(() -> {
|
||||
Stream.of(null, null)
|
||||
.collect(Collectors.toList());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNullCollectorsUnmodifiableToList_thenException() {
|
||||
|
||||
Assertions.assertThrows(NullPointerException.class, () -> {
|
||||
Stream.of(null, null)
|
||||
.collect(Collectors.toUnmodifiableList());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNullStreamToList_thenSuccess() {
|
||||
|
||||
Assertions.assertDoesNotThrow(() -> {
|
||||
Stream.of(null, null)
|
||||
.toList();
|
||||
});
|
||||
}
|
||||
|
||||
}
|
3
core-java-modules/core-java-17/README.md
Normal file
3
core-java-modules/core-java-17/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
### Relevant articles:
|
||||
|
||||
- [Pattern Matching for Switch](https://www.baeldung.com/java-switch-pattern-matching)
|
81
core-java-modules/core-java-17/pom.xml
Normal file
81
core-java-modules/core-java-17/pom.xml
Normal file
@ -0,0 +1,81 @@
|
||||
<?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-17</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-17</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<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-api</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<release>${maven.compiler.release}</release>
|
||||
<compilerArgs>--enable-preview</compilerArgs>
|
||||
<source>${maven.compiler.source.version}</source>
|
||||
<target>${maven.compiler.target.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${surefire.plugin.version}</version>
|
||||
<configuration>
|
||||
<argLine>--enable-preview</argLine>
|
||||
<forkCount>1</forkCount>
|
||||
</configuration>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.maven.surefire</groupId>
|
||||
<artifactId>surefire-api</artifactId>
|
||||
<version>${surefire.plugin.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source.version>17</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>17</maven.compiler.target.version>
|
||||
<maven.compiler.release>17</maven.compiler.release>
|
||||
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
|
||||
<surefire.plugin.version>3.0.0-M5</surefire.plugin.version>
|
||||
<assertj.version>3.17.2</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -0,0 +1,25 @@
|
||||
package com.baeldung.switchpatterns;
|
||||
|
||||
public class GuardedPatterns {
|
||||
|
||||
static double getDoubleValueUsingIf(Object o) {
|
||||
return switch (o) {
|
||||
case String s -> {
|
||||
if (s.length() > 0) {
|
||||
yield Double.parseDouble(s);
|
||||
} else {
|
||||
yield 0d;
|
||||
}
|
||||
}
|
||||
default -> 0d;
|
||||
};
|
||||
}
|
||||
|
||||
static double getDoubleValueUsingGuardedPatterns(Object o) {
|
||||
return switch (o) {
|
||||
case String s && s.length() > 0 -> Double.parseDouble(s);
|
||||
default -> 0d;
|
||||
};
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.switchpatterns;
|
||||
|
||||
public class HandlingNullValues {
|
||||
|
||||
static double getDoubleUsingSwitchNullCase(Object o) {
|
||||
return switch (o) {
|
||||
case String s -> Double.parseDouble(s);
|
||||
case null -> 0d;
|
||||
default -> 0d;
|
||||
};
|
||||
}
|
||||
|
||||
static double getDoubleUsingSwitchTotalType(Object o) {
|
||||
return switch (o) {
|
||||
case String s -> Double.parseDouble(s);
|
||||
case Object ob -> 0d;
|
||||
};
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
package com.baeldung.switchpatterns;
|
||||
|
||||
public class ParenthesizedPatterns {
|
||||
|
||||
static double getDoubleValueUsingIf(Object o) {
|
||||
return switch (o) {
|
||||
case String s -> {
|
||||
if (s.length() > 0) {
|
||||
if (s.contains("#") || s.contains("@")) {
|
||||
yield 0d;
|
||||
} else {
|
||||
yield Double.parseDouble(s);
|
||||
}
|
||||
} else {
|
||||
yield 0d;
|
||||
}
|
||||
}
|
||||
default -> 0d;
|
||||
};
|
||||
}
|
||||
|
||||
static double getDoubleValueUsingParenthesizedPatterns(Object o) {
|
||||
return switch (o) {
|
||||
case String s && s.length() > 0 && !(s.contains("#") || s.contains("@")) -> Double.parseDouble(s);
|
||||
default -> 0d;
|
||||
};
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.switchpatterns;
|
||||
|
||||
public class PatternMatching {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Object o = args[0];
|
||||
if (o instanceof String s) {
|
||||
System.out.printf("Object is a string %s", s);
|
||||
} else if(o instanceof Number n) {
|
||||
System.out.printf("Object is a number %n", n);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.switchpatterns;
|
||||
|
||||
public class SwitchStatement {
|
||||
|
||||
public static void main(String[] args) {
|
||||
final String b = "B";
|
||||
switch (args[0]) {
|
||||
case "A" -> System.out.println("Parameter is A");
|
||||
case b -> System.out.println("Parameter is b");
|
||||
default -> System.out.println("Parameter is unknown");
|
||||
};
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
package com.baeldung.switchpatterns;
|
||||
|
||||
public class TypePatterns {
|
||||
|
||||
static double getDoubleUsingIf(Object o) {
|
||||
double result;
|
||||
|
||||
if (o instanceof Integer) {
|
||||
result = ((Integer) o).doubleValue();
|
||||
} else if (o instanceof Float) {
|
||||
result = ((Float) o).doubleValue();
|
||||
} else if (o instanceof String) {
|
||||
result = Double.parseDouble(((String) o));
|
||||
} else {
|
||||
result = 0d;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
static double getDoubleUsingSwitch(Object o) {
|
||||
return switch (o) {
|
||||
case Integer i -> i.doubleValue();
|
||||
case Float f -> f.doubleValue();
|
||||
case String s -> Double.parseDouble(s);
|
||||
default -> 0d;
|
||||
};
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
package com.baeldung.switchpatterns;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static com.baeldung.switchpatterns.GuardedPatterns.*;
|
||||
|
||||
class GuardedPatternsUnitTest {
|
||||
|
||||
@Test
|
||||
void givenIfImplementation_whenUsingEmptyString_thenDoubleIsReturned() {
|
||||
assertEquals(0d, getDoubleValueUsingIf(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIfImplementation_whenUsingNonEmptyString_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleValueUsingIf("10"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPatternsImplementation_whenUsingEmptyString_thenDoubleIsReturned() {
|
||||
assertEquals(0d, getDoubleValueUsingGuardedPatterns(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPatternsImplementation_whenUsingNonEmptyString_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleValueUsingGuardedPatterns("10"));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
package com.baeldung.switchpatterns;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static com.baeldung.switchpatterns.HandlingNullValues.*;
|
||||
|
||||
class HandlingNullValuesUnitTest {
|
||||
|
||||
@Test
|
||||
void givenNullCaseInSwitch_whenUsingStringAsArgument_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleUsingSwitchNullCase("10"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenTotalTypeInSwitch_whenUsingNullArgument_thenDoubleIsReturned() {
|
||||
assertEquals(0d, getDoubleUsingSwitchNullCase(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenTotalTypeInSwitch_whenUsingStringAsArgument_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleUsingSwitchTotalType("10"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNullCaseInSwitch_whenUsingNullArgument_thenDoubleIsReturned() {
|
||||
assertEquals(0d, getDoubleUsingSwitchTotalType(null));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
package com.baeldung.switchpatterns;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static com.baeldung.switchpatterns.ParenthesizedPatterns.*;
|
||||
|
||||
class ParenthesizedPatternsUnitTest {
|
||||
|
||||
@Test
|
||||
void givenIfImplementation_whenUsingEmptyString_thenDoubleIsReturned() {
|
||||
assertEquals(0d, getDoubleValueUsingIf(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIfImplementation_whenUsingNonEmptyString_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleValueUsingIf("10"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIfImplementation_whenStringContainsSpecialChar_thenDoubleIsReturned() {
|
||||
assertEquals(0d, getDoubleValueUsingIf("@10"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPatternsImplementation_whenUsingEmptyString_thenDoubleIsReturned() {
|
||||
assertEquals(0d, getDoubleValueUsingParenthesizedPatterns(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPatternsImplementation_whenUsingNonEmptyString_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleValueUsingParenthesizedPatterns("10"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPatternsImplementation_whenStringContainsSpecialChar_thenDoubleIsReturned() {
|
||||
assertEquals(0d, getDoubleValueUsingParenthesizedPatterns("@10"));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
package com.baeldung.switchpatterns;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static com.baeldung.switchpatterns.TypePatterns.*;
|
||||
|
||||
class TypePatternsUnitTest {
|
||||
|
||||
@Test
|
||||
void givenIfImplementation_whenUsingIntegerAsArgument_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleUsingIf(10));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIfImplementation_whenUsingDoubleAsArgument_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleUsingIf(10.0f));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIfImplementation_whenUsingStringAsArgument_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleUsingIf("10"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIfImplementation_whenUsingCharAsArgument_thenDoubleIsReturned() {
|
||||
assertEquals(0d, getDoubleUsingIf('c'));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSwitchImplementation_whenUsingIntegerAsArgument_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleUsingSwitch(10));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSwitchImplementation_whenUsingDoubleAsArgument_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleUsingSwitch(10.0f));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSwitchImplementation_whenUsingStringAsArgument_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleUsingSwitch("10"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSwitchImplementation_whenUsingCharAsArgument_thenDoubleIsReturned() {
|
||||
assertEquals(0d, getDoubleUsingSwitch('c'));
|
||||
}
|
||||
|
||||
}
|
@ -7,12 +7,11 @@
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-8-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@ -7,12 +7,11 @@
|
||||
<version>${project.parent.version}</version>
|
||||
<name>core-java-8-datetime-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@ -7,12 +7,11 @@
|
||||
<version>${project.parent.version}</version>
|
||||
<name>core-java-8-datetime</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@ -4,7 +4,6 @@ This module contains articles about Java 8 core features
|
||||
|
||||
### Relevant Articles:
|
||||
- [New Features in Java 8](https://www.baeldung.com/java-8-new-features)
|
||||
- [Guide to Java 8 groupingBy Collector](https://www.baeldung.com/java-groupingby-collector)
|
||||
- [Strategy Design Pattern in Java 8](https://www.baeldung.com/java-strategy-pattern)
|
||||
- [Guide to Java 8 Comparator.comparing()](https://www.baeldung.com/java-8-comparator-comparing)
|
||||
- [Guide to the Java 8 forEach](https://www.baeldung.com/foreach-java)
|
||||
|
@ -7,12 +7,11 @@
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-8</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@ -1,36 +0,0 @@
|
||||
package com.baeldung.java_8_features.groupingby;
|
||||
|
||||
public class BlogPost {
|
||||
private String title;
|
||||
private String author;
|
||||
private BlogPostType type;
|
||||
private int likes;
|
||||
|
||||
public BlogPost(String title, String author, BlogPostType type, int likes) {
|
||||
this.title = title;
|
||||
this.author = author;
|
||||
this.type = type;
|
||||
this.likes = likes;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public BlogPostType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public int getLikes() {
|
||||
return likes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "BlogPost{" + "title='" + title + '\'' + ", type=" + type + ", likes=" + likes + '}';
|
||||
}
|
||||
}
|
@ -1,5 +0,0 @@
|
||||
package com.baeldung.java_8_features.groupingby;
|
||||
|
||||
public enum BlogPostType {
|
||||
NEWS, REVIEW, GUIDE
|
||||
}
|
@ -1,41 +0,0 @@
|
||||
package com.baeldung.java_8_features.groupingby;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class Tuple {
|
||||
private final BlogPostType type;
|
||||
private final String author;
|
||||
|
||||
public Tuple(BlogPostType type, String author) {
|
||||
this.type = type;
|
||||
this.author = author;
|
||||
}
|
||||
|
||||
public BlogPostType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
Tuple tuple = (Tuple) o;
|
||||
return type == tuple.type && author.equals(tuple.author);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(type, author);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Tuple{" + "type=" + type + ", author='" + author + '\'' + '}';
|
||||
}
|
||||
}
|
@ -1,215 +0,0 @@
|
||||
package com.baeldung.java_8_features.groupingby;
|
||||
|
||||
import static java.util.Comparator.comparingInt;
|
||||
import static java.util.stream.Collectors.averagingInt;
|
||||
import static java.util.stream.Collectors.counting;
|
||||
import static java.util.stream.Collectors.groupingBy;
|
||||
import static java.util.stream.Collectors.groupingByConcurrent;
|
||||
import static java.util.stream.Collectors.joining;
|
||||
import static java.util.stream.Collectors.mapping;
|
||||
import static java.util.stream.Collectors.maxBy;
|
||||
import static java.util.stream.Collectors.summarizingInt;
|
||||
import static java.util.stream.Collectors.summingInt;
|
||||
import static java.util.stream.Collectors.toList;
|
||||
import static java.util.stream.Collectors.toSet;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.EnumMap;
|
||||
import java.util.IntSummaryStatistics;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class Java8GroupingByCollectorUnitTest {
|
||||
|
||||
private static final List<BlogPost> posts = Arrays.asList(new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5),
|
||||
new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15));
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() {
|
||||
Map<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType));
|
||||
|
||||
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() {
|
||||
Map<BlogPostType, String> postsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]"))));
|
||||
|
||||
assertEquals("Post titles: [News item 1, News item 2]", postsPerType.get(BlogPostType.NEWS));
|
||||
assertEquals("Post titles: [Programming guide]", postsPerType.get(BlogPostType.GUIDE));
|
||||
assertEquals("Post titles: [Tech review 1, Tech review 2]", postsPerType.get(BlogPostType.REVIEW));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() {
|
||||
Map<BlogPostType, Integer> likesPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes)));
|
||||
|
||||
assertEquals(50, likesPerType.get(BlogPostType.NEWS)
|
||||
.intValue());
|
||||
assertEquals(20, likesPerType.get(BlogPostType.REVIEW)
|
||||
.intValue());
|
||||
assertEquals(20, likesPerType.get(BlogPostType.GUIDE)
|
||||
.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() {
|
||||
EnumMap<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList()));
|
||||
|
||||
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() {
|
||||
Map<BlogPostType, Set<BlogPost>> postsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, toSet()));
|
||||
|
||||
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() {
|
||||
ConcurrentMap<BlogPostType, List<BlogPost>> postsPerType = posts.parallelStream()
|
||||
.collect(groupingByConcurrent(BlogPost::getType));
|
||||
|
||||
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() {
|
||||
Map<BlogPostType, Double> averageLikesPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes)));
|
||||
|
||||
assertEquals(25, averageLikesPerType.get(BlogPostType.NEWS)
|
||||
.intValue());
|
||||
assertEquals(20, averageLikesPerType.get(BlogPostType.GUIDE)
|
||||
.intValue());
|
||||
assertEquals(10, averageLikesPerType.get(BlogPostType.REVIEW)
|
||||
.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() {
|
||||
Map<BlogPostType, Long> numberOfPostsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, counting()));
|
||||
|
||||
assertEquals(2, numberOfPostsPerType.get(BlogPostType.NEWS)
|
||||
.intValue());
|
||||
assertEquals(1, numberOfPostsPerType.get(BlogPostType.GUIDE)
|
||||
.intValue());
|
||||
assertEquals(2, numberOfPostsPerType.get(BlogPostType.REVIEW)
|
||||
.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() {
|
||||
Map<BlogPostType, Optional<BlogPost>> maxLikesPerPostType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes))));
|
||||
|
||||
assertTrue(maxLikesPerPostType.get(BlogPostType.NEWS)
|
||||
.isPresent());
|
||||
assertEquals(35, maxLikesPerPostType.get(BlogPostType.NEWS)
|
||||
.get()
|
||||
.getLikes());
|
||||
|
||||
assertTrue(maxLikesPerPostType.get(BlogPostType.GUIDE)
|
||||
.isPresent());
|
||||
assertEquals(20, maxLikesPerPostType.get(BlogPostType.GUIDE)
|
||||
.get()
|
||||
.getLikes());
|
||||
|
||||
assertTrue(maxLikesPerPostType.get(BlogPostType.REVIEW)
|
||||
.isPresent());
|
||||
assertEquals(15, maxLikesPerPostType.get(BlogPostType.REVIEW)
|
||||
.get()
|
||||
.getLikes());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() {
|
||||
Map<String, Map<BlogPostType, List<BlogPost>>> map = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType)));
|
||||
|
||||
assertEquals(1, map.get("Author 1")
|
||||
.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, map.get("Author 1")
|
||||
.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(1, map.get("Author 1")
|
||||
.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
|
||||
assertEquals(1, map.get("Author 2")
|
||||
.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, map.get("Author 2")
|
||||
.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
assertNull(map.get("Author 2")
|
||||
.get(BlogPostType.GUIDE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() {
|
||||
Map<BlogPostType, IntSummaryStatistics> likeStatisticsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes)));
|
||||
|
||||
IntSummaryStatistics newsLikeStatistics = likeStatisticsPerType.get(BlogPostType.NEWS);
|
||||
|
||||
assertEquals(2, newsLikeStatistics.getCount());
|
||||
assertEquals(50, newsLikeStatistics.getSum());
|
||||
assertEquals(25.0, newsLikeStatistics.getAverage(), 0.001);
|
||||
assertEquals(35, newsLikeStatistics.getMax());
|
||||
assertEquals(15, newsLikeStatistics.getMin());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByComplexMapKeyType_thenGetAMapBetweenTupleAndList() {
|
||||
Map<Tuple, List<BlogPost>> postsPerTypeAndAuthor = posts.stream()
|
||||
.collect(groupingBy(post -> new Tuple(post.getType(), post.getAuthor())));
|
||||
|
||||
List<BlogPost> result = postsPerTypeAndAuthor.get(new Tuple(BlogPostType.GUIDE, "Author 1"));
|
||||
|
||||
assertThat(result.size()).isEqualTo(1);
|
||||
|
||||
BlogPost blogPost = result.get(0);
|
||||
|
||||
assertThat(blogPost.getTitle()).isEqualTo("Programming guide");
|
||||
assertThat(blogPost.getType()).isEqualTo(BlogPostType.GUIDE);
|
||||
assertThat(blogPost.getAuthor()).isEqualTo("Author 1");
|
||||
}
|
||||
}
|
@ -40,7 +40,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<version>${junit-platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
@ -70,7 +70,6 @@
|
||||
<properties>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.10.0</assertj.version>
|
||||
<junit.platform.version>1.2.0</junit.platform.version>
|
||||
<awaitility.version>1.7.0</awaitility.version>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
|
@ -6,7 +6,6 @@ This module contains articles about core Java features that have been introduced
|
||||
|
||||
- [New Features in Java 9](https://www.baeldung.com/new-java-9)
|
||||
- [Java 9 Variable Handles Demystified](http://www.baeldung.com/java-variable-handles)
|
||||
- [Exploring the New HTTP Client in Java 9 and 11](http://www.baeldung.com/java-9-http-client)
|
||||
- [Multi-Release Jar Files](https://www.baeldung.com/java-multi-release-jar)
|
||||
- [Ahead of Time Compilation (AoT)](https://www.baeldung.com/ahead-of-time-compilation)
|
||||
- [Introduction to Java 9 StackWalking API](https://www.baeldung.com/java-9-stackwalking-api)
|
||||
|
@ -29,7 +29,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<version>${junit-platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -39,7 +39,7 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>incubator-features</id>
|
||||
@ -131,7 +131,7 @@
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
|
||||
<build>
|
||||
<finalName>core-java-9-new-features</finalName>
|
||||
<plugins>
|
||||
@ -158,7 +158,6 @@
|
||||
<rxjava.version>3.0.0</rxjava.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.10.0</assertj.version>
|
||||
<junit.platform.version>1.2.0</junit.platform.version>
|
||||
<awaitility.version>4.0.2</awaitility.version>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
|
@ -1,84 +0,0 @@
|
||||
/*
|
||||
* To change this license header, choose License Headers in Project Properties.
|
||||
* To change this template file, choose Tools | Templates
|
||||
* and open the template in the editor.
|
||||
*/
|
||||
package com.baeldung.httpclient;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collectors;
|
||||
import jdk.incubator.http.HttpClient;
|
||||
import jdk.incubator.http.HttpRequest;
|
||||
import jdk.incubator.http.HttpRequest.BodyProcessor;
|
||||
import jdk.incubator.http.HttpResponse;
|
||||
import jdk.incubator.http.HttpResponse.BodyHandler;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author pkaria
|
||||
*/
|
||||
public class HttpClientExample {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
httpGetRequest();
|
||||
httpPostRequest();
|
||||
asynchronousRequest();
|
||||
asynchronousMultipleRequests();
|
||||
}
|
||||
|
||||
public static void httpGetRequest() throws URISyntaxException, IOException, InterruptedException {
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1");
|
||||
HttpRequest request = HttpRequest.newBuilder(httpURI).GET()
|
||||
.headers("Accept-Enconding", "gzip, deflate").build();
|
||||
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString());
|
||||
String responseBody = response.body();
|
||||
int responseStatusCode = response.statusCode();
|
||||
System.out.println(responseBody);
|
||||
}
|
||||
|
||||
public static void httpPostRequest() throws URISyntaxException, IOException, InterruptedException {
|
||||
HttpClient client = HttpClient
|
||||
.newBuilder()
|
||||
.build();
|
||||
HttpRequest request = HttpRequest
|
||||
.newBuilder(new URI("http://jsonplaceholder.typicode.com/posts"))
|
||||
.POST(BodyProcessor.fromString("Sample Post Request"))
|
||||
.build();
|
||||
HttpResponse<String> response
|
||||
= client.send(request, HttpResponse.BodyHandler.asString());
|
||||
String responseBody = response.body();
|
||||
System.out.println(responseBody);
|
||||
}
|
||||
|
||||
public static void asynchronousRequest() throws URISyntaxException {
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1");
|
||||
HttpRequest request = HttpRequest.newBuilder(httpURI).GET().build();
|
||||
CompletableFuture<HttpResponse<String>> futureResponse = client.sendAsync(request,
|
||||
HttpResponse.BodyHandler.asString());
|
||||
}
|
||||
|
||||
public static void asynchronousMultipleRequests() throws URISyntaxException {
|
||||
List<URI> targets = Arrays.asList(new URI("http://jsonplaceholder.typicode.com/posts/1"), new URI("http://jsonplaceholder.typicode.com/posts/2"));
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
List<CompletableFuture<File>> futures = targets
|
||||
.stream()
|
||||
.map(target -> client
|
||||
.sendAsync(
|
||||
HttpRequest.newBuilder(target)
|
||||
.GET()
|
||||
.build(),
|
||||
BodyHandler.asFile(Paths.get("base", target.getPath())))
|
||||
.thenApply(response -> response.body())
|
||||
.thenApply(path -> path.toFile()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
@ -1,3 +0,0 @@
|
||||
module com.baeldung.httpclient {
|
||||
requires jdk.incubator.httpclient;
|
||||
}
|
@ -1,218 +0,0 @@
|
||||
package com.baeldung.java9.httpclient;
|
||||
|
||||
import jdk.incubator.http.HttpClient;
|
||||
import jdk.incubator.http.HttpRequest;
|
||||
import jdk.incubator.http.HttpResponse;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.*;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.collection.IsEmptyCollection.empty;
|
||||
import static org.hamcrest.core.IsNot.not;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
/**
|
||||
* Created by adam.
|
||||
*/
|
||||
public class HttpClientIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyProcessor.fromString("Sample body"))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newBuilder()
|
||||
.proxy(ProxySelector.getDefault())
|
||||
.build()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.body(), containsString("Sample body"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldNotFollowRedirectWhenSetToDefaultNever() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("http://stackoverflow.com"))
|
||||
.version(HttpClient.Version.HTTP_1_1)
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = HttpClient.newBuilder()
|
||||
.build()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM));
|
||||
assertThat(response.body(), containsString(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldFollowRedirectWhenSetToAlways() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("http://stackoverflow.com"))
|
||||
.version(HttpClient.Version.HTTP_1_1)
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = HttpClient.newBuilder()
|
||||
.followRedirects(HttpClient.Redirect.ALWAYS)
|
||||
.build()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.finalRequest()
|
||||
.uri()
|
||||
.toString(), equalTo("https://stackoverflow.com/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnOKStatusForAuthenticatedAccess() throws URISyntaxException, IOException, InterruptedException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/basic-auth"))
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = HttpClient.newBuilder()
|
||||
.authenticator(new Authenticator() {
|
||||
@Override
|
||||
protected PasswordAuthentication getPasswordAuthentication() {
|
||||
return new PasswordAuthentication("postman", "password".toCharArray());
|
||||
}
|
||||
})
|
||||
.build()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldSendRequestAsync() throws URISyntaxException, InterruptedException, ExecutionException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyProcessor.fromString("Sample body"))
|
||||
.build();
|
||||
CompletableFuture<HttpResponse<String>> response = HttpClient.newBuilder()
|
||||
.build()
|
||||
.sendAsync(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.get()
|
||||
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldUseJustTwoThreadWhenProcessingSendAsyncRequest() throws URISyntaxException, InterruptedException, ExecutionException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(2);
|
||||
|
||||
CompletableFuture<HttpResponse<String>> response1 = HttpClient.newBuilder()
|
||||
.executor(executorService)
|
||||
.build()
|
||||
.sendAsync(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
CompletableFuture<HttpResponse<String>> response2 = HttpClient.newBuilder()
|
||||
.executor(executorService)
|
||||
.build()
|
||||
.sendAsync(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
CompletableFuture<HttpResponse<String>> response3 = HttpClient.newBuilder()
|
||||
.executor(executorService)
|
||||
.build()
|
||||
.sendAsync(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
CompletableFuture.allOf(response1, response2, response3)
|
||||
.join();
|
||||
|
||||
assertThat(response1.get()
|
||||
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response2.get()
|
||||
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response3.get()
|
||||
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldNotStoreCookieWhenPolicyAcceptNone() throws URISyntaxException, IOException, InterruptedException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpClient httpClient = HttpClient.newBuilder()
|
||||
.cookieManager(new CookieManager(null, CookiePolicy.ACCEPT_NONE))
|
||||
.build();
|
||||
|
||||
httpClient.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(httpClient.cookieManager()
|
||||
.get()
|
||||
.getCookieStore()
|
||||
.getCookies(), empty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldStoreCookieWhenPolicyAcceptAll() throws URISyntaxException, IOException, InterruptedException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpClient httpClient = HttpClient.newBuilder()
|
||||
.cookieManager(new CookieManager(null, CookiePolicy.ACCEPT_ALL))
|
||||
.build();
|
||||
|
||||
httpClient.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(httpClient.cookieManager()
|
||||
.get()
|
||||
.getCookieStore()
|
||||
.getCookies(), not(empty()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldProcessMultipleRequestViaStream() throws URISyntaxException, ExecutionException, InterruptedException {
|
||||
List<URI> targets = Arrays.asList(new URI("https://postman-echo.com/get?foo1=bar1"), new URI("https://postman-echo.com/get?foo2=bar2"));
|
||||
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
|
||||
List<CompletableFuture<String>> futures = targets.stream()
|
||||
.map(target -> client.sendAsync(HttpRequest.newBuilder(target)
|
||||
.GET()
|
||||
.build(), HttpResponse.BodyHandler.asString())
|
||||
.thenApply(response -> response.body()))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
|
||||
.join();
|
||||
|
||||
if (futures.get(0)
|
||||
.get()
|
||||
.contains("foo1")) {
|
||||
assertThat(futures.get(0)
|
||||
.get(), containsString("bar1"));
|
||||
assertThat(futures.get(1)
|
||||
.get(), containsString("bar2"));
|
||||
} else {
|
||||
assertThat(futures.get(1)
|
||||
.get(), containsString("bar2"));
|
||||
assertThat(futures.get(1)
|
||||
.get(), containsString("bar1"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -1,171 +0,0 @@
|
||||
package com.baeldung.java9.httpclient;
|
||||
|
||||
import jdk.incubator.http.HttpClient;
|
||||
import jdk.incubator.http.HttpRequest;
|
||||
import jdk.incubator.http.HttpResponse;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Paths;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
|
||||
import static java.time.temporal.ChronoUnit.SECONDS;
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
/**
|
||||
* Created by adam.
|
||||
*/
|
||||
public class HttpRequestIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldUseHttp2WhenWebsiteUsesHttp2() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://stackoverflow.com"))
|
||||
.version(HttpClient.Version.HTTP_2)
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.version(), equalTo(HttpClient.Version.HTTP_2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldFallbackToHttp1_1WhenWebsiteDoesNotUseHttp2() throws IOException, InterruptedException, URISyntaxException, NoSuchAlgorithmException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.version(HttpClient.Version.HTTP_2)
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.version(), equalTo(HttpClient.Version.HTTP_1_1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusOKWhenSendGetRequestWithDummyHeaders() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.headers("key1", "value1", "key2", "value2")
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusOKWhenSendGetRequestTimeoutSet() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.timeout(Duration.of(10, SECONDS))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnNoContentWhenPostWithNoBody() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.POST(HttpRequest.noBody())
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnSampleDataContentWhenPostWithBodyText() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyProcessor.fromString("Sample request body"))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.body(), containsString("Sample request body"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnSampleDataContentWhenPostWithInputStream() throws IOException, InterruptedException, URISyntaxException {
|
||||
byte[] sampleData = "Sample request body".getBytes();
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyProcessor.fromInputStream(() -> new ByteArrayInputStream(sampleData)))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.body(), containsString("Sample request body"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnSampleDataContentWhenPostWithByteArrayProcessorStream() throws IOException, InterruptedException, URISyntaxException {
|
||||
byte[] sampleData = "Sample request body".getBytes();
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyProcessor.fromByteArray(sampleData))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.body(), containsString("Sample request body"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnSampleDataContentWhenPostWithFileProcessorStream() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyProcessor.fromFile(Paths.get("src/test/resources/sample.txt")))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.body(), containsString("Sample file content"));
|
||||
}
|
||||
|
||||
}
|
@ -1,55 +0,0 @@
|
||||
package com.baeldung.java9.httpclient;
|
||||
|
||||
import jdk.incubator.http.HttpClient;
|
||||
import jdk.incubator.http.HttpRequest;
|
||||
import jdk.incubator.http.HttpResponse;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.Matchers.isEmptyString;
|
||||
import static org.hamcrest.core.IsNot.not;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
/**
|
||||
* Created by adam.
|
||||
*/
|
||||
public class HttpResponseIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.body(), not(isEmptyString()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldResponseURIDifferentThanRequestUIRWhenRedirect() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("http://stackoverflow.com"))
|
||||
.version(HttpClient.Version.HTTP_1_1)
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = HttpClient.newBuilder()
|
||||
.followRedirects(HttpClient.Redirect.ALWAYS)
|
||||
.build()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(request.uri()
|
||||
.toString(), equalTo("http://stackoverflow.com"));
|
||||
assertThat(response.uri()
|
||||
.toString(), equalTo("https://stackoverflow.com/"));
|
||||
}
|
||||
|
||||
}
|
@ -35,7 +35,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<version>${junit-platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -80,7 +80,6 @@
|
||||
<properties>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.10.0</assertj.version>
|
||||
<junit.platform.version>1.2.0</junit.platform.version>
|
||||
<awaitility.version>1.7.0</awaitility.version>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
|
@ -12,3 +12,4 @@
|
||||
- [Efficient Word Frequency Calculator in Java](https://www.baeldung.com/java-word-frequency)
|
||||
- [Why Missing Annotations Don’t Cause ClassNotFoundException](https://www.baeldung.com/classnotfoundexception-missing-annotation)
|
||||
- [Valid @SuppressWarnings Warning Names](https://www.baeldung.com/java-suppresswarnings-valid-names)
|
||||
- [Get a Field’s Annotations Using Reflection](https://www.baeldung.com/java-get-field-annotations)
|
||||
|
@ -1,7 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-annotations</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
@ -12,9 +12,21 @@
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<assertj-core.version>3.10.0</assertj-core.version>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-annotations</finalName>
|
||||
<resources>
|
||||
|
@ -0,0 +1,9 @@
|
||||
package com.baeldung.readannotations;
|
||||
|
||||
public class ClassWithAnnotations {
|
||||
|
||||
@FirstAnnotation
|
||||
@SecondAnnotation
|
||||
@ThirdAnnotation
|
||||
private String classMember;
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user