Merge remote-tracking branch 'upstream/master'

This commit is contained in:
mcasari 2023-10-01 21:48:56 +02:00
commit a493c570ad
429 changed files with 4132 additions and 625 deletions

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

@ -0,0 +1,32 @@
---
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. You can find the link to the module in the Conclusion section in the "on Github" standard phase.
**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.

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.

3
apache-poi-3/README.md Normal file
View File

@ -0,0 +1,3 @@
## Relevant Articles
- [How To Convert Excel Data Into List Of Java Objects](https://www.baeldung.com/java-convert-excel-data-into-list)
- [Expand Columns with Apache POI](https://www.baeldung.com/java-apache-poi-expand-columns)

View File

@ -24,10 +24,74 @@
<artifactId>poi-scratchpad</artifactId> <artifactId>poi-scratchpad</artifactId>
<version>${poi.version}</version> <version>${poi.version}</version>
</dependency> </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> </dependencies>
<properties> <properties>
<poi.version>5.2.3</poi.version> <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> </properties>
</project> </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

@ -5,3 +5,4 @@
- [Collecting Stream Elements into a List in Java](https://www.baeldung.com/java-stream-to-list-collecting) - [Collecting Stream Elements into a List in Java](https://www.baeldung.com/java-stream-to-list-collecting)
- [New Features in Java 16](https://www.baeldung.com/java-16-new-features) - [New Features in Java 16](https://www.baeldung.com/java-16-new-features)
- [Guide to Java 8 groupingBy Collector](https://www.baeldung.com/java-groupingby-collector) - [Guide to Java 8 groupingBy Collector](https://www.baeldung.com/java-groupingby-collector)
- [Value-Based Classes in Java](https://www.baeldung.com/java-value-based-classes)

View File

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

View File

@ -12,23 +12,36 @@
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
</parent> </parent>
<!-- <build>--> <properties>
<!-- <plugins>--> <maven.compiler.source.version>21</maven.compiler.source.version>
<!-- <plugin>--> <maven.compiler.target.version>21</maven.compiler.target.version>
<!-- <groupId>org.apache.maven.plugins</groupId>--> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- <artifactId>maven-compiler-plugin</artifactId>--> </properties>
<!-- <configuration>-->
<!-- <source>{maven.compiler.source.version}</source>-->
<!-- <target>{maven.compiler.target.version}</target>-->
<!-- </configuration>-->
<!-- </plugin>-->
<!-- </plugins>-->
<!-- </build>-->
<!-- <properties>--> <build>
<!-- <maven.compiler.source.version>21</maven.compiler.source.version>--> <plugins>
<!-- <maven.compiler.target.version>21</maven.compiler.target.version>--> <plugin>
<!-- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>--> <groupId>org.apache.maven.plugins</groupId>
<!-- </properties>--> <artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>21</source>
<target>21</target>
<!-- Needed due to a bug with JDK 21, described here: https://issues.apache.org/jira/browse/MCOMPILER-546?page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel&focusedCommentId=17767513 -->
<debug>false</debug>
<compilerArgs>
<arg>--enable-preview</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>
</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,11 @@
package com.baeldung.unnamed.variables;
public record Car<T extends Engine>(String name, String color, T engine) { }
abstract class Engine { }
class GasEngine extends Engine { }
class ElectricEngine extends Engine { }
class HybridEngine extends Engine { }

View File

@ -0,0 +1,50 @@
package com.baeldung.unnamed.variables;
public class UnnamedPatterns {
static String getObjectsColorWithNamedPattern(Object object) {
if (object instanceof Car(String name, String color, Engine engine)) {
return color;
}
return "No color!";
}
static String getObjectsColorWithUnnamedPattern(Object object) {
if (object instanceof Car(_, String color, _)) {
return color;
}
return "No color!";
}
static String getObjectsColorWithSwitchAndNamedPattern(Object object) {
return switch (object) {
case Car(String name, String color, Engine engine) -> color;
default -> "No color!";
};
}
static String getObjectsColorWithSwitchAndUnnamedPattern(Object object) {
return switch (object) {
case Car(_, String color, _) -> color;
default -> "No color!";
};
}
static String getEngineTypeWithNamedPattern(Car<?> car) {
return switch (car) {
case Car(String name, String color, GasEngine engine) -> "gas";
case Car(String name, String color, ElectricEngine engine) -> "electric";
case Car(String name, String color, HybridEngine engine) -> "hybrid";
default -> "none";
};
}
static String getEngineTypeWithUnnamedPattern(Car<?> car) {
return switch (car) {
case Car(_, _, GasEngine _) -> "gas";
case Car(_, _, ElectricEngine _) -> "electric";
case Car(_, _, HybridEngine _) -> "hybrid";
default -> "none";
};
}
}

View File

@ -0,0 +1,134 @@
package com.baeldung.unnamed.variables;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
class Transaction implements AutoCloseable {
@Override
public void close() {
System.out.println("Closed!");
}
}
public class UnnamedVariables {
static int countCarsOverLimitWithNamedVariable(Collection<Car<?>> cars, int limit) {
var total = 0;
var totalOverLimit = 0;
for (var car : cars) {
total++;
if (total > limit) {
totalOverLimit++;
// side effect
}
}
return totalOverLimit;
}
static int countCarsOverLimitWithUnnamedVariable(Collection<Car<?>> cars, int limit) {
var total = 0;
var totalOverLimit = 0;
for (var _ : cars) {
total++;
if (total > limit) {
totalOverLimit++;
// side effect
}
}
return totalOverLimit;
}
static void sendNotificationToCarsWithNamedVariable(Collection<Car<?>> cars) {
sendOneTimeNotification();
for (int i = 0; i < cars.size(); i++) {
// Notify car
}
}
static void sendNotificationToCarsWithUnnamedVariable(Collection<Car<?>> cars) {
for (int i = 0, _ = sendOneTimeNotification(); i < cars.size(); i++) {
// Notify car
}
}
private static int sendOneTimeNotification() {
System.out.println("Sending one time notification!");
return 1;
}
static Car<?> removeThreeCarsAndReturnFirstRemovedWithNamedVariables(Queue<Car<?>> cars) {
var x = cars.poll();
var y = cars.poll();
var z = cars.poll();
return x;
}
static Car<?> removeThreeCarsAndReturnFirstRemovedWithUnnamedVariables(Queue<Car<?>> cars) {
var car = cars.poll();
var _ = cars.poll();
var _ = cars.poll();
return car;
}
static void handleCarExceptionWithNamedVariables(Car<?> car) {
try {
someOperationThatFails(car);
} catch (IllegalStateException ex) {
System.out.println("Got an illegal state exception for: " + car.name());
} catch (RuntimeException ex) {
System.out.println("Got a runtime exception!");
}
}
static void handleCarExceptionWithUnnamedVariables(Car<?> car) {
try {
someOperationThatFails(car);
} catch (IllegalStateException | NumberFormatException _) {
System.out.println("Got an illegal state exception for: " + car.name());
} catch (RuntimeException _) {
System.out.println("Got a runtime exception!");
}
}
static void obtainTransactionAndUpdateCarWithNamedVariables(Car<?> car) {
try (var transaction = new Transaction()) {
updateCar(car);
}
}
static void obtainTransactionAndUpdateCarWithUnnamedVariables(Car<?> car) {
try (var _ = new Transaction()) {
updateCar(car);
}
}
static void updateCar(Car<?> car) {
// Some update logic
System.out.println("Car updated!");
}
static Map<String, List<Car<?>>> getCarsByFirstLetterWithNamedVariables(List<Car<?>> cars) {
Map<String, List<Car<?>>> carMap = new HashMap<>();
cars.forEach(car ->
carMap.computeIfAbsent(car.name().substring(0, 1), firstLetter -> new ArrayList<>()).add(car)
);
return carMap;
}
static Map<String, List<Car<?>>> getCarsByFirstLetterWithUnnamedVariables(List<Car<?>> cars) {
Map<String, List<Car<?>>> carMap = new HashMap<>();
cars.forEach(car ->
carMap.computeIfAbsent(car.name().substring(0, 1), _ -> new ArrayList<>()).add(car)
);
return carMap;
}
private static void someOperationThatFails(Car<?> car) {
throw new IllegalStateException("Triggered exception for: " + car.name());
}
}

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

@ -0,0 +1,13 @@
package com.baeldung.unnamed.variables;
import java.util.List;
class CarScenario {
protected final List<Car<?>> cars = List.of(
new Car<>("Mitsubishi", "blue", new GasEngine()),
new Car<>("Toyota", "red", new ElectricEngine()),
new Car<>("Jaguar", "white", new HybridEngine())
);
}

View File

@ -0,0 +1,44 @@
package com.baeldung.unnamed.variables;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getEngineTypeWithNamedPattern;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getEngineTypeWithUnnamedPattern;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithNamedPattern;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithSwitchAndNamedPattern;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithSwitchAndUnnamedPattern;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithUnnamedPattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class UnnamedPatternsUnitTest extends CarScenario {
@Test
public void whenExtractingColorWithNamedPatterns_thenReturnBlue() {
assertEquals("blue", getObjectsColorWithNamedPattern(cars.get(0)));
}
@Test
public void whenExtractingColorWithUnnamedPatterns_thenReturnBlue() {
assertEquals("blue", getObjectsColorWithUnnamedPattern(cars.get(0)));
}
@Test
public void whenExtractingColorWithSwitchAndNamedPatterns_thenReturnBlue() {
assertEquals("blue", getObjectsColorWithSwitchAndNamedPattern(cars.get(0)));
}
@Test
public void whenExtractingColorWithSwitchAndUnnamedPatterns_thenReturnBlue() {
assertEquals("blue", getObjectsColorWithSwitchAndUnnamedPattern(cars.get(0)));
}
@Test
public void whenExtractingEngineTypeWithNamedPatterns_thenReturnGas() {
assertEquals("gas", getEngineTypeWithNamedPattern(cars.get(0)));
}
@Test
public void whenExtractingEngineTypeWithUnnamedPatterns_thenReturnGas() {
assertEquals("gas", getEngineTypeWithUnnamedPattern(cars.get(0)));
}
}

View File

@ -0,0 +1,93 @@
package com.baeldung.unnamed.variables;
import static com.baeldung.unnamed.variables.UnnamedVariables.countCarsOverLimitWithNamedVariable;
import static com.baeldung.unnamed.variables.UnnamedVariables.countCarsOverLimitWithUnnamedVariable;
import static com.baeldung.unnamed.variables.UnnamedVariables.getCarsByFirstLetterWithNamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.getCarsByFirstLetterWithUnnamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.handleCarExceptionWithNamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.handleCarExceptionWithUnnamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.obtainTransactionAndUpdateCarWithNamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.obtainTransactionAndUpdateCarWithUnnamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.removeThreeCarsAndReturnFirstRemovedWithNamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.removeThreeCarsAndReturnFirstRemovedWithUnnamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.sendNotificationToCarsWithNamedVariable;
import static com.baeldung.unnamed.variables.UnnamedVariables.sendNotificationToCarsWithUnnamedVariable;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.LinkedList;
import org.junit.jupiter.api.Test;
public class UnnamedVariablesUnitTest extends CarScenario {
@Test
public void whenCountingCarsOverLimitWithNamedVariables_thenShouldReturnOne() {
assertEquals(1, countCarsOverLimitWithNamedVariable(cars, 2));
}
@Test
public void whenCountingCarsOverLimitWithUnnamedVariables_thenShouldReturnOne() {
assertEquals(1, countCarsOverLimitWithUnnamedVariable(cars, 2));
}
@Test
public void whenNotifyingCarsWithNamedVariables_thenShouldNotFail() {
assertDoesNotThrow(() -> sendNotificationToCarsWithNamedVariable(cars));
}
@Test
public void whenNotifyingCarsWithUnnamedVariables_thenShouldNotFail() {
assertDoesNotThrow(() -> sendNotificationToCarsWithUnnamedVariable(cars));
}
@Test
public void whenPollingCarsWithNamedVariables_thenReturnFirstOneAndEmptyQueue() {
var carQueue = new LinkedList<>(cars);
assertEquals("Mitsubishi", removeThreeCarsAndReturnFirstRemovedWithNamedVariables(carQueue).name());
assertEquals(0, carQueue.size());
}
@Test
public void whenPollingCarsWithUnnamedVariables_thenReturnFirstOneAndEmptyQueue() {
var carQueue = new LinkedList<>(cars);
assertEquals("Mitsubishi", removeThreeCarsAndReturnFirstRemovedWithUnnamedVariables(carQueue).name());
assertEquals(0, carQueue.size());
}
@Test
public void whenHandlingExceptionWithNamedVariables_thenNoExceptionIsThrown() {
assertDoesNotThrow(() -> handleCarExceptionWithNamedVariables(cars.get(0)));
}
@Test
public void whenHandlingExceptionWithUnnamedVariables_thenNoExceptionIsThrown() {
assertDoesNotThrow(() -> handleCarExceptionWithUnnamedVariables(cars.get(0)));
}
@Test
public void whenHandlingTransactionUpdateWithNamedVariables_thenNoExceptionIsThrown() {
assertDoesNotThrow(() -> obtainTransactionAndUpdateCarWithNamedVariables(cars.get(0)));
}
@Test
public void whenHandlingTransactionUpdateWithUnnamedVariables_thenNoExceptionIsThrown() {
assertDoesNotThrow(() -> obtainTransactionAndUpdateCarWithUnnamedVariables(cars.get(0)));
}
@Test
public void whenGettingCarsByFirstLetterWithNamedVariables_thenHaveThreeKeys() {
var carsByLetter = getCarsByFirstLetterWithNamedVariables(cars);
assertEquals(1, carsByLetter.get("M").size());
assertEquals(1, carsByLetter.get("T").size());
assertEquals(1, carsByLetter.get("J").size());
}
@Test
public void whenGettingCarsByFirstLetterWithUnnamedVariables_thenHaveThreeKeys() {
var carsByLetter = getCarsByFirstLetterWithUnnamedVariables(cars);
assertEquals(1, carsByLetter.get("M").size());
assertEquals(1, carsByLetter.get("T").size());
assertEquals(1, carsByLetter.get("J").size());
}
}

View File

@ -4,3 +4,4 @@ This module contains articles about Java 9 streams
### Relevant Articles: ### Relevant Articles:
- [How to Break from Java Stream forEach](https://www.baeldung.com/java-break-stream-foreach) - [How to Break from Java Stream forEach](https://www.baeldung.com/java-break-stream-foreach)
- [Creating Stream of Regex Matches](https://www.baeldung.com/java-stream-regex-matches)

View File

@ -9,3 +9,4 @@ This module contains complete guides about arrays in Java
- [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception) - [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception)
- [Creating a Generic Array in Java](https://www.baeldung.com/java-generic-array) - [Creating a Generic Array in Java](https://www.baeldung.com/java-generic-array)
- [Maximum Size of Java Arrays](https://www.baeldung.com/java-arrays-max-size) - [Maximum Size of Java Arrays](https://www.baeldung.com/java-arrays-max-size)
- [Merge Two Arrays and Remove Duplicates in Java](https://www.baeldung.com/java-merge-two-arrays-delete-duplicates)

View File

@ -0,0 +1,2 @@
## Relevant Articles
- [Find the Middle Element of an Array in Java](https://www.baeldung.com/java-array-middle-item)

View File

@ -14,4 +14,3 @@ This module contains articles about advanced operations on arrays in Java. They
- [Slicing Arrays in Java](https://www.baeldung.com/java-slicing-arrays) - [Slicing Arrays in Java](https://www.baeldung.com/java-slicing-arrays)
- [Combining Two or More Byte Arrays](https://www.baeldung.com/java-concatenate-byte-arrays) - [Combining Two or More Byte Arrays](https://www.baeldung.com/java-concatenate-byte-arrays)
- [Calculating the Sum of Two Arrays in Java](https://www.baeldung.com/java-sum-arrays-element-wise) - [Calculating the Sum of Two Arrays in Java](https://www.baeldung.com/java-sum-arrays-element-wise)
- [Find the Middle Element of an Array in Java](https://www.baeldung.com/java-array-middle-item)

View File

@ -0,0 +1,29 @@
package com.baeldung.incrementchar;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class IncrementCharUnitTest {
@Test
void whenUsingForLoop_thenGenerateCharacters(){
final List<Character> allCapitalCharacters = Arrays.asList('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
List<Character> characters = new ArrayList<>();
for (char character = 'A'; character <= 'Z'; character++) {
characters.add(character);
}
Assertions.assertEquals(characters, allCapitalCharacters);
}
@Test
void whenUsingStreams_thenGenerateCharacters() {
final List<Character> allCapitalCharacters = Arrays.asList('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
final List<Character> characters = IntStream.rangeClosed('A', 'Z').mapToObj(c -> (char) c).collect(Collectors.toList());
Assertions.assertEquals(characters, allCapitalCharacters);
}
}

View File

@ -0,0 +1,126 @@
package com.baeldung.skippingfirstelement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class SkipFirstElementExample {
private final List<String> stringList = new ArrayList<>();
private final Set<String> stringSet = new HashSet<>();
private final Map<String, String> stringMap = new HashMap<>();
public SkipFirstElementExample() {
// Initializing a List
stringList.add("Monday");
stringList.add("Tuesday");
stringList.add("Wednesday");
stringList.add("Thursday");
stringList.add("Friday");
stringList.add("Saturday");
stringList.add("Sunday");
// Initializing a Set
stringSet.add("Monday");
stringSet.add("Tuesday");
stringSet.add("Wednesday");
stringSet.add("Thursday");
stringSet.add("Friday");
stringSet.add("Saturday");
stringSet.add("Sunday");
// Initializing a Map
stringMap.put("Monday", "The day when coffee is a life support system.");
stringMap.put("Tuesday", "The day you realize that Monday's optimism was a lie.");
stringMap.put("Wednesday", "Hump Day, or as it's known, the 'Is it Friday yet?' day.");
stringMap.put("Thursday", "The day that says, 'Hold my beer, Friday is coming!'");
stringMap.put("Friday", "The golden child of the weekdays. The superhero of the workweek.");
stringMap.put("Saturday", "The day of rest? More like the day of 'What can I binge-watch next?'");
stringMap.put("Sunday", "The day before you have to adult again.");
}
void skippingFirstElementInListWithForLoop(List<String> stringList) {
for (int i = 1; i < stringList.size(); i++) {
process(stringList.get(i));
}
}
void skippingFirstElementInListWithWhileLoop(List<String> stringList) {
final Iterator<String> iterator = stringList.iterator();
if (iterator.hasNext()) {
iterator.next();
}
while (iterator.hasNext()) {
process(iterator.next());
}
}
void skippingFirstElementInSetWithWhileLoop(Set<String> stringSet) {
final Iterator<String> iterator = stringSet.iterator();
if (iterator.hasNext()) {
iterator.next();
}
while (iterator.hasNext()) {
process(iterator.next());
}
}
void skippingFirstElementInListWithWhileLoopStoringFirstElement(List<String> stringList) {
final Iterator<String> iterator = stringList.iterator();
String firstElement = null;
if (iterator.hasNext()) {
firstElement = iterator.next();
}
while (iterator.hasNext()) {
process(iterator.next());
// additional logic using fistElement
}
}
void skippingFirstElementInMapWithStreamSkip(Map<String, String> stringMap) {
stringMap.entrySet().stream().skip(1).forEach(this::process);
}
void skippingFirstElementInListWithSubList(List<String> stringList) {
for (final String element : stringList.subList(1, stringList.size())) {
process(element);
}
}
void skippingFirstElementInListWithForLoopWithAdditionalCheck(List<String> stringList) {
for (int i = 0; i < stringList.size(); i++) {
if (i == 0) {
// do something else
} else {
process(stringList.get(i));
}
}
}
void skippingFirstElementInListWithWhileLoopWithCounter(List<String> stringList) {
int counter = 0;
while (counter < stringList.size()) {
if (counter != 0) {
process(stringList.get(counter));
}
++counter;
}
}
void skippingFirstElementInListWithReduce(List<String> stringList) {
stringList.stream().reduce((skip, element) -> {
process(element);
return element;
});
}
protected void process(String string) {
System.out.println(string);
}
protected void process(Entry<String, String> mapEntry) {
System.out.println(mapEntry);
}
}

View File

@ -0,0 +1,122 @@
package com.baeldung.skippingfirstelement;
import static org.junit.jupiter.api.Assertions.*;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.condition.EnabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
@EnabledForJreRange(min = JRE.JAVA_9)
class SkipFirstElementExampleUnitTest {
private static TestableSkipFirstElement testableSkip = new TestableSkipFirstElement();
@BeforeEach
void setup() {
testableSkip.reset();
}
private static Stream<Arguments> listProvider() {
return Stream.of(
Arguments.of(
List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
List.of("Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"))
);
}
private static Stream<Arguments> mapProvider() {
return Stream.of(
Arguments.of(
Map.of(
"Monday", "The day when coffee is a life support system.",
"Tuesday", "The day you realize that Monday's optimism was a lie.",
"Wednesday", "Hump Day, or as it's known, the 'Is it Friday yet?' day.",
"Thursday", "The day that says, 'Hold my beer, Friday is coming!'",
"Friday", "The golden child of the weekdays. The superhero of the workweek.",
"Saturday", "The day of rest? More like the day of 'What can I binge-watch next?'",
"Sunday", "The day before you have to adult again."
)
)
);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithForLoop(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithForLoop(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithWhileLoop(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithWhileLoop(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInSetWithWhileLoop(List<String> input) {
testableSkip.skippingFirstElementInSetWithWhileLoop(new HashSet<>(input));
Set<?> actual = new HashSet<>(testableSkip.getResult());
assertEquals(actual.size(), input.size() - 1);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithWhileLoopStoringFirstElement(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithWhileLoopStoringFirstElement(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("mapProvider")
void skippingFirstElementInMapWithStreamSkip(Map<String, String> input) {
testableSkip.skippingFirstElementInMapWithStreamSkip(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual.size(), input.size() - 1);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithSubList(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithSubList(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithForLoopWithAdditionalCheck(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithForLoopWithAdditionalCheck(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithWhileLoopWithCounter(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithWhileLoopWithCounter(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithReduce(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithReduce(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.skippingfirstelement;
import java.util.List;
public interface TestableSkip {
void reset();
List<?> getResult();
}

View File

@ -0,0 +1,37 @@
package com.baeldung.skippingfirstelement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
public class TestableSkipFirstElement extends SkipFirstElementExample implements TestableSkip {
private List<String> processedList = new ArrayList<>();
private List<Entry<String, String>> processedEntryList = new ArrayList<>();
@Override
public void process(String string) {
processedList.add(string);
}
@Override
public void process(Entry<String, String> stringEntry) {
processedEntryList.add(stringEntry);
}
@Override
public void reset() {
processedList.clear();
processedEntryList.clear();
}
@Override
public List<?> getResult() {
if (!processedList.isEmpty())
return processedList;
return processedEntryList;
}
}

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

@ -0,0 +1,2 @@
## Relevant Articles
- [Check if a List Contains a String Element While Ignoring Case](https://www.baeldung.com/java-list-search-case-insensitive)

View File

@ -0,0 +1,15 @@
<?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-list-6</artifactId>
<name>core-java-collections-list-6</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
</project>

View File

@ -0,0 +1,44 @@
package com.baeldung.lists;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
public class StringListCaseInsensitiveContainsUnitTest {
private final static List<String> THE_LIST = List.of("Game of Thrones", "Forrest Gump", "American Beauty", "Pretty Woman", "Catch Me If You Can");
@Test
void whenUsingContains_thenGetExpectedResult() {
assertFalse(THE_LIST.contains("catch me if you can"));
}
boolean ignoreCaseContainsForLoop(List<String> list, String value) {
for (String e : list) {
if (value.equalsIgnoreCase(e))
return true;
}
return false;
}
@Test
void whenUsingIgnoreCaseContainsForLoop_thenGetExpectedResult() {
assertTrue(ignoreCaseContainsForLoop(THE_LIST, "CATCH me if you CAN"));
assertTrue(ignoreCaseContainsForLoop(THE_LIST, "game of thrones"));
assertFalse(ignoreCaseContainsForLoop(THE_LIST, "The Godfather"));
}
@Test
void whenUsingIgnoreCaseContainsStream_thenGetExpectedResult() {
assertTrue(THE_LIST.stream()
.anyMatch(e -> e.equalsIgnoreCase("CATCH me if you CAN")));
assertTrue(THE_LIST.stream()
.anyMatch("game of thrones"::equalsIgnoreCase));
assertFalse(THE_LIST.stream()
.anyMatch("The Godfather"::equalsIgnoreCase));
}
}

View File

@ -1,76 +0,0 @@
package java.com.baeldung.objecttomap;
import com.google.gson.Gson;
import org.junit.Assert;
import org.junit.Test;
import wiremock.com.fasterxml.jackson.core.type.TypeReference;
import wiremock.com.fasterxml.jackson.databind.ObjectMapper;
import wiremock.com.google.common.reflect.TypeToken;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class ObjectToMapUnitTest {
Employee employee = new Employee("John", 3000.0);
@Test
public void givenJavaObject_whenUsingReflection_thenConvertToMap() throws IllegalAccessException {
Map<String, Object> map = convertUsingReflection(employee);
Assert.assertEquals(employee.getName(), map.get("name"));
Assert.assertEquals(employee.getSalary(), map.get("salary"));
}
private Map<String, Object> convertUsingReflection(Object object) throws IllegalAccessException {
Map<String, Object> map = new HashMap<>();
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
map.put(field.getName(), field.get(object));
}
return map;
}
@Test
public void givenJavaObject_whenUsingJackson_thenConvertToMap() {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> map = objectMapper.convertValue(employee, new TypeReference<Map<String, Object>>() {});
Assert.assertEquals(employee.getName(), map.get("name"));
Assert.assertEquals(employee.getSalary(), map.get("salary"));
}
@Test
public void givenJavaObject_whenUsingGson_thenConvertToMap() {
Gson gson = new Gson();
String json = gson.toJson(employee);
Map<String, Object> map = gson.fromJson(json, new TypeToken<Map<String, Object>>() {}.getType());
Assert.assertEquals(employee.getName(), map.get("name"));
Assert.assertEquals(employee.getSalary(), map.get("salary"));
}
private static class Employee {
private String name;
private Double salary;
public Employee(String name, Double salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double age) {
this.salary = salary;
}
}
}

View File

@ -0,0 +1,128 @@
package com.baeldung.objecttomap;
import static org.junit.Assert.assertEquals;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.junit.Test;
import java.lang.reflect.Field;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class ObjectToMapUnitTest {
Employee employee = new Employee("John", 3000.0);
@Test
public void givenJavaObject_whenUsingReflection_thenConvertToMap() throws IllegalAccessException {
Map<String, Object> map = convertUsingReflection(employee);
assertEquals(employee.getName(), map.get("name"));
assertEquals(employee.getSalary(), map.get("salary"));
}
private Map<String, Object> convertUsingReflection(Object object) throws IllegalAccessException {
Map<String, Object> map = new HashMap<>();
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
map.put(field.getName(), field.get(object));
}
return map;
}
@Test
public void givenJavaObject_whenUsingJackson_thenConvertToMap() {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> map = objectMapper.convertValue(employee, new TypeReference<Map<String, Object>>() {});
assertEquals(employee.getName(), map.get("name"));
assertEquals(employee.getSalary(), map.get("salary"));
}
@Test
public void givenJavaObject_whenUsingGson_thenConvertToMap() {
Gson gson = new Gson();
String json = gson.toJson(employee);
Map<String, Object> map = gson.fromJson(json, new TypeToken<Map<String, Object>>() {}.getType());
assertEquals(employee.getName(), map.get("name"));
assertEquals(employee.getSalary(), map.get("salary"));
}
@Test
public void given_UnsortedMap_whenSortingByValueDescending_thenValuesAreInDescendingOrder() {
Map<String, Integer> unsortedMap = new HashMap<>();
unsortedMap.put("one", 1);
unsortedMap.put("three", 3);
unsortedMap.put("five", 5);
unsortedMap.put("two", 2);
unsortedMap.put("four", 4);
Map<String, Integer> sortedMap = sortMapByValueDescending(unsortedMap);
assertEquals(5, sortedMap.size());
final Iterator<Integer> iterator = sortedMap.values().iterator();
assertEquals(5, (int) iterator.next());
assertEquals(4, (int) iterator.next());
assertEquals(3, (int) iterator.next());
assertEquals(2, (int) iterator.next());
assertEquals(1, (int) iterator.next());
}
@Test
public void given_UnsortedMap_whenUsingTreeMap_thenKeysAreInDescendingOrder() {
SortedMap<String, Integer> treeMap = new TreeMap<>(Comparator.reverseOrder());
treeMap.put("one", 1);
treeMap.put("three", 3);
treeMap.put("five", 5);
treeMap.put("two", 2);
treeMap.put("four", 4);
assertEquals(5, treeMap.size());
final Iterator<String> iterator = treeMap.keySet().iterator();
assertEquals("two", iterator.next());
assertEquals("three", iterator.next());
assertEquals("one", iterator.next());
assertEquals("four", iterator.next());
assertEquals("five", iterator.next());
}
private static class Employee {
private String name;
private Double salary;
public Employee(String name, Double salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double age) {
this.salary = salary;
}
}
public static <K, V extends Comparable<? super V>> Map<K, V> sortMapByValueDescending(Map<K, V> map) {
return map.entrySet().stream()
.sorted(Map.Entry.<K, V>comparingByValue().reversed())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
}
}

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

@ -3,4 +3,4 @@
### Relevant Articles: ### Relevant Articles:
- [Introduction to Javadoc](http://www.baeldung.com/javadoc) - [Introduction to Javadoc](http://www.baeldung.com/javadoc)
- [Code Snippets in Java API Documentation](https://www.baeldung.com/java-doc-code-snippets)

View File

@ -0,0 +1,18 @@
package com.baeldung.snippettag;
/**
*
* External code snippet showing the loop process in binary search method.
* {@snippet class="BinarySearch" region="binary"}
*
* Time Zone
* {@snippet file="application.properties" region="zone"}
*
*/
public class GreetingsExternalSnippet {
public void helloBinarySearch() {
System.out.println("Hi, it's great knowing that binary search uses a loop under the hood");
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.snippettag;
/**
* The code below shows a full highlighted line
* {@snippet :
* public void helloBaeldung() {
* System.out.println("Hello From Team Baeldung"); // @highlight
* }
* }
*
* highlighting a substring
* {@snippet :
* public void helloBaeldung() {
* System.out.println("Hello From Team Baeldung"); // @highlight substring="println"
* }
* }
*
* highlighting texts on multiple lines
* {@snippet :
* public void helloBaeldung() {
* System.out.println("Hello From Team Baeldung"); // @highlight region substring="println"
* String country = "USA";
* System.out.println("Hello From Team " + country); // @end
* }
* }
*
*/
public class GreetingsHighlightTag {
public void helloBaeldung() {
System.out.println("Hello From Team Baeldung");
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.snippettag;
/**
* The code below shows the content of {@code helloBaeldung()} method
* {@snippet :
* public void helloBaeldung() {
* System.out.println("Hello From Team Baeldung");
* }
* }
*/
public class GreetingsInlineSnippet {
public void helloBaeldung() {
System.out.println("Hello From Team Baeldung");
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.snippettag;
/**
*
* Using the replace tag
* {@snippet :
* public void helloBaeldung() {
* System.out.println("Hello From Team Baeldung"); // @replace regex='".*"' replacement="..."
* }
* }
* Using the link tag
* {@snippet :
* public void helloBaeldung() {
* System.out.println("Hello From Team Baeldung"); // @link substring="System.out" target="System#out"
* }
* }
*
*/
public class GreetingsReplaceAndLinkTag {
public void helloBaeldung() {
System.out.println("Hello From Team Baeldung");
}
}

View File

@ -0,0 +1,27 @@
public class BinarySearch {
public int search(int[] list, int item) {
int index = Integer.MAX_VALUE;
int low = 0;
int high = list.length - 1;
// @start region="binary"
while (low <= high) {
int mid = high - low;
int guess = list[mid];
if (guess == item) {
index = mid;
break;
} else if (guess > item) {
low = mid - 1;
} else {
low = mid + 1;
}
low++;
}
// @end region="binary"
return index;
}
}

View File

@ -0,0 +1,4 @@
# @start region="zone"
local.timezone = GMT+1
local.zip = 94123
# @end region="zone"

View File

@ -0,0 +1,2 @@
test-link*
0.*

View File

@ -0,0 +1,8 @@
## Core Java IO
This module contains articles about core Java input and output (IO)
### Relevant Articles:
- [[<-- Prev]](/core-java-modules/core-java-io-4)

View File

@ -0,0 +1,66 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-io-5</artifactId>
<name>core-java-io-5</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<!-- Mime Type Resolution Libraries -->
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>${tika.version}</version>
</dependency>
<dependency>
<groupId>net.sf.jmimemagic</groupId>
<artifactId>jmimemagic</artifactId>
<version>${jmime-magic.version}</version>
</dependency>
<dependency>
<groupId>org.jodd</groupId>
<artifactId>jodd-util</artifactId>
<version>${jodd-util.version}</version>
</dependency>
<dependency>
<groupId>com.j256.simplemagic</groupId>
<artifactId>simplemagic</artifactId>
<version>${simplemagic.version}</version>
</dependency>
</dependencies>
<build>
<finalName>core-java-io-5</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<!-- Mime Type Libraries -->
<tika.version>2.8.0</tika.version>
<jmime-magic.version>0.1.5</jmime-magic.version>
<jodd-util.version>6.2.1</jodd-util.version>
<simplemagic.version>1.17</simplemagic.version>
</properties>
</project>

View File

@ -11,10 +11,8 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import org.apache.tika.mime.MimeTypeException; import org.apache.tika.mime.MimeTypeException;
import org.junit.Test;
import com.j256.simplemagic.ContentType; import com.j256.simplemagic.ContentType;
import org.junit.Test;
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";
@ -37,14 +35,14 @@ public class ExtensionFromMimeTypeUnitTest {
} }
@Test @Test
public void whenUsingMimetypesFileTypeMap_thenGetFileExtension() { public void whenUsingSimpleMagic_thenGetFileExtension() {
List<String> expectedExtensions = Arrays.asList("jpeg", "jpg", "jpe"); List<String> expectedExtensions = Arrays.asList("jpeg", "jpg", "jpe");
String[] detectedExtensions = ContentType.fromMimeType(IMAGE_JPEG_MIME_TYPE).getFileExtensions(); String[] detectedExtensions = ContentType.fromMimeType(IMAGE_JPEG_MIME_TYPE).getFileExtensions();
assertThat(detectedExtensions).containsExactlyElementsOf(expectedExtensions); assertThat(detectedExtensions).containsExactlyElementsOf(expectedExtensions);
} }
@Test @Test
public void whenUsingCustomLogic_thenGetFileExtension() { public void whenUsingCustomMap_thenGetFileExtension() {
Map<String, Set<String>> mimeExtensionsMap = new HashMap<>(); Map<String, Set<String>> mimeExtensionsMap = new HashMap<>();
List<String> expectedExtensions = Arrays.asList(".jpg", ".jpe", ".jpeg"); List<String> expectedExtensions = Arrays.asList(".jpg", ".jpe", ".jpeg");
addMimeExtensions(mimeExtensionsMap, "image/jpeg", ".jpg"); addMimeExtensions(mimeExtensionsMap, "image/jpeg", ".jpg");

View File

@ -7,3 +7,4 @@ This module contains articles about core Java input/output(IO) APIs.
- [Get the Desktop Path in Java](https://www.baeldung.com/java-desktop-path) - [Get the Desktop Path in Java](https://www.baeldung.com/java-desktop-path)
- [Check if a File Is Empty in Java](https://www.baeldung.com/java-check-file-empty) - [Check if a File Is Empty in Java](https://www.baeldung.com/java-check-file-empty)
- [Converting Relative to Absolute Paths in Java](https://www.baeldung.com/java-from-relative-to-absolute-paths) - [Converting Relative to Absolute Paths in Java](https://www.baeldung.com/java-from-relative-to-absolute-paths)
- [Detect EOF in Java](https://www.baeldung.com/java-file-detect-end-of-file)

View File

@ -43,17 +43,6 @@
<version>${angus-activation.version}</version> <version>${angus-activation.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.jodd</groupId>
<artifactId>jodd-util</artifactId>
<version>${jodd-util.version}</version>
</dependency>
<dependency>
<groupId>com.j256.simplemagic</groupId>
<artifactId>simplemagic</artifactId>
<version>${simplemagic.version}</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -153,8 +142,6 @@
<fscontext.version>4.4.2</fscontext.version> <fscontext.version>4.4.2</fscontext.version>
<jakarta-activation-api.version>2.1.2</jakarta-activation-api.version> <jakarta-activation-api.version>2.1.2</jakarta-activation-api.version>
<angus-activation.version>2.0.1</angus-activation.version> <angus-activation.version>2.0.1</angus-activation.version>
<jodd-util.version>6.2.1</jodd-util.version>
<simplemagic.version>1.17</simplemagic.version>
</properties> </properties>
</project> </project>

View File

@ -18,7 +18,11 @@
<artifactId>mapstruct</artifactId> <artifactId>mapstruct</artifactId>
<version>${mapstruct.version}</version> <version>${mapstruct.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>

View File

@ -0,0 +1,47 @@
package com.baeldung.compareobjects;
import java.util.Objects;
public class Address {
private String streetAddress;
private String city;
private String postalCode;
public Address(String streetAddress, String city, String postalCode) {
this.streetAddress = streetAddress;
this.city = city;
this.postalCode = postalCode;
}
public String getStreetAddress() {
return streetAddress;
}
public String getCity() {
return city;
}
public String getPostalCode() {
return postalCode;
}
@Override
public String toString() {
return "Address{" + "streetAddress='" + streetAddress + '\'' + ", city='" + city + '\'' + ", postalCode='" + postalCode + '\'' + '}';
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Address address = (Address) o;
return Objects.equals(streetAddress, address.streetAddress) && Objects.equals(city, address.city) && Objects.equals(postalCode, address.postalCode);
}
@Override
public int hashCode() {
return Objects.hash(streetAddress, city, postalCode);
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.compareobjects;
import java.util.List;
import java.util.Objects;
import org.apache.commons.lang3.builder.DiffExclude;
public class Person {
private String firstName;
private String lastName;
private int age;
private List<PhoneNumber> phoneNumbers;
@DiffExclude
private Address address;
public Person(String firstName, String lastName, int age, List<PhoneNumber> phoneNumbers, Address address) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.phoneNumbers = phoneNumbers;
this.address = address;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public List<PhoneNumber> getPhoneNumbers() {
return phoneNumbers;
}
public Address getAddress() {
return address;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Person person = (Person) o;
return age == person.age && Objects.equals(firstName, person.firstName) && Objects.equals(lastName, person.lastName) && Objects.equals(phoneNumbers, person.phoneNumbers) && Objects.equals(address, person.address);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName, age, phoneNumbers, address);
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.compareobjects;
import org.apache.commons.lang3.builder.DiffBuilder;
import org.apache.commons.lang3.builder.DiffResult;
import org.apache.commons.lang3.builder.ToStringStyle;
public class PersonDiffBuilder {
public static DiffResult compare(Person first, Person second) {
DiffBuilder diffBuilder = new DiffBuilder(first, second, ToStringStyle.DEFAULT_STYLE).append("person", first.getFirstName(), second.getFirstName())
.append("lastName", first.getLastName(), second.getLastName())
.append("streetAddress", first.getAddress()
.getStreetAddress(), second.getAddress()
.getStreetAddress())
.append("city", first.getAddress()
.getCity(), second.getAddress()
.getCity())
.append("postalCode", first.getAddress()
.getPostalCode(), second.getAddress()
.getPostalCode())
.append("age", first.getAge(), second.getAge());
for (int i = 0; i < first.getPhoneNumbers()
.size(); i++) {
diffBuilder.append("phoneNumbers[" + i + "].number", first.getPhoneNumbers()
.get(i)
.getNumber(), second.getPhoneNumbers()
.get(i)
.getNumber());
}
return diffBuilder.build();
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.compareobjects;
import org.apache.commons.lang3.builder.DiffResult;
import org.apache.commons.lang3.builder.ReflectionDiffBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
public class PersonReflectionDiffBuilder {
public static DiffResult compare(Person first, Person second) {
return new ReflectionDiffBuilder<>(first, second, ToStringStyle.SHORT_PREFIX_STYLE).build();
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.compareobjects;
import java.util.Objects;
import org.apache.commons.lang3.builder.DiffExclude;
public class PhoneNumber {
private String type;
private String number;
public PhoneNumber(String type, String number) {
this.type = type;
this.number = number;
}
public String getType() {
return type;
}
public String getNumber() {
return number;
}
@Override
public String toString() {
return "PhoneNumber{" + "type='" + type + '\'' + ", number='" + number + '\'' + '}';
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
PhoneNumber that = (PhoneNumber) o;
return Objects.equals(number, that.number);
}
@Override
public int hashCode() {
return Objects.hash(number);
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.compareobjects;
import static org.junit.jupiter.api.Assertions.assertFalse;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.builder.Diff;
import org.apache.commons.lang3.builder.DiffResult;
import org.junit.jupiter.api.Test;
public class PersonDiffBuilderUnitTest {
@Test
void givenTwoPeopleDifferent_whenComparingWithDiffBuilder_thenDifferencesFound() {
List<PhoneNumber> phoneNumbers1 = new ArrayList<>();
phoneNumbers1.add(new PhoneNumber("home", "123-456-7890"));
phoneNumbers1.add(new PhoneNumber("work", "987-654-3210"));
List<PhoneNumber> phoneNumbers2 = new ArrayList<>();
phoneNumbers2.add(new PhoneNumber("mobile1", "123-456-7890"));
phoneNumbers2.add(new PhoneNumber("mobile2", "987-654-3210"));
Address address1 = new Address("123 Main St", "London", "12345");
Address address2 = new Address("123 Main St", "Paris", "54321");
Person person1 = new Person("John", "Doe", 30, phoneNumbers1, address1);
Person person2 = new Person("Jane", "Smith", 28, phoneNumbers2, address2);
DiffResult<Person> diff = PersonDiffBuilder.compare(person1, person2);
for (Diff<?> d : diff.getDiffs()) {
System.out.println(d.getFieldName() + ": " + d.getLeft() + " != " + d.getRight());
}
assertFalse(diff.getDiffs()
.isEmpty());
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.compareobjects;
import static org.junit.jupiter.api.Assertions.assertFalse;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.builder.Diff;
import org.apache.commons.lang3.builder.DiffResult;
import org.junit.jupiter.api.Test;
public class PersonReflectionDiffBuilderUnitTest {
@Test
void givenTwoPeopleDifferent_whenComparingWithReflectionDiffBuilder_thenDifferencesFound() {
List<PhoneNumber> phoneNumbers1 = new ArrayList<>();
phoneNumbers1.add(new PhoneNumber("home", "123-456-7890"));
phoneNumbers1.add(new PhoneNumber("work", "987-654-3210"));
List<PhoneNumber> phoneNumbers2 = new ArrayList<>();
phoneNumbers2.add(new PhoneNumber("mobile1", "123-456-7890"));
phoneNumbers2.add(new PhoneNumber("mobile2", "987-654-3210"));
Address address1 = new Address("123 Main St", "London", "12345");
Address address2 = new Address("123 Main St", "Paris", "54321");
Person person1 = new Person("John", "Doe", 30, phoneNumbers1, address1);
Person person2 = new Person("Jane", "Smith", 28, phoneNumbers2, address2);
DiffResult<Person> diff = PersonReflectionDiffBuilder.compare(person1, person2);
for (Diff<?> d : diff.getDiffs()) {
System.out.println(d.getFieldName() + ": " + d.getLeft() + " != " + d.getRight());
}
assertFalse(diff.getDiffs()
.isEmpty());
}
}

View File

@ -4,4 +4,5 @@
- [Integer.class vs Integer.TYPE vs int.class](https://www.baeldung.com/java-integer-class-vs-type-vs-int) - [Integer.class vs Integer.TYPE vs int.class](https://www.baeldung.com/java-integer-class-vs-type-vs-int)
- [Does Java Read Integers in Little Endian or Big Endian?](https://www.baeldung.com/java-integers-little-big-endian) - [Does Java Read Integers in Little Endian or Big Endian?](https://www.baeldung.com/java-integers-little-big-endian)
- [How to Split an Integer Number Into Digits in Java](https://www.baeldung.com/java-integer-individual-digits) - [How to Split an Integer Number Into Digits in Java](https://www.baeldung.com/java-integer-individual-digits)
- [Java Double vs. BigDecimal](https://www.baeldung.com/java-double-vs-bigdecimal)
- More articles: [[<-- prev]](../core-java-numbers-5) - More articles: [[<-- prev]](../core-java-numbers-5)

View File

@ -18,6 +18,18 @@
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version> <version>${commons-lang3.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -0,0 +1,15 @@
package com.baeldung.floatdoubleconversions;
public class FloatAndDoubleConversions {
public static void main(String args[]){
float vatRate = 14.432511f;
System.out.println("vatRate:"+vatRate);
Float localTaxRate = 20.12434f;
System.out.println("localTaxRate:"+localTaxRate);
double shootingAverage = 56.00000000000001;
System.out.println("shootingAverage:"+shootingAverage);
Double assistAverage = 81.123000000045;
System.out.println("assistAverage:"+assistAverage);
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.floatdoubleconversions;
import org.junit.Assert;
import org.junit.Test;
public class FloatDoubleConversionsTest {
@Test
public void whenDoubleType_thenFloatTypeSuccess(){
double interestRatesYearly = 13.333333333333334;
float interest = (float) interestRatesYearly;
System.out.println(interest); //13.333333
Assert.assertTrue(Float.class.isInstance(interest));//true
Double monthlyRates = 2.111111111111112;
float rates = monthlyRates.floatValue();
System.out.println(rates); //2.1111112
Assert.assertTrue(Float.class.isInstance(rates));//true
}
@Test
public void whenFloatType_thenDoubleTypeSuccess(){
float gradeAverage =2.05f;
double average = gradeAverage;
System.out.println(average); //2.049999952316284
Assert.assertTrue(Double.class.isInstance(average));//true
Float monthlyRates = 2.1111112f;
Double rates = monthlyRates.doubleValue();
System.out.println(rates); //2.1111112
Assert.assertTrue(Double.class.isInstance(rates));//true
}
}

View File

@ -0,0 +1,26 @@
*.class
0.*
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
.resourceCache
# Packaged files #
*.jar
*.war
*.ear
# Files generated by integration tests
*.txt
backup-pom.xml
/bin/
/temp
#IntelliJ specific
.idea/
*.iml

View File

@ -0,0 +1,7 @@
## Core Java OS
This module contains articles about working with the operating system (OS) in Java
### Relevant Articles:

View File

@ -0,0 +1,42 @@
<?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-os</artifactId>
<name>core-java-os</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-os</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
</properties>
</project>

View File

@ -0,0 +1,9 @@
package com.baeldung.system;
public class EnvironmentExample {
public void getUserName() {
String username = System.getenv("USERNAME");
System.out.println("User: " + username);
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.system;
public class PropertiesExample {
public void getUserName() {
String username = System.getProperty("user.name");
System.out.println("User: " + username);
}
public void getCustomProp() {
String customProperty = System.getProperty("custom.prop");
System.out.println("Custom property: " + customProperty);
}
public void getCustomPropWithFallback() {
String customProperty = System.getProperty("non-existent-property", "default value");
System.out.println("Custom property: " + customProperty);
}
}

View File

@ -1,25 +0,0 @@
package com.baeldung.system;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
@Ignore
public class WhenDetectingOSUnitTest {
private DetectOS os = new DetectOS();
@Test
public void whenUsingSystemProperty_shouldReturnOS() {
String expected = "Windows 10";
String actual = os.getOperatingSystem();
Assert.assertEquals(expected, actual);
}
@Test
public void whenUsingSystemUtils_shouldReturnOS() {
String expected = "Windows 10";
String actual = os.getOperatingSystemSystemUtils();
Assert.assertEquals(expected, actual);
}
}

View File

@ -1,64 +0,0 @@
package com.baeldung.system.exit;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.security.Permission;
import static org.junit.Assert.assertEquals;
@Ignore("This test is ignored because it tests deprecated code")
public class SystemExitUnitTest {
private SecurityManager securityManager;
private SystemExitExample example;
@Before
public void setUp() {
example = new SystemExitExample();
securityManager = System.getSecurityManager();
System.setSecurityManager(new NoExitSecurityManager());
}
@After
public void tearDown() throws Exception {
System.setSecurityManager(securityManager);
}
@Test
public void testExit() throws Exception {
try {
example.readFile();
} catch (ExitException e) {
assertEquals("Exit status", 2, e.status);
}
}
protected static class ExitException extends SecurityException {
private static final long serialVersionUID = 1L;
public final int status;
public ExitException(int status) {
this.status = status;
}
}
private static class NoExitSecurityManager extends SecurityManager {
@Override
public void checkPermission(Permission perm) {
}
@Override
public void checkPermission(Permission perm, Object context) {
}
@Override
public void checkExit(int status) {
super.checkExit(status);
throw new ExitException(status);
}
}
}

View File

@ -0,0 +1,91 @@
package com.baeldung.alphanumeric;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
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;
import org.openjdk.jmh.infra.Blackhole;
@Warmup(iterations = 1)
@Measurement(iterations = 1, time = 1, timeUnit = TimeUnit.MINUTES)
@Fork(1)
public class AlphanumericPerformanceBenchmark {
private static final String TEST_STRING = "ABC123abc123";
private static final String REGEX = "[^[a-zA-Z0-9]*$]";
private static final Pattern PATTERN = Pattern.compile(REGEX);
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void alphanumericRegex(Blackhole blackhole) {
final Matcher matcher = PATTERN.matcher(TEST_STRING);
boolean result = matcher.matches();
blackhole.consume(result);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void alphanumericRegexDirectlyOnString(Blackhole blackhole) {
boolean result = TEST_STRING.matches(REGEX);
blackhole.consume(result);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void alphanumericIteration(Blackhole blackhole) {
boolean result = true;
for (int i = 0; i < TEST_STRING.length(); ++i) {
final int codePoint = TEST_STRING.codePointAt(i);
if (!isAlphanumeric(codePoint)) {
result = false;
break;
}
}
blackhole.consume(result);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void alphanumericIterationWithCharacterChecks(Blackhole blackhole) {
boolean result = true;
for (int i = 0; i < TEST_STRING.length(); ++i) {
final int codePoint = TEST_STRING.codePointAt(i);
if (!Character.isAlphabetic(codePoint) || !Character.isDigit(codePoint)) {
result = false;
break;
}
}
blackhole.consume(result);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void alphanumericIterationWithCopy(Blackhole blackhole) {
boolean result = true;
for (final char c : TEST_STRING.toCharArray()) {
if (!isAlphanumeric(c)) {
result = false;
break;
}
}
blackhole.consume(result);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void alphanumericIterationWithStream(Blackhole blackhole) {
boolean result = TEST_STRING.chars().allMatch(this::isAlphanumeric);
blackhole.consume(result);
}
public boolean isAlphanumeric(final int codePoint) {
return (codePoint >= 65 && codePoint <= 90) ||
(codePoint >= 97 && codePoint <= 172) ||
(codePoint >= 48 && codePoint <= 57);
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.alphanumeric;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class AlphanumericUnitTest {
private AlphanumericPerformanceBenchmark alphanumericPerformanceBenchmark = new AlphanumericPerformanceBenchmark();
@ParameterizedTest
@CsvSource({
"A,true",
"B,true",
"C,true",
"1,true",
"2,true",
"3,true",
"!,false",
"@,false",
"#,false",
"$,false",
"%,false"
})
void shouldCorrectlyIdentifyAlphanumericCharacterTest(char character, boolean result) {
boolean actual = alphanumericPerformanceBenchmark.isAlphanumeric(character);
assertEquals(actual, result);
}
}

View File

@ -12,3 +12,4 @@ This module contains articles about string-related algorithms.
- [Find the First Embedded Occurrence of an Integer in a Java String](https://www.baeldung.com/java-string-find-embedded-integer) - [Find the First Embedded Occurrence of an Integer in a Java String](https://www.baeldung.com/java-string-find-embedded-integer)
- [Find the Most Frequent Characters in a String](https://www.baeldung.com/java-string-find-most-frequent-characters) - [Find the Most Frequent Characters in a String](https://www.baeldung.com/java-string-find-most-frequent-characters)
- [Checking If a String Is a Repeated Substring](https://www.baeldung.com/java-repeated-substring) - [Checking If a String Is a Repeated Substring](https://www.baeldung.com/java-repeated-substring)
- [Check if Letter Is Emoji With Java](https://www.baeldung.com/java-check-letter-emoji)

View File

@ -11,4 +11,3 @@
- [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

@ -10,3 +10,5 @@
- [Check if a String Contains Non-Alphanumeric Characters](https://www.baeldung.com/java-string-test-special-characters) - [Check if a String Contains Non-Alphanumeric Characters](https://www.baeldung.com/java-string-test-special-characters)
- [Check if a String Has All Unique Characters in Java](https://www.baeldung.com/java-check-string-all-unique-chars) - [Check if a String Has All Unique Characters in Java](https://www.baeldung.com/java-check-string-all-unique-chars)
- [Performance Comparison Between Different Java String Concatenation Methods](https://www.baeldung.com/java-string-concatenation-methods) - [Performance Comparison Between Different Java String Concatenation Methods](https://www.baeldung.com/java-string-concatenation-methods)
- [Replacing Single Quote with \ in Java String](https://www.baeldung.com/java-replacing-single-quote-string)

View File

@ -78,6 +78,7 @@
<module>core-java-collections-list</module> <module>core-java-collections-list</module>
<module>core-java-collections-list-2</module> <module>core-java-collections-list-2</module>
<module>core-java-collections-list-3</module> <module>core-java-collections-list-3</module>
<module>core-java-collections-list-6</module>
<module>core-java-collections-maps</module> <module>core-java-collections-maps</module>
<module>core-java-collections-maps-2</module> <module>core-java-collections-maps-2</module>
<module>core-java-collections-maps-3</module> <module>core-java-collections-maps-3</module>
@ -108,6 +109,7 @@
<module>core-java-io-2</module> <module>core-java-io-2</module>
<module>core-java-io-3</module> <module>core-java-io-3</module>
<module>core-java-io-4</module> <module>core-java-io-4</module>
<module>core-java-io-5</module>
<module>core-java-io-apis</module> <module>core-java-io-apis</module>
<module>core-java-io-apis-2</module> <module>core-java-io-apis-2</module>
<module>core-java-io-conversions</module> <module>core-java-io-conversions</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

@ -4,3 +4,4 @@
- [A Guide to Rolling File Appenders](http://www.baeldung.com/java-logging-rolling-file-appenders) - [A Guide to Rolling File Appenders](http://www.baeldung.com/java-logging-rolling-file-appenders)
- [Logging Exceptions Using SLF4J](https://www.baeldung.com/slf4j-log-exceptions) - [Logging Exceptions Using SLF4J](https://www.baeldung.com/slf4j-log-exceptions)
- [Log4j Warning: “No Appenders Could Be Found for Logger”](https://www.baeldung.com/log4j-no-appenders-found) - [Log4j Warning: “No Appenders Could Be Found for Logger”](https://www.baeldung.com/log4j-no-appenders-found)
- [A Guide to Log4j and the log4j.properties File in Java](https://www.baeldung.com/java-log4j-properties-guide)

View File

@ -9,3 +9,4 @@
- [Log4j 2 Plugins](https://www.baeldung.com/log4j2-plugins) - [Log4j 2 Plugins](https://www.baeldung.com/log4j2-plugins)
- [Printing Thread Info in Log File Using Log4j2](https://www.baeldung.com/log4j2-print-thread-info) - [Printing Thread Info in Log File Using Log4j2](https://www.baeldung.com/log4j2-print-thread-info)
- [Log4j2 Logging to Both File and Console](https://www.baeldung.com/java-log4j2-file-and-console) - [Log4j2 Logging to Both File and Console](https://www.baeldung.com/java-log4j2-file-and-console)
- [Log4j 2 Configuration Using a Properties File](https://www.baeldung.com/java-log4j2-config-with-prop-file)

View File

@ -17,30 +17,39 @@
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.apache.camel</groupId> <groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-core</artifactId> <artifactId>camel-spring-boot-starter</artifactId>
<version>${env.camel.version}</version> <version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-jackson-starter</artifactId>
<version>${camel.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.camel</groupId> <groupId>org.apache.camel</groupId>
<artifactId>camel-spring-javaconfig</artifactId> <artifactId>camel-test-spring-junit5</artifactId>
<version>${env.camel.version}</version> <version>${camel.version}</version>
<scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.camel</groupId> <groupId>org.junit.platform</groupId>
<artifactId>camel-jackson</artifactId> <artifactId>junit-platform-launcher</artifactId>
<version>${env.camel.version}</version> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.camel</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>camel-test</artifactId> <artifactId>spring-boot-starter-web</artifactId>
<version>${env.camel.version}</version> </dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<properties> <properties>
<env.camel.version>3.14.7</env.camel.version> <camel.version>3.21.0</camel.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,11 @@
package com.baeldung.camel.apache;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@ -5,14 +5,17 @@ import java.util.Date;
import org.apache.camel.Exchange; import org.apache.camel.Exchange;
import org.apache.camel.Processor; import org.apache.camel.Processor;
import org.springframework.stereotype.Component;
@Component
public class FileProcessor implements Processor { public class FileProcessor implements Processor {
@Override
public void process(Exchange exchange) throws Exception { public void process(Exchange exchange) throws Exception {
String originalFileName = (String) exchange.getIn().getHeader(Exchange.FILE_NAME, String.class); String originalFileName = (String) exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
Date date = new Date(); Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String changedFileName = dateFormat.format(date) + originalFileName; String changedFileName = dateFormat.format(date) + originalFileName;
exchange.getIn().setHeader(Exchange.FILE_NAME, changedFileName); exchange.getIn().setHeader(Exchange.FILE_NAME, changedFileName);
} }

View File

@ -1,7 +1,9 @@
package com.baeldung.camel.apache.file; package com.baeldung.camel.apache.file;
import org.apache.camel.builder.RouteBuilder; import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
@Component
public class FileRouter extends RouteBuilder { public class FileRouter extends RouteBuilder {
private static final String SOURCE_FOLDER = "src/test/source-folder"; private static final String SOURCE_FOLDER = "src/test/source-folder";

View File

@ -1,11 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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-3.1.xsd xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<bean id="fileRouter" class="com.baeldung.camel.apache.file.FileRouter" /> <context:component-scan base-package="com.baeldung.camel.apache"/>
<bean id="fileProcessor" class="com.baeldung.camel.apache.file.FileProcessor" /> <context:annotation-config />
<camelContext xmlns="http://camel.apache.org/schema/spring"> <camelContext xmlns="http://camel.apache.org/schema/spring">
<routeBuilder ref="fileRouter" /> <routeBuilder ref="fileRouter" />

View File

@ -1,31 +1,65 @@
package com.apache.baeldung.camel.jackson; package com.apache.baeldung.camel.jackson;
import com.baeldung.camel.apache.Application;
import com.baeldung.camel.apache.jackson.Fruit;
import org.apache.camel.Configuration;
import org.apache.camel.EndpointInject;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jackson.ListJacksonDataFormat;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.test.annotation.DirtiesContext;
import java.io.IOException; import java.io.IOException;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.List; import java.util.List;
import org.apache.camel.builder.RouteBuilder; import static org.springframework.test.util.AssertionErrors.assertEquals;
import org.apache.camel.component.jackson.ListJacksonDataFormat; import static org.springframework.test.util.AssertionErrors.assertNotNull;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
import com.baeldung.camel.apache.jackson.Fruit; @CamelSpringBootTest
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@SpringBootTest(classes = {Application.class, FruitArrayJacksonUnmarshalUnitTest.TestConfig.class})
public class FruitArrayJacksonUnmarshalUnitTest {
public class FruitArrayJacksonUnmarshalUnitTest extends CamelTestSupport { @Autowired
private ProducerTemplate template;
@EndpointInject("mock:marshalledObject")
private MockEndpoint mock;
@Configuration
static class TestConfig {
@Bean
RoutesBuilder route() {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:jsonInput").unmarshal(new ListJacksonDataFormat(Fruit.class))
.to("mock:marshalledObject");
}
};
}
}
@Test @Test
public void givenJsonFruitArray_whenUnmarshalled_thenSuccess() throws Exception { public void givenJsonFruitArray_whenUnmarshalled_thenSuccess() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:marshalledObject"); mock.setExpectedMessageCount(1);
mock.expectedMessageCount(1);
mock.message(0).body().isInstanceOf(List.class); mock.message(0).body().isInstanceOf(List.class);
String json = readJsonFromFile("/json/fruit-array.json"); String json = readJsonFromFile("/json/fruit-array.json");
template.sendBody("direct:jsonInput", json); template.sendBody("direct:jsonInput", json);
assertMockEndpointsSatisfied(); mock.assertIsSatisfied();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
List<Fruit> fruitList = mock.getReceivedExchanges().get(0).getIn().getBody(List.class); List<Fruit> fruitList = mock.getReceivedExchanges().get(0).getIn().getBody(List.class);
@ -42,21 +76,9 @@ public class FruitArrayJacksonUnmarshalUnitTest extends CamelTestSupport {
assertEquals("Fruit id", 101, fruit.getId()); assertEquals("Fruit id", 101, fruit.getId());
} }
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:jsonInput").unmarshal(new ListJacksonDataFormat(Fruit.class))
.to("mock:marshalledObject");
}
};
}
private String readJsonFromFile(String path) throws URISyntaxException, IOException { private String readJsonFromFile(String path) throws URISyntaxException, IOException {
URL resource = FruitArrayJacksonUnmarshalUnitTest.class.getResource(path); URL resource = FruitArrayJacksonUnmarshalUnitTest.class.getResource(path);
return new String(Files.readAllBytes(Paths.get(resource.toURI()))); return new String(Files.readAllBytes(Paths.get(resource.toURI())), StandardCharsets.UTF_8);
} }
} }

View File

@ -1,32 +1,64 @@
package com.apache.baeldung.camel.jackson; package com.apache.baeldung.camel.jackson;
import com.baeldung.camel.apache.Application;
import com.baeldung.camel.apache.jackson.Fruit;
import com.baeldung.camel.apache.jackson.FruitList;
import org.apache.camel.Configuration;
import org.apache.camel.EndpointInject;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jackson.JacksonDataFormat;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import java.io.IOException; import java.io.IOException;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.List; import java.util.List;
import org.apache.camel.builder.RouteBuilder; import static org.springframework.test.util.AssertionErrors.assertEquals;
import org.apache.camel.component.jackson.JacksonDataFormat; import static org.springframework.test.util.AssertionErrors.assertNotNull;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
import com.baeldung.camel.apache.jackson.Fruit; @CamelSpringBootTest
import com.baeldung.camel.apache.jackson.FruitList; @SpringBootTest(classes = {Application.class, FruitListJacksonUnmarshalUnitTest.TestConfig.class})
public class FruitListJacksonUnmarshalUnitTest {
public class FruitListJacksonUnmarshalUnitTest extends CamelTestSupport { @Autowired
private ProducerTemplate template;
@EndpointInject("mock:marshalledObject")
private MockEndpoint mock;
@Configuration
static class TestConfig {
@Bean
RoutesBuilder route() {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:jsonInput").unmarshal(new JacksonDataFormat(FruitList.class))
.to("mock:marshalledObject");
}
};
}
}
@Test @Test
public void givenJsonFruitList_whenUnmarshalled_thenSuccess() throws Exception { public void givenJsonFruitList_whenUnmarshalled_thenSuccess() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:marshalledObject"); mock.setExpectedMessageCount(1);
mock.expectedMessageCount(1);
mock.message(0).body().isInstanceOf(FruitList.class); mock.message(0).body().isInstanceOf(FruitList.class);
String json = readJsonFromFile("/json/fruit-list.json"); String json = readJsonFromFile("/json/fruit-list.json");
template.sendBody("direct:jsonInput", json); template.sendBody("direct:jsonInput", json);
assertMockEndpointsSatisfied(); mock.assertIsSatisfied();
FruitList fruitList = mock.getReceivedExchanges().get(0).getIn().getBody(FruitList.class); FruitList fruitList = mock.getReceivedExchanges().get(0).getIn().getBody(FruitList.class);
assertNotNull("Fruit lists should not be null", fruitList); assertNotNull("Fruit lists should not be null", fruitList);
@ -43,20 +75,9 @@ public class FruitListJacksonUnmarshalUnitTest extends CamelTestSupport {
assertEquals("Fruit id", 101, fruit.getId()); assertEquals("Fruit id", 101, fruit.getId());
} }
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:jsonInput").unmarshal(new JacksonDataFormat(FruitList.class))
.to("mock:marshalledObject");
}
};
}
private String readJsonFromFile(String path) throws URISyntaxException, IOException { private String readJsonFromFile(String path) throws URISyntaxException, IOException {
URL resource = FruitListJacksonUnmarshalUnitTest.class.getResource(path); URL resource = FruitListJacksonUnmarshalUnitTest.class.getResource(path);
return new String(Files.readAllBytes(Paths.get(resource.toURI()))); return new String(Files.readAllBytes(Paths.get(resource.toURI())), StandardCharsets.UTF_8);
} }
} }

View File

@ -1,16 +1,21 @@
package com.apache.camel.file.processor; package com.apache.camel.file.processor;
import java.io.File; import com.baeldung.camel.apache.file.FileProcessor;
import org.apache.camel.CamelContext; import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder; import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext; import org.apache.camel.impl.DefaultCamelContext;
import org.awaitility.Awaitility;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.baeldung.camel.apache.file.FileProcessor; import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
public class FileProcessorIntegrationTest { public class FileProcessorIntegrationTest {
@ -52,7 +57,7 @@ public class FileProcessorIntegrationTest {
} }
@Test @Test
public void moveFolderContentJavaDSLTest() throws Exception { public void givenJavaDSLRoute_whenCamelStart_thenMoveFolderContent() throws Exception {
final CamelContext camelContext = new DefaultCamelContext(); final CamelContext camelContext = new DefaultCamelContext();
camelContext.addRoutes(new RouteBuilder() { camelContext.addRoutes(new RouteBuilder() {
@Override @Override
@ -61,15 +66,26 @@ public class FileProcessorIntegrationTest {
} }
}); });
camelContext.start(); camelContext.start();
Thread.sleep(DURATION_MILIS); verifyFolderContent();
camelContext.stop(); camelContext.stop();
} }
@Test @Test
public void moveFolderContentSpringDSLTest() throws InterruptedException { public void givenSpringDSLRoute_whenCamelStart_thenMoveFolderContent() throws InterruptedException {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("camel-context-test.xml"); ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("camel-context-test.xml");
Thread.sleep(DURATION_MILIS); verifyFolderContent();
applicationContext.close(); applicationContext.close();
}
private void verifyFolderContent() {
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
File destinationFile1 = new File(DESTINATION_FOLDER + "/" + dateFormat.format(date) + "File1.txt");
File destinationFile2 = new File(DESTINATION_FOLDER + "/" + dateFormat.format(date) + "File2.txt");
Awaitility.await().atMost(DURATION_MILIS, TimeUnit.MILLISECONDS).untilAsserted(() -> {
assertThat(destinationFile1.exists()).isTrue();
assertThat(destinationFile2.exists()).isTrue();
});
} }
} }

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>--> <!-- JAVA-25297 --> <module>rethinkdb</module>
<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

@ -10,7 +10,7 @@ import static com.rethinkdb.RethinkDB.r;
/** /**
* Some tests demonstrating inserting data. * Some tests demonstrating inserting data.
*/ */
public class InsertIntegrationTest extends TestBase { public class InsertIntegrationLiveTest extends TestBase {
/** /**
* Create a table for the tests. * Create a table for the tests.
*/ */

View File

@ -16,7 +16,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* Some tests demonstrating querying data. * Some tests demonstrating querying data.
*/ */
public class QueryIntegrationTest extends TestBase { public class QueryIntegrationLiveTest extends TestBase {
/** /**
* Create a table for the tests. * Create a table for the tests.
*/ */

View File

@ -13,7 +13,7 @@ import static com.rethinkdb.RethinkDB.r;
/** /**
* Some tests demonstrating streaming live changes to data. * Some tests demonstrating streaming live changes to data.
*/ */
public class StreamingIntegrationTest extends TestBase { public class StreamingIntegrationLiveTest extends TestBase {
@Test @Test
public void getLiveInserts() throws InterruptedException { public void getLiveInserts() throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool(); ExecutorService executorService = Executors.newCachedThreadPool();

View File

@ -12,7 +12,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* Some tests demonstrating working with tables. * Some tests demonstrating working with tables.
*/ */
public class TablesIntegrationTest extends TestBase { public class TablesIntegrationLiveTest extends TestBase {
@Test @Test
public void createTable() { public void createTable() {

View File

@ -8,7 +8,7 @@ import static com.rethinkdb.RethinkDB.r;
/** /**
* Some tests demonstrating updating data. * Some tests demonstrating updating data.
*/ */
public class UpdateIntegrationTest extends TestBase { public class UpdateIntegrationLiveTest extends TestBase {
/** /**
* Create a table for the tests. * Create a table for the tests.
*/ */

View File

@ -9,27 +9,12 @@
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId> <artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath> <relativePath>../../parent-boot-3</relativePath>
</parent> </parent>
<dependencies> <dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>${mongodb-driver.version}</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-core</artifactId>
<version>${mongodb-driver.version}</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>bson</artifactId>
<version>${mongodb-driver.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
@ -37,16 +22,6 @@
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId> <artifactId>spring-boot-starter-data-mongodb</artifactId>
<exclusions>
<exclusion>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
</exclusion>
<exclusion>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-core</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.mongodb</groupId> <groupId>org.mongodb</groupId>
@ -57,12 +32,13 @@
<groupId>de.flapdoodle.embed</groupId> <groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId> <artifactId>de.flapdoodle.embed.mongo</artifactId>
<scope>test</scope> <scope>test</scope>
<version>${de.flapdoodle.embed.mongo.version}</version>
</dependency> </dependency>
</dependencies> </dependencies>
<properties> <properties>
<mongodb-crypt.version>1.7.3</mongodb-crypt.version> <start-class>com.baeldung.boot.atlassearch.MongoDbAtlasSearchApplication</start-class>
<mongodb-driver.version>4.9.1</mongodb-driver.version> <mongodb-crypt.version>1.8.0</mongodb-crypt.version>
<de.flapdoodle.embed.mongo.version>4.9.2</de.flapdoodle.embed.mongo.version>
</properties> </properties>
</project> </project>

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