Merge branch 'eugenp:master' into master
This commit is contained in:
@@ -7,3 +7,4 @@ You can build the project from the command line using: *mvn clean install*, or i
|
||||
|
||||
### Relevant Articles:
|
||||
- [Guide to Check if Apache Kafka Server Is Running](https://www.baeldung.com/apache-kafka-check-server-is-running)
|
||||
- [Add Custom Headers to a Kafka Message](https://www.baeldung.com/java-kafka-custom-headers)
|
||||
|
||||
@@ -30,6 +30,16 @@
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.dhatim</groupId>
|
||||
<artifactId>fastexcel</artifactId>
|
||||
<version>${fastexcel.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.dhatim</groupId>
|
||||
<artifactId>fastexcel-reader</artifactId>
|
||||
<version>${fastexcel.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -52,6 +62,7 @@
|
||||
<properties>
|
||||
<poi.version>5.2.0</poi.version>
|
||||
<jexcel.version>1.0.6</jexcel.version>
|
||||
<fastexcel.version>0.15.3</fastexcel.version>
|
||||
<maven.resources.plugin.version>3.2.0</maven.resources.plugin.version>
|
||||
</properties>
|
||||
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.baeldung.fastexcel;
|
||||
|
||||
import org.dhatim.fastexcel.Workbook;
|
||||
import org.dhatim.fastexcel.Worksheet;
|
||||
import org.dhatim.fastexcel.reader.Cell;
|
||||
import org.dhatim.fastexcel.reader.ReadableWorkbook;
|
||||
import org.dhatim.fastexcel.reader.Row;
|
||||
import org.dhatim.fastexcel.reader.Sheet;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class FastexcelHelper {
|
||||
|
||||
public Map<Integer, List<String>> readExcel(String fileLocation) throws IOException {
|
||||
Map<Integer, List<String>> data = new HashMap<>();
|
||||
|
||||
try (FileInputStream file = new FileInputStream(fileLocation); ReadableWorkbook wb = new ReadableWorkbook(file)) {
|
||||
Sheet sheet = wb.getFirstSheet();
|
||||
try (Stream<Row> rows = sheet.openStream()) {
|
||||
rows.forEach(r -> {
|
||||
data.put(r.getRowNum(), new ArrayList<>());
|
||||
|
||||
for (Cell cell : r) {
|
||||
data.get(r.getRowNum()).add(cell.getRawValue());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
public void writeExcel() throws IOException {
|
||||
File currDir = new File(".");
|
||||
String path = currDir.getAbsolutePath();
|
||||
String fileLocation = path.substring(0, path.length() - 1) + "fastexcel.xlsx";
|
||||
|
||||
try (OutputStream os = Files.newOutputStream(Paths.get(fileLocation)); Workbook wb = new Workbook(os, "MyApplication", "1.0")) {
|
||||
Worksheet ws = wb.newWorksheet("Sheet 1");
|
||||
|
||||
ws.width(0, 25);
|
||||
ws.width(1, 15);
|
||||
|
||||
ws.range(0, 0, 0, 1).style().fontName("Arial").fontSize(16).bold().fillColor("3366FF").set();
|
||||
ws.value(0, 0, "Name");
|
||||
ws.value(0, 1, "Age");
|
||||
|
||||
ws.range(2, 0, 2, 1).style().wrapText(true).set();
|
||||
ws.value(2, 0, "John Smith");
|
||||
ws.value(2, 1, 20L);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.fastexcel;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class FastexcelIntegrationTest {
|
||||
|
||||
private FastexcelHelper fastexcelHelper;
|
||||
private static String FILE_NAME = "fastexcel.xlsx";
|
||||
private String fileLocation;
|
||||
|
||||
@Before
|
||||
public void generateExcelFile() throws IOException {
|
||||
|
||||
File currDir = new File(".");
|
||||
String path = currDir.getAbsolutePath();
|
||||
fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
|
||||
|
||||
fastexcelHelper = new FastexcelHelper();
|
||||
fastexcelHelper.writeExcel();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenParsingExcelFile_thenCorrect() throws IOException {
|
||||
Map<Integer, List<String>> data = fastexcelHelper.readExcel(fileLocation);
|
||||
|
||||
assertEquals("Name", data.get(1).get(0));
|
||||
assertEquals("Age", data.get(1).get(1));
|
||||
|
||||
assertEquals("John Smith", data.get(3).get(0));
|
||||
assertEquals("20", data.get(3).get(1));
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup() {
|
||||
File testFile = new File(fileLocation);
|
||||
if (testFile.exists()) {
|
||||
testFile.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.s3;
|
||||
|
||||
import org.apache.http.HttpStatus;
|
||||
|
||||
import com.amazonaws.AmazonServiceException;
|
||||
import com.amazonaws.services.s3.AmazonS3;
|
||||
|
||||
public class AWSS3ObjectUtils {
|
||||
|
||||
private AmazonS3 s3Client;
|
||||
|
||||
public AWSS3ObjectUtils(AmazonS3 s3client) {
|
||||
this.s3Client = s3client;
|
||||
}
|
||||
|
||||
public boolean doesObjectExistByDefaultMethod(String bucket, String key) {
|
||||
return s3Client.doesObjectExist(bucket, key);
|
||||
}
|
||||
|
||||
public boolean doesObjectExistByListObjects(String bucket, String key) {
|
||||
return s3Client.listObjects(bucket)
|
||||
.getObjectSummaries()
|
||||
.stream()
|
||||
.filter(s3ObjectSummary -> s3ObjectSummary.getKey()
|
||||
.equals(key))
|
||||
.findFirst()
|
||||
.isPresent();
|
||||
}
|
||||
|
||||
public boolean doesObjectExistByMetaData(String bucket, String key) {
|
||||
try {
|
||||
s3Client.getObjectMetadata(bucket, key);
|
||||
return true;
|
||||
} catch (AmazonServiceException e) {
|
||||
if (e.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
|
||||
return false;
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.s3;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.amazonaws.auth.EnvironmentVariableCredentialsProvider;
|
||||
import com.amazonaws.regions.Regions;
|
||||
import com.amazonaws.services.s3.AmazonS3;
|
||||
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
|
||||
|
||||
public class AWSS3ObjectIntegrationTest {
|
||||
|
||||
private static final String BUCKET = "your-bucket";
|
||||
private static final String KEY_THAT_EXIST = "your-key-that-exist";
|
||||
private AWSS3ObjectUtils s3ObjectUtils;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
AmazonS3 client = AmazonS3ClientBuilder.standard()
|
||||
.withRegion(Regions.DEFAULT_REGION)
|
||||
.withCredentials(new EnvironmentVariableCredentialsProvider())
|
||||
.build();
|
||||
|
||||
s3ObjectUtils = new AWSS3ObjectUtils(client);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVerifyIfObjectExistByDefaultMethod_thenCorrect() {
|
||||
assertTrue(s3ObjectUtils.doesObjectExistByDefaultMethod(BUCKET, KEY_THAT_EXIST), "Key: " + KEY_THAT_EXIST + " doesn't exist");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVerifyIfObjectExistByListObjects_thenCorrect() {
|
||||
assertTrue(s3ObjectUtils.doesObjectExistByListObjects(BUCKET, KEY_THAT_EXIST), "Key: " + KEY_THAT_EXIST + " doesn't exist");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVerifyIfObjectExistByMetaData_thenCorrect() {
|
||||
assertTrue(s3ObjectUtils.doesObjectExistByMetaData(BUCKET, KEY_THAT_EXIST), "Key: " + KEY_THAT_EXIST + " doesn't exist");
|
||||
}
|
||||
}
|
||||
@@ -12,3 +12,4 @@ This module contains articles about Java array fundamentals. They assume no prev
|
||||
- [Extending an Array’s Length](https://www.baeldung.com/java-array-add-element-at-the-end)
|
||||
- [Initializing a Boolean Array in Java](https://www.baeldung.com/java-initializing-boolean-array)
|
||||
- [Find the Index of an Element in a Java Array](https://www.baeldung.com/java-array-find-index)
|
||||
- [Comparing Two Byte Arrays in Java](https://www.baeldung.com/java-comparing-byte-arrays)
|
||||
|
||||
+7
-3
@@ -1,6 +1,9 @@
|
||||
package com.baeldung.producerconsumer;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class Consumer implements Runnable {
|
||||
private static final Logger log = Logger.getLogger(Consumer.class.getCanonicalName());
|
||||
private final DataQueue dataQueue;
|
||||
|
||||
public Consumer(DataQueue dataQueue) {
|
||||
@@ -14,7 +17,7 @@ public class Consumer implements Runnable {
|
||||
|
||||
public void consume() {
|
||||
while (dataQueue.runFlag) {
|
||||
synchronized (this) {
|
||||
synchronized (dataQueue) {
|
||||
while (dataQueue.isEmpty() && dataQueue.runFlag) {
|
||||
try {
|
||||
dataQueue.waitOnEmpty();
|
||||
@@ -31,12 +34,13 @@ public class Consumer implements Runnable {
|
||||
useMessage(message);
|
||||
}
|
||||
}
|
||||
System.out.println("Consumer Stopped");
|
||||
log.info("Consumer Stopped");
|
||||
}
|
||||
|
||||
private void useMessage(Message message) {
|
||||
if (message != null) {
|
||||
System.out.printf("[%s] Consuming Message. Id: %d, Data: %f\n", Thread.currentThread().getName(), message.getId(), message.getData());
|
||||
log.info(String.format("[%s] Consuming Message. Id: %d, Data: %f%n",
|
||||
Thread.currentThread().getName(), message.getId(), message.getData()));
|
||||
|
||||
//Sleeping on random time to make it realistic
|
||||
ThreadUtil.sleep((long) (message.getData() * 100));
|
||||
|
||||
+12
-4
@@ -1,6 +1,9 @@
|
||||
package com.baeldung.producerconsumer;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class Producer implements Runnable {
|
||||
private static final Logger log = Logger.getLogger(Producer.class.getCanonicalName());
|
||||
private final DataQueue dataQueue;
|
||||
|
||||
private static int idSequence = 0;
|
||||
@@ -16,7 +19,7 @@ public class Producer implements Runnable {
|
||||
|
||||
public void produce() {
|
||||
while (dataQueue.runFlag) {
|
||||
synchronized (this) {
|
||||
synchronized (dataQueue) {
|
||||
while (dataQueue.isFull() && dataQueue.runFlag) {
|
||||
try {
|
||||
dataQueue.waitOnFull();
|
||||
@@ -33,12 +36,13 @@ public class Producer implements Runnable {
|
||||
dataQueue.notifyAllForEmpty();
|
||||
}
|
||||
}
|
||||
System.out.println("Producer Stopped");
|
||||
log.info("Producer Stopped");
|
||||
}
|
||||
|
||||
private Message generateMessage() {
|
||||
Message message = new Message(++idSequence, Math.random());
|
||||
System.out.printf("[%s] Generated Message. Id: %d, Data: %f\n", Thread.currentThread().getName(), message.getId(), message.getData());
|
||||
Message message = new Message(incrementAndGetId(), Math.random());
|
||||
log.info(String.format("[%s] Generated Message. Id: %d, Data: %f%n",
|
||||
Thread.currentThread().getName(), message.getId(), message.getData()));
|
||||
|
||||
//Sleeping on random time to make it realistic
|
||||
ThreadUtil.sleep((long) (message.getData() * 100));
|
||||
@@ -46,6 +50,10 @@ public class Producer implements Runnable {
|
||||
return message;
|
||||
}
|
||||
|
||||
private static int incrementAndGetId() {
|
||||
return ++idSequence;
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
dataQueue.runFlag = false;
|
||||
dataQueue.notifyAllForFull();
|
||||
|
||||
+4
-2
@@ -2,10 +2,12 @@ package com.baeldung.producerconsumer;
|
||||
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.LinkedBlockingDeque;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static com.baeldung.producerconsumer.ThreadUtil.sleep;
|
||||
|
||||
public class SimpleProducerConsumerDemonstrator {
|
||||
private static final Logger log = Logger.getLogger(SimpleProducerConsumerDemonstrator.class.getCanonicalName());
|
||||
BlockingQueue<Double> blockingQueue = new LinkedBlockingDeque<>(5);
|
||||
|
||||
private void produce() {
|
||||
@@ -17,7 +19,7 @@ public class SimpleProducerConsumerDemonstrator {
|
||||
e.printStackTrace();
|
||||
break;
|
||||
}
|
||||
System.out.printf("[%s] Value produced: %f\n", Thread.currentThread().getName(), value);
|
||||
log.info(String.format("[%s] Value produced: %f%n", Thread.currentThread().getName(), value));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,7 +33,7 @@ public class SimpleProducerConsumerDemonstrator {
|
||||
break;
|
||||
}
|
||||
// Consume value
|
||||
System.out.printf("[%s] Value consumed: %f\n", Thread.currentThread().getName(), value);
|
||||
log.info(String.format("[%s] Value consumed: %f%n", Thread.currentThread().getName(), value));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,4 +6,5 @@ This module contains articles about basic Java concurrency.
|
||||
|
||||
- [How to Handle InterruptedException in Java](https://www.baeldung.com/java-interrupted-exception)
|
||||
- [Thread.sleep() vs Awaitility.await()](https://www.baeldung.com/java-thread-sleep-vs-awaitility-await)
|
||||
- [Is CompletableFuture Non-blocking?](https://www.baeldung.com/java-completablefuture-non-blocking)
|
||||
- [[<-- Prev]](../core-java-concurrency-basic-2)
|
||||
|
||||
+4
-2
@@ -20,7 +20,8 @@ public class RequestProcessorUnitTest {
|
||||
void whenWaitingWithThreadSleep_thenStatusIsDone() throws InterruptedException {
|
||||
String requestId = requestProcessor.processRequest();
|
||||
|
||||
Thread.sleep(2000);
|
||||
//The sleep value should be greater than the maximum time the request takes to complete
|
||||
Thread.sleep(2010);
|
||||
|
||||
assertEquals("DONE", requestProcessor.getStatus(requestId));
|
||||
}
|
||||
@@ -31,7 +32,8 @@ public class RequestProcessorUnitTest {
|
||||
String requestId = requestProcessor.processRequest();
|
||||
|
||||
Awaitility.await()
|
||||
.atMost(2, TimeUnit.SECONDS)
|
||||
//The timeout value should exceed the maximum time the request takes to complete, for the time amount of a poll (500 ms)
|
||||
.atMost(2501, TimeUnit.MILLISECONDS)
|
||||
.pollDelay(500, TimeUnit.MILLISECONDS)
|
||||
.until(() -> requestProcessor.getStatus(requestId), not(equalTo("PROCESSING")));
|
||||
|
||||
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.concurrent.queue;
|
||||
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class BlockingQueueUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenArrayBlockingQueue_whenAddedElements_thenReturnQueueRemainingCapacity() {
|
||||
BlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue<>(10);
|
||||
arrayBlockingQueue.add("TestString1");
|
||||
arrayBlockingQueue.add("TestString2");
|
||||
assertEquals(8, arrayBlockingQueue.remainingCapacity());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLinkedBlockingQueue_whenAddedElements_thenReturnQueueRemainingCapacity() {
|
||||
BlockingQueue<String> linkedBlockingQueue = new LinkedBlockingQueue<>(10);
|
||||
linkedBlockingQueue.add("TestString1");
|
||||
assertEquals(9, linkedBlockingQueue.remainingCapacity());
|
||||
}
|
||||
}
|
||||
@@ -7,3 +7,4 @@ This module contains articles about core Java input/output(IO) APIs.
|
||||
- [Java Scanner Taking a Character Input](https://www.baeldung.com/java-scanner-character-input)
|
||||
- [Get the Desktop Path in Java](https://www.baeldung.com/java-desktop-path)
|
||||
- [Integer.parseInt(scanner.nextLine()) and scanner.nextInt() in Java](https://www.baeldung.com/java-scanner-integer)
|
||||
- [Difference Between FileReader and BufferedReader in Java](https://www.baeldung.com/java-filereader-vs-bufferedreader)
|
||||
|
||||
@@ -1,46 +1,115 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-io-apis-2</artifactId>
|
||||
<name>core-java-io-apis-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- logging -->
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-io-apis-2</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-io-apis-2</artifactId>
|
||||
<name>core-java-io-apis-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- logging -->
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>5.7.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
</dependency>
|
||||
<!-- this is all you need to write tests with JUnit Jupiter -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>${junit-jupiter-version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- this dependency is needed to create parameterized tests -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-params</artifactId>
|
||||
<version>${junit-jupiter-version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- contains the engine that actually runs the Jupiter-tests -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>${junit-jupiter-version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testng</groupId>
|
||||
<artifactId>testng</artifactId>
|
||||
<version>7.1.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testng</groupId>
|
||||
<artifactId>testng</artifactId>
|
||||
<version>7.5</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<properties>
|
||||
<junit-jupiter-version>5.2.0</junit-jupiter-version>
|
||||
</properties>
|
||||
<build>
|
||||
<finalName>core-java-io-apis-2</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.multinput;
|
||||
|
||||
import java.util.InputMismatchException;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class MultiInputs {
|
||||
public void UsingSpaceDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
System.out.print("Enter two numbers: ");
|
||||
int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2);
|
||||
|
||||
}
|
||||
public void UsingREDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
scanner.useDelimiter("[\\s,]+");
|
||||
System.out.print("Enter two numbers separated by a space or a comma: ");
|
||||
int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2);
|
||||
|
||||
}
|
||||
public void UsingCustomDelimiter(){
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
scanner.useDelimiter(";");
|
||||
System.out.print("Enter two numbers separated by a semicolon: ");
|
||||
try { int num1 = scanner.nextInt();
|
||||
int num2 = scanner.nextInt();
|
||||
System.out.println("You entered " + num1 + " and " + num2); }
|
||||
catch (InputMismatchException e)
|
||||
{ System.out.println("Invalid input. Please enter two integers separated by a semicolon."); }
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
+92
-93
@@ -1,93 +1,92 @@
|
||||
package com.baeldung.absolutetorelative;
|
||||
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
public class AbsoluteToRelativeUnitTest {
|
||||
|
||||
// given - until using Paths, no need to create physical files
|
||||
private final Path pathOne = Paths.get("/baeldung/bar/one.txt");
|
||||
private final Path pathTwo = Paths.get("/baeldung/bar/two.txt");
|
||||
private final Path pathThree = Paths.get("/baeldung/foo/three.txt");
|
||||
|
||||
private final URI uriOne = pathOne.toUri();
|
||||
private final URI uriTwo = pathTwo.toUri();
|
||||
private final URI uriThree = pathThree.toUri();
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePaths_whenRelativizePathOneToPathTwo_thenRelativeIsReturned() {
|
||||
Path result = pathOne.relativize(pathTwo);
|
||||
|
||||
Assertions.assertThat(result)
|
||||
.isRelative()
|
||||
.isEqualTo(Paths.get("../two.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePaths_whenRelativizePathTwoToPathOne_thenRelativeIsReturned() {
|
||||
Path result = pathTwo.relativize(pathOne);
|
||||
|
||||
Assertions.assertThat(result)
|
||||
.isRelative()
|
||||
.isEqualTo(Paths.get("../one.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePaths_whenRelativizePathOneParentToPathTwo_thenRelativeIsReturned() {
|
||||
Path result = pathOne.getParent().relativize(pathTwo);
|
||||
|
||||
Assertions.assertThat(result)
|
||||
.isRelative()
|
||||
.isEqualTo(Paths.get("two.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePaths_whenRelativizePathOneToPathThree_thenRelativeIsReturned() {
|
||||
Path result = pathOne.relativize(pathThree);
|
||||
|
||||
Assertions.assertThat(result)
|
||||
.isRelative()
|
||||
.isEqualTo(Paths.get("../../foo/three.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePaths_whenRelativizePathThreeToPathOne_thenRelativeIsReturned() {
|
||||
Path result = pathThree.relativize(pathOne);
|
||||
|
||||
Assertions.assertThat(result)
|
||||
.isRelative()
|
||||
.isEqualTo(Paths.get("../../bar/one.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsoluteURIs_whenRelativizeUriOneToUriTwo_thenAbsoluteIsReturned() {
|
||||
URI result = uriOne.relativize(uriTwo);
|
||||
|
||||
Assertions.assertThat(result)
|
||||
.asString()
|
||||
.contains("/baeldung/bar/two.txt");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsoluteURIs_whenRelativizeUriOneParentToUriTwo_thenRelativeIsReturned() {
|
||||
URI result = pathOne.getParent().toUri().relativize(uriTwo);
|
||||
|
||||
Assertions.assertThat(result)
|
||||
.asString()
|
||||
.contains("two.txt");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsoluteURIs_whenRelativizeUriOneParentToUriThree_thenAbsoluteIsReturned() {
|
||||
URI result = pathOne.getParent().toUri().relativize(uriThree);
|
||||
|
||||
Assertions.assertThat(result)
|
||||
.asString()
|
||||
.contains("/baeldung/foo/three.txt");
|
||||
}
|
||||
|
||||
}
|
||||
package com.baeldung.absolutetorelative;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class AbsoluteToRelativeUnitTest {
|
||||
|
||||
// given - until using Paths, no need to create physical files
|
||||
private final Path pathOne = Paths.get("/baeldung/bar/one.txt");
|
||||
private final Path pathTwo = Paths.get("/baeldung/bar/two.txt");
|
||||
private final Path pathThree = Paths.get("/baeldung/foo/three.txt");
|
||||
|
||||
private final URI uriOne = pathOne.toUri();
|
||||
private final URI uriTwo = pathTwo.toUri();
|
||||
private final URI uriThree = pathThree.toUri();
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePaths_whenRelativizePathOneToPathTwo_thenRelativeIsReturned() {
|
||||
Path result = pathOne.relativize(pathTwo);
|
||||
|
||||
org.assertj.core.api.Assertions.assertThat(result)
|
||||
.isRelative()
|
||||
.isEqualTo(Paths.get("../two.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePaths_whenRelativizePathTwoToPathOne_thenRelativeIsReturned() {
|
||||
Path result = pathTwo.relativize(pathOne);
|
||||
|
||||
org.assertj.core.api.Assertions.assertThat(result)
|
||||
.isRelative()
|
||||
.isEqualTo(Paths.get("../one.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePaths_whenRelativizePathOneParentToPathTwo_thenRelativeIsReturned() {
|
||||
Path result = pathOne.getParent().relativize(pathTwo);
|
||||
|
||||
org.assertj.core.api.Assertions.assertThat(result)
|
||||
.isRelative()
|
||||
.isEqualTo(Paths.get("two.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePaths_whenRelativizePathOneToPathThree_thenRelativeIsReturned() {
|
||||
Path result = pathOne.relativize(pathThree);
|
||||
|
||||
org.assertj.core.api.Assertions.assertThat(result)
|
||||
.isRelative()
|
||||
.isEqualTo(Paths.get("../../foo/three.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePaths_whenRelativizePathThreeToPathOne_thenRelativeIsReturned() {
|
||||
Path result = pathThree.relativize(pathOne);
|
||||
|
||||
org.assertj.core.api.Assertions.assertThat(result)
|
||||
.isRelative()
|
||||
.isEqualTo(Paths.get("../../bar/one.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsoluteURIs_whenRelativizeUriOneToUriTwo_thenAbsoluteIsReturned() {
|
||||
URI result = uriOne.relativize(uriTwo);
|
||||
|
||||
org.assertj.core.api.Assertions.assertThat(result)
|
||||
.asString()
|
||||
.contains("/baeldung/bar/two.txt");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsoluteURIs_whenRelativizeUriOneParentToUriTwo_thenRelativeIsReturned() {
|
||||
URI result = pathOne.getParent().toUri().relativize(uriTwo);
|
||||
|
||||
org.assertj.core.api.Assertions.assertThat(result)
|
||||
.asString()
|
||||
.contains("two.txt");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsoluteURIs_whenRelativizeUriOneParentToUriThree_thenAbsoluteIsReturned() {
|
||||
URI result = pathOne.getParent().toUri().relativize(uriThree);
|
||||
|
||||
org.assertj.core.api.Assertions.assertThat(result)
|
||||
.asString()
|
||||
.contains("/baeldung/foo/three.txt");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+31
-31
@@ -1,31 +1,31 @@
|
||||
package com.baeldung.bufferedreadervsfilereader;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
|
||||
public class BufferedReaderUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenReadingAFile_thenReadsLineByLine() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
try (BufferedReader br = new BufferedReader(new FileReader("src/test/resources/sampleText1.txt"))) {
|
||||
String line;
|
||||
|
||||
while((line = br.readLine()) != null) {
|
||||
result.append(line);
|
||||
result.append('\n');
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
assertEquals("first line\nsecond line\nthird line\n", result.toString());
|
||||
}
|
||||
|
||||
}
|
||||
package com.baeldung.bufferedreadervsfilereader;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.testng.annotations.Test;
|
||||
public class BufferedReaderUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenReadingAFile_thenReadsLineByLine() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
try (BufferedReader br = new BufferedReader(new FileReader("src/test/resources/sampleText1.txt"))) {
|
||||
String line;
|
||||
|
||||
while((line = br.readLine()) != null) {
|
||||
result.append(line);
|
||||
result.append('\n');
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
assertEquals("first line\nsecond line\nthird line\n", result.toString());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+30
-30
@@ -1,30 +1,30 @@
|
||||
package com.baeldung.bufferedreadervsfilereader;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class FileReaderUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenReadingAFile_thenReadsCharByChar() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
try (FileReader fr = new FileReader("src/test/resources/sampleText2.txt")) {
|
||||
int i = fr.read();
|
||||
|
||||
while(i != -1) {
|
||||
result.append((char)i);
|
||||
|
||||
i = fr.read();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
assertEquals("qwerty", result.toString());
|
||||
}
|
||||
}
|
||||
package com.baeldung.bufferedreadervsfilereader;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class FileReaderUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenReadingAFile_thenReadsCharByChar() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
try (FileReader fr = new FileReader("src/test/resources/sampleText2.txt")) {
|
||||
int i = fr.read();
|
||||
|
||||
while(i != -1) {
|
||||
result.append((char)i);
|
||||
|
||||
i = fr.read();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
assertEquals("qwerty", result.toString());
|
||||
}
|
||||
}
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.multinput;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.util.InputMismatchException;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.testng.annotations.Test;
|
||||
import com.baeldung.multinput.MultiInputs;
|
||||
public class TestMultipleInputsUnitTest {
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingSpaceDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "10 20\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingSpaceDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingREDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "30, 40\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingREDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleInputs_whenUsingCustomDelimiter_thenExpectPrintingOutputs() {
|
||||
String input = "50; 60\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
mi.UsingCustomDelimiter();
|
||||
// You can add assertions here to verify the behavior of the method
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidInput_whenUsingSpaceDelimiter_thenExpectInputMismatchException() {
|
||||
String input = "abc\n";
|
||||
InputStream in = new ByteArrayInputStream(input.getBytes());
|
||||
System.setIn(in);
|
||||
MultiInputs mi = new MultiInputs();
|
||||
Assertions.assertThrows(InputMismatchException.class, mi::UsingSpaceDelimiter);
|
||||
}
|
||||
}
|
||||
+27
-29
@@ -1,29 +1,27 @@
|
||||
package com.baeldung.path;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import javax.swing.filechooser.FileSystemView;
|
||||
|
||||
public class DesktopPathUnitTest {
|
||||
// Adapt DESKTOP_PATH variable to your own system path
|
||||
// private static final String DESKTOP_PATH = "C:\\Users\\HRAF\\Desktop";
|
||||
|
||||
@Test
|
||||
public void whenUsingGetUserHomeProperty_thenShouldEqualDesktopPath() {
|
||||
String desktopPath = System.getProperty("user.home") + File.separator + "Desktop";
|
||||
// assertEquals(DESKTOP_PATH, desktopPath);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFileSystemViewGetHomeDirectory_thenShouldEqualDesktopPath() {
|
||||
FileSystemView view = FileSystemView.getFileSystemView();
|
||||
File file = view.getHomeDirectory();
|
||||
String path = file.getPath();
|
||||
// assertEquals(DESKTOP_PATH, path);
|
||||
}
|
||||
|
||||
}
|
||||
package com.baeldung.path;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import javax.swing.filechooser.FileSystemView;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class DesktopPathUnitTest {
|
||||
// Adapt DESKTOP_PATH variable to your own system path
|
||||
// private static final String DESKTOP_PATH = "C:\\Users\\HRAF\\Desktop";
|
||||
|
||||
@Test
|
||||
public void whenUsingGetUserHomeProperty_thenShouldEqualDesktopPath() {
|
||||
String desktopPath = System.getProperty("user.home") + File.separator + "Desktop";
|
||||
// assertEquals(DESKTOP_PATH, desktopPath);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFileSystemViewGetHomeDirectory_thenShouldEqualDesktopPath() {
|
||||
FileSystemView view = FileSystemView.getFileSystemView();
|
||||
File file = view.getHomeDirectory();
|
||||
String path = file.getPath();
|
||||
// assertEquals(DESKTOP_PATH, path);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+84
-84
@@ -1,85 +1,85 @@
|
||||
package com.baeldung.scanner;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import java.util.InputMismatchException;
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class NextLineVsNextIntUnitTest {
|
||||
|
||||
@Test
|
||||
void whenInputLineIsNumber_thenNextLineAndNextIntBothWork() {
|
||||
String input = "42\n";
|
||||
|
||||
//nextLine()
|
||||
Scanner sc1 = new Scanner(input);
|
||||
int num1 = Integer.parseInt(sc1.nextLine());
|
||||
assertEquals(42, num1);
|
||||
|
||||
//nextInt()
|
||||
Scanner sc2 = new Scanner(input);
|
||||
int num2 = sc2.nextInt();
|
||||
assertEquals(42, num2);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenInputIsNotValidNumber_thenNextLineAndNextIntThrowDifferentException() {
|
||||
String input = "Nan\n";
|
||||
|
||||
//nextLine() -> NumberFormatException
|
||||
Scanner sc1 = new Scanner(input);
|
||||
assertThrows(NumberFormatException.class, () -> Integer.parseInt(sc1.nextLine()));
|
||||
|
||||
//nextInt() -> InputMismatchException
|
||||
Scanner sc2 = new Scanner(input);
|
||||
assertThrows(InputMismatchException.class, sc2::nextInt);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingNextInt_thenTheNextTokenAfterItFailsToParseIsNotConsumed() {
|
||||
String input = "42 is a magic number\n";
|
||||
|
||||
//nextInt() to read '42'
|
||||
Scanner sc2 = new Scanner(input);
|
||||
int num2 = sc2.nextInt();
|
||||
assertEquals(42, num2);
|
||||
|
||||
// call nextInt() again on "is"
|
||||
assertThrows(InputMismatchException.class, sc2::nextInt);
|
||||
|
||||
String theNextToken = sc2.next();
|
||||
assertEquals("is", theNextToken);
|
||||
|
||||
theNextToken = sc2.next();
|
||||
assertEquals("a", theNextToken);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenReadingTwoInputLines_thenNextLineAndNextIntBehaveDifferently() {
|
||||
|
||||
String input = new StringBuilder().append("42\n")
|
||||
.append("It is a magic number.\n")
|
||||
.toString();
|
||||
|
||||
//nextLine()
|
||||
Scanner sc1 = new Scanner(input);
|
||||
int num1 = Integer.parseInt(sc1.nextLine());
|
||||
String nextLineText1 = sc1.nextLine();
|
||||
assertEquals(42, num1);
|
||||
assertEquals("It is a magic number.", nextLineText1);
|
||||
|
||||
//nextInt()
|
||||
Scanner sc2 = new Scanner(input);
|
||||
int num2 = sc2.nextInt();
|
||||
assertEquals(42, num2);
|
||||
|
||||
// nextInt() leaves the newline character (\n) behind
|
||||
String nextLineText2 = sc2.nextLine();
|
||||
assertEquals("", nextLineText2);
|
||||
}
|
||||
|
||||
package com.baeldung.scanner;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import java.util.InputMismatchException;
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class NextLineVsNextIntUnitTest {
|
||||
|
||||
@Test
|
||||
void whenInputLineIsNumber_thenNextLineAndNextIntBothWork() {
|
||||
String input = "42\n";
|
||||
|
||||
//nextLine()
|
||||
Scanner sc1 = new Scanner(input);
|
||||
int num1 = Integer.parseInt(sc1.nextLine());
|
||||
assertEquals(42, num1);
|
||||
|
||||
//nextInt()
|
||||
Scanner sc2 = new Scanner(input);
|
||||
int num2 = sc2.nextInt();
|
||||
assertEquals(42, num2);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenInputIsNotValidNumber_thenNextLineAndNextIntThrowDifferentException() {
|
||||
String input = "Nan\n";
|
||||
|
||||
//nextLine() -> NumberFormatException
|
||||
Scanner sc1 = new Scanner(input);
|
||||
assertThrows(NumberFormatException.class, () -> Integer.parseInt(sc1.nextLine()));
|
||||
|
||||
//nextInt() -> InputMismatchException
|
||||
Scanner sc2 = new Scanner(input);
|
||||
assertThrows(InputMismatchException.class, sc2::nextInt);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingNextInt_thenTheNextTokenAfterItFailsToParseIsNotConsumed() {
|
||||
String input = "42 is a magic number\n";
|
||||
|
||||
//nextInt() to read '42'
|
||||
Scanner sc2 = new Scanner(input);
|
||||
int num2 = sc2.nextInt();
|
||||
assertEquals(42, num2);
|
||||
|
||||
// call nextInt() again on "is"
|
||||
assertThrows(InputMismatchException.class, sc2::nextInt);
|
||||
|
||||
String theNextToken = sc2.next();
|
||||
assertEquals("is", theNextToken);
|
||||
|
||||
theNextToken = sc2.next();
|
||||
assertEquals("a", theNextToken);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenReadingTwoInputLines_thenNextLineAndNextIntBehaveDifferently() {
|
||||
|
||||
String input = new StringBuilder().append("42\n")
|
||||
.append("It is a magic number.\n")
|
||||
.toString();
|
||||
|
||||
//nextLine()
|
||||
Scanner sc1 = new Scanner(input);
|
||||
int num1 = Integer.parseInt(sc1.nextLine());
|
||||
String nextLineText1 = sc1.nextLine();
|
||||
assertEquals(42, num1);
|
||||
assertEquals("It is a magic number.", nextLineText1);
|
||||
|
||||
//nextInt()
|
||||
Scanner sc2 = new Scanner(input);
|
||||
int num2 = sc2.nextInt();
|
||||
assertEquals(42, num2);
|
||||
|
||||
// nextInt() leaves the newline character (\n) behind
|
||||
String nextLineText2 = sc2.nextLine();
|
||||
assertEquals("", nextLineText2);
|
||||
}
|
||||
|
||||
}
|
||||
+38
-38
@@ -1,38 +1,38 @@
|
||||
package com.baeldung.scanner;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class ScanACharacterUnitTest {
|
||||
|
||||
// given - input scanner source, no need to scan from console
|
||||
String input = new StringBuilder().append("abc\n")
|
||||
.append("mno\n")
|
||||
.append("xyz\n")
|
||||
.toString();
|
||||
|
||||
@Test
|
||||
public void givenInputSource_whenScanCharUsingNext_thenOneCharIsRead() {
|
||||
Scanner sc = new Scanner(input);
|
||||
char c = sc.next().charAt(0);
|
||||
assertEquals('a', c);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInputSource_whenScanCharUsingFindInLine_thenOneCharIsRead() {
|
||||
Scanner sc = new Scanner(input);
|
||||
char c = sc.findInLine(".").charAt(0);
|
||||
assertEquals('a', c);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInputSource_whenScanCharUsingUseDelimiter_thenOneCharIsRead() {
|
||||
Scanner sc = new Scanner(input);
|
||||
char c = sc.useDelimiter("").next().charAt(0);
|
||||
assertEquals('a', c);
|
||||
}
|
||||
|
||||
}
|
||||
package com.baeldung.scanner;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class ScanACharacterUnitTest {
|
||||
|
||||
// given - input scanner source, no need to scan from console
|
||||
String input = new StringBuilder().append("abc\n")
|
||||
.append("mno\n")
|
||||
.append("xyz\n")
|
||||
.toString();
|
||||
|
||||
@Test
|
||||
public void givenInputSource_whenScanCharUsingNext_thenOneCharIsRead() {
|
||||
Scanner sc = new Scanner(input);
|
||||
char c = sc.next().charAt(0);
|
||||
assertEquals('a', c);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInputSource_whenScanCharUsingFindInLine_thenOneCharIsRead() {
|
||||
Scanner sc = new Scanner(input);
|
||||
char c = sc.findInLine(".").charAt(0);
|
||||
assertEquals('a', c);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInputSource_whenScanCharUsingUseDelimiter_thenOneCharIsRead() {
|
||||
Scanner sc = new Scanner(input);
|
||||
char c = sc.useDelimiter("").next().charAt(0);
|
||||
assertEquals('a', c);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package com.baeldung.scanner;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.ObjectArrays;
|
||||
|
||||
public class ScannerToArrayUnitTest {
|
||||
|
||||
@Test
|
||||
void whenMultipleElementsInOneLine_thenGetExpectedArray() {
|
||||
String input = "Java Kotlin Ruby Python Go\n";
|
||||
String[] expected = new String[] { "Java", "Kotlin", "Ruby", "Python", "Go" };
|
||||
|
||||
// scanner.next()
|
||||
Scanner scanner1 = new Scanner(input);
|
||||
String[] result1 = new String[5];
|
||||
int i = 0;
|
||||
while (i < result1.length) {
|
||||
result1[i] = scanner1.next();
|
||||
i++;
|
||||
}
|
||||
assertArrayEquals(expected, result1);
|
||||
|
||||
//split()
|
||||
Scanner scanner2 = new Scanner(input);
|
||||
String[] result2 = scanner2.nextLine()
|
||||
.split("\\s+");
|
||||
assertArrayEquals(expected, result2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenOneElementPerLine_thenGetExpectedArray() {
|
||||
String input = new StringBuilder().append("Baeldung Java\n")
|
||||
.append("Baeldung Kotlin\n")
|
||||
.append("Baeldung Linux\n")
|
||||
.toString();
|
||||
|
||||
String[] expected = new String[] { "Baeldung Java", "Baeldung Kotlin", "Baeldung Linux" };
|
||||
|
||||
String[] result = new String[3];
|
||||
Scanner scanner = new Scanner(input);
|
||||
int i = 0;
|
||||
while (i < result.length) {
|
||||
result[i] = scanner.nextLine();
|
||||
i++;
|
||||
}
|
||||
assertArrayEquals(expected, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenOneElementPerLine_thenGetExpectedList() {
|
||||
String input = new StringBuilder().append("Baeldung Java\n")
|
||||
.append("Baeldung Kotlin\n")
|
||||
.append("Baeldung Linux\n")
|
||||
.toString();
|
||||
|
||||
List<String> expected = Lists.newArrayList("Baeldung Java", "Baeldung Kotlin", "Baeldung Linux");
|
||||
|
||||
List<String> result = new ArrayList<>();
|
||||
Scanner scanner = new Scanner(input);
|
||||
while (scanner.hasNextLine()) {
|
||||
result.add(scanner.nextLine());
|
||||
}
|
||||
assertEquals(expected, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenEveryTokenIsAnElement_thenGetExpectedList() {
|
||||
String input = new StringBuilder().append("Linux Windows MacOS\n")
|
||||
.append("Java Kotlin Python Go\n")
|
||||
.toString();
|
||||
|
||||
List<String> expected = Lists.newArrayList("Linux", "Windows", "MacOS", "Java", "Kotlin", "Python", "Go");
|
||||
List<String> result = new ArrayList<>();
|
||||
Scanner scanner = new Scanner(input);
|
||||
while (scanner.hasNext()) {
|
||||
result.add(scanner.next());
|
||||
}
|
||||
assertEquals(expected, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenEveryTokenIsAnElement_thenGetExpectedArray() {
|
||||
String input = new StringBuilder().append("Linux Windows MacOS\n")
|
||||
.append("Java Kotlin Python Go\n")
|
||||
.toString();
|
||||
|
||||
String[] expected = new String[] { "Linux", "Windows", "MacOS", "Java", "Kotlin", "Python", "Go" };
|
||||
String[] result = new String[] {};
|
||||
|
||||
Scanner scanner = new Scanner(input);
|
||||
while (scanner.hasNextLine()) {
|
||||
String[] lineInArray = scanner.nextLine()
|
||||
.split("\\s+");
|
||||
result = ObjectArrays.concat(result, lineInArray, String.class);
|
||||
}
|
||||
assertArrayEquals(expected, result);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,3 @@
|
||||
first line
|
||||
second line
|
||||
third line
|
||||
first line
|
||||
second line
|
||||
third line
|
||||
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.outputstreamtoinputstream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.PipedInputStream;
|
||||
import java.io.PipedOutputStream;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class ConvertOutputStreamToInputStreamUnitTest {
|
||||
|
||||
@Test
|
||||
void whenUsingByteArray_thenGetExpectedInputStream() throws IOException {
|
||||
String content = "I'm an important message.";
|
||||
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
|
||||
out.write(content.getBytes());
|
||||
try (ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray())) {
|
||||
String inContent = new String(in.readAllBytes());
|
||||
|
||||
assertEquals(content, inContent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingPipeStream_thenGetExpectedInputStream() throws IOException {
|
||||
String content = "I'm going through the pipe.";
|
||||
|
||||
ByteArrayOutputStream originOut = new ByteArrayOutputStream();
|
||||
originOut.write(content.getBytes());
|
||||
|
||||
//connect the pipe
|
||||
PipedInputStream in = new PipedInputStream();
|
||||
PipedOutputStream out = new PipedOutputStream(in);
|
||||
|
||||
try (in) {
|
||||
new Thread(() -> {
|
||||
try (out) {
|
||||
originOut.writeTo(out);
|
||||
} catch (IOException iox) {
|
||||
// handle IOExceptions
|
||||
}
|
||||
}).start();
|
||||
|
||||
String inContent = new String(in.readAllBytes());
|
||||
assertEquals(content, inContent);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -23,7 +23,7 @@
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<h2.version>1.4.197</h2.version> <!-- needs to be specified as it fails with parent's 1.4.200 -->
|
||||
<h2.version>2.1.214</h2.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.interfacesingleimpl;
|
||||
|
||||
public interface Animal {
|
||||
String makeSound();
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.interfacesingleimpl;
|
||||
|
||||
public class AnimalCare {
|
||||
private Animal animal;
|
||||
|
||||
public AnimalCare(Animal animal) {
|
||||
this.animal = animal;
|
||||
}
|
||||
|
||||
public String animalSound() {
|
||||
return animal.makeSound();
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.interfacesingleimpl;
|
||||
|
||||
public class Cat {
|
||||
private String name;
|
||||
|
||||
public Cat(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String makeSound() {
|
||||
return "Meow! My name is " + name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user