Merge remote-tracking branch 'upstream/master' into feature/BAEL-6695-BooleanValidation

This commit is contained in:
Niket Agrawal 2023-09-26 18:54:18 +05:30
commit 74c42deb4e
508 changed files with 3836 additions and 721 deletions

38
.github/ISSUE_TEMPLATE/issue_report.md vendored Normal file
View File

@ -0,0 +1,38 @@
---
name: Issue Report
about: Report an issue to help us improve
title: '[ISSUE] '
---
**Article and Module Links**
A link to the affected article and the affected module. The link to the module is the one in the "over on GitHub" standard phrase.
**Describe the Issue**
A clear and concise description of what the issue is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected Behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Environment (please complete the following information):**
- OS: [e.g. Windows]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Additional Context**
Add any other context about the issue here.
Note that, unfortunately, we can only help with issues that are specifically and directly related to the article - not with your own, custom application.
StackOverflow is a great place to ask more general questions.
That's primarily because we get a large number of questions and - while we do try to go through as much as everything and help wherever we can, we can't really get back to all of them.

11
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,11 @@
# Contributing to Baeldung Tutorials
First off, thank you for considering contributing to Baeldung Tutorials.
## Reporting Issues
Before you submit an issue, please review the guidelines below:
1. **No Custom Modifications:** If your issue arises from any custom modifications you've made to the code in the repository, we won't be able to assist. We can only help if the issue is reproducible with the untouched codebase from this repo. If you're working with a modified version, consider asking for help on StackOverflow or other relevant forums.
2. **Use a clear and descriptive title** for the issue to identify the problem.
3. **Include a link to the article** you're having issues with.
4. **Describe the exact steps which reproduce the problem** in as many details as possible.
5. **Additional Details:** Offer any other context or descriptions that could be useful. Screenshots, error messages, copy/pasteable snippets, or logs can be immensely helpful.

97
apache-poi-3/pom.xml Normal file
View File

@ -0,0 +1,97 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
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>apache-poi-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apache-poi-3</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>${poi.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.ozlerhakan/poiji -->
<dependency>
<groupId>com.github.ozlerhakan</groupId>
<artifactId>poiji</artifactId>
<version>${poiji.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi/5.2.3 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas/4.1.2 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans/5.1.1 -->
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>5.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.dhatim/fastexcel/0.15.7 -->
<dependency>
<groupId>org.dhatim</groupId>
<artifactId>fastexcel</artifactId>
<version>${fastexcel.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.dhatim/fastexcel-reader/0.15.7 -->
<dependency>
<groupId>org.dhatim</groupId>
<artifactId>fastexcel-reader</artifactId>
<version>${fastexcel.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl/2.6.12 -->
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>${jxl.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.17.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.17.1</version>
</dependency>
</dependencies>
<properties>
<poi.version>5.2.3</poi.version>
<poiji.version>4.1.1</poiji.version>
<fastexcel.version>0.15.7</fastexcel.version>
<jxl.version>2.6.12</jxl.version>
</properties>
</project>

View File

@ -0,0 +1,54 @@
package com.baeldung.convert.exceldatatolist;
import com.poiji.annotation.ExcelCellName;
public class FoodInfo {
@ExcelCellName("Category")
private String category; //food category
@ExcelCellName("Name")
private String name; // food name
@ExcelCellName("Measure")
private String measure;
@ExcelCellName("Calories")
private double calories; //amount of calories in kcal/measure
@Override
public String toString() {
return "FoodInfo{" + "category='" + category + '\'' + ", name='" + name + '\'' + ", measure='" + measure + '\'' + ", calories=" + calories + "} \n";
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMeasure() {
return measure;
}
public void setMeasure(String measure) {
this.measure = measure;
}
public double getCalories() {
return calories;
}
public void setCalories(double calories) {
this.calories = calories;
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.convert.exceldatatolist.fastexcel;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;
import org.dhatim.fastexcel.reader.ReadableWorkbook;
import org.dhatim.fastexcel.reader.Row;
import org.dhatim.fastexcel.reader.Sheet;
import com.baeldung.convert.exceldatatolist.FoodInfo;
public class ExcelDataToListOfObjectsFastExcel {
public static List<FoodInfo> excelDataToListOfObjets_withFastExcel(String fileLocation)throws IOException, NumberFormatException {
List<FoodInfo> foodData = new ArrayList<FoodInfo>();
try (FileInputStream file = new FileInputStream(fileLocation);
ReadableWorkbook wb = new ReadableWorkbook(file)) {
Sheet sheet = wb.getFirstSheet();
for (Row row:
sheet.read()
) {
if(row.getRowNum() == 1) {
continue;
}
FoodInfo food = new FoodInfo();
food.setCategory(row.getCellText(0));
food.setName(row.getCellText(1));
food.setMeasure(row.getCellText(2));
food.setCalories(Double.parseDouble(row.getCellText(3)));
foodData.add(food);
}
}
return foodData;
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.convert.exceldatatolist.jexcelapi;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.convert.exceldatatolist.FoodInfo;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class ExcelDataToListOfObjectsJxl {
public static List<FoodInfo> excelDataToListOfObjets_withJxl(String fileLocation) throws IOException, BiffException {
List<FoodInfo> foodData = new ArrayList<FoodInfo>();
Workbook workbook = Workbook.getWorkbook(new File(fileLocation));
Sheet sheet = workbook.getSheet(0);
int rows = sheet.getRows();
for (int i = 1; i < rows; i++) {
FoodInfo foodInfo = new FoodInfo();
foodInfo.setCategory(sheet.getCell(0, i).getContents());
foodInfo.setName(sheet.getCell(1, i).getContents());
foodInfo.setMeasure(sheet.getCell(2, i).getContents());
foodInfo.setCalories(Double.parseDouble(sheet.getCell(3, i).getContents()));
foodData.add(foodInfo);
}
return foodData;
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.convert.exceldatatolist.poi;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.baeldung.convert.exceldatatolist.FoodInfo;
public class ExcelDataToListApachePOI {
public static List<FoodInfo> excelDataToListOfObjets_withApachePOI(String fileLocation) throws IOException {
FileInputStream file = new FileInputStream(new File(fileLocation));
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet = workbook.getSheetAt(0);
List<FoodInfo> foodData = new ArrayList<FoodInfo>();
DataFormatter dataFormatter = new DataFormatter();
for (int n = 1; n < sheet.getPhysicalNumberOfRows(); n++) {
Row row = sheet.getRow(n);
FoodInfo foodInfo = new FoodInfo();
int i = row.getFirstCellNum();
foodInfo.setCategory(dataFormatter.formatCellValue(row.getCell(i)));
foodInfo.setName(dataFormatter.formatCellValue(row.getCell(++i)));
foodInfo.setMeasure(dataFormatter.formatCellValue(row.getCell(++i)));
foodInfo.setCalories(Double.parseDouble(dataFormatter.formatCellValue(row.getCell(++i))));
foodData.add(foodInfo);
}
return foodData;
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.convert.exceldatatolist.poiji;
import java.io.File;
import java.util.List;
import com.baeldung.convert.exceldatatolist.FoodInfo;
import com.poiji.bind.Poiji;
public class ExcelDataToListOfObjectsPOIJI {
public static List<FoodInfo> excelDataToListOfObjets_withPOIJI(String fileLocation){
return Poiji.fromExcel(new File(fileLocation), FoodInfo.class);
}
}

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,53 @@
package com.baeldung.convert.exceldatatolist;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.List;
// import org.junit.jupiter.api.Test;
// import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test;
import com.baeldung.convert.exceldatatolist.fastexcel.ExcelDataToListOfObjectsFastExcel;
import com.baeldung.convert.exceldatatolist.jexcelapi.ExcelDataToListOfObjectsJxl;
import com.baeldung.convert.exceldatatolist.poi.ExcelDataToListApachePOI;
import com.baeldung.convert.exceldatatolist.poiji.ExcelDataToListOfObjectsPOIJI;
import jxl.read.biff.BiffException;
public class ExcelDataToListOfObjectsUnitTest {
@Test
public void whenParsingExcelFileWithPOIJI_thenConvertsToList() throws IOException {
List<FoodInfo> foodInfoList = ExcelDataToListOfObjectsPOIJI.excelDataToListOfObjets_withPOIJI("src/main/resources/food_info.xlsx");
assertEquals("Beverages", foodInfoList.get(0).getCategory());
assertEquals("Dairy", foodInfoList.get(3).getCategory());
}
@Test
public void whenParsingExcelFileWithApachePOI_thenConvertsToList() throws IOException {
List<FoodInfo> foodInfoList = ExcelDataToListApachePOI.excelDataToListOfObjets_withApachePOI("src/main/resources/food_info.xlsx");
assertEquals("Beverages", foodInfoList.get(0).getCategory());
assertEquals("Dairy", foodInfoList.get(3).getCategory());
}
@Test
public void whenParsingExcelFileWithFastExcel_thenConvertsToList() throws IOException {
List<FoodInfo> foodInfoList = ExcelDataToListOfObjectsFastExcel.excelDataToListOfObjets_withFastExcel("src/main/resources/food_info.xlsx");
assertEquals("Beverages", foodInfoList.get(0).getCategory());
assertEquals("Dairy", foodInfoList.get(3).getCategory());
}
@Test
public void whenParsingExcelFileWithJxl_thenConvertsToList() throws IOException, BiffException {
List<FoodInfo> foodInfoList = ExcelDataToListOfObjectsJxl.excelDataToListOfObjets_withJxl("src/main/resources/food_info.xls");
assertEquals("Beverages", foodInfoList.get(0).getCategory());
assertEquals("Dairy", foodInfoList.get(3).getCategory());
}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.poi.excel.expandcolumn;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
import java.io.IOException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class ExpandColumnUnitTest {
private Workbook workbook;
private Sheet sheet;
@BeforeEach
void prepareSpreadsheet() {
workbook = new XSSFWorkbook();
sheet = workbook.createSheet();
Row headerRow = sheet.createRow(0);
Cell headerCell1 = headerRow.createCell(0);
headerCell1.setCellValue("Full Name");
Cell headerCell2 = headerRow.createCell(1);
headerCell2.setCellValue("Abbreviation");
Row dataRow = sheet.createRow(1);
Cell dataCell1 = dataRow.createCell(0);
dataCell1.setCellValue("Java Virtual Machine");
Cell dataCell2 = dataRow.createCell(1);
dataCell2.setCellValue("JVM");
dataRow = sheet.createRow(2);
dataCell1 = dataRow.createCell(0);
dataCell1.setCellValue("Java Runtime Environment");
dataCell2 = dataRow.createCell(1);
dataCell2.setCellValue("JRE");
}
@Test
void whenSetColumnWidth_thenColumnSetToTheSpecifiedWidth() {
Row row = sheet.getRow(2);
String cellValue = row.getCell(0).getStringCellValue();
int targetWidth = cellValue.length() * 256;
sheet.setColumnWidth(0, targetWidth);
assertEquals(targetWidth, sheet.getColumnWidth(0));
}
@Test
void whenAutoSizeColumn_thenColumnExpands() {
int originalWidth = sheet.getColumnWidth(0);
sheet.autoSizeColumn(0);
assertThat(sheet.getColumnWidth(0)).isGreaterThan(originalWidth);
}
@AfterEach
void cleanup() throws IOException {
workbook.close();
}
}

View File

@ -4,7 +4,7 @@ This module contains articles about Simple Storage Service (S3) on AWS
### Relevant articles ### Relevant articles
- [AWS S3 with Java](https://www.baeldung.com/aws-s3-java) - [AWS S3 with Java](https://www.baeldung.com/java-aws-s3)
- [Multipart Uploads in Amazon S3 with Java](https://www.baeldung.com/aws-s3-multipart-upload) - [Multipart Uploads in Amazon S3 with Java](https://www.baeldung.com/aws-s3-multipart-upload)
- [Using the JetS3t Java Client With Amazon S3](https://www.baeldung.com/jets3t-amazon-s3) - [Using the JetS3t Java Client With Amazon S3](https://www.baeldung.com/jets3t-amazon-s3)
- [Check if a Specified Key Exists in a Given S3 Bucket Using Java](https://www.baeldung.com/java-aws-s3-check-specified-key-exists) - [Check if a Specified Key Exists in a Given S3 Bucket Using Java](https://www.baeldung.com/java-aws-s3-check-specified-key-exists)

View File

@ -0,0 +1,49 @@
package com.baeldung.value_based_class;
import java.util.Objects;
import jdk.internal.ValueBased;
/**
* This class is written with the intention that it can serve as an example of
* what a Value-based class could be.
*/
@ValueBased
public final class Point {
private final int x;
private final int y;
private final int z;
private static Point ORIGIN = new Point(0, 0, 0);
private Point(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public static Point valueOfPoint(int x, int y, int z) {
// returns a cached instance if it is origin, or a new instance
if (isOrigin(x, y, z))
return ORIGIN;
return new Point(x, y, z);
}
@Override
public boolean equals(Object other) {
if (other == null || getClass() != other.getClass())
return false;
Point point = (Point) other;
return x == point.x && y == point.y && z == point.z;
}
@Override
public int hashCode() {
return Objects.hash(x, y, z);
}
private static boolean isOrigin(int x, int y, int z) {
return x == 0 && y == 0 && z == 0;
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.value_based_class;
import org.junit.Assert;
import org.junit.Test;
public class ValueBasedClassUnitTest {
@Test
public void givenAutoboxedAndPrimitive_whenCompared_thenReturnEquals() {
int primitive_a = 125;
Integer obj_a = 125; // this is autoboxed
Assert.assertSame(primitive_a, obj_a);
}
@Test
public void givenValueBasedPoint_whenCreated_thenReturnsObjects() {
Point p1 = Point.valueOfPoint(1, 2, 3);
Point p2 = Point.valueOfPoint(2, 3, 4);
Assert.assertNotEquals(p1, p2);
}
@Test
public void givenValueBasedPoint_whenCompared_thenReturnEquals() {
Point p1 = Point.valueOfPoint(1, 2, 3);
Point p2 = Point.valueOfPoint(1, 2, 3);
Assert.assertEquals(p1, p2);
}
@Test
public void givenValueBasedPoint_whenOrigin_thenReturnCachedInstance() {
Point p1 = Point.valueOfPoint(0, 0, 0);
Point p2 = Point.valueOfPoint(0, 0, 0);
Point p3 = Point.valueOfPoint(1, 2, 3);
// the following should not be assumed for value-based classes
Assert.assertTrue(p1 == p2);
Assert.assertFalse(p1 == p3);
}
}

View File

@ -1 +1,2 @@
## Relevant Articles ## Relevant Articles
- [Sequenced Collections in Java 21](https://www.baeldung.com/java-21-sequenced-collections)

View File

@ -12,23 +12,22 @@
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
</parent> </parent>
<!-- <build>--> <build>
<!-- <plugins>--> <plugins>
<!-- <plugin>--> <plugin>
<!-- <groupId>org.apache.maven.plugins</groupId>--> <groupId>org.apache.maven.plugins</groupId>
<!-- <artifactId>maven-compiler-plugin</artifactId>--> <artifactId>maven-compiler-plugin</artifactId>
<!-- <configuration>--> <configuration>
<!-- <source>{maven.compiler.source.version}</source>--> <source>21</source>
<!-- <target>{maven.compiler.target.version}</target>--> <target>21</target>
<!-- </configuration>--> <compilerArgs>--enable-preview</compilerArgs>
<!-- </plugin>--> </configuration>
<!-- </plugins>--> </plugin>
<!-- </build>--> </plugins>
</build>
<!-- <properties>--> <properties>
<!-- <maven.compiler.source.version>21</maven.compiler.source.version>--> <maven.compiler.source.version>21</maven.compiler.source.version>
<!-- <maven.compiler.target.version>21</maven.compiler.target.version>--> <maven.compiler.target.version>21</maven.compiler.target.version>
<!-- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>--> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- </properties>--> </properties>
</project> </project>

View File

@ -0,0 +1,37 @@
package com.baeldung.stringtemplates;
import java.text.MessageFormat;
public class StringCompositionTechniques {
String composeUsingPlus(String feelsLike, String temperature, String unit) {
return "Today's weather is " + feelsLike + ", with a temperature of " + temperature + " degrees " + unit;
}
String composeUsingStringBuffer(String feelsLike, String temperature, String unit) {
return new StringBuffer().append("Today's weather is ")
.append(feelsLike)
.append(", with a temperature of ")
.append(temperature)
.append(" degrees ")
.append(unit)
.toString();
}
String composeUsingStringBuilder(String feelsLike, String temperature, String unit) {
return new StringBuilder().append("Today's weather is ")
.append(feelsLike)
.append(", with a temperature of ")
.append(temperature)
.append(" degrees ")
.append(unit)
.toString();
}
String composeUsingFormatters(String feelsLike, String temperature, String unit) {
return String.format("Today's weather is %s, with a temperature of %s degrees %s", feelsLike, temperature, unit);
}
String composeUsingMessageFormatter(String feelsLike, String temperature, String unit) {
return MessageFormat.format("Today''s weather is {0}, with a temperature of {1} degrees {2}", feelsLike, temperature, unit);
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.stringtemplates;
import static java.lang.StringTemplate.RAW;
import static java.util.FormatProcessor.FMT;
public class StringTemplateExamples {
String interpolationUsingSTRProcessor(String feelsLike, String temperature, String unit) {
return STR
. "Today's weather is \{ feelsLike }, with a temperature of \{ temperature } degrees \{ unit }" ;
}
String interpolationOfJSONBlock(String feelsLike, String temperature, String unit) {
return STR
. """
{
"feelsLike": "\{ feelsLike }",
"temperature": "\{ temperature }",
"unit": "\{ unit }"
}
""" ;
}
String interpolationWithExpressions() {
return STR
. "Today's weather is \{ getFeelsLike() }, with a temperature of \{ getTemperature() } degrees \{ getUnit() }" ;
}
String interpolationWithTemplates() {
StringTemplate str = RAW
. "Today's weather is \{ getFeelsLike() }, with a temperature of \{ getTemperature() } degrees \{ getUnit() }" ;
return STR.process(str);
}
String interpolationOfJSONBlockWithFMT(String feelsLike, float temperature, String unit) {
return FMT
. """
{
"feelsLike": "%1s\{ feelsLike }",
"temperature": "%2.2f\{ temperature }",
"unit": "%1s\{ unit }"
}
""" ;
}
private String getFeelsLike() {
return "pleasant";
}
private String getTemperature() {
return "25";
}
private String getUnit() {
return "Celsius";
}
}

View File

@ -0,0 +1,67 @@
package com.baeldung.stringtemplates;
import org.junit.Assert;
import org.junit.Test;
public class StringTemplatesUnitTest {
@Test
public void whenStringConcat_thenReturnComposedString() {
StringCompositionTechniques stringCompositionTechniques = new StringCompositionTechniques();
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", stringCompositionTechniques.composeUsingPlus("pleasant", "25", "Celsius"));
}
@Test
public void whenStringBuffer_thenReturnComposedString() {
StringCompositionTechniques stringCompositionTechniques = new StringCompositionTechniques();
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", stringCompositionTechniques.composeUsingStringBuffer("pleasant", "25", "Celsius"));
}
@Test
public void whenStringBuilder_thenReturnComposedString() {
StringCompositionTechniques stringCompositionTechniques = new StringCompositionTechniques();
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", stringCompositionTechniques.composeUsingStringBuilder("pleasant", "25", "Celsius"));
}
@Test
public void whenStringFormatter_thenReturnComposedFormattedString() {
StringCompositionTechniques stringCompositionTechniques = new StringCompositionTechniques();
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", stringCompositionTechniques.composeUsingFormatters("pleasant", "25", "Celsius"));
}
@Test
public void whenMessageFormatter_thenReturnComposedFormattedString() {
StringCompositionTechniques stringCompositionTechniques = new StringCompositionTechniques();
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", stringCompositionTechniques.composeUsingMessageFormatter("pleasant", "25", "Celsius"));
}
@Test
public void whenUsingStringTemplateSTR_thenReturnInterpolatedString() {
StringTemplateExamples templateExamples = new StringTemplateExamples();
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", templateExamples.interpolationUsingSTRProcessor("pleasant", "25", "Celsius"));
}
@Test
public void whenUsingMultilineStringTemplateSTR_thenReturnInterpolatedString() {
StringTemplateExamples templateExamples = new StringTemplateExamples();
Assert.assertEquals("{\n" + " \"feelsLike\": \"pleasant\",\n" + " \"temperature\": \"25\",\n" + " \"unit\": \"Celsius\"\n" + "}\n", templateExamples.interpolationOfJSONBlock("pleasant", "25", "Celsius"));
}
@Test
public void whenUsingExpressionSTR_thenReturnInterpolatedString() {
StringTemplateExamples templateExamples = new StringTemplateExamples();
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", templateExamples.interpolationWithExpressions());
}
@Test
public void whenUsingExpressionRAW_thenReturnInterpolatedString() {
StringTemplateExamples templateExamples = new StringTemplateExamples();
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", templateExamples.interpolationWithTemplates());
}
@Test
public void whenUsingExpressionFMT_thenReturnInterpolatedString() {
StringTemplateExamples templateExamples = new StringTemplateExamples();
Assert.assertEquals("{\n" + " \"feelsLike\": \"pleasant\",\n" + " \"temperature\": \"25.86\",\n" + " \"unit\": \"Celsius\"\n" + "}\n", templateExamples.interpolationOfJSONBlockWithFMT("pleasant", 25.8636F, "Celsius"));
}
}

View File

@ -5,4 +5,5 @@
- [Parsing Date Strings with Varying Formats](https://www.baeldung.com/java-parsing-dates-many-formats) - [Parsing Date Strings with Varying Formats](https://www.baeldung.com/java-parsing-dates-many-formats)
- [How Many Days Are There in a Particular Month of a Given Year?](https://www.baeldung.com/days-particular-month-given-year) - [How Many Days Are There in a Particular Month of a Given Year?](https://www.baeldung.com/days-particular-month-given-year)
- [Difference Between Instant and LocalDateTime](https://www.baeldung.com/java-instant-vs-localdatetime) - [Difference Between Instant and LocalDateTime](https://www.baeldung.com/java-instant-vs-localdatetime)
- [Add Minutes to a Time String in Java](https://www.baeldung.com/java-string-time-add-mins)
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1) - [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)

View File

@ -3,9 +3,11 @@ package com.baeldung.dateapi;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Duration; import java.time.Duration;
import java.time.Instant; import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime; import java.time.LocalTime;
import java.time.temporal.ChronoUnit; import java.time.temporal.ChronoUnit;
@ -34,6 +36,22 @@ public class JavaDurationUnitTest {
assertThat(seconds).isEqualTo(30); assertThat(seconds).isEqualTo(30);
} }
@Test
public void givenADuration_whenCallingisZeroAndisNegative_thenGetExpectedResult() {
LocalDateTime start = LocalDateTime.parse("2020-01-01T08:00:00");
LocalDateTime end = LocalDateTime.parse("2020-01-01T12:00:00");
assertFalse(Duration.between(start, end)
.isNegative());
assertTrue(Duration.between(end, start)
.isNegative());
LocalDateTime theTime = LocalDateTime.parse("2023-09-09T08:00:00");
assertTrue(Duration.between(theTime, theTime)
.isZero());
assertFalse(Duration.between(theTime, theTime)
.isNegative());
}
@Test @Test
public void test2() { public void test2() {
Instant start = Instant.parse("2017-10-03T10:15:30.00Z"); Instant start = Instant.parse("2017-10-03T10:15:30.00Z");

View File

@ -0,0 +1,96 @@
package com.baeldung.mergeandremoveduplicate;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;
public class MergeArraysAndRemoveDuplicate {
public static int[] removeDuplicateOnSortedArray(int[] arr) {
// Initialize a new array to store unique elements
int[] uniqueArray = new int[arr.length];
uniqueArray[0] = arr[0];
int uniqueCount = 1;
// Iterate through the sorted array to remove duplicates
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
uniqueArray[uniqueCount] = arr[i];
uniqueCount++;
}
}
int[] truncatedArray = new int[uniqueCount];
System.arraycopy(uniqueArray, 0, truncatedArray, 0, uniqueCount);
return truncatedArray;
}
public static int[] mergeAndRemoveDuplicatesUsingStream(int[] arr1, int[] arr2) {
Stream<Integer> s1 = Arrays.stream(arr1).boxed();
Stream<Integer> s2 = Arrays.stream(arr2).boxed();
return Stream.concat(s1, s2)
.distinct()
.mapToInt(Integer::intValue)
.toArray();
}
public static int[] mergeAndRemoveDuplicatesUsingSet(int[] arr1, int[] arr2) {
int[] mergedArr = mergeArrays(arr1, arr2);
Set<Integer> uniqueInts = new HashSet<>();
for (int el : mergedArr) {
uniqueInts.add(el);
}
return getArrayFromSet(uniqueInts);
}
private static int[] getArrayFromSet(Set<Integer> set) {
int[] mergedArrWithoutDuplicated = new int[set.size()];
int i = 0;
for (Integer el: set) {
mergedArrWithoutDuplicated[i] = el;
i++;
}
return mergedArrWithoutDuplicated;
}
public static int[] mergeAndRemoveDuplicates(int[] arr1, int[] arr2) {
return removeDuplicate(mergeArrays(arr1, arr2));
}
public static int[] mergeAndRemoveDuplicatesOnSortedArray(int[] arr1, int[] arr2) {
return removeDuplicateOnSortedArray(mergeArrays(arr1, arr2));
}
private static int[] mergeArrays(int[] arr1, int[] arr2) {
int[] mergedArrays = new int[arr1.length + arr2.length];
System.arraycopy(arr1, 0, mergedArrays, 0, arr1.length);
System.arraycopy(arr2, 0, mergedArrays, arr1.length, arr2.length);
return mergedArrays;
}
private static int[] removeDuplicate(int[] arr) {
int[] withoutDuplicates = new int[arr.length];
int i = 0;
for(int element : arr) {
if(!isElementPresent(withoutDuplicates, element)) {
withoutDuplicates[i] = element;
i++;
}
}
int[] truncatedArray = new int[i];
System.arraycopy(withoutDuplicates, 0, truncatedArray, 0, i);
return truncatedArray;
}
private static boolean isElementPresent(int[] arr, int element) {
for(int el : arr) {
if(el == element) {
return true;
}
}
return false;
}
}

View File

@ -0,0 +1,74 @@
package com.baeldung.mergeandremoveduplicate;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
public class MergeArraysAndRemoveDuplicateUnitTest {
private final Logger logger = LoggerFactory.getLogger(MergeArraysAndRemoveDuplicateUnitTest.class);
private static String getCommaDelimited(int[] arr) {
return Arrays.stream(arr)
.mapToObj(Integer::toString)
.collect(Collectors.joining(", "));
}
@Test
public void givenNoLibraryAndUnSortedArrays_whenArr1andArr2_thenMergeAndRemoveDuplicates() {
int[] arr1 = {3, 2, 1, 4, 5, 6, 8, 7, 9};
int[] arr2 = {8, 9, 10, 11, 12, 13, 15, 14, 15, 14, 16, 17};
int[] expectedArr = {3, 2, 1, 4, 5, 6, 8, 7, 9, 10, 11, 12, 13, 15, 14, 16, 17};
int[] mergedArr = MergeArraysAndRemoveDuplicate.mergeAndRemoveDuplicates(arr1, arr2);
//merged array maintains the order of the elements in the arrays
assertArrayEquals(expectedArr, mergedArr);
logger.info(getCommaDelimited(mergedArr));
}
@Test
public void givenNoLibraryAndSortedArrays_whenArr1andArr2_thenMergeAndRemoveDuplicates() {
int[] arr1 = {1, 2, 3, 4, 5, 5, 6, 7, 7, 8};
int[] arr2 = {8, 9, 10, 11, 12, 13, 14, 15, 15, 16, 17};
int[] expectedArr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17};
int[] mergedArr = MergeArraysAndRemoveDuplicate.mergeAndRemoveDuplicatesOnSortedArray(arr1, arr2);
assertArrayEquals(expectedArr, mergedArr);
logger.info(getCommaDelimited(mergedArr));
}
@Test
public void givenSet_whenArr1andArr2_thenMergeAndRemoveDuplicates() {
int[] arr1 = {3, 2, 1, 4, 5, 6, 8, 7, 9};
int[] arr2 = {8, 9, 10, 11, 12, 13, 15, 14, 15, 14, 16, 17};
int[] expectedArr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17};
int[] mergedArr = MergeArraysAndRemoveDuplicate.mergeAndRemoveDuplicatesUsingSet(arr1, arr2);
assertArrayEquals(expectedArr, mergedArr);
logger.info(getCommaDelimited(mergedArr));
}
@Test
public void givenStream_whenArr1andArr2_thenMergeAndRemoveDuplicates() {
int[] arr1 = {3, 2, 1, 4, 5, 6, 8, 7, 9};
int[] arr2 = {8, 9, 10, 11, 12, 13, 15, 14, 15, 14, 16, 17};
int[] expectedArr = {3, 2, 1, 4, 5, 6, 8, 7, 9, 10, 11, 12, 13, 15, 14, 16, 17};
int[] mergedArr = MergeArraysAndRemoveDuplicate.mergeAndRemoveDuplicatesUsingStream(arr1, arr2);
assertArrayEquals(expectedArr, mergedArr);
logger.info(getCommaDelimited(mergedArr));
}
}

View File

@ -0,0 +1,46 @@
<?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-arrays-operations-advanced-2</artifactId>
<name>core-java-arrays-operations-advanced-2</name>
<packaging>jar</packaging>
<parent>
<artifactId>core-java-modules</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,26 @@
package com.baeldung.collectionsvsarrays;
import com.baeldung.collectionsvsarrays.sorting.Quicksort;
import java.util.Comparator;
import java.util.List;
public class NonStableSortExample {
public static void main(String[] args) {
List<Task> tasks = Tasks.supplier.get();
Quicksort.sort(tasks, Comparator.comparingInt(Task::getPriority));
System.out.println("After sorting by priority:");
for (Task task : tasks) {
System.out.println(task);
}
Quicksort.sort(tasks, Comparator.comparing(Task::getDueDate));
System.out.println("\nAfter sorting by due date:");
for (Task task : tasks) {
System.out.println(task);
}
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.collectionsvsarrays;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
@Measurement(iterations = 2, time = 10, timeUnit = TimeUnit.MINUTES)
@Warmup(iterations = 5, time = 10)
@Fork(value = 2)
public class ObjectOverheadBenchmark {
private static final ThreadLocalRandom RANDOM = ThreadLocalRandom.current();
@State(Scope.Benchmark)
public static class Input {
public Supplier<List<Integer>> randomNumbers = () -> RANDOM.ints().limit(10000).boxed().collect(Collectors.toList());
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void sortingPrimitiveArray(Input input, Blackhole blackhole) {
final int[] array = input.randomNumbers.get().stream().mapToInt(Integer::intValue).toArray();
Arrays.sort(array);
final List<Integer> result = Arrays.stream(array).boxed().collect(Collectors.toList());
blackhole.consume(result);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void sortingObjectArray(Input input, Blackhole blackhole) {
final Integer[] array = input.randomNumbers.get().toArray(new Integer[0]);
Arrays.sort(array);
blackhole.consume(array);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void sortingObjects(Input input, Blackhole blackhole) {
final List<Integer> list = input.randomNumbers.get();
Collections.sort(list);
blackhole.consume(list);
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.collectionsvsarrays;
import com.baeldung.collectionsvsarrays.sorting.MergeSort;
import com.baeldung.collectionsvsarrays.sorting.Quicksort;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Warmup;
@Measurement(iterations = 2, time = 10, timeUnit = TimeUnit.MINUTES)
@Warmup(iterations = 5, time = 10)
public class PerformanceBenchmark {
private static final Random RANDOM = new Random();
private static final int ARRAY_SIZE = 10000;
private static final int[] randomNumbers = RANDOM.ints(ARRAY_SIZE).toArray();
private static final int[] sameNumbers = IntStream.generate(() -> 42).limit(ARRAY_SIZE).toArray();
public static final Supplier<int[]> randomNumbersSupplier = randomNumbers::clone;
public static final Supplier<int[]> sameNumbersSupplier = sameNumbers::clone;
@Benchmark
@BenchmarkMode(Mode.Throughput)
@Fork(value = 1, jvmArgs = {"-Xlog:gc:file=gc-logs-quick-sort-same-number-%t.txt,filesize=900m -Xmx6gb -Xms6gb"})
public void quickSortSameNumber() {
Quicksort.sort(sameNumbersSupplier.get());
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
@Fork(value = 1, jvmArgs = {"-Xlog:gc:file=gc-logs-quick-sort-random-number-%t.txt,filesize=900m -Xmx6gb -Xms6gb"})
public void quickSortRandomNumber() {
Quicksort.sort(randomNumbersSupplier.get());
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
@Fork(value = 1, jvmArgs = {"-Xlog:gc:file=gc-logs-merge-sort-same-number-%t.txt,filesize=900m -Xmx6gb -Xms6gb"})
public void mergeSortSameNumber() {
MergeSort.sort(sameNumbersSupplier.get());
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
@Fork(value = 1, jvmArgs = {"-Xlog:gc:file=gc-logs-merge-sort-random-number-%t.txt,filesize=900m -Xmx6gb -Xms6gb"})
public void mergeSortRandomNumber() {
MergeSort.sort(randomNumbersSupplier.get());
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.collectionsvsarrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class StableSortExample {
public static void main(String[] args) {
final List<Task> tasks = Tasks.supplier.get();
Collections.sort(tasks, Comparator.comparingInt(Task::getPriority));
System.out.println("After sorting by priority:");
for (Task task : tasks) {
System.out.println(task);
}
Collections.sort(tasks, Comparator.comparing(Task::getDueDate));
System.out.println("\nAfter sorting by due date:");
for (Task task : tasks) {
System.out.println(task);
}
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.collectionsvsarrays;
public class Task {
private final long id;
private final int priority;
private final String dueDate;
public Task(final long id, int priority, String dueDate) {
this.id = id;
this.priority = priority;
this.dueDate = dueDate;
}
@Override
public String toString() {
return String.format("Task: #%-2d | Priority: %d | Due Date: %s", getId(), getPriority(), getDueDate());
}
public int getPriority() {
return priority;
}
public String getDueDate() {
return dueDate;
}
private long getId() {
return id;
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.collectionsvsarrays;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
public class Tasks {
private static final List<Task> tasks;
public static final Supplier<List<Task>> supplier;
static {
tasks = new ArrayList<>();
tasks.add(new Task(1, 1, "2023-09-01"));
tasks.add(new Task(2, 2, "2023-08-30"));
tasks.add(new Task(3, 1, "2023-08-29"));
tasks.add(new Task(4, 2, "2023-09-02"));
tasks.add(new Task(5, 3, "2023-09-05"));
tasks.add(new Task(6, 1, "2023-09-03"));
tasks.add(new Task(7, 3, "2023-08-28"));
tasks.add(new Task(8, 2, "2023-09-01"));
tasks.add(new Task(9, 1, "2023-08-28"));
tasks.add(new Task(10, 2, "2023-09-04"));
tasks.add(new Task(11, 3, "2023-08-31"));
tasks.add(new Task(12, 1, "2023-08-30"));
tasks.add(new Task(13, 3, "2023-09-02"));
supplier = () -> new ArrayList<>(tasks);
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.collectionsvsarrays.sorting;
public class MergeSort {
public static void sort(int[] a) {
sort(a, a.length);
}
public static void sort(int[] a, int n) {
if (n < 2) {
return;
}
int mid = n / 2;
int[] l = new int[mid];
int[] r = new int[n - mid];
for (int i = 0; i < mid; i++) {
l[i] = a[i];
}
for (int i = mid; i < n; i++) {
r[i - mid] = a[i];
}
sort(l, mid);
sort(r, n - mid);
merge(a, l, r, mid, n - mid);
}
private static void merge(
int[] a, int[] l, int[] r, int left, int right) {
int i = 0, j = 0, k = 0;
while (i < left && j < right) {
if (l[i] <= r[j]) {
a[k++] = l[i++];
}
else {
a[k++] = r[j++];
}
}
while (i < left) {
a[k++] = l[i++];
}
while (j < right) {
a[k++] = r[j++];
}
}
}

View File

@ -0,0 +1,72 @@
package com.baeldung.collectionsvsarrays.sorting;
import java.util.Comparator;
import java.util.List;
public class Quicksort {
public static void sort(int arr[]) {
sort(arr, 0, arr.length - 1);
}
public static void sort(int arr[], int begin, int end) {
if (begin < end) {
int partitionIndex = partition(arr, begin, end);
sort(arr, begin, partitionIndex-1);
sort(arr, partitionIndex+1, end);
}
}
private static int partition(int arr[], int begin, int end) {
int pivot = arr[end];
int i = (begin-1);
for (int j = begin; j < end; j++) {
if (arr[j] <= pivot) {
i++;
int swapTemp = arr[i];
arr[i] = arr[j];
arr[j] = swapTemp;
}
}
int swapTemp = arr[i+1];
arr[i+1] = arr[end];
arr[end] = swapTemp;
return i+1;
}
public static <T> void sort(List<T> list, Comparator<T> comparator) {
sort(list, 0, list.size() - 1, comparator);
}
public static <T> void sort(List<T> list, int low, int high, Comparator<T> comparator) {
if (low < high) {
int partitionIndex = partition(list, low, high, comparator);
sort(list, low, partitionIndex - 1, comparator);
sort(list, partitionIndex + 1, high, comparator);
}
}
private static <T> int partition(List<T> list, int begin, int end, Comparator<T> comparator) {
T pivot = list.get(end);
int i = (begin-1);
for (int j = begin; j < end; j++) {
if (comparator.compare(list.get(j), pivot) <= 0) {
i++;
T swapTemp = list.get(i);
list.set(i, list.get(j));
list.set(j, swapTemp);
}
}
T swapTemp = list.get(i+1);
list.set(i+1,list.get(end));
list.set(end, swapTemp);
return i+1;
}
}

View File

@ -0,0 +1,5 @@
## Java Collections Cookbooks and Examples
This module contains articles about conversions among Collection types in Java.
### Relevant Articles:

View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-conversions-3</artifactId>
<name>core-java-collections-conversions-3</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<build>
<finalName>core-java-collections-conversions-3</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>

View File

@ -0,0 +1,66 @@
package com.baeldung.hashmaptoarraylist;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Maps.EntryTransformer;
public class HashMapToArrayListConverterUtils {
static ArrayList<String> convertUsingConstructor(HashMap<Integer, String> hashMap) {
if (hashMap == null) {
return null;
}
return new ArrayList<String>(hashMap.values());
}
static ArrayList<String> convertUsingAddAllMethod(HashMap<Integer, String> hashMap) {
if (hashMap == null) {
return null;
}
ArrayList<String> arrayList = new ArrayList<String>(hashMap.size());
arrayList.addAll(hashMap.values());
return arrayList;
}
static ArrayList<String> convertUsingStreamApi(HashMap<Integer, String> hashMap) {
if (hashMap == null) {
return null;
}
return hashMap.values()
.stream()
.collect(Collectors.toCollection(ArrayList::new));
}
static ArrayList<String> convertUsingForLoop(HashMap<Integer, String> hashMap) {
if (hashMap == null) {
return null;
}
ArrayList<String> arrayList = new ArrayList<String>(hashMap.size());
for (Map.Entry<Integer, String> entry : hashMap.entrySet()) {
arrayList.add(entry.getValue());
}
return arrayList;
}
static public ArrayList<String> convertUsingGuava(HashMap<Integer, String> hashMap) {
if (hashMap == null) {
return null;
}
EntryTransformer<Integer, String, String> entryMapTransformer = (key, value) -> value;
return Lists.newArrayList(Maps.transformEntries(hashMap, entryMapTransformer)
.values());
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.hashmaptoarraylist;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import java.util.ArrayList;
import java.util.HashMap;
import org.junit.Before;
import org.junit.Test;
public class HashMapToArrayListConverterUtilsUnitTest {
private HashMap<Integer, String> hashMap;
@Before
public void beforeEach() {
hashMap = new HashMap<>();
hashMap.put(1, "AAA");
hashMap.put(2, "BBB");
hashMap.put(3, "CCC");
hashMap.put(4, "DDD");
}
@Test
public void givenAHashMap_whenConvertUsingConstructor_thenReturnArrayList() {
ArrayList<String> myList = HashMapToArrayListConverterUtils.convertUsingConstructor(hashMap);
assertThat(hashMap.values(), containsInAnyOrder(myList.toArray()));
}
@Test
public void givenAHashMap_whenConvertUsingAddAllMethod_thenReturnArrayList() {
ArrayList<String> myList = HashMapToArrayListConverterUtils.convertUsingAddAllMethod(hashMap);
assertThat(hashMap.values(), containsInAnyOrder(myList.toArray()));
}
@Test
public void givenAHashMap_whenConvertUsingForLoop_thenReturnArrayList() {
ArrayList<String> myList = HashMapToArrayListConverterUtils.convertUsingForLoop(hashMap);
assertThat(hashMap.values(), containsInAnyOrder(myList.toArray()));
}
@Test
public void givenAHashMap_whenConvertUsingStreamApi_thenReturnArrayList() {
ArrayList<String> myList = HashMapToArrayListConverterUtils.convertUsingStreamApi(hashMap);
assertThat(hashMap.values(), containsInAnyOrder(myList.toArray()));
}
@Test
public void givenAHashMap_whenConvertUsingGuava_thenReturnArrayList() {
ArrayList<String> myList = HashMapToArrayListConverterUtils.convertUsingGuava(hashMap);
assertThat(hashMap.values(), containsInAnyOrder(myList.toArray()));
}
}

View File

@ -53,7 +53,7 @@ public class IdentityHashMapDemonstrator {
} }
} }
private static class Book { static class Book {
String title; String title;
int year; int year;

View File

@ -1,8 +1,11 @@
package com.baeldung.map.identity; package com.baeldung.map.identity;
import com.baeldung.map.identity.IdentityHashMapDemonstrator.Book;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.util.IdentityHashMap; import java.util.IdentityHashMap;
import org.junit.jupiter.api.condition.EnabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
@ -18,4 +21,44 @@ public class IdentityHashMapDemonstratorUnitTest {
assertEquals("Fantasy", identityHashMap.get("genre")); assertEquals("Fantasy", identityHashMap.get("genre"));
assertEquals("Drama", identityHashMap.get(newGenreKey)); assertEquals("Drama", identityHashMap.get(newGenreKey));
} }
@Test
@EnabledForJreRange(max = JRE.JAVA_19)
public void removeEntryComparingValueByEquality() {
Book book = new Book("A Passage to India", 1924);
IdentityHashMap<Book, String> identityHashMap = new IdentityHashMap<>(10);
identityHashMap.put(book, "A great work of fiction");
identityHashMap.remove(book, new String("A great work of fiction"));
assertEquals(null, identityHashMap.get(book));
}
@Test
@EnabledForJreRange(max = JRE.JAVA_19)
public void replaceEntryComparingValueByEquality() {
Book book = new Book("A Passage to India", 1924);
IdentityHashMap<Book, String> identityHashMap = new IdentityHashMap<>(10);
identityHashMap.put(book, "A great work of fiction");
identityHashMap.replace(book, new String("A great work of fiction"), "One of the greatest books");
assertEquals("One of the greatest books", identityHashMap.get(book));
}
@Test
@EnabledForJreRange(min = JRE.JAVA_20)
public void dontRemoveEntryComparingValueByEquality() {
Book book = new Book("A Passage to India", 1924);
IdentityHashMap<Book, String> identityHashMap = new IdentityHashMap<>(10);
identityHashMap.put(book, "A great work of fiction");
identityHashMap.remove(book, new String("A great work of fiction"));
assertEquals("A great work of fiction", identityHashMap.get(book));
}
@Test
@EnabledForJreRange(min = JRE.JAVA_20)
public void dontReplaceEntryComparingValueByEquality() {
Book book = new Book("A Passage to India", 1924);
IdentityHashMap<Book, String> identityHashMap = new IdentityHashMap<>(10);
identityHashMap.put(book, "A great work of fiction");
identityHashMap.replace(book, new String("A great work of fiction"), "One of the greatest books");
assertEquals("A great work of fiction", identityHashMap.get(book));
}
} }

View File

@ -5,4 +5,5 @@
- [Sorting a HashSet in Java](https://www.baeldung.com/java-sort-hashset) - [Sorting a HashSet in Java](https://www.baeldung.com/java-sort-hashset)
- [How to Get First Item From a Java Set](https://www.baeldung.com/first-item-set) - [How to Get First Item From a Java Set](https://www.baeldung.com/first-item-set)
- [Cartesian Product of Any Number of Sets in Java](https://www.baeldung.com/java-cartesian-product-sets) - [Cartesian Product of Any Number of Sets in Java](https://www.baeldung.com/java-cartesian-product-sets)
- [How to Get Index of an Item in Java Set](https://www.baeldung.com/java-set-element-find-index)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-set) - More articles: [[<-- prev]](/core-java-modules/core-java-collections-set)

View File

@ -5,4 +5,5 @@
- [Java Concurrent HashSet Equivalent to ConcurrentHashMap](https://www.baeldung.com/java-concurrent-hashset-concurrenthashmap) - [Java Concurrent HashSet Equivalent to ConcurrentHashMap](https://www.baeldung.com/java-concurrent-hashset-concurrenthashmap)
- [Reading and Writing With a ConcurrentHashMap](https://www.baeldung.com/concurrenthashmap-reading-and-writing) - [Reading and Writing With a ConcurrentHashMap](https://www.baeldung.com/concurrenthashmap-reading-and-writing)
- [ArrayBlockingQueue vs. LinkedBlockingQueue](https://www.baeldung.com/java-arrayblockingqueue-vs-linkedblockingqueue) - [ArrayBlockingQueue vs. LinkedBlockingQueue](https://www.baeldung.com/java-arrayblockingqueue-vs-linkedblockingqueue)
- [Difference Between Hashtable and ConcurrentHashMap in Java](https://www.baeldung.com/java-hashtable-vs-concurrenthashmap)
- [[<-- Prev]](/core-java-modules/core-java-concurrency-collections) - [[<-- Prev]](/core-java-modules/core-java-concurrency-collections)

View File

@ -96,7 +96,8 @@ public class DateTimeFormatterUnitTest {
String newYorkDateTimePattern = "dd.MM.yyyy HH:mm z"; String newYorkDateTimePattern = "dd.MM.yyyy HH:mm z";
DateTimeFormatter newYorkDateFormatter = DateTimeFormatter.ofPattern(newYorkDateTimePattern); DateTimeFormatter newYorkDateFormatter = DateTimeFormatter.ofPattern(newYorkDateTimePattern);
LocalDateTime summerDay = LocalDateTime.of(2016, 7, 31, 14, 15); LocalDateTime summerDay = LocalDateTime.of(2016, 7, 31, 14, 15);
Assert.assertEquals("31.07.2016 14:15 EDT", newYorkDateFormatter.format(ZonedDateTime.of(summerDay, ZoneId.of("America/New_York")))); Assert.assertEquals("31.07.2016 14:15 EDT",
newYorkDateFormatter.format(ZonedDateTime.of(summerDay, ZoneId.of("America/New_York"))));
} }
@Test @Test
@ -121,8 +122,10 @@ public class DateTimeFormatterUnitTest {
@Test @Test
public void shouldPrintFormattedDateTimeWithPredefined() { public void shouldPrintFormattedDateTimeWithPredefined() {
Assert.assertEquals("2018-03-09", DateTimeFormatter.ISO_LOCAL_DATE.format(LocalDate.of(2018, 3, 9))); Assert.assertEquals("2018-03-09", DateTimeFormatter.ISO_LOCAL_DATE.format(LocalDate.of(2018, 3, 9)));
Assert.assertEquals("2018-03-09-03:00", DateTimeFormatter.ISO_OFFSET_DATE.format(LocalDate.of(2018, 3, 9).atStartOfDay(ZoneId.of("UTC-3")))); Assert.assertEquals("2018-03-09-03:00",
Assert.assertEquals("Fri, 9 Mar 2018 00:00:00 -0300", DateTimeFormatter.RFC_1123_DATE_TIME.format(LocalDate.of(2018, 3, 9).atStartOfDay(ZoneId.of("UTC-3")))); DateTimeFormatter.ISO_OFFSET_DATE.format(LocalDate.of(2018, 3, 9).atStartOfDay(ZoneId.of("UTC-3"))));
Assert.assertEquals("Fri, 9 Mar 2018 00:00:00 -0300",
DateTimeFormatter.RFC_1123_DATE_TIME.format(LocalDate.of(2018, 3, 9).atStartOfDay(ZoneId.of("UTC-3"))));
} }
@Test @Test
@ -191,4 +194,36 @@ public class DateTimeFormatterUnitTest {
public void shouldExpectAnExceptionIfSecondIsMissing() { public void shouldExpectAnExceptionIfSecondIsMissing() {
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2021-12-02T08:06Z", DateTimeFormatter.ISO_INSTANT); ZonedDateTime zonedDateTime = ZonedDateTime.parse("2021-12-02T08:06Z", DateTimeFormatter.ISO_INSTANT);
} }
@Test
public void testUSShortFormatting() {
LocalDate date = LocalDate.of(2023, 9, 18);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yy: EEE").withLocale(Locale.US);
String formattedDate = date.format(formatter);
Assert.assertEquals("Sep 18, 23: Mon", formattedDate);
}
@Test
public void testUSFullFormatting() {
LocalDate date = LocalDate.of(2023, 9, 18);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM dd, yyyy: EEEE").withLocale(Locale.US);
String formattedDate = date.format(formatter);
Assert.assertEquals("September 18, 2023: Monday", formattedDate);
}
@Test
public void testKoreanShortFormatting() {
LocalDate date = LocalDate.of(2023, 9, 18);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yy: EEE").withLocale(Locale.KOREA);
String formattedDate = date.format(formatter);
Assert.assertEquals("9월 18, 23: 월", formattedDate);
}
@Test
public void testKoreanFullFormatting() {
LocalDate date = LocalDate.of(2023, 9, 18);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM dd, yyyy: EEEE").withLocale(Locale.KOREA);
String formattedDate = date.format(formatter);
Assert.assertEquals("9월 18, 2023: 월요일", formattedDate);
}
} }

View File

@ -0,0 +1,60 @@
package com.baeldung.eofdetections;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class EOFDetection {
public String readWithFileInputStream(String pathFile) throws IOException {
try (FileInputStream fis = new FileInputStream(pathFile);
ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
int data;
while ((data = fis.read()) != -1) {
baos.write(data);
}
return baos.toString();
}
}
public String readWithBufferedReader(String pathFile) throws IOException {
try (FileInputStream fis = new FileInputStream(pathFile);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader reader = new BufferedReader(isr)) {
StringBuilder actualContent = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
actualContent.append(line);
}
return actualContent.toString();
}
}
public String readWithScanner(String pathFile) throws IOException {
File file = new File(pathFile);
Scanner scanner = new Scanner(file);
StringBuilder actualContent = new StringBuilder();
while (scanner.hasNext()) {
String line = scanner.nextLine();
actualContent.append(line);
}
scanner.close();
return actualContent.toString();
}
public String readFileWithFileChannelAndByteBuffer(String pathFile) throws IOException {
try (FileInputStream fis = new FileInputStream(pathFile);
FileChannel channel = fis.getChannel()) {
ByteBuffer buffer = ByteBuffer.allocate((int) channel.size());
while (channel.read(buffer) != -1) {
buffer.flip();
buffer.clear();
}
return StandardCharsets.UTF_8.decode(buffer).toString();
}
}
}

View File

@ -0,0 +1,80 @@
package com.baeldung.eofdetections;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class EOFDetectionUnitTest {
static final String LOREM_IPSUM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum";
String pathToFile = "sample.txt"; // init sample file path
EOFDetection eofDetection = new EOFDetection();
@Test
@Order(1)
public void givenDummyText_whenReadWithFileInputStream_returnText() {
try {
String actualText = eofDetection.readWithFileInputStream(pathToFile);
assertEquals(LOREM_IPSUM, actualText);
} catch (IOException e) {
fail(e.getMessage());
}
}
@Test
@Order(2)
public void givenDummyText_whenReadFileWithBufferedReader_returnText() {
try {
String actualText = eofDetection.readWithBufferedReader(pathToFile);
assertEquals(LOREM_IPSUM, actualText);
} catch (IOException e) {
fail(e.getMessage());
}
}
@Test
@Order(3)
public void givenDummyText_whenReadFileWithScanner_returnText() {
try {
String actualText = eofDetection.readWithScanner(pathToFile);
assertEquals(LOREM_IPSUM, actualText);
} catch (IOException e) {
fail(e.getMessage());
}
}
@Test
@Order(4)
public void givenDummyText_whenReadFileWithFileChannelAndByteBuffer_returnText() {
try {
String actualText = eofDetection.readFileWithFileChannelAndByteBuffer(pathToFile);
assertEquals(LOREM_IPSUM, actualText);
} catch (IOException e) {
fail(e.getMessage());
}
}
@Test
@Order(0)
public void prepareFileForTest() {
File file = new File(pathToFile);
if (!file.exists()) {
try {
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(LOREM_IPSUM);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

View File

@ -14,7 +14,7 @@ import org.apache.tika.mime.MimeTypeException;
import org.junit.Test; import org.junit.Test;
import com.j256.simplemagic.ContentInfo; import com.j256.simplemagic.ContentType;
public class ExtensionFromMimeTypeUnitTest { public class ExtensionFromMimeTypeUnitTest {
private static final String IMAGE_JPEG_MIME_TYPE = "image/jpeg"; private static final String IMAGE_JPEG_MIME_TYPE = "image/jpeg";
@ -39,8 +39,7 @@ public class ExtensionFromMimeTypeUnitTest {
@Test @Test
public void whenUsingMimetypesFileTypeMap_thenGetFileExtension() { public void whenUsingMimetypesFileTypeMap_thenGetFileExtension() {
List<String> expectedExtensions = Arrays.asList("jpeg", "jpg", "jpe"); List<String> expectedExtensions = Arrays.asList("jpeg", "jpg", "jpe");
ContentInfo contentInfo = new ContentInfo("", IMAGE_JPEG_MIME_TYPE, "", true); String[] detectedExtensions = ContentType.fromMimeType(IMAGE_JPEG_MIME_TYPE).getFileExtensions();
String[] detectedExtensions = contentInfo.getFileExtensions();
assertThat(detectedExtensions).containsExactlyElementsOf(expectedExtensions); assertThat(detectedExtensions).containsExactlyElementsOf(expectedExtensions);
} }

View File

@ -12,4 +12,4 @@ This module contains articles about inheritance in Java
- [Guide to Inheritance in Java](https://www.baeldung.com/java-inheritance) - [Guide to Inheritance in Java](https://www.baeldung.com/java-inheritance)
- [Object Type Casting in Java](https://www.baeldung.com/java-type-casting) - [Object Type Casting in Java](https://www.baeldung.com/java-type-casting)
- [Variable and Method Hiding in Java](https://www.baeldung.com/java-variable-method-hiding) - [Variable and Method Hiding in Java](https://www.baeldung.com/java-variable-method-hiding)
- [Inner Classes Vs. Subclasses in Java](https://www.baeldung.com/java-inner-classes-vs-subclasses) - [Inner Classes vs. Subclasses in Java](https://www.baeldung.com/java-inner-classes-vs-subclasses)

View File

@ -24,7 +24,7 @@ public class EchoIntegrationTest {
Executors.newSingleThreadExecutor() Executors.newSingleThreadExecutor()
.submit(() -> new EchoServer().start(port)); .submit(() -> new EchoServer().start(port));
Thread.sleep(500); Thread.sleep(2000);
} }
private EchoClient client = new EchoClient(); private EchoClient client = new EchoClient();

View File

@ -27,7 +27,7 @@ public class GreetServerIntegrationTest {
Executors.newSingleThreadExecutor() Executors.newSingleThreadExecutor()
.submit(() -> new GreetServer().start(port)); .submit(() -> new GreetServer().start(port));
Thread.sleep(500); Thread.sleep(2000);
} }
@Before @Before

View File

@ -23,7 +23,7 @@ public class SocketEchoMultiIntegrationTest {
s.close(); s.close();
Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(port)); Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(port));
Thread.sleep(500); Thread.sleep(2000);
} }
@Test @Test

View File

@ -2,3 +2,4 @@
- [Difference Between parallelStream() and stream().parallel() in Java](https://www.baeldung.com/java-parallelstream-vs-stream-parallel) - [Difference Between parallelStream() and stream().parallel() in Java](https://www.baeldung.com/java-parallelstream-vs-stream-parallel)
- [Working With Empty Stream in Java](https://www.baeldung.com/java-empty-stream) - [Working With Empty Stream in Java](https://www.baeldung.com/java-empty-stream)
- [Aggregate Runtime Exceptions in Java Streams](https://www.baeldung.com/java-streams-aggregate-exceptions) - [Aggregate Runtime Exceptions in Java Streams](https://www.baeldung.com/java-streams-aggregate-exceptions)
- [Streams vs. Loops in Java](https://www.baeldung.com/java-streams-vs-loops)

View File

@ -23,6 +23,11 @@
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>
<version>${apache-commons-lang3.version}</version> <version>${apache-commons-lang3.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.vdurmont</groupId>
<artifactId>emoji-java</artifactId>
<version>${emoji-java.version}</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -52,6 +57,7 @@
<maven.compiler.target>11</maven.compiler.target> <maven.compiler.target>11</maven.compiler.target>
<validator.version>1.7</validator.version> <validator.version>1.7</validator.version>
<apache-commons-lang3.version>3.12.0</apache-commons-lang3.version> <apache-commons-lang3.version>3.12.0</apache-commons-lang3.version>
<emoji-java.version>5.1.1</emoji-java.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,33 @@
package com.baeldung.findemojis;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.vdurmont.emoji.EmojiManager;
public class FindEmojisUnitTest {
@Test
public void givenAWord_whenUsingEmojiJava_thenDetectEmoji() {
boolean emoji = EmojiManager.isEmoji("\uD83D\uDC3B");
assertTrue(emoji);
boolean notEmoji = EmojiManager.isEmoji("w");
assertFalse(notEmoji);
}
@Test
public void givenAWord_whenUsingRegex_thenDetectEmoji() {
String regexPattern = "[\uD800-\uDBFF\uDC00-\uDFFF]+";
String emojiString = "\uD83D\uDC3B";
boolean emoji = emojiString.matches(regexPattern);
assertTrue(emoji);
String notEmojiString = "w";
boolean notEmoji = notEmojiString.matches(regexPattern);
assertFalse(notEmoji);
}
}

View File

@ -11,3 +11,4 @@
- [Check if the First Letter of a String Is a Number](https://www.baeldung.com/java-check-if-string-starts-with-number) - [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) - [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) - [Remove Punctuation From a String in Java](https://www.baeldung.com/java-remove-punctuation-from-string)
- [Replacing Single Quote with \ in Java String](https://www.baeldung.com/java-replacing-single-quote-string)

View File

@ -65,6 +65,7 @@
<module>core-java-arrays-convert</module> <module>core-java-arrays-convert</module>
<module>core-java-arrays-operations-basic</module> <module>core-java-arrays-operations-basic</module>
<module>core-java-arrays-operations-advanced</module> <module>core-java-arrays-operations-advanced</module>
<module>core-java-arrays-operations-advanced-2</module>
<module>core-java-booleans</module> <module>core-java-booleans</module>
<module>core-java-char</module> <module>core-java-char</module>
<module>core-java-collections</module> <module>core-java-collections</module>

View File

@ -1,8 +1,15 @@
package com.baeldung.drools.config; package com.baeldung.drools.config;
import java.util.Arrays;
import java.util.List;
import org.drools.decisiontable.DecisionTableProviderImpl; import org.drools.decisiontable.DecisionTableProviderImpl;
import org.kie.api.KieServices; import org.kie.api.KieServices;
import org.kie.api.builder.*; import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieModule;
import org.kie.api.builder.KieRepository;
import org.kie.api.builder.ReleaseId;
import org.kie.api.io.Resource; import org.kie.api.io.Resource;
import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession; import org.kie.api.runtime.KieSession;
@ -10,8 +17,6 @@ import org.kie.internal.builder.DecisionTableConfiguration;
import org.kie.internal.builder.DecisionTableInputType; import org.kie.internal.builder.DecisionTableInputType;
import org.kie.internal.builder.KnowledgeBuilderFactory; import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.io.ResourceFactory; import org.kie.internal.io.ResourceFactory;
import java.util.Arrays;
import java.util.List;
public class DroolsBeanFactory { public class DroolsBeanFactory {
@ -20,25 +25,11 @@ public class DroolsBeanFactory {
private KieFileSystem getKieFileSystem() { private KieFileSystem getKieFileSystem() {
KieFileSystem kieFileSystem = kieServices.newKieFileSystem(); KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
List<String> rules = Arrays.asList("BackwardChaining.drl", "SuggestApplicant.drl", "Product_rules.drl.xls"); List<String> rules = Arrays.asList("com/baeldung/drools/rules/BackwardChaining.drl", "com/baeldung/drools/rules/SuggestApplicant.drl", "com/baeldung/drools/rules/Product_rules.drl.xls");
for (String rule : rules) { for (String rule : rules) {
kieFileSystem.write(ResourceFactory.newClassPathResource(rule)); kieFileSystem.write(ResourceFactory.newClassPathResource(rule));
} }
return kieFileSystem; return kieFileSystem;
}
public KieContainer getKieContainer() {
getKieRepository();
KieBuilder kb = kieServices.newKieBuilder(getKieFileSystem());
kb.buildAll();
KieModule kieModule = kb.getKieModule();
KieContainer kContainer = kieServices.newKieContainer(kieModule.getReleaseId());
return kContainer;
} }
private void getKieRepository() { private void getKieRepository() {
@ -47,20 +38,14 @@ public class DroolsBeanFactory {
} }
public KieSession getKieSession() { public KieSession getKieSession() {
getKieRepository(); KieBuilder kb = kieServices.newKieBuilder(getKieFileSystem());
KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/BackwardChaining.drl"));
kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/SuggestApplicant.drl"));
kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/Product_rules.drl.xls"));
KieBuilder kb = kieServices.newKieBuilder(kieFileSystem);
kb.buildAll(); kb.buildAll();
KieModule kieModule = kb.getKieModule();
KieContainer kContainer = kieServices.newKieContainer(kieModule.getReleaseId()); KieRepository kieRepository = kieServices.getRepository();
ReleaseId krDefaultReleaseId = kieRepository.getDefaultReleaseId();
KieContainer kieContainer = kieServices.newKieContainer(krDefaultReleaseId);
return kContainer.newKieSession(); return kieContainer.newKieSession();
} }
public KieSession getKieSession(Resource dt) { public KieSession getKieSession(Resource dt) {

View File

@ -2,3 +2,4 @@
- [Run a Java main Method Using Gradle](https://www.baeldung.com/gradle-run-java-main) - [Run a Java main Method Using Gradle](https://www.baeldung.com/gradle-run-java-main)
- [Finding Unused Gradle Dependencies](https://www.baeldung.com/gradle-finding-unused-dependencies) - [Finding Unused Gradle Dependencies](https://www.baeldung.com/gradle-finding-unused-dependencies)
- [Intro to Gradle Lint Plugin](https://www.baeldung.com/java-gradle-lint-intro)

View File

@ -1,14 +1,21 @@
plugins { plugins {
id "nebula.lint" version "16.9.0" id "nebula.lint" version "18.1.0"
} }
description = "Gradle 5 root project" description = "Gradle 5 root project"
allprojects { allprojects {
apply plugin: "java" apply plugin: "java"
apply plugin: "nebula.lint" apply plugin: "nebula.lint"
gradleLint { gradleLint {
rules=['unused-dependency'] rules = [
// 'unused-dependency',
// 'dependency-parentheses',
// 'undeclared-dependency',
// 'minimum-dependency-version'
]
reportFormat = 'text' reportFormat = 'text'
reportOnlyFixableViolations = true
} }
group = "com.baeldung" group = "com.baeldung"
version = "0.0.1" version = "0.0.1"
@ -16,6 +23,6 @@ allprojects {
targetCompatibility = "1.8" targetCompatibility = "1.8"
repositories { repositories {
jcenter() mavenCentral()
} }
} }

View File

@ -0,0 +1,6 @@
allprojects {
apply plugin: "nebula.lint"
gradleLint {
rules = ['dependency-parenthesis']
}
}

View File

@ -0,0 +1 @@
/build/

View File

@ -0,0 +1,15 @@
description = "Introduction to Gradle Lint Plugin"
ext {
awsVersion = '2.20.83'
}
dependencies {
implementation platform("software.amazon.awssdk:bom:$awsVersion")
testImplementation('junit:junit:4.13.1')
gradleLint.ignore('unused-dependency', 'dependency-parentheses') {
implementation('software.amazon.awssdk:sts')
}
}

View File

@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip

View File

@ -0,0 +1,16 @@
import com.netflix.nebula.lint.plugin.GradleLintPlugin
initscript {
repositories { mavenCentral() }
dependencies {
classpath 'com.netflix.nebula:gradle-lint-plugin:18.1.0'
}
}
allprojects {
apply plugin: GradleLintPlugin
gradleLint {
rules=[]
alwaysRun= false
}
}

View File

@ -3,3 +3,4 @@ include 'java-exec'
include 'unused-dependencies' include 'unused-dependencies'
include 'source-sets' include 'source-sets'
include 'cmd-line-args' include 'cmd-line-args'
include 'gradle-lint-intro'

View File

@ -101,6 +101,7 @@
<module>spring-data-shardingsphere</module> <module>spring-data-shardingsphere</module>
<!-- <module>spring-hibernate-3</module> FAILED --> <!-- <module>spring-hibernate-3</module> FAILED -->
<!-- <module>spring-hibernate-5</module> FAILED --> <!-- long running --> <!-- <module>spring-hibernate-5</module> FAILED --> <!-- long running -->
<module>spring-hibernate-6</module>
<module>spring-jpa</module> <module>spring-jpa</module>
<module>spring-jpa-2</module> <module>spring-jpa-2</module>
<module>spring-jdbc</module> <module>spring-jdbc</module>
@ -114,7 +115,7 @@
<module>java-mongodb</module> <module>java-mongodb</module>
<module>questdb</module> <module>questdb</module>
<module>neo4j</module> <module>neo4j</module>
<module>rethinkdb</module> <!--<module>rethinkdb</module>--> <!-- JAVA-25297 -->
<module>scylladb</module> <module>scylladb</module>
<module>spring-data-cassandra-2</module> <module>spring-data-cassandra-2</module>
<module>spring-data-jpa-repo-3</module> <module>spring-data-jpa-repo-3</module>

View File

@ -2,3 +2,4 @@
- [Using Test Containers With Spring Data Cassandra](https://www.baeldung.com/spring-data-cassandra-test-containers) - [Using Test Containers With Spring Data Cassandra](https://www.baeldung.com/spring-data-cassandra-test-containers)
- [Cassandra Object Mapping with DataStax Java Driver](https://www.baeldung.com/cassandra-object-mapping-datastax-java-driver) - [Cassandra Object Mapping with DataStax Java Driver](https://www.baeldung.com/cassandra-object-mapping-datastax-java-driver)
- [Query With IN Clause in Spring Data Cassandra](https://www.baeldung.com/spring-cassandra-query-in-clause)

View File

@ -0,0 +1,4 @@
FROM couchbase/server:community-5.0.1
COPY configure.sh /configure.sh
CMD ["/configure.sh"]

View File

@ -0,0 +1,106 @@
#!/bin/bash
function retry() {
for i in $(seq 1 10); do
$1 "$2"
if [[ $? == 0 ]]; then
return 0
fi
sleep 1
done
return 1
}
function bucketCreate(){
couchbase-cli bucket-create -c localhost -u Administrator -p password \
--bucket="$1" \
--bucket-type=couchbase \
--bucket-ramsize=512 \
--bucket-replica=1 \
--wait
if [[ $? != 0 ]]; then
return 1
fi
}
function userCreate(){
createOutput=$(couchbase-cli user-manage -c localhost -u Administrator -p password \
--set --rbac-username "$1" --rbac-password "$1" \
--roles admin --auth-domain local)
if [[ $? != 0 ]]; then
echo $createOutput >&2
return 1
fi
}
function clusterUp(){
# wait for service to come up
until $(curl --output /dev/null --silent --head --fail http://localhost:8091); do
printf '.'
sleep 1
done
# initialize cluster
initOutput=$(couchbase-cli cluster-init -c localhost \
--cluster-username=Administrator \
--cluster-password=password \
--cluster-port=8091 \
--services=data,index,query,fts \
--cluster-ramsize=1024 \
--cluster-index-ramsize=256 \
--cluster-fts-ramsize=256 \
--index-storage-setting=default)
if [[ $? != 0 ]]; then
echo $initOutput >&2
return 1
fi
}
function main(){
set -ex
echo "Couchbase UI :8091"
echo "Couchbase logs /opt/couchbase/var/lib/couchbase/logs"
./entrypoint.sh couchbase-server &
if [[ $? != 0 ]]; then
echo "Couchbase startup failed. Exiting." >&2
exit 1
fi
clusterUp
if [[ $? != 0 ]]; then
echo "Cluster init failed. Exiting." >&2
exit 1
fi
retry userCreate baeldung
if [[ $? != 0 ]]; then
echo "User create failed. Exiting." >&2
exit 1
fi
retry userCreate baeldung2
if [[ $? != 0 ]]; then
echo "User create failed. Exiting." >&2
exit 1
fi
retry bucketCreate baeldung
if [[ $? != 0 ]]; then
echo "Bucket create failed. Exiting." >&2
exit 1
fi
retry bucketCreate baeldung2
if [[ $? != 0 ]]; then
echo "Bucket create failed. Exiting." >&2
exit 1
fi
set +ex
# entrypoint.sh launches the server but since config.sh is pid 1 we keep it
# running so that the docker container does not exit.
wait
}
main

View File

@ -0,0 +1,14 @@
#!/bin/bash
# setup
set -ex
docker rm couchbase_container -f
# main
docker build -t couchbase_image .
# cleanup
set +ex
# run
docker run -d --name couchbase_container -p 8091-8096:8091-8096 -p 11210-11211:11210-11211 couchbase_image

View File

@ -12,16 +12,10 @@ import org.springframework.test.context.support.DependencyInjectionTestExecution
/** /**
* This LiveTest requires: * This LiveTest requires:
* *
* 1- Couchbase instance running (e.g. with `docker run -d --name db -p 8091-8096:8091-8096 -p 11210-11211:11210-11211 couchbase`) * 1- Couchbase 5 instance Running and Configured.
* It's enough to execute the "dockerbuild.sh" script in the test/docker folder.
* *
* * 2.1- Spacial View: Add new spacial view (in Index tab) in document 'campus_spatial', view 'byLocation' with the following function:
* 2- Couchbase configured with (we can use the console in localhost:8091):
*
* 2.1- Buckets: named 'baeldung' and 'baeldung2'
*
* 2.2- Security: users 'baeldung' and 'baeldung2'. Note: in newer versions an empty password is not allowed, then we have to change the passwords in the project)
*
* 2.3- Spacial View: Add new spacial view (in Index tab) in document 'campus_spatial', view 'byLocation' with the following function:
* {@code * {@code
* function (doc) { * function (doc) {
* if (doc.location && * if (doc.location &&
@ -30,8 +24,9 @@ import org.springframework.test.context.support.DependencyInjectionTestExecution
* } * }
* }} * }}
* *
* 2.4- MapReduce Views: Add new views in document 'campus': * 2.2- MapReduce Views: Add new views in document 'campus':
* 2.4.1- view 'all' with function: *
* 2.2.1- view 'all' with function:
* {@code * {@code
* function (doc, meta) { * function (doc, meta) {
* if(doc._class == "com.baeldung.spring.data.couchbase.model.Campus") { * if(doc._class == "com.baeldung.spring.data.couchbase.model.Campus") {
@ -39,7 +34,7 @@ import org.springframework.test.context.support.DependencyInjectionTestExecution
* } * }
* }} * }}
* *
* 2.4.2- view 'byName' with function: * 2.2.2- view 'byName' with function:
* {@code * {@code
* function (doc, meta) { * function (doc, meta) {
* if(doc._class == "com.baeldung.spring.data.couchbase.model.Campus" && * if(doc._class == "com.baeldung.spring.data.couchbase.model.Campus" &&

View File

@ -1,26 +0,0 @@
package com.baeldung.spring.data.couchbase;
import org.springframework.data.couchbase.core.convert.MappingCouchbaseConverter;
public class CustomTypeKeyCouchbaseConfig extends MyCouchbaseConfig {
@Override
public String getConnectionString() {
return NODE_LIST;
}
@Override
public String getUserName() {
return BUCKET_USERNAME;
}
@Override
public String getPassword() {
return BUCKET_PASSWORD;
}
@Override
public String typeKey() {
return MappingCouchbaseConverter.TYPEKEY_SYNCGATEWAY_COMPATIBLE;
}
}

View File

@ -1,11 +0,0 @@
package com.baeldung.spring.data.couchbase;
import com.couchbase.client.java.query.QueryScanConsistency;
public class ReadYourOwnWritesCouchbaseConfig extends MyCouchbaseConfig {
@Override
public QueryScanConsistency getDefaultConsistency() {
return QueryScanConsistency.REQUEST_PLUS;
}
}

View File

@ -8,31 +8,19 @@
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-spring-5</artifactId> <artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-spring-5</relativePath> <relativePath>../../parent-boot-2</relativePath>
</parent> </parent>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.springframework.data</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-data-mongodb</artifactId> <artifactId>spring-boot-starter-data-mongodb</artifactId>
<version>${org.springframework.data.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.mongodb</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>mongodb-driver-sync</artifactId> <artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
<version>${mongodb-driver.version}</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-reactivestreams</artifactId>
<version>${mongodb-reactivestreams.version}</version>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
<version>${projectreactor.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.projectreactor</groupId> <groupId>io.projectreactor</groupId>
@ -40,23 +28,6 @@
<version>${projectreactor.version}</version> <version>${projectreactor.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>com.querydsl</groupId> <groupId>com.querydsl</groupId>
<artifactId>querydsl-mongodb</artifactId> <artifactId>querydsl-mongodb</artifactId>
@ -103,12 +74,9 @@
</build> </build>
<properties> <properties>
<org.springframework.data.version>3.4.7</org.springframework.data.version>
<querydsl.version>5.0.0</querydsl.version> <querydsl.version>5.0.0</querydsl.version>
<mysema.maven.version>1.1.3</mysema.maven.version> <mysema.maven.version>1.1.3</mysema.maven.version>
<mongodb-reactivestreams.version>4.1.0</mongodb-reactivestreams.version>
<projectreactor.version>3.5.4</projectreactor.version> <projectreactor.version>3.5.4</projectreactor.version>
<mongodb-driver.version>4.6.1</mongodb-driver.version>
<embed.mongo.version>4.6.3</embed.mongo.version> <embed.mongo.version>4.6.3</embed.mongo.version>
</properties> </properties>

View File

@ -28,6 +28,7 @@ import com.baeldung.model.User;
* *
* This test requires: * This test requires:
* * mongodb instance running on the environment * * mongodb instance running on the environment
* Run the src/live-test/resources/live-test-setup.sh
* *
*/ */
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)

View File

@ -26,6 +26,7 @@ import com.baeldung.repository.UserRepository;
* *
* This test requires: * This test requires:
* * mongodb instance running on the environment * * mongodb instance running on the environment
* Run the src/live-test/resources/live-test-setup.sh
* *
*/ */
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)

View File

@ -4,10 +4,7 @@ This module contains articles about Hibernate 5 with Spring.
### Relevant articles ### Relevant articles
- [Programmatic Transactions in the Spring TestContext Framework](https://www.baeldung.com/spring-test-programmatic-transactions)
- [Introduction to Hibernate Search](https://www.baeldung.com/hibernate-search) - [Introduction to Hibernate Search](https://www.baeldung.com/hibernate-search)
- [@DynamicUpdate with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-dynamicupdate)
- [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache) - [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache)
- [Deleting Objects with Hibernate](http://www.baeldung.com/delete-with-hibernate) - [Deleting Objects with Hibernate](http://www.baeldung.com/delete-with-hibernate)
- [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource) - [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource)
- [Bootstrapping Hibernate 5 with Spring](https://www.baeldung.com/hibernate-5-spring)

View File

@ -1,24 +0,0 @@
package com.baeldung.hibernate.bootstrap;
import com.google.common.base.Preconditions;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EnableTransactionManagement
@ImportResource({ "classpath:hibernate5Configuration.xml" })
public class HibernateXMLConf {
}

View File

@ -1,44 +0,0 @@
package com.baeldung.hibernate.dynamicupdate;
import javax.transaction.Transactional;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Commit;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.hibernate.dynamicupdate.model.Account;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = DynamicUpdateConfig.class, loader = AnnotationConfigContextLoader.class)
@Transactional
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class DynamicUpdateIntegrationTest {
private static final Integer ACCOUNT_ID = 1;
@Autowired
private AccountRepository accountRepository;
@Test
@Commit
public void testA_whenTestAccountIsSaved_thenSuccess() {
Account account = new Account(ACCOUNT_ID, "account1", "regional", true);
accountRepository.save(account);
}
@Test
@Commit
// Enable Hibernate's debug logging in logback.xml to see the generated SQL statement.
public void testB_whenAccountNameUpdated_thenSuccess() {
Account account = accountRepository.findOne(ACCOUNT_ID);
account.setName("Test Account");
accountRepository.save(account);
}
}

View File

@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -0,0 +1,9 @@
## Hibernate 6 with Spring
This module contains articles about Hibernate 6 with Spring.
### Relevant articles
- [Programmatic Transactions in the Spring TestContext Framework](https://www.baeldung.com/spring-test-programmatic-transactions)
- [@DynamicUpdate with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-dynamicupdate)
- [Bootstrapping Hibernate 5 with Spring](https://www.baeldung.com/hibernate-5-spring)

View File

@ -0,0 +1,109 @@
<?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>spring-hibernate-6</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-hibernate-6</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>persistence-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- persistence -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${org.springframework.data.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-dbcp</artifactId>
<version>${tomcat-dbcp.version}</version>
</dependency>
<!-- validation -->
<!-- utils -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>${org.springframework.security.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>${hsqldb.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
</dependencies>
<properties>
<!-- Spring -->
<org.springframework.version>6.0.11</org.springframework.version>
<org.springframework.data.version>3.1.3</org.springframework.data.version>
<org.springframework.security.version>6.1.3</org.springframework.security.version>
<!-- persistence -->
<hibernate.version>6.2.8.Final</hibernate.version>
<mysql-connector-java.version>8.0.7-dmr</mysql-connector-java.version>
<tomcat-dbcp.version>9.0.80</tomcat-dbcp.version>
</properties>
</project>

View File

@ -0,0 +1,12 @@
package com.baeldung.hibernate.bootstrap;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@ImportResource({ "classpath:hibernate6Configuration.xml" })
public class HibernateXMLConf {
}

View File

@ -1,7 +1,7 @@
package com.baeldung.hibernate.bootstrap.model; package com.baeldung.hibernate.bootstrap.model;
import javax.persistence.Entity; import jakarta.persistence.Entity;
import javax.persistence.Id; import jakarta.persistence.Id;
@Entity @Entity
public class TestEntity { public class TestEntity {

View File

@ -2,7 +2,7 @@ package com.baeldung.hibernate.dynamicupdate;
import java.util.Properties; import java.util.Properties;
import javax.persistence.EntityManagerFactory; import jakarta.persistence.EntityManagerFactory;
import javax.sql.DataSource; import javax.sql.DataSource;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;

View File

@ -2,9 +2,9 @@ package com.baeldung.hibernate.dynamicupdate.model;
import java.text.MessageFormat; import java.text.MessageFormat;
import javax.persistence.Column; import jakarta.persistence.Column;
import javax.persistence.Entity; import jakarta.persistence.Entity;
import javax.persistence.Id; import jakarta.persistence.Id;
import org.hibernate.annotations.DynamicUpdate; import org.hibernate.annotations.DynamicUpdate;

View File

@ -0,0 +1,8 @@
package com.baeldung.persistence.dao;
import com.baeldung.persistence.model.Foo;
import com.baeldung.persistence.dao.common.IOperations;
public interface IFooDao extends IOperations<Foo> {
//
}

View File

@ -0,0 +1,14 @@
package com.baeldung.persistence.dao.common;
import java.io.Serializable;
import com.google.common.base.Preconditions;
public abstract class AbstractDao<T extends Serializable> implements IOperations<T> {
protected Class<T> clazz;
protected final void setClazz(final Class<T> clazzToSet) {
clazz = Preconditions.checkNotNull(clazzToSet);
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.persistence.dao.common;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.google.common.base.Preconditions;
@SuppressWarnings("unchecked")
public abstract class AbstractHibernateDao<T extends Serializable> extends AbstractDao<T> implements IOperations<T> {
@Autowired
protected SessionFactory sessionFactory;
// API
@Override
public T findOne(final long id) {
return (T) getCurrentSession().get(clazz, id);
}
@Override
public List<T> findAll() {
return getCurrentSession().createQuery("from " + clazz.getName()).getResultList();
}
@Override
public void create(final T entity) {
Preconditions.checkNotNull(entity);
getCurrentSession().saveOrUpdate(entity);
}
@Override
public T update(final T entity) {
Preconditions.checkNotNull(entity);
return (T) getCurrentSession().merge(entity);
}
@Override
public void delete(final T entity) {
Preconditions.checkNotNull(entity);
getCurrentSession().delete(entity);
}
@Override
public void deleteById(final long entityId) {
final T entity = findOne(entityId);
Preconditions.checkState(entity != null);
delete(entity);
}
protected Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.persistence.dao.common;
import java.io.Serializable;
import java.util.List;
public interface IOperations<T extends Serializable> {
T findOne(final long id);
List<T> findAll();
void create(final T entity);
T update(final T entity);
void delete(final T entity);
void deleteById(final long entityId);
}

View File

@ -0,0 +1,19 @@
package com.baeldung.persistence.dao.impl;
import com.baeldung.persistence.dao.common.AbstractHibernateDao;
import com.baeldung.persistence.dao.IFooDao;
import com.baeldung.persistence.model.Foo;
import org.springframework.stereotype.Repository;
@Repository
public class FooHibernateDao extends AbstractHibernateDao<Foo> implements IFooDao {
public FooHibernateDao() {
super();
setClazz(Foo.class);
}
// API
}

View File

@ -0,0 +1,73 @@
package com.baeldung.persistence.model;
import jakarta.persistence.*;
import java.io.Serializable;
@Entity
public class Foo implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private long id;
@Column(name = "name")
private String name;
public Foo() {
super();
}
public Foo(final String name) {
super();
this.name = name;
}
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Foo other = (Foo) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Foo [name=").append(name).append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,82 @@
package com.baeldung.spring;
import com.baeldung.persistence.dao.IFooDao;
import com.baeldung.persistence.dao.impl.FooHibernateDao;
import com.google.common.base.Preconditions;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-h2.properties" })
@ComponentScan({ "com.baeldung.persistence" })
public class PersistenceConfig {
@Autowired
private Environment env;
@Bean
public LocalSessionFactoryBean sessionFactory() {
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(myDataSource());
sessionFactory.setPackagesToScan(new String[] { "com.baeldung.persistence.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public DataSource myDataSource() {
final BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
@Bean
public PlatformTransactionManager hibernateTransactionManager() {
final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
@Bean
public IFooDao fooHibernateDao() {
return new FooHibernateDao();
}
private final Properties hibernateProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", "false");
// Envers properties
hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix"));
return hibernateProperties;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.baeldung.persistence.dao", "com.baeldung.persistence.service" })
@ImportResource({ "classpath:hibernate6Config.xml" })
public class PersistenceXmlConfig {
}

View File

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
>
<context:property-placeholder location="classpath:persistence-mysql.properties"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.baeldung.persistence.model"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.eventGeneratedId}"/>
<property name="password" value="${jdbc.pass}"/>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
</beans>

View File

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:persistence-h2.properties"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.baeldung.hibernate.bootstrap.model"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.pass}"/>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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