Merge branch 'eugenp:master' into master

This commit is contained in:
Zahid Khan 2023-05-15 11:48:09 +05:30 committed by GitHub
commit a3acf733da
223 changed files with 2800 additions and 1258 deletions

View File

@ -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)

View File

@ -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>

View File

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

View File

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

View File

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

View File

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

View File

@ -12,3 +12,4 @@ This module contains articles about Java array fundamentals. They assume no prev
- [Extending an Arrays 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)

View File

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

View File

@ -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();

View File

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

View File

@ -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)

View File

@ -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")));

View File

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

View File

@ -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)

View File

@ -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>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,3 +1,3 @@
first line
second line
third line
first line
second line
third line

View File

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

View File

@ -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>

View File

@ -0,0 +1,5 @@
package com.baeldung.interfacesingleimpl;
public interface Animal {
String makeSound();
}

View File

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

View File

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

View File

@ -0,0 +1,22 @@
package com.baeldung.interfacesingleimpl;
public class Dog implements Animal {
private String name;
public Dog(String name) {
this.name = name;
}
@Override
public String makeSound() {
return "Woof! My name is " + name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.interfacesingleimpl;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class InterfaceSingleImplUnitTest {
@Test
public void whenUsingMockAnimal_thenAnimalSoundIsCorrect() {
MockAnimal mockAnimal = new MockAnimal();
String expected = "Mock animal sound!";
AnimalCare animalCare = new AnimalCare(mockAnimal);
assertThat(animalCare.animalSound()).isEqualTo(expected);
}
@Test
public void whenCreatingDog_thenDogMakesWoofSound() {
Dog dog = new Dog("Buddy");
String expected = "Woof! My name is Buddy";
assertThat(dog.makeSound()).isEqualTo(expected);
}
@Test
public void whenCreatingCat_thenCatMakesMeowSound() {
Cat cat = new Cat("FuzzBall");
String expected = "Meow! My name is FuzzBall";
assertThat(cat.makeSound()).isEqualTo(expected);
}
@Test
public void whenCreatingAnimalCareWithDog_thenDogMakesWoofSound() {
Animal dog = new Dog("Ham");
AnimalCare animalCare = new AnimalCare(dog);
String expected = "Woof! My name is Ham";
assertThat(animalCare.animalSound()).isEqualTo(expected);
}
@Test
public void whenCreatingCatCareWithCat_thenCatMakesMeowSound() {
Cat cat = new Cat("Grumpy");
String expected = "Meow! My name is Grumpy";
assertThat(cat.makeSound()).isEqualTo(expected);
}
@Test
public void whenCreatingMockAnimal_thenMockAnimalMakesMockAnimalSound() {
MockAnimal mockAnimal = new MockAnimal();
String expected = "Mock animal sound!";
assertThat(mockAnimal.makeSound()).isEqualTo(expected);
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.interfacesingleimpl;
public class MockAnimal implements Animal {
@Override
public String makeSound() {
return "Mock animal sound!";
}
}

View File

@ -0,0 +1,2 @@
## Relevant Articles
- [Overridding hashCode() And equals() For Records](https://www.baeldung.com/java-override-hashcode-equals-records)

View File

@ -0,0 +1,35 @@
package com.baeldung.regex.z_regexp;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class ZRegularExpressionUnitTest {
@Test
public void givenCreditCardNumber_thenReturnIfMatched() {
String creditCardNumber = "1234567890123456";
String pattern = "\\d{16}\\z";
Assertions.assertTrue(creditCardNumber.matches(pattern));
}
@Test
public void givenLogOutput_thenReturnIfMatched() {
String logLine = "2022-05-01 14:30:00,123 INFO Some log message";
String pattern = ".*message\\z";
Assertions.assertTrue(logLine.matches(pattern));
}
@Test
public void givenEmailMessage_thenReturnIfMatched() {
String myMessage = "Hello HR, I hope i can write to Baeldung\n";
String pattern = ".*Baeldung\\s*\\Z";
Assertions.assertTrue(myMessage.matches(pattern));
}
@Test
public void givenFileExtension_thenReturnIfMatched() {
String fileName = "image.jpeg";
String pattern = ".*\\.jpeg\\Z";
Assertions.assertTrue(fileName.matches(pattern));
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.nullandempty;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.jupiter.api.Test;
public class NullAndEmptyStringUnitTest {
@Test
void givenANullAndEmptyString_whenUsingStringMethods_thenShouldGetExpectedResult() {
String nullString = null;
String emptyString = "";
assertTrue(emptyString.equals(""));
assertThrows(NullPointerException.class, () -> nullString.length());
}
@Test
void givenANullAndEmptyString_whenCheckingEquality_thenShouldGetExpectedResult() {
String nullString = null;
String emptyString = "";
assertFalse(emptyString.equals(nullString));
assertFalse(emptyString == nullString);
}
}

View File

@ -10,3 +10,5 @@
- [Guide to Splitting a String by Whitespace in Java](https://www.baeldung.com/java-splitting-a-string-by-whitespace)
- [Check if the First Letter of a String Is a Number](https://www.baeldung.com/java-check-if-string-starts-with-number)
- [Print “” Quotes Around a String in Java](https://www.baeldung.com/java-string-print-quotes)
- [Remove Punctuation From a String in Java](https://www.baeldung.com/java-remove-punctuation-from-string)
- [Find the Longest Word in a Given String in Java](https://www.baeldung.com/java-longest-word-string)

View File

@ -0,0 +1,36 @@
package com.baeldung.longestword;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class LongestWordFinder {
public Optional<String> findLongestWord(String sentence) {
return Optional.ofNullable(sentence)
.filter(string -> !string.trim()
.isEmpty())
.map(string -> string.split("\\s"))
.map(Arrays::asList)
.map(list -> Collections.max(list, Comparator.comparingInt(String::length)));
}
public List<String> findLongestWords(String sentence) {
if (sentence == null || sentence.trim()
.isEmpty()) {
return Collections.emptyList();
}
String[] words = sentence.split("\\s");
int maxWordLength = Arrays.stream(words)
.mapToInt(String::length)
.max()
.orElseThrow();
return Arrays.stream(words)
.filter(word -> word.length() == maxWordLength)
.collect(Collectors.toList());
}
}

View File

@ -0,0 +1,62 @@
package com.baeldung.longestword;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
class LongestWordFinderUnitTest {
LongestWordFinder longestWordFinder = new LongestWordFinder();
@Test
void givenNull_whenFindLongestWord_thenEmpty() {
assertThat(longestWordFinder.findLongestWord(null)).isEmpty();
}
@Test
void givenEmptyString_whenFindLongestWord_thenEmpty() {
assertThat(longestWordFinder.findLongestWord("")).isEmpty();
}
@Test
void givenStringWithOnlySpaces_whenFindLongestWord_thenEmpty() {
assertThat(longestWordFinder.findLongestWord(" ")).isEmpty();
}
@Test
void givenAPhraseWithALongestWord_whenFindLongestWord_thenLongestWordOfThePhrase() {
assertThat(longestWordFinder.findLongestWord("This is a phrase with words")).hasValue("phrase");
}
@Test
void givenAPhraseWithVariousWordsOfMaxLength_whenFindLongestWord_thenAnyOfTheLongestsWordsOfThePhrase() {
assertThat(longestWordFinder.findLongestWord("Baeldung is another word of size eight in this sentence")
.get()).isIn("Baeldung", "sentence");
}
@Test
void givenNull_whenFindLongestWords_thenEmpty() {
assertThat(longestWordFinder.findLongestWords(null)).isEmpty();
}
@Test
void givenEmptyString_whenFindLongestWords_thenEmpty() {
assertThat(longestWordFinder.findLongestWords("")).isEmpty();
}
@Test
void givenStringWithOnlySpaces_whenFindLongestWords_thenEmpty() {
assertThat(longestWordFinder.findLongestWords(" ")).isEmpty();
}
@Test
void givenAPhraseWithALongestWord_whenFindLongestWords_thenLongestWordOfThePhrase() {
assertThat(longestWordFinder.findLongestWords("This is a phrase with words")).containsExactly("phrase");
}
@Test
void givenAPhraseWithVariousWordsOfMaxLength_whenFindLongestWords_thenAllLongestsWords() {
assertThat(longestWordFinder.findLongestWords("Baeldung is another word of size eight in this sentence")).containsExactly("Baeldung", "sentence");
}
}

View File

@ -0,0 +1,55 @@
package com.baeldung.stringbuilder;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.SingleShotTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Measurement(batchSize = 100000, iterations = 10)
@Warmup(batchSize = 100000, iterations = 10)
@State(Scope.Thread)
public class ReuseStringBuilderPerformance {
@Benchmark
public void benchmarkStringBuilder() {
for (int i = 0; i < 100; i++) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("baeldung");
stringBuilder.toString();
}
}
@Benchmark
public void benchmarkStringBuilderReuseWithSetLength() {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 100; i++) {
stringBuilder.append("baeldung");
stringBuilder.toString();
stringBuilder.setLength(0);
}
}
@Benchmark()
public void benchmarkStringBuilderReuseWithDelete() {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 100; i++) {
stringBuilder.append("baeldung");
stringBuilder.toString();
stringBuilder.delete(0, stringBuilder.length());
}
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(ReuseStringBuilderPerformance.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
}

View File

@ -1,9 +1,11 @@
package com.baeldung.jsonpath.introduction;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.Criteria;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.Filter;
import org.junit.Test;
import java.io.InputStream;
@ -98,4 +100,14 @@ public class ServiceIntegrationTest {
assertEquals("Spectre", title);
}
@Test
public void givenJsonPathWithFilterPredicate_whenReadingRootNode_thenCorrect() {
Filter expensiveFilter = Filter.filter(Criteria.where("director")
.contains("Sam Mendes"));
List<Map<String, Object>> predicate = JsonPath.parse(jsonString)
.read("$[?]['director']", expensiveFilter);
assertEquals(predicate.size(), 2);
}
}

View File

@ -65,4 +65,4 @@
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
</properties>
</project>
</project>

View File

@ -11,4 +11,5 @@ This module contains articles about Project Lombok.
- [Jacksons Deserialization With Lombok](https://www.baeldung.com/java-jackson-deserialization-lombok)
- [Constructor Injection in Spring with Lombok](https://www.baeldung.com/spring-injection-lombok)
- [@StandardException Annotation in Lombok](https://www.baeldung.com/lombok-standardexception-annotation)
- [Lombok EqualsAndHashCode Annotation](https://www.baeldung.com/java-lombok-equalsandhashcode)
- More articles: [[<-- prev]](../lombok)

View File

@ -19,6 +19,7 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@ -37,14 +38,15 @@
</property>
</properties>
</configuration>
<dependencies>
<!-- Activate this for understanding the article only -->
<!-- <dependencies>
<dependency>
<!-- Deactivate JUnit 4.7 engine by overriding it with an empty dummy -->
Deactivate JUnit 4.7 engine by overriding it with an empty dummy
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId>
<version>dummy</version>
</dependency>
</dependencies>
</dependencies> -->
</plugin>
</plugins>
</build>

View File

@ -6,4 +6,10 @@
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId>
<version>dummy</version>
<parent>
<groupId>com.baeldung.dependency-exclusion</groupId>
<artifactId>dependency-exclusion</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
</project>

View File

@ -94,7 +94,7 @@
<rest-assured.version>3.3.0</rest-assured.version>
<!-- plugins -->
<thin.version>1.0.22.RELEASE</thin.version>
<spring-boot.version>2.7.8</spring-boot.version>
<spring-boot.version>2.7.11</spring-boot.version>
<aspectjweaver.version>1.9.1</aspectjweaver.version>
<mysql-connector-java.version>8.0.31</mysql-connector-java.version>
</properties>

View File

@ -28,12 +28,12 @@
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.3</version>
<version>${itextpdf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>3.0.0-RC1</version>
<version>${pdfbox.version}</version>
</dependency>
</dependencies>
@ -48,8 +48,10 @@
</build>
<properties>
<itextpdf.version>5.5.13.3</itextpdf.version>
<itextpdf.core.version>7.2.3</itextpdf.core.version>
<itextpdf.cleanup.version>3.0.1</itextpdf.cleanup.version>
<pdfbox.version>3.0.0-RC1</pdfbox.version>
</properties>
</project>

View File

@ -106,7 +106,7 @@
<properties>
<pdfbox-tools.version>2.0.25</pdfbox-tools.version>
<pdf2dom.version>2.0.1</pdf2dom.version>
<itextpdf.version>5.5.10</itextpdf.version>
<itextpdf.version>5.5.13.3</itextpdf.version>
<xmlworker.version>5.5.10</xmlworker.version>
<poi-scratchpad.version>3.15</poi-scratchpad.version>
<batik-transcoder.version>1.8</batik-transcoder.version>

View File

@ -76,13 +76,18 @@
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.hypersistence</groupId>
<artifactId>hypersistence-utils-hibernate-60</artifactId>
<version>3.3.1</version>
</dependency>
</dependencies>
<properties>
<!-- Spring -->
<org.springframework.version>5.0.2.RELEASE</org.springframework.version>
<org.springframework.data.version>1.10.6.RELEASE</org.springframework.data.version>
<hibernate-core.version>5.6.7.Final</hibernate-core.version>
<org.springframework.version>6.0.6</org.springframework.version>
<org.springframework.data.version>3.0.3</org.springframework.data.version>
<hibernate-core.version>6.1.7.Final</hibernate-core.version>
<maven.deploy.skip>true</maven.deploy.skip>
<tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version>
</properties>

View File

@ -2,9 +2,9 @@ package com.baeldung.hibernate.creationupdatetimestamp.model;
import java.time.Instant;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

View File

@ -1,11 +1,11 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.type.IntegerType;
import org.hibernate.type.StringType;
import org.hibernate.type.Type;
import org.hibernate.metamodel.spi.ValueAccess;
import org.hibernate.usertype.CompositeUserType;
import org.hibernate.usertype.UserType;
import java.io.Serializable;
import java.sql.PreparedStatement;
@ -14,74 +14,51 @@ import java.sql.SQLException;
import java.sql.Types;
import java.util.Objects;
public class AddressType implements CompositeUserType {
public class AddressType implements CompositeUserType<Address>, UserType<Address> {
@Override
public String[] getPropertyNames() {
return new String[]{"addressLine1", "addressLine2",
"city", "country", "zipcode"};
}
@Override
public Type[] getPropertyTypes() {
return new Type[]{StringType.INSTANCE, StringType.INSTANCE,
StringType.INSTANCE, StringType.INSTANCE, IntegerType.INSTANCE};
}
@Override
public Object getPropertyValue(Object component, int property) throws HibernateException {
Address empAdd = (Address) component;
public Object getPropertyValue(Address component, int property) throws HibernateException {
switch (property) {
case 0:
return empAdd.getAddressLine1();
return component.getAddressLine1();
case 1:
return empAdd.getAddressLine2();
return component.getAddressLine2();
case 2:
return empAdd.getCity();
return component.getCity();
case 3:
return empAdd.getCountry();
return component.getCountry();
case 4:
return Integer.valueOf(empAdd.getZipCode());
return component.getZipCode();
default:
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
}
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
}
@Override
public void setPropertyValue(Object component, int property, Object value) throws HibernateException {
Address empAdd = (Address) component;
switch (property) {
case 0:
empAdd.setAddressLine1((String) value);
case 1:
empAdd.setAddressLine2((String) value);
case 2:
empAdd.setCity((String) value);
case 3:
empAdd.setCountry((String) value);
case 4:
empAdd.setZipCode((Integer) value);
}
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
public Address instantiate(ValueAccess values, SessionFactoryImplementor sessionFactory) {
return null;
}
@Override
public Class returnedClass() {
public Class<?> embeddable() {
return Address.class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
public int getSqlType() {
return Types.VARCHAR;
}
@Override
public Class<Address> returnedClass() {
return Address.class;
}
@Override
public boolean equals(Address x, Address y) {
if (x == y)
return true;
@ -92,57 +69,52 @@ public class AddressType implements CompositeUserType {
}
@Override
public int hashCode(Object x) throws HibernateException {
public int hashCode(Address x) {
return x.hashCode();
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
public Address nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException {
Address empAdd = new Address();
empAdd.setAddressLine1(rs.getString(names[0]));
empAdd.setAddressLine1(rs.getString(position));
if (rs.wasNull())
return null;
empAdd.setAddressLine2(rs.getString(names[1]));
empAdd.setCity(rs.getString(names[2]));
empAdd.setCountry(rs.getString(names[3]));
empAdd.setZipCode(rs.getInt(names[4]));
empAdd.setAddressLine2(rs.getString(position));
empAdd.setCity(rs.getString(position));
empAdd.setCountry(rs.getString(position));
empAdd.setZipCode(rs.getInt(position));
return empAdd;
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
public void nullSafeSet(PreparedStatement st, Address value, int index, SharedSessionContractImplementor session) throws SQLException {
if (Objects.isNull(value))
st.setNull(index, Types.VARCHAR);
else {
Address empAdd = (Address) value;
st.setString(index, empAdd.getAddressLine1());
st.setString(index + 1, empAdd.getAddressLine2());
st.setString(index + 2, empAdd.getCity());
st.setString(index + 3, empAdd.getCountry());
st.setInt(index + 4, empAdd.getZipCode());
st.setString(index, value.getAddressLine1());
st.setString(index + 1, value.getAddressLine2());
st.setString(index + 2, value.getCity());
st.setString(index + 3, value.getCountry());
st.setInt(index + 4, value.getZipCode());
}
}
@Override
public Object deepCopy(Object value) throws HibernateException {
public Address deepCopy(Address value) {
if (Objects.isNull(value))
return null;
Address oldEmpAdd = (Address) value;
Address newEmpAdd = new Address();
newEmpAdd.setAddressLine1(oldEmpAdd.getAddressLine1());
newEmpAdd.setAddressLine2(oldEmpAdd.getAddressLine2());
newEmpAdd.setCity(oldEmpAdd.getCity());
newEmpAdd.setCountry(oldEmpAdd.getCountry());
newEmpAdd.setZipCode(oldEmpAdd.getZipCode());
newEmpAdd.setAddressLine1(value.getAddressLine1());
newEmpAdd.setAddressLine2(value.getAddressLine2());
newEmpAdd.setCity(value.getCity());
newEmpAdd.setCountry(value.getCountry());
newEmpAdd.setZipCode(value.getZipCode());
return newEmpAdd;
}
@ -153,17 +125,27 @@ public class AddressType implements CompositeUserType {
}
@Override
public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException {
public Serializable disassemble(Address value) {
return (Serializable) deepCopy(value);
}
@Override
public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException {
return deepCopy(cached);
public Address assemble(Serializable cached, Object owner) {
return deepCopy((Address) cached);
}
@Override
public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException {
return original;
public Address replace(Address detached, Address managed, Object owner) {
return detached;
}
@Override
public boolean isInstance(Object object, SessionFactoryImplementor sessionFactory) {
return CompositeUserType.super.isInstance(object, sessionFactory);
}
@Override
public boolean isSameClass(Object object, SessionFactoryImplementor sessionFactory) {
return CompositeUserType.super.isSameClass(object, sessionFactory);
}
}

View File

@ -1,14 +1,14 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.type.LocalDateType;
import org.hibernate.type.descriptor.WrapperOptions;
import org.hibernate.type.descriptor.java.AbstractTypeDescriptor;
import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan;
import org.hibernate.type.descriptor.java.MutabilityPlan;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor<LocalDate> {
import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayTypeDescriptor;
public class LocalDateStringJavaDescriptor extends AbstractArrayTypeDescriptor<LocalDate> {
public static final LocalDateStringJavaDescriptor INSTANCE = new LocalDateStringJavaDescriptor();
@ -18,12 +18,12 @@ public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor<LocalD
@Override
public String toString(LocalDate value) {
return LocalDateType.FORMATTER.format(value);
return DateTimeFormatter.ISO_LOCAL_DATE.format(value);
}
@Override
public LocalDate fromString(String string) {
return LocalDate.from(LocalDateType.FORMATTER.parse(string));
public LocalDate fromString(CharSequence string) {
return LocalDate.from( DateTimeFormatter.ISO_LOCAL_DATE.parse(string));
}
@Override
@ -33,7 +33,7 @@ public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor<LocalD
return null;
if (String.class.isAssignableFrom(type))
return (X) LocalDateType.FORMATTER.format(value);
return (X) DateTimeFormatter.ISO_LOCAL_DATE.format(value);
throw unknownUnwrap(type);
}
@ -44,7 +44,7 @@ public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor<LocalD
return null;
if(String.class.isInstance(value))
return LocalDate.from(LocalDateType.FORMATTER.parse((CharSequence) value));
return LocalDate.from( DateTimeFormatter.ISO_LOCAL_DATE.parse((CharSequence) value));
throw unknownWrap(value.getClass());
}

View File

@ -2,18 +2,16 @@ package com.baeldung.hibernate.customtypes;
import org.hibernate.dialect.Dialect;
import org.hibernate.type.AbstractSingleColumnStandardBasicType;
import org.hibernate.type.DiscriminatorType;
import org.hibernate.type.descriptor.java.LocalDateJavaDescriptor;
import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor;
import org.hibernate.type.descriptor.jdbc.VarcharJdbcType;
import java.time.LocalDate;
public class LocalDateStringType extends AbstractSingleColumnStandardBasicType<LocalDate> implements DiscriminatorType<LocalDate> {
public class LocalDateStringType extends AbstractSingleColumnStandardBasicType<LocalDate> {
public static final LocalDateStringType INSTANCE = new LocalDateStringType();
public LocalDateStringType() {
super(VarcharTypeDescriptor.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE);
super(VarcharJdbcType.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE);
}
@Override
@ -21,14 +19,12 @@ public class LocalDateStringType extends AbstractSingleColumnStandardBasicType<L
return "LocalDateString";
}
@Override
public LocalDate stringToObject(String xml) throws Exception {
public LocalDate stringToObject(String xml) {
return fromString(xml);
}
@Override
public String objectToSQLString(LocalDate value, Dialect dialect) throws Exception {
return '\'' + toString(value) + '\'';
public String objectToSQLString(LocalDate value, Dialect dialect) {
return '\'' + LocalDateStringJavaDescriptor.INSTANCE.toString(value) + '\'';
}
}

View File

@ -1,20 +1,19 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.annotations.Columns;
import org.hibernate.annotations.CompositeType;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import org.hibernate.usertype.UserTypeLegacyBridge;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import jakarta.persistence.AttributeOverride;
import jakarta.persistence.AttributeOverrides;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.time.LocalDate;
@TypeDef(name = "PhoneNumber",
typeClass = PhoneNumberType.class,
defaultForType = PhoneNumber.class)
@Entity
@Table(name = "OfficeEmployee")
public class OfficeEmployee {
@ -24,25 +23,36 @@ public class OfficeEmployee {
private long id;
@Column
@Type(type = "LocalDateString")
@Type(
value = UserTypeLegacyBridge.class,
parameters = @Parameter(name = UserTypeLegacyBridge.TYPE_NAME_PARAM_KEY, value = "LocalDateString")
)
private LocalDate dateOfJoining;
@Columns(columns = {@Column(name = "country_code"),
@Column(name = "city_code"),
@Column(name = "number")})
@AttributeOverrides({
@AttributeOverride(name = "countryCode", column = @Column(name = "country_code")),
@AttributeOverride(name = "cityCode", column = @Column(name = "city_code")),
@AttributeOverride(name = "number", column = @Column(name = "number"))
})
@Type(value = PhoneNumberType.class)
private PhoneNumber employeeNumber;
@Columns(columns = {@Column(name = "address_line_1"),
@Column(name = "address_line_2"),
@Column(name = "city"), @Column(name = "country"),
@Column(name = "zip_code")})
@Type(type = "com.baeldung.hibernate.customtypes.AddressType")
@CompositeType(value = com.baeldung.hibernate.customtypes.AddressType.class)
@AttributeOverrides({
@AttributeOverride(name = "addressLine1", column = @Column(name = "address_line_1")),
@AttributeOverride(name = "addressLine2", column = @Column(name = "address_line_2")),
@AttributeOverride(name = "city", column = @Column(name = "city")),
@AttributeOverride(name = "country", column = @Column(name = "country")),
@AttributeOverride(name = "zipCode", column = @Column(name = "zip_code"))
})
private Address empAddress;
@Type(type = "com.baeldung.hibernate.customtypes.SalaryType",
@Type(value = com.baeldung.hibernate.customtypes.SalaryType.class,
parameters = {@Parameter(name = "currency", value = "USD")})
@Columns(columns = {@Column(name = "amount"),
@Column(name = "currency")})
@AttributeOverrides({
@AttributeOverride(name = "amount", column = @Column(name = "amount")),
@AttributeOverride(name = "currency", column = @Column(name = "currency"))
})
private Salary salary;
public Salary getSalary() {

View File

@ -2,11 +2,11 @@ package com.baeldung.hibernate.customtypes;
import java.util.Objects;
public final class PhoneNumber {
public class PhoneNumber {
private final int countryCode;
private final int cityCode;
private final int number;
private int countryCode;
private int cityCode;
private int number;
public PhoneNumber(int countryCode, int cityCode, int number) {
this.countryCode = countryCode;

View File

@ -1,6 +1,5 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.UserType;
@ -11,11 +10,11 @@ import java.sql.SQLException;
import java.sql.Types;
import java.util.Objects;
public class PhoneNumberType implements UserType<PhoneNumber> {
public class PhoneNumberType implements UserType {
@Override
public int[] sqlTypes() {
return new int[]{Types.INTEGER, Types.INTEGER, Types.INTEGER};
public int getSqlType() {
return Types.INTEGER;
}
@Override
@ -24,7 +23,7 @@ public class PhoneNumberType implements UserType {
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
public boolean equals(PhoneNumber x, PhoneNumber y) {
if (x == y)
return true;
if (Objects.isNull(x) || Objects.isNull(y))
@ -34,48 +33,42 @@ public class PhoneNumberType implements UserType {
}
@Override
public int hashCode(Object x) throws HibernateException {
public int hashCode(PhoneNumber x) {
return x.hashCode();
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
int countryCode = rs.getInt(names[0]);
public PhoneNumber nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException {
int countryCode = rs.getInt(position);
if (rs.wasNull())
return null;
int cityCode = rs.getInt(names[1]);
int number = rs.getInt(names[2]);
PhoneNumber employeeNumber = new PhoneNumber(countryCode, cityCode, number);
int cityCode = rs.getInt(position);
int number = rs.getInt(position);
return employeeNumber;
return new PhoneNumber(countryCode, cityCode, number);
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
public void nullSafeSet(PreparedStatement st, PhoneNumber value, int index, SharedSessionContractImplementor session) throws SQLException {
if (Objects.isNull(value)) {
st.setNull(index, Types.INTEGER);
st.setNull(index+1, Types.INTEGER);
st.setNull(index+2, Types.INTEGER);
} else {
PhoneNumber employeeNumber = (PhoneNumber) value;
st.setInt(index,employeeNumber.getCountryCode());
st.setInt(index+1,employeeNumber.getCityCode());
st.setInt(index+2,employeeNumber.getNumber());
st.setInt(index, value.getCountryCode());
st.setInt(index+1, value.getCityCode());
st.setInt(index+2, value.getNumber());
}
}
@Override
public Object deepCopy(Object value) throws HibernateException {
public PhoneNumber deepCopy(PhoneNumber value) {
if (Objects.isNull(value))
return null;
PhoneNumber empNumber = (PhoneNumber) value;
PhoneNumber newEmpNumber = new PhoneNumber(empNumber.getCountryCode(),empNumber.getCityCode(),empNumber.getNumber());
return newEmpNumber;
return new PhoneNumber(value.getCountryCode(), value.getCityCode(), value.getNumber());
}
@Override
@ -84,17 +77,17 @@ public class PhoneNumberType implements UserType {
}
@Override
public Serializable disassemble(Object value) throws HibernateException {
public Serializable disassemble(PhoneNumber value) {
return (Serializable) value;
}
@Override
public Object assemble(Serializable cached, Object owner) throws HibernateException {
return cached;
public PhoneNumber assemble(Serializable cached, Object owner) {
return (PhoneNumber) cached;
}
@Override
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
public PhoneNumber replace(PhoneNumber detached, PhoneNumber managed, Object owner) {
return detached;
}
}

View File

@ -1,12 +1,12 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.type.LongType;
import org.hibernate.type.StringType;
import org.hibernate.type.Type;
import org.hibernate.metamodel.spi.ValueAccess;
import org.hibernate.usertype.CompositeUserType;
import org.hibernate.usertype.DynamicParameterizedType;
import org.hibernate.usertype.UserType;
import java.io.Serializable;
import java.sql.PreparedStatement;
@ -16,65 +16,47 @@ import java.sql.Types;
import java.util.Objects;
import java.util.Properties;
public class SalaryType implements CompositeUserType, DynamicParameterizedType {
public class SalaryType implements UserType<Salary>, CompositeUserType<Salary>, DynamicParameterizedType {
private String localCurrency;
@Override
public String[] getPropertyNames() {
return new String[]{"amount", "currency"};
}
@Override
public Type[] getPropertyTypes() {
return new Type[]{LongType.INSTANCE, StringType.INSTANCE};
}
@Override
public Object getPropertyValue(Object component, int property) throws HibernateException {
Salary salary = (Salary) component;
public Object getPropertyValue(Salary component, int property) throws HibernateException {
switch (property) {
case 0:
return salary.getAmount();
return component.getAmount();
case 1:
return salary.getCurrency();
return component.getCurrency();
default:
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
}
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
}
@Override
public void setPropertyValue(Object component, int property, Object value) throws HibernateException {
Salary salary = (Salary) component;
switch (property) {
case 0:
salary.setAmount((Long) value);
case 1:
salary.setCurrency((String) value);
}
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
}
@Override
public Class returnedClass() {
public Salary instantiate(ValueAccess values, SessionFactoryImplementor sessionFactory) {
return null;
}
@Override
public Class<?> embeddable() {
return Salary.class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
public int getSqlType() {
return Types.BIGINT;
}
@Override
public Class<Salary> returnedClass() {
return Salary.class;
}
@Override
public boolean equals(Salary x, Salary y) {
if (x == y)
return true;
@ -82,54 +64,48 @@ public class SalaryType implements CompositeUserType, DynamicParameterizedType {
return false;
return x.equals(y);
}
@Override
public int hashCode(Object x) throws HibernateException {
public int hashCode(Salary x) {
return x.hashCode();
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
public Salary nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException {
Salary salary = new Salary();
salary.setAmount(rs.getLong(names[0]));
salary.setAmount(rs.getLong(position));
if (rs.wasNull())
return null;
salary.setCurrency(rs.getString(names[1]));
salary.setCurrency(rs.getString(position));
return salary;
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
public void nullSafeSet(PreparedStatement st, Salary value, int index, SharedSessionContractImplementor session) throws SQLException {
if (Objects.isNull(value))
st.setNull(index, Types.BIGINT);
else {
Salary salary = (Salary) value;
st.setLong(index, SalaryCurrencyConvertor.convert(salary.getAmount(),
salary.getCurrency(), localCurrency));
st.setString(index + 1, salary.getCurrency());
st.setLong(index, SalaryCurrencyConvertor.convert(
value.getAmount(),
value.getCurrency(), localCurrency));
st.setString(index + 1, value.getCurrency());
}
}
@Override
public Object deepCopy(Object value) throws HibernateException {
public Salary deepCopy(Salary value) {
if (Objects.isNull(value))
return null;
Salary oldSal = (Salary) value;
Salary newSal = new Salary();
newSal.setAmount(oldSal.getAmount());
newSal.setCurrency(oldSal.getCurrency());
newSal.setAmount(value.getAmount());
newSal.setCurrency(value.getCurrency());
return newSal;
}
@ -140,18 +116,18 @@ public class SalaryType implements CompositeUserType, DynamicParameterizedType {
}
@Override
public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException {
public Serializable disassemble(Salary value) {
return (Serializable) deepCopy(value);
}
@Override
public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException {
return deepCopy(cached);
public Salary assemble(Serializable cached, Object owner) {
return deepCopy((Salary) cached);
}
@Override
public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException {
return original;
public Salary replace(Salary detached, Salary managed, Object owner) {
return detached;
}
@Override

View File

@ -4,7 +4,7 @@ import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.Immutable;
import javax.persistence.*;
import jakarta.persistence.*;
import java.util.Set;
@Entity

View File

@ -3,7 +3,7 @@ package com.baeldung.hibernate.immutable.entities;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Immutable;
import javax.persistence.*;
import jakarta.persistence.*;
@Entity
@Immutable

View File

@ -1,12 +1,12 @@
package com.baeldung.hibernate.joincolumn;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
@Entity
public class Email {

View File

@ -1,13 +1,13 @@
package com.baeldung.hibernate.joincolumn;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.JoinColumns;
import jakarta.persistence.ManyToOne;
@Entity
public class Office {

View File

@ -1,10 +1,10 @@
package com.baeldung.hibernate.joincolumn;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class OfficeAddress {

View File

@ -1,12 +1,12 @@
package com.baeldung.hibernate.joincolumn;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
@Entity
public class OfficialEmployee {

View File

@ -3,12 +3,12 @@ package com.baeldung.hibernate.lazycollection.model;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OrderColumn;
import javax.persistence.OneToMany;
import javax.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OrderColumn;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Entity;
import java.util.ArrayList;
import java.util.List;

View File

@ -1,11 +1,10 @@
package com.baeldung.hibernate.lazycollection.model;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OrderColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Entity;
@Entity
public class Employee {

View File

@ -43,8 +43,8 @@ public class HibernateAnnotationUtil {
return metadata.buildSessionFactory();
}
private static Map<String, String> dbSettings() {
Map<String, String> dbSettings = new HashMap<>();
private static Map<String, Object> dbSettings() {
Map<String, Object> dbSettings = new HashMap<>();
dbSettings.put(Environment.URL, "jdbc:h2:mem:spring_hibernate_one_to_many");
dbSettings.put(Environment.USER, "sa");
dbSettings.put(Environment.PASS, "");

View File

@ -2,13 +2,13 @@ package com.baeldung.hibernate.oneToMany.model;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
@Entity
@Table(name = "CART")

View File

@ -1,13 +1,13 @@
package com.baeldung.hibernate.oneToMany.model;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
@Entity
@Table(name = "CARTOIO")

View File

@ -1,13 +1,13 @@
package com.baeldung.hibernate.oneToMany.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
@Entity
@Table(name = "ITEMS")

View File

@ -1,12 +1,12 @@
package com.baeldung.hibernate.oneToMany.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
@Entity
@Table(name = "ITEMSOIO")

View File

@ -1,9 +1,9 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import java.io.Serializable;
@Entity

View File

@ -3,10 +3,10 @@ package com.baeldung.hibernate.wherejointable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToMany;
@Entity(name = "e_group")
public class Group {

View File

@ -3,12 +3,12 @@ package com.baeldung.hibernate.wherejointable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.JoinTable;
import jakarta.persistence.ManyToMany;
import org.hibernate.annotations.WhereJoinTable;

View File

@ -2,11 +2,11 @@ package com.baeldung.hibernate.wherejointable;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.Id;
@Entity(name = "r_user_group")
public class UserGroupRelation implements Serializable {

View File

@ -7,12 +7,12 @@
<description>Hibernate EntityManager Demo</description>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/moviecatalog"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="jakarta.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/moviecatalog"/>
<property name="jakarta.persistence.jdbc.user" value="root"/>
<property name="jakarta.persistence.jdbc.password" value="root"/>
</properties>
</persistence-unit>
</persistence>

View File

@ -1,5 +1,6 @@
package com.baeldung.hibernate.creationupdatetimestamp;
import static org.hibernate.FlushMode.MANUAL;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@ -71,22 +72,22 @@ class HibernateCreationUpdateTimestampIntegrationTest {
}
@Test
void whenCreatingEntity_ThenCreatedOnAndLastUpdatedOnAreNotEqual() {
void whenCreatingEntity_ThenCreatedOnAndLastUpdatedOnAreEqual() {
session = sessionFactory.openSession();
session.beginTransaction();
Book book = new Book();
session.save(book);
session.getTransaction()
.commit();
session.getTransaction().commit();
session.close();
assertNotEquals(book.getCreatedOn(), book.getLastUpdatedOn());
assertEquals(book.getCreatedOn(), book.getLastUpdatedOn());
}
@Test
void whenUpdatingEntity_ThenLastUpdatedOnIsUpdatedAndCreatedOnStaysTheSame() {
session = sessionFactory.openSession();
session.setHibernateFlushMode(MANUAL);
session.beginTransaction();
Book book = new Book();
session.save(book);
@ -96,8 +97,9 @@ class HibernateCreationUpdateTimestampIntegrationTest {
String newName = "newName";
book.setTitle(newName);
session.getTransaction()
.commit();
session.save(book);
session.flush();
session.getTransaction().commit();
session.close();
Instant createdOnAfterUpdate = book.getCreatedOn();
Instant lastUpdatedOnAfterUpdate = book.getLastUpdatedOn();

View File

@ -6,10 +6,9 @@ import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
import org.junit.Assert;
import org.junit.Test;
import javax.persistence.TypedQuery;
import jakarta.persistence.TypedQuery;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
@ -76,7 +75,7 @@ public class HibernateCustomTypesIntegrationTest {
doInHibernate(this::sessionFactory, session -> {
session.save(e);
TypedQuery<OfficeEmployee> query = session.createQuery("FROM OfficeEmployee OE WHERE OE.empAddress.zipcode = :pinCode", OfficeEmployee.class);
TypedQuery<OfficeEmployee> query = session.createQuery("FROM OfficeEmployee OE WHERE OE.empAddress.zipCode = :pinCode", OfficeEmployee.class);
query.setParameter("pinCode",100);
int size = query.getResultList().size();
@ -100,8 +99,8 @@ public class HibernateCustomTypesIntegrationTest {
return metadata.buildSessionFactory();
}
private static Map<String, String> getProperties() {
Map<String, String> dbSettings = new HashMap<>();
private static Map<String, Object> getProperties() {
Map<String, Object> dbSettings = new HashMap<>();
dbSettings.put(Environment.URL, "jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1");
dbSettings.put(Environment.USER, "sa");
dbSettings.put(Environment.PASS, "");

View File

@ -8,7 +8,7 @@ import org.hibernate.Session;
import org.junit.*;
import org.junit.rules.ExpectedException;
import javax.persistence.PersistenceException;
import jakarta.persistence.PersistenceException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;

View File

@ -78,8 +78,8 @@ public class JoinColumnIntegrationTest {
return metadata.buildSessionFactory();
}
private static Map<String, String> getProperties() {
Map<String, String> dbSettings = new HashMap<>();
private static Map<String, Object> getProperties() {
Map<String, Object> dbSettings = new HashMap<>();
dbSettings.put(Environment.URL, "jdbc:h2:mem:mydbJoinColumn;DB_CLOSE_DELAY=-1");
dbSettings.put(Environment.USER, "sa");
dbSettings.put(Environment.PASS, "");

View File

@ -78,10 +78,11 @@
</repositories>
<properties>
<hibernate.version>5.3.7.Final</hibernate.version>
<mysql.version>6.0.6</mysql.version>
<mariaDB4j.version>2.2.3</mariaDB4j.version>
<hibernate.version>6.1.7.Final</hibernate.version>
<mysql.version>8.0.32</mysql.version>
<mariaDB4j.version>2.6.0</mariaDB4j.version>
<geodb.version>0.9</geodb.version>
<byte-buddy.version>1.14.2</byte-buddy.version>
</properties>
</project>

View File

@ -1,6 +1,6 @@
package com.baeldung.hibernate.exception;
import javax.persistence.Entity;
import jakarta.persistence.Entity;
@Entity
public class EntityWithNoId {

View File

@ -1,9 +1,9 @@
package com.baeldung.hibernate.exception;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "PRODUCT")

View File

@ -1,8 +1,8 @@
package com.baeldung.hibernate.exception;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "PRODUCT")

View File

@ -0,0 +1,32 @@
package com.baeldung.hibernate.exception;
public class ProductNotMapped {
private int id;
private String name;
private String description;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@ -1,9 +1,9 @@
package com.baeldung.hibernate.logging;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Employee {

View File

@ -1,11 +1,11 @@
package com.baeldung.hibernate.pojo;
import com.vividsolutions.jts.geom.Point;
import org.locationtech.jts.geom.Point;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
@Entity
public class PointEntity {

View File

@ -1,10 +1,10 @@
package com.baeldung.hibernate.pojo;
import com.vividsolutions.jts.geom.Polygon;
import org.locationtech.jts.geom.Polygon;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
@Entity
public class PolygonEntity {

View File

@ -1,9 +1,9 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Student {

View File

@ -1,8 +1,8 @@
package com.baeldung.persistence.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
@Entity
public class Person {

View File

@ -7,12 +7,12 @@
<description>Hibernate EntityManager Demo</description>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/moviecatalog"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="jakarta.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/moviecatalog"/>
<property name="jakarta.persistence.jdbc.user" value="root"/>
<property name="jakarta.persistence.jdbc.password" value="root"/>
</properties>
</persistence-unit>
</persistence>

View File

@ -9,23 +9,23 @@ import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import javax.persistence.Query;
import jakarta.persistence.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.util.GeometricShapeFactory;
import com.baeldung.hibernate.pojo.PointEntity;
import com.baeldung.hibernate.pojo.PolygonEntity;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import com.vividsolutions.jts.util.GeometricShapeFactory;
import geodb.GeoDB;
@ -39,7 +39,7 @@ public class HibernateSpatialIntegrationTest {
session = HibernateUtil.getSessionFactory("hibernate-spatial.properties")
.openSession();
transaction = session.beginTransaction();
session.doWork(conn -> { GeoDB.InitGeoDB(conn); });
session.doWork(GeoDB::InitGeoDB);
}
@After
@ -135,9 +135,7 @@ public class HibernateSpatialIntegrationTest {
private Geometry wktToGeometry(String wellKnownText) throws ParseException {
WKTReader fromText = new WKTReader();
Geometry geom = null;
geom = fromText.read(wellKnownText);
return geom;
return fromText.read(wellKnownText);
}
private static Geometry createCircle(double x, double y, double radius) {

View File

@ -6,28 +6,25 @@ import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.util.List;
import javax.persistence.OptimisticLockException;
import javax.persistence.PersistenceException;
import jakarta.persistence.OptimisticLockException;
import jakarta.persistence.PersistenceException;
import org.hibernate.AnnotationException;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.NonUniqueObjectException;
import org.hibernate.PropertyValueException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StaleObjectStateException;
import org.hibernate.StaleStateException;
import org.hibernate.Transaction;
import org.hibernate.TransactionException;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.DataException;
import org.hibernate.exception.SQLGrammarException;
import org.hibernate.hql.internal.ast.QuerySyntaxException;
import org.hibernate.id.IdentifierGenerationException;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.sqm.UnknownEntityException;
import org.hibernate.tool.schema.spi.CommandAcceptanceException;
import org.hibernate.tool.schema.spi.SchemaManagementException;
import org.junit.Before;
@ -63,12 +60,15 @@ public class HibernateExceptionUnitTest {
@Test
public void whenQueryExecutedWithUnmappedEntity_thenMappingException() {
thrown.expectCause(isA(MappingException.class));
thrown.expectMessage("Unknown entity: java.lang.String");
thrown.expect(isA(MappingException.class));
thrown.expectMessage("Unable to locate persister: com.baeldung.hibernate.exception.ProductNotMapped");
ProductNotMapped product = new ProductNotMapped();
product.setId(1);
product.setName("test");
Session session = sessionFactory.openSession();
NativeQuery<String> query = session.createNativeQuery("select name from PRODUCT", String.class);
query.getResultList();
session.save(product);
}
@Test
@ -82,8 +82,8 @@ public class HibernateExceptionUnitTest {
@Test
public void whenQueryExecutedWithInvalidClassName_thenQuerySyntaxException() {
thrown.expectCause(isA(QuerySyntaxException.class));
thrown.expectMessage("PRODUCT is not mapped [from PRODUCT]");
thrown.expectCause(isA(UnknownEntityException.class));
thrown.expectMessage("Could not resolve root entity 'PRODUCT");
Session session = sessionFactory.openSession();
List<Product> results = session.createQuery("from PRODUCT", Product.class)
@ -92,8 +92,8 @@ public class HibernateExceptionUnitTest {
@Test
public void givenEntityWithoutId_whenSessionFactoryCreated_thenAnnotationException() {
thrown.expect(AnnotationException.class);
thrown.expectMessage("No identifier specified for entity");
thrown.expect(isA(HibernateException.class));
thrown.expectMessage("Entity 'com.baeldung.hibernate.exception.EntityWithNoId' has no identifier (every '@Entity' class must declare or inherit at least one '@Id' or '@EmbeddedId' property)");
Configuration cfg = getConfiguration();
cfg.addAnnotatedClass(EntityWithNoId.class);
@ -132,9 +132,8 @@ public class HibernateExceptionUnitTest {
@Test
public void givenMissingTable_whenEntitySaved_thenSQLGrammarException() {
thrown.expect(isA(PersistenceException.class));
thrown.expectCause(isA(SQLGrammarException.class));
thrown.expectMessage("SQLGrammarException: could not prepare statement");
thrown.expectMessage("could not prepare statement");
Configuration cfg = getConfiguration();
cfg.addAnnotatedClass(Product.class);
@ -162,9 +161,8 @@ public class HibernateExceptionUnitTest {
@Test
public void givenMissingTable_whenQueryExecuted_thenSQLGrammarException() {
thrown.expect(isA(PersistenceException.class));
thrown.expectCause(isA(SQLGrammarException.class));
thrown.expectMessage("SQLGrammarException: could not prepare statement");
thrown.expectMessage("could not prepare statement");
Session session = sessionFactory.openSession();
NativeQuery<Product> query = session.createNativeQuery("select * from NON_EXISTING_TABLE", Product.class);
@ -173,9 +171,8 @@ public class HibernateExceptionUnitTest {
@Test
public void whenDuplicateIdSaved_thenConstraintViolationException() {
thrown.expect(isA(PersistenceException.class));
thrown.expectCause(isA(ConstraintViolationException.class));
thrown.expectMessage("ConstraintViolationException: could not execute statement");
thrown.expectMessage("could not execute statement");
Session session = null;
Transaction transaction = null;
@ -253,7 +250,7 @@ public class HibernateExceptionUnitTest {
@Test
public void givenQueryWithDataTypeMismatch_WhenQueryExecuted_thenDataException() {
thrown.expectCause(isA(DataException.class));
thrown.expectMessage("org.hibernate.exception.DataException: could not prepare statement");
thrown.expectMessage("could not prepare statement");
Session session = sessionFactory.openSession();
NativeQuery<Product> query = session.createNativeQuery("select * from PRODUCT where id='wrongTypeId'", Product.class);
@ -330,9 +327,8 @@ public class HibernateExceptionUnitTest {
@Test
public void whenUpdatingNonExistingObject_thenStaleStateException() {
thrown.expect(isA(OptimisticLockException.class));
thrown.expectMessage("Row was updated or deleted by another transaction");
thrown.expectCause(isA(StaleObjectStateException.class));
thrown.expectCause(isA(StaleStateException.class));
thrown.expectMessage("Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; statement executed: update PRODUCT set description=?, name=? where id=?");
Session session = null;
Transaction transaction = null;
@ -356,7 +352,8 @@ public class HibernateExceptionUnitTest {
@Test
public void givenTxnMarkedRollbackOnly_whenCommitted_thenTransactionException() {
thrown.expect(isA(TransactionException.class));
thrown.expect(isA(IllegalStateException.class));
thrown.expectMessage("Transaction already active");
Session session = null;
Transaction transaction = null;
@ -368,6 +365,7 @@ public class HibernateExceptionUnitTest {
product1.setId(15);
product1.setName("Product1");
session.save(product1);
transaction = session.beginTransaction();
transaction.setRollbackOnly();
transaction.commit();

View File

@ -2,9 +2,9 @@ package com.baeldung.hibernate.multitenancy;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity(name = "Car")
@Table(name = "Car")

View File

@ -79,9 +79,9 @@ public abstract class MultitenancyIntegrationTest {
private void createCarTable() {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.createSQLQuery("drop table Car if exists")
session.createNativeQuery("drop table Car if exists")
.executeUpdate();
session.createSQLQuery("create table Car (brand varchar(255) primary key)")
session.createNativeQuery("create table Car (brand varchar(255) primary key)")
.executeUpdate();
tx.commit();
}

View File

@ -1,7 +1,5 @@
package com.baeldung.hibernate.multitenancy.database;
import java.io.IOException;
import org.junit.Test;
import com.baeldung.hibernate.multitenancy.MultitenancyIntegrationTest;
@ -14,7 +12,7 @@ public class DatabaseApproachMultitenancyIntegrationTest extends MultitenancyInt
}
@Test
public void givenDatabaseApproach_whenAddingEntries_thenOnlyAddedToConcreteDatabase() throws IOException {
public void givenDatabaseApproach_whenAddingEntries_thenOnlyAddedToConcreteDatabase() {
whenCurrentTenantIs(TenantIdNames.MYDB1);
whenAddCar("myCar");
thenCarFound("myCar");

View File

@ -34,8 +34,13 @@ public class MapMultiTenantConnectionProvider extends AbstractMultiTenantConnect
private void initConnectionProviderForTenant(String tenantId) throws IOException {
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream(String.format("/hibernate-database-%s.properties", tenantId)));
Map<String, Object> configProperties = new HashMap<>();
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
configProperties.put(key, value);
}
DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl();
connectionProvider.configure(properties);
connectionProvider.configure(configProperties);
this.connectionProviderMap.put(tenantId, connectionProvider);
}

View File

@ -3,6 +3,8 @@ package com.baeldung.hibernate.multitenancy.schema;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
@ -39,9 +41,14 @@ public class SchemaMultiTenantConnectionProvider extends AbstractMultiTenantConn
private ConnectionProvider initConnectionProvider() throws IOException {
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("/hibernate-schema-multitenancy.properties"));
Map<String, Object> configProperties = new HashMap<>();
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
configProperties.put(key, value);
}
DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl();
connectionProvider.configure(properties);
connectionProvider.configure(configProperties);
return connectionProvider;
}

View File

@ -7,7 +7,7 @@ import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import javax.persistence.PersistenceException;
import jakarta.persistence.PersistenceException;
import org.hibernate.HibernateException;
import org.hibernate.Session;

View File

@ -12,5 +12,3 @@ hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=5
hibernate.c3p0.timeout=1800
hibernate.transaction.factory_class=org.hibernate.transaction.JTATransactionFactory

View File

@ -4,7 +4,7 @@ hibernate.connection.username=sa
hibernate.connection.autocommit=true
jdbc.password=
hibernate.dialect=org.hibernate.spatial.dialect.h2geodb.GeoDBDialect
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop

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