diff --git a/algorithms-miscellaneous-3/pom.xml b/algorithms-miscellaneous-3/pom.xml index 525a2556de..11a64eba8b 100644 --- a/algorithms-miscellaneous-3/pom.xml +++ b/algorithms-miscellaneous-3/pom.xml @@ -37,7 +37,7 @@ org.apache.commons commons-lang3 - ${commons.lang3.version} + ${commons-lang3.version} pl.pragmatists @@ -63,10 +63,8 @@ - 4.3 28.0-jre 2.6.0 - 3.8.1 1.1.0 diff --git a/apache-poi-2/.gitignore b/apache-poi-2/.gitignore new file mode 100644 index 0000000000..9552c1e63d --- /dev/null +++ b/apache-poi-2/.gitignore @@ -0,0 +1,3 @@ +*.docx +temp.xls +temp.xlsx diff --git a/apache-poi-2/README.md b/apache-poi-2/README.md new file mode 100644 index 0000000000..69aabf4616 --- /dev/null +++ b/apache-poi-2/README.md @@ -0,0 +1,8 @@ +## Apache POI + +This module contains articles about Apache POI + +### Relevant Articles: + +- [Adding a Column to an Excel Sheet Using Apache POI](https://www.baeldung.com/java-excel-add-column) +- More articles: [[<-- prev]](/apache-poi) diff --git a/apache-poi-2/pom.xml b/apache-poi-2/pom.xml new file mode 100644 index 0000000000..1cb6509457 --- /dev/null +++ b/apache-poi-2/pom.xml @@ -0,0 +1,24 @@ + + + 4.0.0 + apache-poi + 0.0.1-SNAPSHOT + apache-poi + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.apache.poi + poi-ooxml + 5.0.0 + + + + \ No newline at end of file diff --git a/apache-poi-2/src/main/java/com/baeldung/poi/excel/newcolumn/ExcelColumn.java b/apache-poi-2/src/main/java/com/baeldung/poi/excel/newcolumn/ExcelColumn.java new file mode 100644 index 0000000000..00ca24f6e8 --- /dev/null +++ b/apache-poi-2/src/main/java/com/baeldung/poi/excel/newcolumn/ExcelColumn.java @@ -0,0 +1,16 @@ +package com.baeldung.poi.excel.newcolumn; +import org.apache.poi.ss.usermodel.CellType; +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; + + +public class ExcelColumn { + + public void addColumn(Sheet sheet, CellType cellType) { + for (Row currentRow : sheet) { + currentRow.createCell(currentRow.getLastCellNum(), cellType); + } + } +} diff --git a/apache-poi-2/src/test/java/com/baeldung/poi/excel/newcolumn/ExcelColumnUnitTest.java b/apache-poi-2/src/test/java/com/baeldung/poi/excel/newcolumn/ExcelColumnUnitTest.java new file mode 100644 index 0000000000..9b991719b1 --- /dev/null +++ b/apache-poi-2/src/test/java/com/baeldung/poi/excel/newcolumn/ExcelColumnUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.poi.excel.newcolumn; + +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Paths; + +import static org.junit.Assert.assertEquals; + +public class ExcelColumnUnitTest { + private static final String FILE_NAME = "newColumnTest.xlsx"; + private String fileLocation; + + @Before + public void setup() throws URISyntaxException { + fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME).toURI()).toString(); + } + + @Test + public void givenExistingRows_whenAddNewColumn_thenRowColumnNumberIncreased() throws IOException { + Workbook workbook = new XSSFWorkbook(fileLocation); + Sheet sheet = workbook.getSheetAt(0); + Row row = sheet.getRow(0); + assertEquals(5, row.getLastCellNum()); + + ExcelColumn excelColumn = new ExcelColumn(); + excelColumn.addColumn(sheet, CellType.STRING); + assertEquals(6, row.getLastCellNum()); + + workbook.close(); + } + +} \ No newline at end of file diff --git a/apache-poi-2/src/test/resources/newColumnTest.xlsx b/apache-poi-2/src/test/resources/newColumnTest.xlsx new file mode 100644 index 0000000000..54e8734d58 Binary files /dev/null and b/apache-poi-2/src/test/resources/newColumnTest.xlsx differ diff --git a/apache-poi/README.md b/apache-poi/README.md index d3d60358c5..6d5b80b03a 100644 --- a/apache-poi/README.md +++ b/apache-poi/README.md @@ -15,3 +15,4 @@ This module contains articles about Apache POI - [Multiline Text in Excel Cell Using Apache POI](https://www.baeldung.com/apache-poi-write-multiline-text) - [Set Background Color of a Cell with Apache POI](https://www.baeldung.com/apache-poi-background-color) - [Add Borders to Excel Cells With Apache POI](https://www.baeldung.com/apache-poi-add-borders) +- More articles: [[next -->]](/apache-poi-2) diff --git a/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelUtility.java b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelUtility.java new file mode 100644 index 0000000000..e4a5b791c9 --- /dev/null +++ b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelUtility.java @@ -0,0 +1,66 @@ +package com.baeldung.poi.excel; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; + +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.DateUtil; +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; + +public class ExcelUtility { + private static final String ENDLINE = System.getProperty("line.separator"); + + public static String readExcel(String filePath) throws IOException { + File file = new File(filePath); + FileInputStream inputStream = null; + StringBuilder toReturn = new StringBuilder(); + try { + inputStream = new FileInputStream(file); + Workbook baeuldungWorkBook = new XSSFWorkbook(inputStream); + for (Sheet sheet : baeuldungWorkBook) { + toReturn.append("--------------------------------------------------------------------").append(ENDLINE); + toReturn.append("Worksheet :").append(sheet.getSheetName()).append(ENDLINE); + toReturn.append("--------------------------------------------------------------------").append(ENDLINE); + int firstRow = sheet.getFirstRowNum(); + int lastRow = sheet.getLastRowNum(); + for (int index = firstRow + 1; index <= lastRow; index++) { + Row row = sheet.getRow(index); + toReturn.append("|| "); + for (int cellIndex = row.getFirstCellNum(); cellIndex < row.getLastCellNum(); cellIndex++) { + Cell cell = row.getCell(cellIndex, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK); + printCellValue(cell, toReturn); + } + toReturn.append(" ||").append(ENDLINE); + } + } + inputStream.close(); + + } catch (IOException e) { + throw e; + } + return toReturn.toString(); + } + + public static void printCellValue(Cell cell, StringBuilder toReturn) { + CellType cellType = cell.getCellType().equals(CellType.FORMULA) ? cell.getCachedFormulaResultType() + : cell.getCellType(); + if (cellType.equals(CellType.STRING)) { + toReturn.append(cell.getStringCellValue()).append(" | "); + } + if (cellType.equals(CellType.NUMERIC)) { + if (DateUtil.isCellDateFormatted(cell)) { + toReturn.append(cell.getDateCellValue()).append(" | "); + } else { + toReturn.append(cell.getNumericCellValue()).append(" | "); + } + } + if (cellType.equals(CellType.BOOLEAN)) { + toReturn.append(cell.getBooleanCellValue()).append(" | "); + } + } +} \ No newline at end of file diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelUtilityUnitTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelUtilityUnitTest.java new file mode 100644 index 0000000000..6638d77066 --- /dev/null +++ b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelUtilityUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.poi.excel; + +import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Paths; +import java.text.ParseException; +import java.text.SimpleDateFormat; + +import org.junit.Before; +import org.junit.Test; + +public class ExcelUtilityUnitTest { + private static final String FILE_NAME = "baeldung.xlsx"; + private String fileLocation; + private static final String ENDLINE = System.getProperty("line.separator"); + private StringBuilder output; + + @Before + public void setupUnitTest() throws IOException, URISyntaxException, ParseException { + output = new StringBuilder(); + output.append("--------------------------------------------------------------------").append(ENDLINE); + output.append("Worksheet :Sheet1").append(ENDLINE); + output.append("--------------------------------------------------------------------").append(ENDLINE); + output.append("|| Name1 | Surname1 | 3.55696564113E11 | ").append(new SimpleDateFormat("dd/MM/yyyy").parse("4/11/2021").toString()).append(" | ‡ | ||") + .append(ENDLINE); + output.append("|| Name2 | Surname2 | 5.646513512E9 | ").append(new SimpleDateFormat("dd/MM/yyyy").parse("4/12/2021").toString()).append(" | false | ||") + .append(ENDLINE); + output.append("|| Name3 | Surname3 | 3.55696564113E11 | ").append(new SimpleDateFormat("dd/MM/yyyy").parse("4/11/2021").toString()).append(" | 7.17039641738E11 | ||") + .append(ENDLINE); + output.append("--------------------------------------------------------------------").append(ENDLINE); + output.append("Worksheet :Sheet2").append(ENDLINE); + output.append("--------------------------------------------------------------------").append(ENDLINE); + output.append("|| Name4 | Surname4 | 3.55675623232E11 | 13/04/2021 | ||").append(ENDLINE); + + fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME).toURI()).toString(); + } + + @Test + public void givenStringPath_whenReadExcel_thenReturnStringValue() throws IOException { + assertEquals(output.toString(), ExcelUtility.readExcel(fileLocation)); + + } + + @Test + public void givenStringPath_whenReadExcel_thenThrowException() { + assertThrows(IOException.class, () -> { + ExcelUtility.readExcel("baeldung"); + }); + } + +} diff --git a/apache-poi/src/test/resources/baeldung.xlsx b/apache-poi/src/test/resources/baeldung.xlsx new file mode 100644 index 0000000000..a6ed6c4e6a Binary files /dev/null and b/apache-poi/src/test/resources/baeldung.xlsx differ diff --git a/aws-lambda/lambda/pom.xml b/aws-lambda/lambda/pom.xml index b2e5cc3b2d..8bfe7a0ade 100644 --- a/aws-lambda/lambda/pom.xml +++ b/aws-lambda/lambda/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-modules + aws-lambda 1.0.0-SNAPSHOT - ../../ diff --git a/aws-lambda/pom.xml b/aws-lambda/pom.xml index 3264356977..fc655f282d 100644 --- a/aws-lambda/pom.xml +++ b/aws-lambda/pom.xml @@ -11,7 +11,6 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT - ../ diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-client/pom.xml b/cloud-foundry-uaa/cf-uaa-oauth2-client/pom.xml index 74603bf0fb..7fcce181a3 100644 --- a/cloud-foundry-uaa/cf-uaa-oauth2-client/pom.xml +++ b/cloud-foundry-uaa/cf-uaa-oauth2-client/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-boot-2 + cloud-foundry-uaa 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/pom.xml b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/pom.xml index 276c8bbaa6..4dffd4d768 100644 --- a/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/pom.xml +++ b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-boot-2 + cloud-foundry-uaa 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/cloud-foundry-uaa/pom.xml b/cloud-foundry-uaa/pom.xml index 03a5b978d4..6ae43b2c08 100644 --- a/cloud-foundry-uaa/pom.xml +++ b/cloud-foundry-uaa/pom.xml @@ -4,14 +4,14 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 cloud-foundry-uaa - 0.0.1-SNAPSHOT cloud-foundry-uaa pom com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 diff --git a/core-java-modules/core-java-10/pom.xml b/core-java-modules/core-java-10/pom.xml index c3406751dc..e2ac8db919 100644 --- a/core-java-modules/core-java-10/pom.xml +++ b/core-java-modules/core-java-10/pom.xml @@ -39,7 +39,6 @@ 10 10 - 4.1 \ No newline at end of file diff --git a/core-java-modules/core-java-11-2/src/test/java/com/baeldung/version/VersionUnitTest.java b/core-java-modules/core-java-11-2/src/test/java/com/baeldung/version/VersionManualTest.java similarity index 92% rename from core-java-modules/core-java-11-2/src/test/java/com/baeldung/version/VersionUnitTest.java rename to core-java-modules/core-java-11-2/src/test/java/com/baeldung/version/VersionManualTest.java index 128c7f60f4..74035a3e2f 100644 --- a/core-java-modules/core-java-11-2/src/test/java/com/baeldung/version/VersionUnitTest.java +++ b/core-java-modules/core-java-11-2/src/test/java/com/baeldung/version/VersionManualTest.java @@ -5,7 +5,8 @@ import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -public class VersionUnitTest { +// manual test as the runtime JDK version can be different depending on where the test is run +public class VersionManualTest { @Test public void givenJava_whenUsingRuntime_thenGetVersion() { diff --git a/core-java-modules/core-java-8/pom.xml b/core-java-modules/core-java-8/pom.xml index 85e289280b..89925bdbbb 100644 --- a/core-java-modules/core-java-8/pom.xml +++ b/core-java-modules/core-java-8/pom.xml @@ -43,9 +43,4 @@ - - - 4.1 - - \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/src/test/java/com/baeldung/java9/modules/ModuleAPIUnitTest.java b/core-java-modules/core-java-9-jigsaw/src/test/java/com/baeldung/java9/modules/ModuleAPIUnitTest.java index b909636b56..f6ea266676 100644 --- a/core-java-modules/core-java-9-jigsaw/src/test/java/com/baeldung/java9/modules/ModuleAPIUnitTest.java +++ b/core-java-modules/core-java-9-jigsaw/src/test/java/com/baeldung/java9/modules/ModuleAPIUnitTest.java @@ -16,6 +16,7 @@ import java.util.stream.Collectors; import org.junit.Before; import org.junit.Test; +import org.junit.Ignore; public class ModuleAPIUnitTest { @@ -110,6 +111,7 @@ public class ModuleAPIUnitTest { } @Test + @Ignore // fixing in http://team.baeldung.com/browse/JAVA-8679 public void givenModules_whenAccessingModuleDescriptorProvides_thenProvidesAreReturned() { Set javaBaseProvides = javaBaseModule.getDescriptor().provides(); Set javaSqlProvides = javaSqlModule.getDescriptor().provides(); diff --git a/core-java-modules/core-java-9/pom.xml b/core-java-modules/core-java-9/pom.xml index 03a097e7a9..274d9ccb43 100644 --- a/core-java-modules/core-java-9/pom.xml +++ b/core-java-modules/core-java-9/pom.xml @@ -76,7 +76,6 @@ 1.9 1.9 25.1-jre - 4.1 \ No newline at end of file diff --git a/core-java-modules/core-java-collections-2/pom.xml b/core-java-modules/core-java-collections-2/pom.xml index 23100b1d87..e78f7b5dda 100644 --- a/core-java-modules/core-java-collections-2/pom.xml +++ b/core-java-modules/core-java-collections-2/pom.xml @@ -44,7 +44,6 @@ 7.1.0 - 4.1 1.3 diff --git a/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/DynamicTypeValue.java b/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/DynamicTypeValue.java new file mode 100644 index 0000000000..4c9ed89f63 --- /dev/null +++ b/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/DynamicTypeValue.java @@ -0,0 +1,5 @@ +package com.baeldung.collections.mulipletypesinmap; + +public interface DynamicTypeValue { + String valueDescription(); +} diff --git a/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/InstantTypeValue.java b/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/InstantTypeValue.java new file mode 100644 index 0000000000..448e66d872 --- /dev/null +++ b/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/InstantTypeValue.java @@ -0,0 +1,24 @@ +package com.baeldung.collections.mulipletypesinmap; + +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; + +public class InstantTypeValue implements DynamicTypeValue { + private static DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") + .withZone(ZoneId.systemDefault()); + private Instant value; + + public InstantTypeValue(Instant value) { + this.value = value; + } + + @Override + public String valueDescription() { + if (value == null) { + return "The value is null."; + } + return String.format("The value is an instant: %s", FORMATTER.format(value)); + } + +} diff --git a/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/IntArrayTypeValue.java b/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/IntArrayTypeValue.java new file mode 100644 index 0000000000..290982183f --- /dev/null +++ b/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/IntArrayTypeValue.java @@ -0,0 +1,20 @@ +package com.baeldung.collections.mulipletypesinmap; + +import java.util.Arrays; + +public class IntArrayTypeValue implements DynamicTypeValue { + private int[] value; + + public IntArrayTypeValue(int[] value) { + this.value = value; + } + + @Override + public String valueDescription() { + if (value == null) { + return "The value is null."; + } + return String.format("The value is an array of %d integers: %s", value.length, Arrays.toString(value)); + } + +} diff --git a/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/IntegerTypeValue.java b/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/IntegerTypeValue.java new file mode 100644 index 0000000000..463b06f768 --- /dev/null +++ b/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/collections/mulipletypesinmap/IntegerTypeValue.java @@ -0,0 +1,17 @@ +package com.baeldung.collections.mulipletypesinmap; + +public class IntegerTypeValue implements DynamicTypeValue { + private Integer value; + + public IntegerTypeValue(Integer value) { + this.value = value; + } + + @Override + public String valueDescription() { + if(value == null){ + return "The value is null."; + } + return String.format("The value is a %s integer: %d", value > 0 ? "positive" : "negative", value); + } +} diff --git a/core-java-modules/core-java-collections-4/src/test/java/com/baeldung/multipletypesinmap/MultipleTypesInMapUnitTest.java b/core-java-modules/core-java-collections-4/src/test/java/com/baeldung/multipletypesinmap/MultipleTypesInMapUnitTest.java new file mode 100644 index 0000000000..87ea310ab0 --- /dev/null +++ b/core-java-modules/core-java-collections-4/src/test/java/com/baeldung/multipletypesinmap/MultipleTypesInMapUnitTest.java @@ -0,0 +1,75 @@ +package com.baeldung.multipletypesinmap; + +import com.baeldung.collections.mulipletypesinmap.DynamicTypeValue; +import com.baeldung.collections.mulipletypesinmap.InstantTypeValue; +import com.baeldung.collections.mulipletypesinmap.IntArrayTypeValue; +import com.baeldung.collections.mulipletypesinmap.IntegerTypeValue; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +class MultipleTypesInMapUnitTest { + private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") + .withZone(ZoneId.systemDefault()); + + private static final Integer intValue = 777; + private static final int[] intArray = new int[]{2, 3, 5, 7, 11, 13}; + private static final Instant instant = Instant.now(); + + private static final String KEY_INT = "E1 (Integer)"; + private static final String KEY_INT_ARRAY = "E2 (IntArray)"; + private static final String KEY_INSTANT = "E3 (Instant)"; + + @Test + void givenThreeTypes_whenUsingRawMap_thenPrintDescription() { + Map rawMap = new HashMap<>(); + rawMap.put(KEY_INT, intValue); + rawMap.put(KEY_INT_ARRAY, intArray); + rawMap.put(KEY_INSTANT, instant); + + rawMap.forEach((k, v) -> { + if (v instanceof Integer) { + Integer theV = (Integer) v; + String desc = String.format("The value is a %s integer: %d", theV > 0 ? "positive" : "negative", theV); + System.out.println(k + " -> " + desc); + assertThat(k).isEqualTo(KEY_INT); + assertThat(desc).isEqualTo("The value is a positive integer: 777"); + } else if (v instanceof int[]) { + int[] theV = (int[]) v; + String desc = String.format("The value is an array of %d integers: %s", theV.length, Arrays.toString(theV)); + System.out.println(k + " -> " + desc); + assertThat(k).isEqualTo(KEY_INT_ARRAY); + assertThat(desc).isEqualTo("The value is an array of 6 integers: [2, 3, 5, 7, 11, 13]"); + } else if (v instanceof Instant) { + Instant theV = (Instant) v; + String desc = String.format("The value is an instant: %s", FORMATTER.format(theV)); + System.out.println(k + " -> " + desc); + assertThat(k).isEqualTo(KEY_INSTANT); + assertThat(desc).matches("^The value is an instant: \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}"); + } else { + throw new IllegalStateException("Unknown Type found."); + } + }); + } + + @Test + void givenThreeTypes_whenUsingAnInterface_thenPrintDescription() { + Map theMap = new HashMap<>(); + theMap.put(KEY_INT, new IntegerTypeValue(intValue)); + theMap.put(KEY_INT_ARRAY, new IntArrayTypeValue(intArray)); + theMap.put(KEY_INSTANT, new InstantTypeValue(instant)); + + theMap.forEach((k, v) -> System.out.println(k + " -> " + v.valueDescription())); + + assertThat(theMap.get(KEY_INT).valueDescription()).isEqualTo("The value is a positive integer: 777"); + assertThat(theMap.get(KEY_INT_ARRAY).valueDescription()).isEqualTo("The value is an array of 6 integers: [2, 3, 5, 7, 11, 13]"); + assertThat(theMap.get(KEY_INSTANT).valueDescription()).matches("^The value is an instant: \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}"); + } +} diff --git a/core-java-modules/core-java-collections-array-list/pom.xml b/core-java-modules/core-java-collections-array-list/pom.xml index ca9c173947..6b040739e8 100644 --- a/core-java-modules/core-java-collections-array-list/pom.xml +++ b/core-java-modules/core-java-collections-array-list/pom.xml @@ -22,8 +22,4 @@ - - 4.1 - - \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-2/pom.xml b/core-java-modules/core-java-collections-list-2/pom.xml index 7876b19cf9..59ab8c5f27 100644 --- a/core-java-modules/core-java-collections-list-2/pom.xml +++ b/core-java-modules/core-java-collections-list-2/pom.xml @@ -28,8 +28,4 @@ - - 4.1 - - \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-3/pom.xml b/core-java-modules/core-java-collections-list-3/pom.xml index 9238939df7..3bb0fb4a33 100644 --- a/core-java-modules/core-java-collections-list-3/pom.xml +++ b/core-java-modules/core-java-collections-list-3/pom.xml @@ -54,7 +54,6 @@ - 4.1 3.0.2 8.1.0 1.2.0 diff --git a/core-java-modules/core-java-collections-list/pom.xml b/core-java-modules/core-java-collections-list/pom.xml index b60906d1ba..0cc8828a0d 100644 --- a/core-java-modules/core-java-collections-list/pom.xml +++ b/core-java-modules/core-java-collections-list/pom.xml @@ -27,8 +27,4 @@ - - 4.1 - - \ No newline at end of file diff --git a/core-java-modules/core-java-collections-maps-2/pom.xml b/core-java-modules/core-java-collections-maps-2/pom.xml index 060796fafa..36b15c24d5 100644 --- a/core-java-modules/core-java-collections-maps-2/pom.xml +++ b/core-java-modules/core-java-collections-maps-2/pom.xml @@ -55,7 +55,6 @@ 0.6.5 - 4.1 1.7.0 8.2.0 0.7.2 diff --git a/core-java-modules/core-java-collections-maps-4/pom.xml b/core-java-modules/core-java-collections-maps-4/pom.xml index 2109804ff0..c5296e9a43 100644 --- a/core-java-modules/core-java-collections-maps-4/pom.xml +++ b/core-java-modules/core-java-collections-maps-4/pom.xml @@ -28,12 +28,6 @@ ${junit.version} test - - org.hamcrest - hamcrest-all - ${hamcrest-all.version} - test - diff --git a/core-java-modules/core-java-collections-maps/pom.xml b/core-java-modules/core-java-collections-maps/pom.xml index 66aca9c1b2..34b878df53 100644 --- a/core-java-modules/core-java-collections-maps/pom.xml +++ b/core-java-modules/core-java-collections-maps/pom.xml @@ -22,8 +22,4 @@ - - 4.1 - - \ No newline at end of file diff --git a/core-java-modules/core-java-collections-set/pom.xml b/core-java-modules/core-java-collections-set/pom.xml index 359c0fc86f..0b6e324c78 100644 --- a/core-java-modules/core-java-collections-set/pom.xml +++ b/core-java-modules/core-java-collections-set/pom.xml @@ -49,7 +49,6 @@ 11 11 - 4.3 2.8.5 diff --git a/core-java-modules/core-java-concurrency-advanced/pom.xml b/core-java-modules/core-java-concurrency-advanced/pom.xml index a026bdb2cd..b50a66cefc 100644 --- a/core-java-modules/core-java-concurrency-advanced/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced/pom.xml @@ -56,7 +56,6 @@ 21.0 3.6.1 - 4.1 4.01 1.7.0 diff --git a/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionUnitTest.java b/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionUnitTest.java index bef90e671f..857ab02c13 100644 --- a/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionUnitTest.java +++ b/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionUnitTest.java @@ -1,11 +1,12 @@ package com.baeldung.exceptions.illegalmonitorstate; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.junit.jupiter.api.Test; -import java.time.Duration; - -import static org.junit.jupiter.api.Assertions.*; - public class IllegalMonitorStateExceptionUnitTest { @Test @@ -20,11 +21,11 @@ public class IllegalMonitorStateExceptionUnitTest { Thread senderThread = new Thread(sender, "sender-thread"); senderThread.start(); - senderThread.join(1000); - receiverThread.join(1000); + // we need to wait for the sender and receiver threads to finish + senderThread.join(10_000); + receiverThread.join(10_000); - // we need to wait for enough time so that sender has had a chance to send the data - assertTimeout(Duration.ofSeconds(10), () -> assertEquals("test", receiver.getMessage())); + assertEquals("test", receiver.getMessage()); assertFalse(sender.hasIllegalMonitorStateExceptionOccurred()); assertFalse(receiver.hasIllegalMonitorStateExceptionOccurred()); } diff --git a/core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/readertox/JavaReaderToXUnitTest.java b/core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/readertox/JavaReaderToXUnitTest.java index 72813df9b1..fa3c34d479 100644 --- a/core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/readertox/JavaReaderToXUnitTest.java +++ b/core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/readertox/JavaReaderToXUnitTest.java @@ -1,7 +1,7 @@ package com.baeldung.readertox; import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.io.ByteArrayInputStream; import java.io.File; @@ -17,6 +17,7 @@ import java.nio.charset.StandardCharsets; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.io.input.CharSequenceReader; +import org.apache.commons.io.input.ReaderInputStream; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -181,7 +182,7 @@ public class JavaReaderToXUnitTest { } @Test - public void givenUsingCommonsIO_whenConvertingReaderIntoInputStream() throws IOException { + public void givenUsingCommonsIOUtils_whenConvertingReaderIntoInputStream() throws IOException { final Reader initialReader = new StringReader("With Commons IO"); final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader)); @@ -191,7 +192,7 @@ public class JavaReaderToXUnitTest { } @Test - public void givenUsingCommonsIO_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException { + public void givenUsingCommonsIOUtils_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException { String initialString = "With Commons IO"; final Reader initialReader = new StringReader(initialString); @@ -204,6 +205,30 @@ public class JavaReaderToXUnitTest { targetStream.close(); } + @Test + public void givenUsingCommonsIOReaderInputStream_whenConvertingReaderIntoInputStream() throws IOException { + final Reader initialReader = new StringReader("With Commons IO"); + + final InputStream targetStream = new ReaderInputStream(initialReader); + + initialReader.close(); + targetStream.close(); + } + + @Test + public void givenUsingCommonsIOReaderInputStream_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException { + String initialString = "With Commons IO"; + final Reader initialReader = new StringReader(initialString); + + final InputStream targetStream = new ReaderInputStream(initialReader); + + final String finalString = IOUtils.toString(targetStream); + assertThat(finalString, equalTo(initialString)); + + initialReader.close(); + targetStream.close(); + } + // tests - Reader to InputStream with encoding @Test @@ -233,7 +258,7 @@ public class JavaReaderToXUnitTest { } @Test - public void givenUsingCommonsIO_whenConvertingReaderIntoInputStreamWithEncoding() throws IOException { + public void givenUsingCommonsIOUtils_whenConvertingReaderIntoInputStreamWithEncoding() throws IOException { final Reader initialReader = new StringReader("With Commons IO"); final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader), Charsets.UTF_8); @@ -243,7 +268,7 @@ public class JavaReaderToXUnitTest { } @Test - public void givenUsingCommonsIO_whenConvertingReaderIntoInputStreamWithEncoding_thenCorrect() throws IOException { + public void givenUsingCommonsIOUtils_whenConvertingReaderIntoInputStreamWithEncoding_thenCorrect() throws IOException { String initialString = "With Commons IO"; final Reader initialReader = new StringReader(initialString); final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader), Charsets.UTF_8); @@ -255,4 +280,27 @@ public class JavaReaderToXUnitTest { targetStream.close(); } + @Test + public void givenUsingCommonsIOReaderInputStream_whenConvertingReaderIntoInputStreamWithEncoding() throws IOException { + final Reader initialReader = new StringReader("With Commons IO"); + + final InputStream targetStream = new ReaderInputStream(initialReader, Charsets.UTF_8); + + initialReader.close(); + targetStream.close(); + } + + @Test + public void givenUsingCommonsIOReaderInputStream_whenConvertingReaderIntoInputStreamWithEncoding_thenCorrect() throws IOException { + String initialString = "With Commons IO"; + final Reader initialReader = new StringReader(initialString); + + final InputStream targetStream = new ReaderInputStream(initialReader, Charsets.UTF_8); + + String finalString = IOUtils.toString(targetStream, Charsets.UTF_8); + assertThat(finalString, equalTo(initialString)); + + initialReader.close(); + targetStream.close(); + } } diff --git a/core-java-modules/core-java-lang-oop-modifiers/pom.xml b/core-java-modules/core-java-lang-oop-modifiers/pom.xml index 109a87c41e..14ba397b4a 100644 --- a/core-java-modules/core-java-lang-oop-modifiers/pom.xml +++ b/core-java-modules/core-java-lang-oop-modifiers/pom.xml @@ -22,4 +22,7 @@ + + 1.4.197 + \ No newline at end of file diff --git a/core-java-modules/core-java-networking-3/README.md b/core-java-modules/core-java-networking-3/README.md index 0dc9ad9f70..82e75820ba 100644 --- a/core-java-modules/core-java-networking-3/README.md +++ b/core-java-modules/core-java-networking-3/README.md @@ -9,4 +9,5 @@ This module contains articles about networking in Java - [Connection Timeout vs. Read Timeout for Java Sockets](https://www.baeldung.com/java-socket-connection-read-timeout) - [Find Whether an IP Address Is in the Specified Range or Not in Java](https://www.baeldung.com/java-check-ip-address-range) - [Find the IP Address of a Client Connected to a Server](https://www.baeldung.com/java-client-get-ip-address) +- [Unix Domain Socket in Java 16](https://www.baeldung.com/java-unix-domain-socket) - [[<-- Prev]](/core-java-modules/core-java-networking-2) diff --git a/core-java-modules/core-java-networking-3/pom.xml b/core-java-modules/core-java-networking-3/pom.xml index ee822e57cb..297d665544 100644 --- a/core-java-modules/core-java-networking-3/pom.xml +++ b/core-java-modules/core-java-networking-3/pom.xml @@ -64,6 +64,16 @@ + + + org.apache.maven.plugins + maven-compiler-plugin + + 16 + 16 + + + diff --git a/core-java-modules/core-java-networking-3/src/main/java/com/baeldung/socket/UnixDomainSocketClient.java b/core-java-modules/core-java-networking-3/src/main/java/com/baeldung/socket/UnixDomainSocketClient.java new file mode 100644 index 0000000000..2a8ae05628 --- /dev/null +++ b/core-java-modules/core-java-networking-3/src/main/java/com/baeldung/socket/UnixDomainSocketClient.java @@ -0,0 +1,49 @@ +package com.baeldung.socket; + +import java.io.IOException; +import java.net.StandardProtocolFamily; +import java.net.UnixDomainSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; +import java.nio.file.Path; + +class UnixDomainSocketClient { + + public static void main(String[] args) throws Exception { + new UnixDomainSocketClient().runClient(); + } + + void runClient() throws IOException { + Path socketPath = Path.of(System.getProperty("user.home")) + .resolve("baeldung.socket"); + UnixDomainSocketAddress socketAddress = getAddress(socketPath); + + SocketChannel channel = openSocketChannel(socketAddress); + + String message = "Hello from Baeldung Unix domain socket article"; + writeMessage(channel, message); + } + + UnixDomainSocketAddress getAddress(Path socketPath) { + return UnixDomainSocketAddress.of(socketPath); + } + + SocketChannel openSocketChannel(UnixDomainSocketAddress socketAddress) throws IOException { + SocketChannel channel = SocketChannel + .open(StandardProtocolFamily.UNIX); + channel.connect(socketAddress); + return channel; + } + + void writeMessage(SocketChannel socketChannel, String message) throws IOException { + ByteBuffer buffer = ByteBuffer.allocate(1024); + buffer.clear(); + buffer.put(message.getBytes()); + buffer.flip(); + + while (buffer.hasRemaining()) { + socketChannel.write(buffer); + } + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-networking-3/src/main/java/com/baeldung/socket/UnixDomainSocketServer.java b/core-java-modules/core-java-networking-3/src/main/java/com/baeldung/socket/UnixDomainSocketServer.java new file mode 100644 index 0000000000..c3093ae00c --- /dev/null +++ b/core-java-modules/core-java-networking-3/src/main/java/com/baeldung/socket/UnixDomainSocketServer.java @@ -0,0 +1,57 @@ +package com.baeldung.socket; + +import java.io.IOException; +import java.net.StandardProtocolFamily; +import java.net.UnixDomainSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Optional; + +class UnixDomainSocketServer { + + public static void main(String[] args) throws IOException, InterruptedException { + new UnixDomainSocketServer().runServer(); + } + + void runServer() throws IOException, InterruptedException { + Path socketPath = Path.of(System.getProperty("user.home")) + .resolve("baeldung.socket"); + Files.deleteIfExists(socketPath); + UnixDomainSocketAddress socketAddress = getAddress(socketPath); + + ServerSocketChannel serverChannel = createServerSocketChannel(socketAddress); + + SocketChannel channel = serverChannel.accept(); + + while (true) { + readSocketMessage(channel) + .ifPresent(message -> System.out.printf("[Client message] %s%n", message)); + Thread.sleep(100); + } + } + + UnixDomainSocketAddress getAddress(Path socketPath) { + return UnixDomainSocketAddress.of(socketPath); + } + + ServerSocketChannel createServerSocketChannel(UnixDomainSocketAddress socketAddress) throws IOException { + ServerSocketChannel serverChannel = ServerSocketChannel.open(StandardProtocolFamily.UNIX); + serverChannel.bind(socketAddress); + return serverChannel; + } + + Optional readSocketMessage(SocketChannel channel) throws IOException { + ByteBuffer buffer = ByteBuffer.allocate(1024); + int bytesRead = channel.read(buffer); + if (bytesRead < 0) return Optional.empty(); + byte[] bytes = new byte[bytesRead]; + buffer.flip(); + buffer.get(bytes); + String message = new String(bytes); + return Optional.of(message); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/FindFreePortUnitTest.java b/core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/FindFreePortManualTest.java similarity index 98% rename from core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/FindFreePortUnitTest.java rename to core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/FindFreePortManualTest.java index 95530ef292..3e533b3fc0 100644 --- a/core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/FindFreePortUnitTest.java +++ b/core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/FindFreePortManualTest.java @@ -14,7 +14,8 @@ import java.net.ServerSocket; import static org.assertj.core.api.Assertions.*; import static org.assertj.core.api.Assertions.assertThat; -public class FindFreePortUnitTest { +// fixing in JAVA-8748 +public class FindFreePortManualTest { private static int FREE_PORT_NUMBER; private static int[] FREE_PORT_RANGE; diff --git a/core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/UnixDomainSocketClientUnitTest.java b/core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/UnixDomainSocketClientUnitTest.java new file mode 100644 index 0000000000..8cd2ee94d4 --- /dev/null +++ b/core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/UnixDomainSocketClientUnitTest.java @@ -0,0 +1,82 @@ +package com.baeldung.socket; + +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.stubbing.Answer; + +import java.io.File; +import java.io.IOException; +import java.net.StandardProtocolFamily; +import java.net.UnixDomainSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; +import java.nio.file.Path; +import java.util.UUID; + +import static java.nio.file.Files.deleteIfExists; +import static org.assertj.core.util.Files.newTemporaryFile; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class UnixDomainSocketClientUnitTest { + + @Test + public void givenSocketPath_shouldCreateUnixDomainSocketAddress() { + // given + File tempFile = newTemporaryFile(); + Path socketPath = tempFile.toPath(); + + // when + UnixDomainSocketAddress address = new UnixDomainSocketClient().getAddress(socketPath); + + // then + assertEquals(address.getPath(), socketPath); + + // cleanup + tempFile.delete(); + } + + @Test + public void givenUnixDomainSocketAddress_shouldOpenSocketChannel() throws IOException { + // given + File tempFile = newTemporaryFile(); + Path socketPath = tempFile.toPath(); + deleteIfExists(socketPath); + UnixDomainSocketAddress address = UnixDomainSocketAddress.of(socketPath); + + // bind address as a unix domain socket + ServerSocketChannel serverChannel = ServerSocketChannel.open(StandardProtocolFamily.UNIX); + serverChannel.bind(address); + + // when + SocketChannel socketChannel = new UnixDomainSocketClient().openSocketChannel(address); + + // then + assertTrue(socketChannel.isOpen()); + assertEquals(socketChannel.getRemoteAddress(), address); + + // cleanup + tempFile.delete(); + } + + @Test + public void givenSocketChannelAndMessage_shouldWriteMessage() throws IOException { + // given + SocketChannel socketChannel = Mockito.mock(SocketChannel.class); + String message = UUID.randomUUID().toString(); + Mockito.when(socketChannel.write(Mockito.any(ByteBuffer.class))) + .thenAnswer( + (Answer) invocationOnMock -> { + ((ByteBuffer) invocationOnMock.getArguments()[0]).position(message.getBytes().length); + return -1; + } + ); + + // when + new UnixDomainSocketClient().writeMessage(socketChannel, message); + + // then + Mockito.verify(socketChannel, Mockito.times(1)).write(Mockito.any(ByteBuffer.class)); + } +} diff --git a/core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/UnixDomainSocketServerUnitTest.java b/core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/UnixDomainSocketServerUnitTest.java new file mode 100644 index 0000000000..1d0a68ac2f --- /dev/null +++ b/core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket/UnixDomainSocketServerUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.socket; + +import org.junit.Test; + +import java.io.File; +import java.io.IOException; +import java.net.UnixDomainSocketAddress; +import java.nio.channels.ServerSocketChannel; +import java.nio.file.Path; + +import static java.nio.file.Files.deleteIfExists; +import static org.assertj.core.util.Files.newTemporaryFile; +import static org.junit.Assert.assertEquals; + +public class UnixDomainSocketServerUnitTest { + + @Test + public void givenSocketPath_shouldCreateUnixDomainSocketAddress() { + // given + File tempFile = newTemporaryFile(); + Path socketPath = tempFile.toPath(); + + // when + UnixDomainSocketAddress address = new UnixDomainSocketServer().getAddress(socketPath); + + // then + assertEquals(address.getPath(), socketPath); + + // cleanup + tempFile.delete(); + } + + @Test + public void givenUnixDomainSocketAddress_shouldCreateServerSocketChannel() throws IOException { + // given + File tempFile = newTemporaryFile(); + Path socketPath = tempFile.toPath(); + deleteIfExists(socketPath); + UnixDomainSocketAddress address = UnixDomainSocketAddress.of(socketPath); + + // when + ServerSocketChannel serverSocketChannel = new UnixDomainSocketServer().createServerSocketChannel(address); + + // then + assertEquals(serverSocketChannel.getLocalAddress(), address); + + // cleanup + tempFile.delete(); + } +} diff --git a/core-java-modules/core-java-os/pom.xml b/core-java-modules/core-java-os/pom.xml index 970c8a562a..54b86522f4 100644 --- a/core-java-modules/core-java-os/pom.xml +++ b/core-java-modules/core-java-os/pom.xml @@ -45,6 +45,12 @@ grep4j ${grep4j.version} + + org.projectlombok + lombok + ${lombok.version} + provided + @@ -69,7 +75,6 @@ - 4.1 4.01 1.8.9 1.9 @@ -77,6 +82,7 @@ 25.1-jre 0.4 1.8.7 + 1.18.22 diff --git a/core-java-modules/core-java-os/src/test/java/com/baeldung/shell/JavaProcessUnitIntegrationTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/shell/JavaProcessUnitIntegrationTest.java index 53e9364207..9d24dd1578 100644 --- a/core-java-modules/core-java-os/src/test/java/com/baeldung/shell/JavaProcessUnitIntegrationTest.java +++ b/core-java-modules/core-java-os/src/test/java/com/baeldung/shell/JavaProcessUnitIntegrationTest.java @@ -1,12 +1,23 @@ -package com.baeldung.java.shell; +package com.baeldung.shell; +import org.junit.After; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; -import java.io.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import java.util.function.Consumer; +import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + public class JavaProcessUnitIntegrationTest { private static final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().startsWith("windows"); @@ -29,6 +40,18 @@ public class JavaProcessUnitIntegrationTest { private String homeDirectory = System.getProperty("user.home"); + private ExecutorService executorService; + + @Before + public void setUp() { + executorService = Executors.newSingleThreadExecutor(); + } + + @After + public void tearDown() { + executorService.shutdown(); + } + @Test public void givenProcess_whenCreatingViaRuntime_shouldSucceed() throws Exception { Process process; @@ -38,9 +61,13 @@ public class JavaProcessUnitIntegrationTest { process = Runtime.getRuntime().exec(String.format("sh -c ls %s", homeDirectory)); } StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), consumer); - Executors.newSingleThreadExecutor().submit(streamGobbler); + + Future future = executorService.submit(streamGobbler); int exitCode = process.waitFor(); - Assert.assertEquals(0, exitCode); + + // verify the stream output from the process + assertDoesNotThrow(() -> future.get(10, TimeUnit.SECONDS)); + assertEquals(0, exitCode); } @Test @@ -54,8 +81,12 @@ public class JavaProcessUnitIntegrationTest { builder.directory(new File(homeDirectory)); Process process = builder.start(); StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), consumer); - Executors.newSingleThreadExecutor().submit(streamGobbler); + + Future future = executorService.submit(streamGobbler); int exitCode = process.waitFor(); - Assert.assertEquals(0, exitCode); + + // verify the stream output from the process + assertDoesNotThrow(() -> future.get(10, TimeUnit.SECONDS)); + assertEquals(0, exitCode); } } diff --git a/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/matcher/MatcherUnitTest.java b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/matcher/MatcherUnitTest.java index 304b9f2f1d..7ec4a1ae58 100644 --- a/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/matcher/MatcherUnitTest.java +++ b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/matcher/MatcherUnitTest.java @@ -11,6 +11,9 @@ import org.junit.jupiter.api.Test; public class MatcherUnitTest { + private static final String STRING_INPUT = "test+"; + private static final String REGEX = "\\+"; + @Test public void whenFindFourDigitWorks_thenCorrect() { Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d"); @@ -60,4 +63,16 @@ public class MatcherUnitTest { assertTrue(m.matches());// matches will always return the same return } + @Test + public void whenUsingMatcher_thenReturnTrue() { + Pattern pattern = Pattern.compile(REGEX); + Matcher matcher = pattern.matcher(STRING_INPUT); + assertTrue(matcher.find()); + } + + @Test + public void whenUsingMatches_thenReturnFalse() { + assertFalse(Pattern.matches(REGEX, STRING_INPUT)); + } + } diff --git a/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/isuppercase/StringFirstCharacterUppercaseUnitTest.java b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/isuppercase/StringFirstCharacterUppercaseUnitTest.java index ede31a3649..524f7ca839 100644 --- a/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/isuppercase/StringFirstCharacterUppercaseUnitTest.java +++ b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/isuppercase/StringFirstCharacterUppercaseUnitTest.java @@ -18,6 +18,7 @@ public class StringFirstCharacterUppercaseUnitTest { public void givenString_whenCheckingWithRegex_thenStringCapitalized() { String example = "Katie"; String regEx = "[A-Z]\\w*"; + Assertions.assertTrue(example.matches(regEx)); } diff --git a/core-java-modules/core-java-string-conversions-2/README.md b/core-java-modules/core-java-string-conversions-2/README.md index 46eb783a27..22f4cd89a1 100644 --- a/core-java-modules/core-java-string-conversions-2/README.md +++ b/core-java-modules/core-java-string-conversions-2/README.md @@ -9,4 +9,5 @@ This module contains articles about string conversions from/to another type. - [Converting String to BigDecimal in Java](https://www.baeldung.com/java-string-to-bigdecimal) - [Converting String to BigInteger in Java](https://www.baeldung.com/java-string-to-biginteger) - [Convert a String to Camel Case](https://www.baeldung.com/java-string-to-camel-case) +- [Convert a ByteBuffer to String] - More articles: [[<-- prev]](/core-java-string-conversions) diff --git a/core-java-modules/core-java-string-conversions-2/pom.xml b/core-java-modules/core-java-string-conversions-2/pom.xml index f97443d9ca..45eb0dc2e2 100644 --- a/core-java-modules/core-java-string-conversions-2/pom.xml +++ b/core-java-modules/core-java-string-conversions-2/pom.xml @@ -20,12 +20,6 @@ guava ${guava.version} - - org.hamcrest - hamcrest - ${hamcrest.version} - test - com.ibm.icu icu4j diff --git a/core-java-modules/core-java-string-conversions-2/src/test/java/com/baeldung/bytebuffertostring/ByteArrayToStringUnitTest.java b/core-java-modules/core-java-string-conversions-2/src/test/java/com/baeldung/bytebuffertostring/ByteArrayToStringUnitTest.java new file mode 100644 index 0000000000..c498921d9a --- /dev/null +++ b/core-java-modules/core-java-string-conversions-2/src/test/java/com/baeldung/bytebuffertostring/ByteArrayToStringUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.bytebuffertostring; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +import org.junit.Test; + +public class ByteArrayToStringUnitTest { + private static Charset charset = StandardCharsets.UTF_8; + private static final String content = "baeldung"; + + @Test + public void convertUsingNewStringFromBufferArray_thenOK() { + // Allocate a ByteBuffer + ByteBuffer byteBuffer = ByteBuffer.wrap(content.getBytes()); + if (byteBuffer.hasArray()) { + String newContent = new String(byteBuffer.array(), charset); + assertEquals(content, newContent); + } + } + + @Test + public void convertUsingNewStringFromByteBufferGetBytes_thenOK() { + // Allocate a ByteBuffer + ByteBuffer byteBuffer = ByteBuffer.wrap(content.getBytes()); + byte[] bytes = new byte[byteBuffer.remaining()]; + byteBuffer.get(bytes); + String newContent = new String(bytes, charset); + assertEquals(content, newContent); + } + + @Test + public void convertUsingCharsetDecode_thenOK() { + // Allocate a ByteBuffer + ByteBuffer byteBuffer = ByteBuffer.wrap(content.getBytes()); + String newContent = charset.decode(byteBuffer) + .toString(); + assertEquals(content, newContent); + } + +} diff --git a/core-java-modules/core-java-string-conversions/pom.xml b/core-java-modules/core-java-string-conversions/pom.xml index 148f04101f..8ed3e1d628 100644 --- a/core-java-modules/core-java-string-conversions/pom.xml +++ b/core-java-modules/core-java-string-conversions/pom.xml @@ -35,12 +35,6 @@ guava ${guava.version} - - org.hamcrest - hamcrest - ${hamcrest.version} - test - diff --git a/core-java-modules/core-java-string-operations-2/README.md b/core-java-modules/core-java-string-operations-2/README.md index d66515d372..f95b002906 100644 --- a/core-java-modules/core-java-string-operations-2/README.md +++ b/core-java-modules/core-java-string-operations-2/README.md @@ -12,5 +12,5 @@ This module contains articles about string operations. - [L-Trim and R-Trim Alternatives in Java](https://www.baeldung.com/java-trim-alternatives) - [Encode a String to UTF-8 in Java](https://www.baeldung.com/java-string-encode-utf-8) - [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding) -- [Convert Hex to ASCII in Java](https://www.baeldung.com/java-convert-hex-to-ascii) #remove additional readme file +- [Convert Hex to ASCII in Java](https://www.baeldung.com/java-convert-hex-to-ascii) - More articles: [[<-- prev]](../core-java-string-operations) diff --git a/core-java-modules/core-java-string-operations-2/pom.xml b/core-java-modules/core-java-string-operations-2/pom.xml index 0d31486759..848a358aa2 100644 --- a/core-java-modules/core-java-string-operations-2/pom.xml +++ b/core-java-modules/core-java-string-operations-2/pom.xml @@ -45,12 +45,6 @@ javax.el ${javax.el.version} - - org.hamcrest - hamcrest - ${hamcrest.version} - test - org.openjdk.jmh jmh-core diff --git a/core-java-modules/core-java-string-operations-4/README.md b/core-java-modules/core-java-string-operations-4/README.md index be4c9ae05f..83bfeb4d05 100644 --- a/core-java-modules/core-java-string-operations-4/README.md +++ b/core-java-modules/core-java-string-operations-4/README.md @@ -2,4 +2,5 @@ - [Ignoring Commas in Quotes When Splitting a Comma-separated String](https://www.baeldung.com/java-split-string-commas) - [Compare Strings While Ignoring Whitespace in Java](https://www.baeldung.com/java-compare-string-whitespace) +- [Concatenating Null Strings in Java](https://www.baeldung.com/java-concat-null-string) diff --git a/core-java-modules/core-java-string-operations-4/src/main/java/com/baeldung/concatenation/ConcatenatingNull.java b/core-java-modules/core-java-string-operations-4/src/main/java/com/baeldung/concatenation/ConcatenatingNull.java new file mode 100644 index 0000000000..250a0d6b25 --- /dev/null +++ b/core-java-modules/core-java-string-operations-4/src/main/java/com/baeldung/concatenation/ConcatenatingNull.java @@ -0,0 +1,86 @@ +package com.baeldung.concatenation; + +import java.util.StringJoiner; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class ConcatenatingNull { + + public static void main(String[] args) { + String[] values = { "Java ", null, "", "is ", "great!" }; + + concatenateUsingPlusOperator(values); + concatenateUsingHelperMethod(values); + concatenateUsingStringBuilder(values); + concatenateUsingJoin(values); + concatenateUsingStringJoiner(values); + concatenateUsingCollectorsJoining(values); + concatenateUsingStringConcat(values); + } + + public static String concatenateUsingStringConcat(String[] values) { + String result = ""; + + for (String value : values) { + result = result.concat(getNonNullString(value)); + } + + return result; + } + + public static String concatenateUsingCollectorsJoining(String[] values) { + String result = Stream.of(values).filter(value -> null != value).collect(Collectors.joining("")); + + return result; + } + + public static String concatenateUsingStringJoiner(String[] values) { + StringJoiner result = new StringJoiner(""); + + for (String value : values) { + result = result.add(getNonNullString(value)); + } + + return result.toString(); + } + + public static String concatenateUsingJoin(String[] values) { + String result = String.join("", values); + + return result; + } + + public static String concatenateUsingStringBuilder(String[] values) { + StringBuilder result = new StringBuilder(); + + for (String value : values) { + result = result.append(getNonNullString(value)); + } + + return result.toString(); + } + + public static String concatenateUsingHelperMethod(String[] values) { + String result = ""; + + for (String value : values) { + result = result + getNonNullString(value); + } + + return result; + } + + public static String concatenateUsingPlusOperator(String[] values) { + String result = ""; + + for (String value : values) { + result = result + (value == null ? "" : value); + } + + return result; + } + + private static String getNonNullString(String value) { + return value == null ? "" : value; + } +} diff --git a/core-java-modules/core-java-string-operations-4/src/test/java/com/baeldung/concatenation/ConcatenatingNullUnitTest.java b/core-java-modules/core-java-string-operations-4/src/test/java/com/baeldung/concatenation/ConcatenatingNullUnitTest.java new file mode 100644 index 0000000000..20e5f6ad7d --- /dev/null +++ b/core-java-modules/core-java-string-operations-4/src/test/java/com/baeldung/concatenation/ConcatenatingNullUnitTest.java @@ -0,0 +1,59 @@ +package com.baeldung.concatenation; + +import static com.baeldung.concatenation.ConcatenatingNull.concatenateUsingCollectorsJoining; +import static com.baeldung.concatenation.ConcatenatingNull.concatenateUsingHelperMethod; +import static com.baeldung.concatenation.ConcatenatingNull.concatenateUsingJoin; +import static com.baeldung.concatenation.ConcatenatingNull.concatenateUsingPlusOperator; +import static com.baeldung.concatenation.ConcatenatingNull.concatenateUsingStringBuilder; +import static com.baeldung.concatenation.ConcatenatingNull.concatenateUsingStringConcat; +import static com.baeldung.concatenation.ConcatenatingNull.concatenateUsingStringJoiner; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class ConcatenatingNullUnitTest { + + String[] values = { "Java ", null, "", "is ", "great!" }; + + @Test + public void givenStringElementsWithNull_whenConcatenatedUsingPlus_thenNullIsIgnored() { + String result = concatenateUsingPlusOperator(values); + assertEquals("Java is great!", result); + } + + @Test + public void givenStringElementsWithNull_whenConcatenatedUsingHelperMethod_thenNullIsIgnored() { + String result = concatenateUsingHelperMethod(values); + assertEquals("Java is great!", result); + } + + @Test + public void givenStringElementsWithNull_whenConcatenatedUsingStringBuilder_thenNullIsIgnored() { + String result = concatenateUsingStringBuilder(values); + assertEquals("Java is great!", result); + } + + @Test + public void givenStringElementsWithNull_whenConcatenatedUsingJoin_thenNullIsNotIgnored() { + String result = concatenateUsingJoin(values); + assertEquals("Java nullis great!", result); + } + + @Test + public void givenStringElementsWithNull_whenConcatenatedUsingStringJoiner_thenNullIsIgnored() { + String result = concatenateUsingStringJoiner(values); + assertEquals("Java is great!", result); + } + + @Test + public void givenStringElementsWithNull_whenConcatenatedUsingCollectorsJoining_thenNullIsIgnored() { + String result = concatenateUsingCollectorsJoining(values); + assertEquals("Java is great!", result); + } + + @Test + public void givenStringElementsWithNull_whenConcatenatedUsingStringConcat_thenNullIsIgnored() { + String result = concatenateUsingStringConcat(values); + assertEquals("Java is great!", result); + } +} diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index a57cd54191..d9da5a845b 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -90,7 +90,6 @@ core-java-lang-syntax-2 core-java-networking core-java-networking-2 - core-java-networking-3 core-java-nio core-java-nio-2 core-java-optional diff --git a/ethereum/pom.xml b/ethereum/pom.xml index 95dd1c0955..d2b05222c3 100644 --- a/ethereum/pom.xml +++ b/ethereum/pom.xml @@ -144,12 +144,6 @@ test - - org.hamcrest - hamcrest - ${hamcrest.version} - test - com.jayway.jsonpath json-path diff --git a/gson/pom.xml b/gson/pom.xml index a928d87b61..082e53baf0 100644 --- a/gson/pom.xml +++ b/gson/pom.xml @@ -61,10 +61,7 @@ - 2.8.0 - - 4.1 2.9.6 diff --git a/guava-modules/guava-collections-list/pom.xml b/guava-modules/guava-collections-list/pom.xml index 1b989e79b0..6863b4011c 100644 --- a/guava-modules/guava-collections-list/pom.xml +++ b/guava-modules/guava-collections-list/pom.xml @@ -45,9 +45,6 @@ - - 4.1 - 2.0.0.0 diff --git a/guava-modules/guava-collections/pom.xml b/guava-modules/guava-collections/pom.xml index 7929283616..9283107023 100644 --- a/guava-modules/guava-collections/pom.xml +++ b/guava-modules/guava-collections/pom.xml @@ -50,10 +50,7 @@ - - 4.1 0.9.12 - 2.0.0.0 diff --git a/guest/core-kotlin/README.md b/guest/core-kotlin/README.md deleted file mode 100644 index fad62ebea6..0000000000 --- a/guest/core-kotlin/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Kotlin vs Java](https://www.baeldung.com/kotlin/vs-java) diff --git a/jackson-modules/jackson-conversions-2/README.md b/jackson-modules/jackson-conversions-2/README.md index bddbb60bd7..fa3568652a 100644 --- a/jackson-modules/jackson-conversions-2/README.md +++ b/jackson-modules/jackson-conversions-2/README.md @@ -11,4 +11,5 @@ This module contains articles about Jackson conversions. - [Jackson Streaming API](https://www.baeldung.com/jackson-streaming-api) - [Jackson: java.util.LinkedHashMap cannot be cast to X](https://www.baeldung.com/jackson-linkedhashmap-cannot-be-cast) - [Deserialize Snake Case to Camel Case With Jackson](https://www.baeldung.com/jackson-deserialize-snake-to-camel-case) +- [Serialize and Deserialize Booleans as Integers With Jackson](https://www.baeldung.com/jackson-booleans-as-integers) - More articles: [[<-- prev]](../jackson-conversions) diff --git a/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/Game.java b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/Game.java new file mode 100644 index 0000000000..0ad77640d4 --- /dev/null +++ b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/Game.java @@ -0,0 +1,49 @@ +package com.baeldung.jackson.booleanAsInt; + +public class Game { + + private Long id; + private String name; + private Boolean paused; + private Boolean over; + + public Game() { + } + + public Game(Long id, String name) { + this.id = id; + this.name = name; + } + + public Long getId() { + return this.id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public Boolean isPaused() { + return paused; + } + + public void setPaused(Boolean paused) { + this.paused = paused; + } + + public Boolean isOver() { + return over; + } + + public void setOver(Boolean over) { + this.over = over; + } +} diff --git a/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/GameAnnotatedByJsonFormat.java b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/GameAnnotatedByJsonFormat.java new file mode 100644 index 0000000000..b97625fa6b --- /dev/null +++ b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/GameAnnotatedByJsonFormat.java @@ -0,0 +1,56 @@ +package com.baeldung.jackson.booleanAsInt; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonFormat.Shape; + +public class GameAnnotatedByJsonFormat { + + private Long id; + private String name; + + @JsonFormat(shape = Shape.NUMBER) + private boolean paused; + + @JsonFormat(shape = Shape.NUMBER) + private boolean over; + + public GameAnnotatedByJsonFormat() { + } + + public GameAnnotatedByJsonFormat(Long id, String name) { + this.id = id; + this.name = name; + } + + public Long getId() { + return this.id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public boolean isPaused() { + return paused; + } + + public void setPaused(boolean paused) { + this.paused = paused; + } + + public boolean isOver() { + return over; + } + + public void setOver(boolean over) { + this.over = over; + } +} diff --git a/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/GameAnnotatedByJsonSerializeDeserialize.java b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/GameAnnotatedByJsonSerializeDeserialize.java new file mode 100644 index 0000000000..50c6d96009 --- /dev/null +++ b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/GameAnnotatedByJsonSerializeDeserialize.java @@ -0,0 +1,58 @@ +package com.baeldung.jackson.booleanAsInt; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +public class GameAnnotatedByJsonSerializeDeserialize { + + private Long id; + private String name; + + @JsonSerialize(using = NumericBooleanSerializer.class) + @JsonDeserialize(using = NumericBooleanDeserializer.class) + private Boolean paused; + + @JsonSerialize(using = NumericBooleanSerializer.class) + @JsonDeserialize(using = NumericBooleanDeserializer.class) + private Boolean over; + + public GameAnnotatedByJsonSerializeDeserialize() { + } + + public GameAnnotatedByJsonSerializeDeserialize(Long id, String name) { + this.id = id; + this.name = name; + } + + public Long getId() { + return this.id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public Boolean isPaused() { + return paused; + } + + public void setPaused(Boolean paused) { + this.paused = paused; + } + + public Boolean isOver() { + return over; + } + + public void setOver(Boolean over) { + this.over = over; + } +} diff --git a/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/NumericBooleanDeserializer.java b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/NumericBooleanDeserializer.java new file mode 100644 index 0000000000..e9cb41e91d --- /dev/null +++ b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/NumericBooleanDeserializer.java @@ -0,0 +1,23 @@ +package com.baeldung.jackson.booleanAsInt; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import java.io.IOException; + +public class NumericBooleanDeserializer extends JsonDeserializer { + + @Override + public Boolean deserialize(JsonParser p, DeserializationContext ctxt) + throws IOException { + if ("1".equals(p.getText())) { + return Boolean.TRUE; + } + if ("0".equals(p.getText())) { + return Boolean.FALSE; + } + // for other than "1" or "0" throw exception by using Jackson internals + throw ctxt.weirdStringException(p.getText(), Boolean.class, "only \"1\" or \"0\" recognized"); + } + +} diff --git a/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/NumericBooleanSerializer.java b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/NumericBooleanSerializer.java new file mode 100644 index 0000000000..e9f7112b53 --- /dev/null +++ b/jackson-modules/jackson-conversions-2/src/main/java/com/baeldung/jackson/booleanAsInt/NumericBooleanSerializer.java @@ -0,0 +1,15 @@ +package com.baeldung.jackson.booleanAsInt; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import java.io.IOException; + +public class NumericBooleanSerializer extends JsonSerializer { + + @Override + public void serialize(Boolean value, JsonGenerator gen, SerializerProvider serializers) + throws IOException { + gen.writeString(value ? "1" : "0"); + } +} diff --git a/jackson-modules/jackson-conversions-2/src/test/java/com/baeldung/jackson/booleanAsInt/BooleanAsIntegerUnitTest.java b/jackson-modules/jackson-conversions-2/src/test/java/com/baeldung/jackson/booleanAsInt/BooleanAsIntegerUnitTest.java new file mode 100644 index 0000000000..976f3f4915 --- /dev/null +++ b/jackson-modules/jackson-conversions-2/src/test/java/com/baeldung/jackson/booleanAsInt/BooleanAsIntegerUnitTest.java @@ -0,0 +1,132 @@ +package com.baeldung.jackson.booleanAsInt; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonFormat.Shape; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.exc.InvalidFormatException; +import com.fasterxml.jackson.databind.module.SimpleModule; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class BooleanAsIntegerUnitTest { + + private ObjectMapper mapper; + + @BeforeEach + public void setup() { + mapper = new ObjectMapper(); + } + + @Test + public void givenBoolean_serializedAsInteger() throws Exception { + GameAnnotatedByJsonFormat + game = new GameAnnotatedByJsonFormat(1L, "My Game"); + game.setPaused(true); + game.setOver(false); + String json = mapper.writeValueAsString(game); + + assertThat(json) + .isEqualTo("{\"id\":1,\"name\":\"My Game\",\"paused\":1,\"over\":0}"); + } + + @Test + public void givenInteger_deserializedAsBooleanByDefault() throws Exception { + // Integer "1" and "0" values deserialized correctly out of the box. + // No configuration or @JsonFormat annotation needed. + String json = "{\"id\":1,\"name\":\"My Game\",\"paused\":1,\"over\":0}"; + Game game = mapper.readValue(json, Game.class); + + assertThat(game.isPaused()).isEqualTo(true); + assertThat(game.isOver()).isEqualTo(false); + } + + @Test + public void givenBoolean_serializedAsIntegerGlobally() throws Exception { + // global configuration override for the type Boolean + mapper.configOverride(Boolean.class) + .setFormat(JsonFormat.Value.forShape(Shape.NUMBER)); + + Game game = new Game(1L, "My Game"); + game.setPaused(true); + game.setOver(false); + String json = mapper.writeValueAsString(game); + + assertThat(json) + .isEqualTo("{\"id\":1,\"name\":\"My Game\",\"paused\":1,\"over\":0}"); + } + + @Test + public void givenBooleanWithCustomSerializer_serializedAsNumericString() throws Exception { + GameAnnotatedByJsonSerializeDeserialize + game = new GameAnnotatedByJsonSerializeDeserialize(1L, "My Game"); + game.setPaused(true); + game.setOver(false); + String json = mapper.writeValueAsString(game); + + assertThat(json) + .isEqualTo("{\"id\":1,\"name\":\"My Game\",\"paused\":\"1\",\"over\":\"0\"}"); + } + + @Test + public void givenNumericStringWithCustomDeserializer_deserializedAsBoolean() throws Exception { + String json = "{\"id\":1,\"name\":\"My Game\",\"paused\":\"1\",\"over\":\"0\"}"; + GameAnnotatedByJsonSerializeDeserialize + game = mapper.readValue(json, GameAnnotatedByJsonSerializeDeserialize.class); + + assertThat(game.isPaused()).isEqualTo(true); + assertThat(game.isOver()).isEqualTo(false); + } + + @Test + public void givenBooleanWithCustomSerializer_serializedAsNumericStringGlobally() throws Exception { + // setting serializers globally + SimpleModule module = new SimpleModule(); + module.addSerializer(Boolean.class, new NumericBooleanSerializer()); + mapper.registerModule(module); + + Game game = new Game(1L, "My Game"); + game.setPaused(true); + game.setOver(false); + String json = mapper.writeValueAsString(game); + + assertThat(json) + .isEqualTo("{\"id\":1,\"name\":\"My Game\",\"paused\":\"1\",\"over\":\"0\"}"); + } + + @Test + public void givenNumericStringWithCustomDeserializer_deserializedAsBooleanGlobally() throws Exception { + // setting deserializers globally + SimpleModule module = new SimpleModule(); + module.addDeserializer(Boolean.class, new NumericBooleanDeserializer()); + mapper.registerModule(module); + + String json = "{\"id\":1,\"name\":\"My Game\",\"paused\":\"1\",\"over\":\"0\"}"; + Game game = mapper.readValue(json, Game.class); + + assertThat(game.isPaused()).isEqualTo(true); + assertThat(game.isOver()).isEqualTo(false); + } + + @Test + public void givenInvalidStringWithCustomDeserializer_throwsInvalidFormatException() { + // another number other than "1" or "0" + String json = "{\"id\":1,\"name\":\"My Game\",\"paused\":\"5\"}"; + InvalidFormatException e = Assertions.assertThrows( + InvalidFormatException.class, () -> mapper.readValue(json, GameAnnotatedByJsonSerializeDeserialize.class) + ); + + assertThat(e.getValue()).isEqualTo("5"); + + // non-numeric string + String json2 = "{\"id\":1,\"name\":\"My Game\",\"paused\":\"xxx\"}"; + InvalidFormatException e2 = Assertions.assertThrows( + InvalidFormatException.class, () -> mapper.readValue(json2, GameAnnotatedByJsonSerializeDeserialize.class) + ); + + assertThat(e2.getValue()).isEqualTo("xxx"); + } + +} diff --git a/java-collections-conversions-2/pom.xml b/java-collections-conversions-2/pom.xml index 694b416169..9f8ef7addc 100644 --- a/java-collections-conversions-2/pom.xml +++ b/java-collections-conversions-2/pom.xml @@ -26,12 +26,6 @@ modelmapper ${modelmapper.version} - - org.hamcrest - hamcrest - ${hamcrest.version} - test - io.vavr vavr diff --git a/java-collections-conversions/pom.xml b/java-collections-conversions/pom.xml index ae800b21c1..7f5ba38e3e 100644 --- a/java-collections-conversions/pom.xml +++ b/java-collections-conversions/pom.xml @@ -38,8 +38,4 @@ - - 4.4 - - \ No newline at end of file diff --git a/java-collections-maps-3/pom.xml b/java-collections-maps-3/pom.xml index 6f724ab5ef..81466b17ba 100644 --- a/java-collections-maps-3/pom.xml +++ b/java-collections-maps-3/pom.xml @@ -30,7 +30,6 @@ - 4.1 5.2.5.RELEASE diff --git a/json/pom.xml b/json/pom.xml index 2919a3a4ee..dfe42ee4c1 100644 --- a/json/pom.xml +++ b/json/pom.xml @@ -74,7 +74,6 @@ 1.4.1 1.2.21 1.0 - 4.1 1.0.1 20171018 2.8.5 diff --git a/libraries-6/pom.xml b/libraries-6/pom.xml index accf5f3a9a..3b932f2bd2 100644 --- a/libraries-6/pom.xml +++ b/libraries-6/pom.xml @@ -146,7 +146,6 @@ 3.5-beta72 3.0 1.8.1 - 4.4 8.12.9 2.4.4 diff --git a/libraries-apache-commons-collections/pom.xml b/libraries-apache-commons-collections/pom.xml index 2cb73babe6..c1a158b16e 100644 --- a/libraries-apache-commons-collections/pom.xml +++ b/libraries-apache-commons-collections/pom.xml @@ -16,7 +16,7 @@ org.apache.commons commons-collections4 - ${commons.collections.version} + ${commons-collections4.version} org.hamcrest @@ -27,7 +27,6 @@ - 4.1 2.0.0.0 diff --git a/libraries-data-db/pom.xml b/libraries-data-db/pom.xml index 20119da8a2..c0f2848705 100644 --- a/libraries-data-db/pom.xml +++ b/libraries-data-db/pom.xml @@ -63,7 +63,6 @@ com.h2database h2 - ${h2.version} diff --git a/libraries-testing/pom.xml b/libraries-testing/pom.xml index d62d094f08..4bc6eba7fc 100644 --- a/libraries-testing/pom.xml +++ b/libraries-testing/pom.xml @@ -118,7 +118,6 @@ ${spring-mock-mvc.version} test - org.hamcrest java-hamcrest @@ -196,7 +195,6 @@ 4.3.8.RELEASE 4.1.1 2.0.0.0 - 1.4.200 2.7.0 3.14.0 1.8 diff --git a/libraries/pom.xml b/libraries/pom.xml index b0a0aa22ea..7bef56deb0 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -167,12 +167,6 @@ google-oauth-client-jetty ${google-api.version} - - org.hamcrest - hamcrest-all - ${hamcrest-all.version} - test - @@ -279,7 +273,6 @@ 1.15 1.23.0 0.9.4.0006L - 1.3 3.2.0-m7 5.1.1 5.0.2 diff --git a/linux-bash/text/README.md b/linux-bash/text/README.md index 1c27abc8c6..5423ddf916 100644 --- a/linux-bash/text/README.md +++ b/linux-bash/text/README.md @@ -1,4 +1,3 @@ ### Relevant Articles: -- [Linux Commands – Remove All Text After X](https://www.baeldung.com/linux/remove-text-after-x-in-file) - [Linux Commands for Appending Multiple Lines to a File](https://www.baeldung.com/linux/appending-multiple-lines-to-file2) diff --git a/logging-modules/logback/pom.xml b/logging-modules/logback/pom.xml index 48bb37b881..b4ee42367f 100644 --- a/logging-modules/logback/pom.xml +++ b/logging-modules/logback/pom.xml @@ -74,4 +74,40 @@ 1.1.1 + + + integration-lite-first + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + ${project.basedir}/src/test/resources/logback-test.xml + + + + + + + + integration-lite-second + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + ${project.basedir}/src/test/resources/logback-test.xml + + + + + + + \ No newline at end of file diff --git a/parent-java/pom.xml b/parent-java/pom.xml index 4e5081393c..808eed1c44 100644 --- a/parent-java/pom.xml +++ b/parent-java/pom.xml @@ -43,7 +43,6 @@ 31.0.1-jre 2.3.7 - 2.2 \ No newline at end of file diff --git a/persistence-modules/core-java-persistence-2/pom.xml b/persistence-modules/core-java-persistence-2/pom.xml index 15676bf03e..780c1fcfca 100644 --- a/persistence-modules/core-java-persistence-2/pom.xml +++ b/persistence-modules/core-java-persistence-2/pom.xml @@ -44,7 +44,6 @@ - 1.4.200 8.4.1.jre11 10.2.0.4.0 8.0.22 diff --git a/persistence-modules/core-java-persistence/pom.xml b/persistence-modules/core-java-persistence/pom.xml index efef12a525..5cc1df483f 100644 --- a/persistence-modules/core-java-persistence/pom.xml +++ b/persistence-modules/core-java-persistence/pom.xml @@ -55,7 +55,6 @@ - 1.4.200 2.4.0 3.2.0 0.9.5.2 diff --git a/persistence-modules/hibernate-annotations/pom.xml b/persistence-modules/hibernate-annotations/pom.xml index e5c19915a4..634cd64cca 100644 --- a/persistence-modules/hibernate-annotations/pom.xml +++ b/persistence-modules/hibernate-annotations/pom.xml @@ -45,7 +45,6 @@ 5.4.7.Final - 1.4.200 true 2.1.7.RELEASE 5.4.7.Final diff --git a/persistence-modules/hibernate-jpa/src/test/resources/hibernate-pessimistic-locking.properties b/persistence-modules/hibernate-jpa/src/test/resources/hibernate-pessimistic-locking.properties index 4f1ff5e93a..342f7b0bf5 100644 --- a/persistence-modules/hibernate-jpa/src/test/resources/hibernate-pessimistic-locking.properties +++ b/persistence-modules/hibernate-jpa/src/test/resources/hibernate-pessimistic-locking.properties @@ -1,5 +1,5 @@ hibernate.connection.driver_class=org.h2.Driver -hibernate.connection.url=jdbc:h2:mem:mydb3;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=100;MVCC=FALSE +hibernate.connection.url=jdbc:h2:mem:mydb3;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=100 hibernate.connection.username=sa hibernate.connection.autocommit=true hibernate.dialect=org.hibernate.dialect.H2Dialect diff --git a/persistence-modules/hibernate-mapping/pom.xml b/persistence-modules/hibernate-mapping/pom.xml index 9661c3fd4c..506283a4fb 100644 --- a/persistence-modules/hibernate-mapping/pom.xml +++ b/persistence-modules/hibernate-mapping/pom.xml @@ -69,6 +69,7 @@ + 1.4.197 5.4.12.Final 2.10.4 6.0.16.Final diff --git a/persistence-modules/java-jpa-3/README.md b/persistence-modules/java-jpa-3/README.md index 202c97a830..aa33644b17 100644 --- a/persistence-modules/java-jpa-3/README.md +++ b/persistence-modules/java-jpa-3/README.md @@ -13,5 +13,4 @@ This module contains articles about the Java Persistence API (JPA) in Java. - [Returning an Auto-Generated Id with JPA](https://www.baeldung.com/jpa-get-auto-generated-id) - [How to Return Multiple Entities In JPA Query](https://www.baeldung.com/jpa-return-multiple-entities) - [Defining Unique Constraints in JPA](https://www.baeldung.com/jpa-unique-constraints) -- [How to Check Field Existence in MongoDB?](https://www.baeldung.com/mongodb-check-field-exists) - [Connecting to a Specific Schema in JDBC](https://www.baeldung.com/jdbc-connect-to-schema) diff --git a/persistence-modules/java-mongodb/README.md b/persistence-modules/java-mongodb/README.md index f632e7c662..34acd60c57 100644 --- a/persistence-modules/java-mongodb/README.md +++ b/persistence-modules/java-mongodb/README.md @@ -11,3 +11,4 @@ This module contains articles about MongoDB in Java. - [Introduction to Morphia – Java ODM for MongoDB](https://www.baeldung.com/mongodb-morphia) - [MongoDB Aggregations Using Java](https://www.baeldung.com/java-mongodb-aggregations) - [BSON to JSON Document Conversion in Java](https://www.baeldung.com/java-convert-bson-to-json) +- [How to Check Field Existence in MongoDB?](https://www.baeldung.com/mongodb-check-field-exists) diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/existence.field/FieldExistenceLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/existence/field/FieldExistenceLiveTest.java similarity index 100% rename from persistence-modules/java-mongodb/src/test/java/com/baeldung/existence.field/FieldExistenceLiveTest.java rename to persistence-modules/java-mongodb/src/test/java/com/baeldung/existence/field/FieldExistenceLiveTest.java diff --git a/persistence-modules/jooq/pom.xml b/persistence-modules/jooq/pom.xml index c66be9db77..b9229377ab 100644 --- a/persistence-modules/jooq/pom.xml +++ b/persistence-modules/jooq/pom.xml @@ -45,7 +45,6 @@ 3.13.4 - 1.4.200 \ No newline at end of file diff --git a/persistence-modules/r2dbc/pom.xml b/persistence-modules/r2dbc/pom.xml index ae4ca4d91d..1ce5eb3e96 100644 --- a/persistence-modules/r2dbc/pom.xml +++ b/persistence-modules/r2dbc/pom.xml @@ -63,7 +63,6 @@ 0.8.1.RELEASE - 1.4.200 \ No newline at end of file diff --git a/persistence-modules/r2dbc/src/test/resources/logback-test.xml b/persistence-modules/r2dbc/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/persistence-modules/r2dbc/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-2/src/test/resources/logback-test.xml b/persistence-modules/spring-boot-persistence-2/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/config/DatasourceProxyBeanPostProcessor.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/config/DatasourceProxyBeanPostProcessor.java index c087427b65..1952a26f2f 100644 --- a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/config/DatasourceProxyBeanPostProcessor.java +++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2db/lazy_load_no_trans/config/DatasourceProxyBeanPostProcessor.java @@ -1,10 +1,7 @@ package com.baeldung.h2db.lazy_load_no_trans.config; import net.ttddyy.dsproxy.listener.DataSourceQueryCountListener; -import net.ttddyy.dsproxy.listener.logging.CommonsQueryLoggingListener; -import net.ttddyy.dsproxy.listener.logging.DefaultQueryLogEntryCreator; import net.ttddyy.dsproxy.listener.logging.SLF4JLogLevel; -import net.ttddyy.dsproxy.listener.logging.SLF4JQueryLoggingListener; import net.ttddyy.dsproxy.support.ProxyDataSource; import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder; import org.aopalliance.intercept.MethodInterceptor; @@ -49,7 +46,7 @@ public class DatasourceProxyBeanPostProcessor implements BeanPostProcessor { this.dataSource = ProxyDataSourceBuilder.create(dataSource) .name("MyDS") .multiline() - .logQueryBySlf4j(SLF4JLogLevel.INFO) + .logQueryBySlf4j(SLF4JLogLevel.DEBUG) .listener(new DataSourceQueryCountListener()) .build(); } diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/resources/application.properties b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application.properties index 134cda6628..2499d7cd06 100644 --- a/persistence-modules/spring-boot-persistence-h2/src/main/resources/application.properties +++ b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application.properties @@ -4,7 +4,7 @@ spring.datasource.username=sa spring.datasource.password= spring.jpa.defer-datasource-initialization=true spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.show-sql=true +spring.jpa.show-sql=false spring.jpa.properties.hibernate.format_sql=true spring.jpa.properties.hibernate.validator.apply_to_ddl=false #spring.jpa.properties.hibernate.check_nullability=true diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/test/resources/logback-test.xml b/persistence-modules/spring-boot-persistence-mongodb/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-cassandra-reactive/src/test/resources/logback-test.xml b/persistence-modules/spring-data-cassandra-reactive/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/persistence-modules/spring-data-cassandra-reactive/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-eclipselink/pom.xml b/persistence-modules/spring-data-eclipselink/pom.xml index a344d64864..561d144fe3 100644 --- a/persistence-modules/spring-data-eclipselink/pom.xml +++ b/persistence-modules/spring-data-eclipselink/pom.xml @@ -66,6 +66,7 @@ 1.5.9.RELEASE 2.7.0 + 1.4.197 \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java index da840dc027..a7763bb0f8 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooFixtures.java @@ -10,8 +10,13 @@ import org.hibernate.SessionFactory; import org.hibernate.Transaction; import com.google.common.collect.Lists; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class FooFixtures { + + private static final Logger LOGGER = LoggerFactory.getLogger(FooFixtures.class); + private SessionFactory sessionFactory; public FooFixtures(final SessionFactory sessionFactory) { @@ -36,8 +41,9 @@ public class FooFixtures { foo.setBar(bar); session.save(foo); final Foo foo2 = new Foo(null); - if (i % 2 == 0) + if (i % 2 == 0) { foo2.setName("LuckyFoo" + (i + 120)); + } foo2.setBar(bar); session.save(foo2); bar.getFooSet().add(foo); @@ -47,15 +53,16 @@ public class FooFixtures { tx.commit(); session.flush(); } catch (final HibernateException he) { - if (tx != null) + if (tx != null) { tx.rollback(); - System.out.println("Not able to open session"); - he.printStackTrace(); + } + LOGGER.error("Not able to open session", he); } catch (final Exception e) { - e.printStackTrace(); + LOGGER.error(e.getLocalizedMessage(), e); } finally { - if (session != null) + if (session != null) { session.close(); + } } } @@ -86,15 +93,16 @@ public class FooFixtures { tx.commit(); session.flush(); } catch (final HibernateException he) { - if (tx != null) + if (tx != null) { tx.rollback(); - System.out.println("Not able to open session"); - he.printStackTrace(); + } + LOGGER.error("Not able to open session", he); } catch (final Exception e) { - e.printStackTrace(); + LOGGER.error(e.getLocalizedMessage(), e); } finally { - if (session != null) + if (session != null) { session.close(); + } } } diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java index 8173088af0..6078eb3af0 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java @@ -15,6 +15,8 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -29,6 +31,8 @@ import com.baeldung.spring.config.PersistenceTestConfig; @SuppressWarnings("unchecked") public class FooSortingPersistenceIntegrationTest { + private static final Logger LOGGER = LoggerFactory.getLogger(FooSortingPersistenceIntegrationTest.class); + @Autowired private SessionFactory sessionFactory; @@ -56,7 +60,7 @@ public class FooSortingPersistenceIntegrationTest { final Query query = session.createQuery(hql); final List fooList = query.list(); for (final Foo foo : fooList) { - System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); + LOGGER.debug("Name: {} , Id: {}", foo.getName(), foo.getId()); } } @@ -68,7 +72,7 @@ public class FooSortingPersistenceIntegrationTest { assertNull(fooList.get(fooList.toArray().length - 1).getName()); for (final Foo foo : fooList) { - System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); + LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId()); } } @@ -79,7 +83,7 @@ public class FooSortingPersistenceIntegrationTest { final List fooList = query.list(); assertNull(fooList.get(0).getName()); for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName()); + LOGGER.debug("Name: {}", foo.getName()); } } @@ -90,7 +94,7 @@ public class FooSortingPersistenceIntegrationTest { final Query query = session.createQuery(hql); final List fooList = query.list(); for (final Foo foo : fooList) { - System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); + LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId()); } } @@ -100,7 +104,7 @@ public class FooSortingPersistenceIntegrationTest { final Query query = session.createQuery(hql); final List fooList = query.list(); for (final Foo foo : fooList) { - System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); + LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId()); } } @@ -110,7 +114,7 @@ public class FooSortingPersistenceIntegrationTest { final Query query = session.createQuery(hql); final List fooList = query.list(); for (final Foo foo : fooList) { - System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); + LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId()); } } @@ -120,7 +124,7 @@ public class FooSortingPersistenceIntegrationTest { criteria.addOrder(Order.asc("id")); final List fooList = criteria.list(); for (final Foo foo : fooList) { - System.out.println("Id: " + foo.getId() + ", FirstName: " + foo.getName()); + LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName()); } } @@ -131,7 +135,7 @@ public class FooSortingPersistenceIntegrationTest { criteria.addOrder(Order.asc("id")); final List fooList = criteria.list(); for (final Foo foo : fooList) { - System.out.println("Id: " + foo.getId() + ", FirstName: " + foo.getName()); + LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName()); } } @@ -142,7 +146,7 @@ public class FooSortingPersistenceIntegrationTest { final List fooList = criteria.list(); assertNull(fooList.get(fooList.toArray().length - 1).getName()); for (final Foo foo : fooList) { - System.out.println("Id: " + foo.getId() + ", FirstName: " + foo.getName()); + LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName()); } } @@ -153,7 +157,7 @@ public class FooSortingPersistenceIntegrationTest { final List fooList = criteria.list(); assertNull(fooList.get(0).getName()); for (final Foo foo : fooList) { - System.out.println("Id: " + foo.getId() + ", FirstName: " + foo.getName()); + LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName()); } } @@ -164,9 +168,9 @@ public class FooSortingPersistenceIntegrationTest { final List barList = query.list(); for (final Bar bar : barList) { final Set fooSet = bar.getFooSet(); - System.out.println("Bar Id:" + bar.getId()); + LOGGER.debug("Bar Id:{}", bar.getId()); for (final Foo foo : fooSet) { - System.out.println("FooName:" + foo.getName()); + LOGGER.debug("FooName:{}", foo.getName()); } } } diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java index 5a73e39ca2..8c766954ff 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java @@ -1,7 +1,10 @@ package com.baeldung.persistence.service; +import com.baeldung.persistence.hibernate.FooSortingPersistenceIntegrationTest; import org.junit.Test; import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.test.context.ContextConfiguration; @@ -16,6 +19,8 @@ import com.baeldung.spring.config.PersistenceTestConfig; @ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) public class ParentServicePersistenceIntegrationTest { + private static final Logger LOGGER = LoggerFactory.getLogger(ParentServicePersistenceIntegrationTest.class); + @Autowired private IParentService service; @@ -37,11 +42,11 @@ public class ParentServicePersistenceIntegrationTest { final Parent parentEntity = new Parent(childEntity); service.create(parentEntity); - System.out.println("Child = " + childService.findOne(childEntity.getId())); - System.out.println("Child - parent = " + childService.findOne(childEntity.getId()).getParent()); + LOGGER.debug("Child = {}", childService.findOne(childEntity.getId())); + LOGGER.debug("Child - parent = {}", childService.findOne(childEntity.getId()).getParent()); - System.out.println("Parent = " + service.findOne(parentEntity.getId())); - System.out.println("Parent - child = " + service.findOne(parentEntity.getId()).getChild()); + LOGGER.debug("Parent = {}", service.findOne(parentEntity.getId())); + LOGGER.debug("Parent - child = {}", service.findOne(parentEntity.getId()).getChild()); } @Test(expected = DataIntegrityViolationException.class) diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/config/PersistenceTestConfig.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/config/PersistenceTestConfig.java index 34301741fe..c8f14c5563 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/config/PersistenceTestConfig.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/config/PersistenceTestConfig.java @@ -166,7 +166,7 @@ public class PersistenceTestConfig { hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - hibernateProperties.setProperty("hibernate.show_sql", "true"); + hibernateProperties.setProperty("hibernate.show_sql", "false"); // hibernateProperties.setProperty("hibernate.format_sql", "true"); // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/UserRepositoryIntegrationTest.java index a9ab13feed..19760f2bfe 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/UserRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/UserRepositoryIntegrationTest.java @@ -19,7 +19,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(SpringRunner.class) -@DataJpaTest(properties = "spring.sql.init.data-locations=classpath:insert_users.sql") +@DataJpaTest(properties = "spring.sql.init.data-locations=classpath:insert_users.sql", showSql = false) public class UserRepositoryIntegrationTest { @Autowired diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepositoryIntegrationTest.java index e00a340615..b97fbc5275 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepositoryIntegrationTest.java @@ -17,7 +17,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) -@DataJpaTest(properties="spring.sql.init.data-locations=classpath:import_entities.sql") +@DataJpaTest(properties="spring.sql.init.data-locations=classpath:import_entities.sql", showSql = false) public class ArticleRepositoryIntegrationTest { @Autowired diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/resources/fetching.cfg.xml b/persistence-modules/spring-data-jpa-query-2/src/test/resources/fetching.cfg.xml index 55a3aeb51c..4d3ff2ae63 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/resources/fetching.cfg.xml +++ b/persistence-modules/spring-data-jpa-query-2/src/test/resources/fetching.cfg.xml @@ -11,7 +11,7 @@ org.hibernate.dialect.H2Dialect update - true + false diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/resources/fetchingLazy.cfg.xml b/persistence-modules/spring-data-jpa-query-2/src/test/resources/fetchingLazy.cfg.xml index 8fcf578660..8a2bf593cb 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/resources/fetchingLazy.cfg.xml +++ b/persistence-modules/spring-data-jpa-query-2/src/test/resources/fetchingLazy.cfg.xml @@ -11,7 +11,7 @@ org.hibernate.dialect.H2Dialect update - true + false diff --git a/persistence-modules/spring-data-jpa-query/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-query/src/main/resources/application.properties index 9bb870895d..eb0e519ef0 100644 --- a/persistence-modules/spring-data-jpa-query/src/main/resources/application.properties +++ b/persistence-modules/spring-data-jpa-query/src/main/resources/application.properties @@ -1,2 +1,2 @@ -spring.jpa.show-sql=true +spring.jpa.show-sql=false spring.jpa.defer-datasource-initialization=true \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java index 779ade7a3f..a73ad949db 100644 --- a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java @@ -16,8 +16,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; @RunWith(SpringRunner.class) -@DataJpaTest - +@DataJpaTest(showSql = false) @Sql(scripts = "/test-aggregation-data.sql") public class SpringDataAggregateIntegrationTest { diff --git a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/boot/passenger/PassengerRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/boot/passenger/PassengerRepositoryIntegrationTest.java index f082350019..d80380854d 100644 --- a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/boot/passenger/PassengerRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/boot/passenger/PassengerRepositoryIntegrationTest.java @@ -26,8 +26,7 @@ import static org.hamcrest.core.IsNot.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; - -@DataJpaTest +@DataJpaTest(showSql = false) @RunWith(SpringRunner.class) public class PassengerRepositoryIntegrationTest { diff --git a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/entitygraph/EntityGraphIntegrationTest.java b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/entitygraph/EntityGraphIntegrationTest.java index 24880a5dff..b6bf51ac65 100644 --- a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/entitygraph/EntityGraphIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/entitygraph/EntityGraphIntegrationTest.java @@ -14,7 +14,7 @@ import com.baeldung.entitygraph.model.Item; import com.baeldung.entitygraph.repository.CharacteristicsRepository; import com.baeldung.entitygraph.repository.ItemRepository; -@DataJpaTest +@DataJpaTest(showSql = false) @RunWith(SpringRunner.class) @Sql(scripts = "/entitygraph-data.sql") public class EntityGraphIntegrationTest { diff --git a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java index d99f6671a3..53f22ed0d1 100644 --- a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java @@ -9,6 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Example; import org.springframework.data.domain.ExampleMatcher; +import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import java.util.Arrays; diff --git a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/joins/JpaJoinsIntegrationTest.java b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/joins/JpaJoinsIntegrationTest.java index 9b0d23f3e4..e24b2ae4b7 100644 --- a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/joins/JpaJoinsIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/joins/JpaJoinsIntegrationTest.java @@ -13,10 +13,11 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) -@DataJpaTest +@DataJpaTest(showSql = false) @ActiveProfiles("joins") public class JpaJoinsIntegrationTest { diff --git a/persistence-modules/spring-data-jpa-query/src/test/resources/logback-test.xml b/persistence-modules/spring-data-jpa-query/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/saveperformance/BookApplication.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/saveperformance/BookApplication.java index 56ad918be3..46cb8d3453 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/saveperformance/BookApplication.java +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/saveperformance/BookApplication.java @@ -1,5 +1,7 @@ package com.baeldung.spring.data.persistence.saveperformance; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -12,6 +14,8 @@ import java.util.List; @SpringBootApplication public class BookApplication { + private static final Logger LOGGER = LoggerFactory.getLogger(BookApplication.class); + @Autowired private BookRepository bookRepository; @@ -25,13 +29,13 @@ public class BookApplication { int bookCount = 10000; long start = System.currentTimeMillis(); - for(int i = 0; i < bookCount; i++) { + for (int i = 0; i < bookCount; i++) { bookRepository.save(new Book("Book " + i, "Author " + i)); } long end = System.currentTimeMillis(); bookRepository.deleteAll(); - System.out.println("It took " + (end - start) + "ms to execute save() for " + bookCount + " books"); + LOGGER.debug("It took {}ms to execute save() for {} books.", (end - start), bookCount); List bookList = new ArrayList<>(); for (int i = 0; i < bookCount; i++) { @@ -42,7 +46,7 @@ public class BookApplication { bookRepository.saveAll(bookList); end = System.currentTimeMillis(); - System.out.println("It took " + (end - start) + "ms to execute saveAll() with " + bookCount + " books\n"); + LOGGER.debug("It took {}ms to execute saveAll() with {}} books.", (end - start), bookCount); } } diff --git a/persistence-modules/spring-data-jpa-repo-2/src/test/resources/logback-test.xml b/persistence-modules/spring-data-jpa-repo-2/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-repo/src/main/resources/application.properties index ae1afe6e98..1a370121c5 100644 --- a/persistence-modules/spring-data-jpa-repo/src/main/resources/application.properties +++ b/persistence-modules/spring-data-jpa-repo/src/main/resources/application.properties @@ -1,4 +1,4 @@ -spring.jpa.show-sql=true +spring.jpa.show-sql=false spring.jpa.defer-datasource-initialization=true #MySql #spring.datasource.url=jdbc:mysql://localhost:3306/baeldung diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/JpaRepositoriesIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/JpaRepositoriesIntegrationTest.java index fe02f79a56..34de77a2b3 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/JpaRepositoriesIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/JpaRepositoriesIntegrationTest.java @@ -21,7 +21,7 @@ import com.baeldung.boot.domain.Location; import com.baeldung.boot.domain.Store; @RunWith(SpringRunner.class) -@DataJpaTest(properties="spring.sql.init.data-locations=classpath:import_entities.sql") +@DataJpaTest(properties="spring.sql.init.data-locations=classpath:import_entities.sql", showSql = false) public class JpaRepositoriesIntegrationTest { @Autowired private LocationRepository locationRepository; diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/PassengerRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/PassengerRepositoryIntegrationTest.java index 37fcef7dab..fd06710084 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/PassengerRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/PassengerRepositoryIntegrationTest.java @@ -18,7 +18,7 @@ import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.entity.Passenger; -@DataJpaTest +@DataJpaTest(showSql = false) @RunWith(SpringRunner.class) public class PassengerRepositoryIntegrationTest { diff --git a/persistence-modules/spring-data-jpa-repo/src/test/resources/logback-test.xml b/persistence-modules/spring-data-jpa-repo/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-mongodb-reactive/pom.xml b/persistence-modules/spring-data-mongodb-reactive/pom.xml index c1398ca80d..2220418ac3 100644 --- a/persistence-modules/spring-data-mongodb-reactive/pom.xml +++ b/persistence-modules/spring-data-mongodb-reactive/pom.xml @@ -71,7 +71,6 @@ com.h2database h2 - ${h2.version} org.apache.httpcomponents @@ -126,7 +125,6 @@ 5.2.2.RELEASE 4.5.2 - 1.4.200 3.3.1.RELEASE diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/dynamicupdate/DynamicUpdateConfig.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/dynamicupdate/DynamicUpdateConfig.java index 4871a3d1e2..23e28a9e3b 100644 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/dynamicupdate/DynamicUpdateConfig.java +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/dynamicupdate/DynamicUpdateConfig.java @@ -74,7 +74,7 @@ public class DynamicUpdateConfig { Properties properties = new Properties(); properties.setProperty("hibernate.hbm2ddl.auto", Preconditions.checkNotNull(env.getProperty("hibernate.hbm2ddl.auto"))); properties.setProperty("hibernate.dialect", Preconditions.checkNotNull(env.getProperty("hibernate.dialect"))); - properties.setProperty("hibernate.show_sql", "true"); + properties.setProperty("hibernate.show_sql", "false"); return properties; } } \ No newline at end of file diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/util/HibernateUtil.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/util/HibernateUtil.java index 722f0251d1..aee4206e53 100644 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/util/HibernateUtil.java +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/immutable/util/HibernateUtil.java @@ -6,8 +6,12 @@ import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class HibernateUtil { + + private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class); private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { @@ -20,7 +24,7 @@ public class HibernateUtil { ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); return configuration.buildSessionFactory(serviceRegistry); } catch (Throwable ex) { - System.out.println("Initial SessionFactory creation failed." + ex); + LOGGER.debug("Initial SessionFactory creation failed.", ex); throw new ExceptionInInitializerError(ex); } } diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java index 5f489dd027..29e8d7515a 100644 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java @@ -6,8 +6,12 @@ import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import com.baeldung.hibernate.manytomany.model.Employee; import com.baeldung.hibernate.manytomany.model.Project; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class HibernateUtil { + + private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class); private static SessionFactory sessionFactory; private static SessionFactory buildSessionFactory() { @@ -17,25 +21,25 @@ public class HibernateUtil { configuration.addAnnotatedClass(Employee.class); configuration.addAnnotatedClass(Project.class); configuration.configure("manytomany.cfg.xml"); - System.out.println("Hibernate Annotation Configuration loaded"); + LOGGER.debug("Hibernate Annotation Configuration loaded"); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) - .build(); - System.out.println("Hibernate Annotation serviceRegistry created"); + .build(); + LOGGER.debug("Hibernate Annotation serviceRegistry created"); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; } catch (Throwable ex) { - System.err.println("Initial SessionFactory creation failed." + ex); - ex.printStackTrace(); + LOGGER.error("Initial SessionFactory creation failed.", ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { - if (sessionFactory == null) + if (sessionFactory == null) { sessionFactory = buildSessionFactory(); + } return sessionFactory; } } diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java index 44cbfadb25..b8e7e1b2fd 100644 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java @@ -63,7 +63,7 @@ public class PersistenceConfig { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - hibernateProperties.setProperty("hibernate.show_sql", "true"); + hibernateProperties.setProperty("hibernate.show_sql", "false"); return hibernateProperties; } diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceConfig.java index 74ac0a269e..159d6e2e8e 100644 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceConfig.java +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceConfig.java @@ -71,7 +71,7 @@ public class PersistenceConfig { hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - hibernateProperties.setProperty("hibernate.show_sql", "true"); + hibernateProperties.setProperty("hibernate.show_sql", "false"); // Envers properties hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix")); diff --git a/persistence-modules/spring-hibernate-5/src/main/resources/immutable.cfg.xml b/persistence-modules/spring-hibernate-5/src/main/resources/immutable.cfg.xml index a572ebeac2..4e55b4632f 100644 --- a/persistence-modules/spring-hibernate-5/src/main/resources/immutable.cfg.xml +++ b/persistence-modules/spring-hibernate-5/src/main/resources/immutable.cfg.xml @@ -23,7 +23,7 @@ thread - true + false update diff --git a/persistence-modules/spring-hibernate-5/src/main/resources/manytomany.cfg.xml b/persistence-modules/spring-hibernate-5/src/main/resources/manytomany.cfg.xml index 3c753a89af..315e2e3118 100644 --- a/persistence-modules/spring-hibernate-5/src/main/resources/manytomany.cfg.xml +++ b/persistence-modules/spring-hibernate-5/src/main/resources/manytomany.cfg.xml @@ -10,6 +10,6 @@ tutorialuser org.hibernate.dialect.MySQLDialect thread - true + false diff --git a/persistence-modules/spring-hibernate-5/src/test/resources/manytomany.cfg.xml b/persistence-modules/spring-hibernate-5/src/test/resources/manytomany.cfg.xml index a7a23ec70d..2ca23d57d3 100644 --- a/persistence-modules/spring-hibernate-5/src/test/resources/manytomany.cfg.xml +++ b/persistence-modules/spring-hibernate-5/src/test/resources/manytomany.cfg.xml @@ -10,7 +10,7 @@ sa org.hibernate.dialect.H2Dialect thread - true + false create-drop diff --git a/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAOIntegrationTest.java b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAOIntegrationTest.java index c29d5c4534..b382895143 100644 --- a/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAOIntegrationTest.java +++ b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAOIntegrationTest.java @@ -9,6 +9,8 @@ import com.baeldung.spring.jdbc.template.guide.config.SpringJdbcConfig; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; import org.springframework.test.context.ContextConfiguration; @@ -19,6 +21,8 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @ContextConfiguration(classes = { SpringJdbcConfig.class }, loader = AnnotationConfigContextLoader.class) public class EmployeeDAOIntegrationTest { + private static final Logger LOGGER = LoggerFactory.getLogger(EmployeeDAOIntegrationTest.class); + @Autowired private EmployeeDAO employeeDao; @@ -70,7 +74,7 @@ public class EmployeeDAOIntegrationTest { try { employeeDao.addEmplyee(7); } catch (final DuplicateKeyException e) { - System.out.println(e.getMessage()); + LOGGER.error(e.getMessage(), e); Assert.assertTrue(e.getMessage().contains("Custome Exception translator - Integrity contraint voilation.")); } } diff --git a/persistence-modules/spring-jdbc/src/test/resources/logback-test.xml b/persistence-modules/spring-jdbc/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/persistence-modules/spring-jdbc/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-jpa-2/src/main/resources/persistence-h2.properties b/persistence-modules/spring-jpa-2/src/main/resources/persistence-h2.properties index 716a96fde3..b429ce3a16 100644 --- a/persistence-modules/spring-jpa-2/src/main/resources/persistence-h2.properties +++ b/persistence-modules/spring-jpa-2/src/main/resources/persistence-h2.properties @@ -6,7 +6,7 @@ jdbc.pass= # hibernate.X hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=true +hibernate.show_sql=false hibernate.hbm2ddl.auto=create-drop hibernate.cache.use_second_level_cache=true hibernate.cache.use_query_cache=true diff --git a/persistence-modules/spring-jpa-2/src/test/resources/logback-test.xml b/persistence-modules/spring-jpa-2/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/persistence-modules/spring-jpa-2/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-jpa-2/src/test/resources/manytomany/test.properties b/persistence-modules/spring-jpa-2/src/test/resources/manytomany/test.properties index 9e4236a6c2..db92a1b8c1 100644 --- a/persistence-modules/spring-jpa-2/src/test/resources/manytomany/test.properties +++ b/persistence-modules/spring-jpa-2/src/test/resources/manytomany/test.properties @@ -2,5 +2,5 @@ jdbc.driverClassName=org.h2.Driver jdbc.url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1 hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=true +hibernate.show_sql=false hibernate.hbm2ddl.auto=validate diff --git a/persistence-modules/spring-jpa/src/main/resources/persistence-h2.properties b/persistence-modules/spring-jpa/src/main/resources/persistence-h2.properties index a3060cc796..72b51f02b7 100644 --- a/persistence-modules/spring-jpa/src/main/resources/persistence-h2.properties +++ b/persistence-modules/spring-jpa/src/main/resources/persistence-h2.properties @@ -6,5 +6,5 @@ jdbc.pass= # hibernate.X hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=true +hibernate.show_sql=false hibernate.hbm2ddl.auto=create-drop \ No newline at end of file diff --git a/persistence-modules/spring-jpa/src/main/resources/persistence-student-h2.properties b/persistence-modules/spring-jpa/src/main/resources/persistence-student-h2.properties index 405e6ff109..a5d2bec189 100644 --- a/persistence-modules/spring-jpa/src/main/resources/persistence-student-h2.properties +++ b/persistence-modules/spring-jpa/src/main/resources/persistence-student-h2.properties @@ -6,7 +6,7 @@ jdbc.pass= # hibernate.X hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=true +hibernate.show_sql=false hibernate.hbm2ddl.auto=create-drop hibernate.cache.use_second_level_cache=false hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/persistence-modules/spring-jpa/src/main/resources/persistence-student.properties b/persistence-modules/spring-jpa/src/main/resources/persistence-student.properties index d4c82420de..9a06518238 100644 --- a/persistence-modules/spring-jpa/src/main/resources/persistence-student.properties +++ b/persistence-modules/spring-jpa/src/main/resources/persistence-student.properties @@ -4,7 +4,7 @@ jdbc.user=tutorialuser jdbc.pass=tutorialpass hibernate.dialect=org.hibernate.dialect.MySQL5Dialect -hibernate.show_sql=true +hibernate.show_sql=false hibernate.hbm2ddl.auto=create-drop hibernate.cache.use_second_level_cache=false diff --git a/persistence-modules/spring-jpa/src/test/java/META-INF/persistence.xml b/persistence-modules/spring-jpa/src/test/java/META-INF/persistence.xml index 495f076fef..76a3b61399 100644 --- a/persistence-modules/spring-jpa/src/test/java/META-INF/persistence.xml +++ b/persistence-modules/spring-jpa/src/test/java/META-INF/persistence.xml @@ -11,7 +11,7 @@ - + diff --git a/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java index fbda459d65..66f20a6724 100644 --- a/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java @@ -20,6 +20,8 @@ import com.baeldung.persistence.model.Foo; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; @@ -31,6 +33,8 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @DirtiesContext public class FooPaginationPersistenceIntegrationTest { + private static final Logger LOGGER = LoggerFactory.getLogger(FooPaginationPersistenceIntegrationTest.class); + @PersistenceContext private EntityManager entityManager; @@ -137,7 +141,7 @@ public class FooPaginationPersistenceIntegrationTest { typedQuery = entityManager.createQuery(select); typedQuery.setFirstResult(pageNumber - 1); typedQuery.setMaxResults(pageSize); - System.out.println("Current page: " + typedQuery.getResultList()); + LOGGER.debug("Current page: {}", typedQuery.getResultList()); pageNumber += pageSize; } diff --git a/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooServiceSortingIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooServiceSortingIntegrationTest.java index c3db45ab41..8d1f94edf8 100644 --- a/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooServiceSortingIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooServiceSortingIntegrationTest.java @@ -15,6 +15,8 @@ import com.baeldung.persistence.model.Bar; import com.baeldung.persistence.model.Foo; import org.junit.Test; import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -26,6 +28,8 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @SuppressWarnings("unchecked") public class FooServiceSortingIntegrationTest { + private static final Logger LOGGER = LoggerFactory.getLogger(FooServiceSortingIntegrationTest.class); + @PersistenceContext private EntityManager entityManager; @@ -37,7 +41,7 @@ public class FooServiceSortingIntegrationTest { final Query sortQuery = entityManager.createQuery(jql); final List fooList = sortQuery.getResultList(); for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId()); + LOGGER.debug("Name:{}-------Id:{}", foo.getName(), foo.getId()); } } @@ -47,7 +51,7 @@ public class FooServiceSortingIntegrationTest { final Query sortQuery = entityManager.createQuery(jql); final List fooList = sortQuery.getResultList(); for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId()); + LOGGER.debug("Name:{}-------Id:{}", foo.getName(), foo.getId()); } } @@ -57,7 +61,7 @@ public class FooServiceSortingIntegrationTest { final Query sortQuery = entityManager.createQuery(jql); final List fooList = sortQuery.getResultList(); for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId()); + LOGGER.debug("Name:{}-------Id:{}", foo.getName(), foo.getId()); } } @@ -67,9 +71,9 @@ public class FooServiceSortingIntegrationTest { final Query barJoinQuery = entityManager.createQuery(jql); final List fooList = barJoinQuery.getResultList(); for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName()); + LOGGER.debug("Name:{}", foo.getName()); if (foo.getBar() != null) { - System.out.print("-------BarId:" + foo.getBar().getId()); + LOGGER.debug("-------BarId:{}", foo.getBar().getId()); } } } @@ -80,9 +84,9 @@ public class FooServiceSortingIntegrationTest { final Query barQuery = entityManager.createQuery(jql); final List barList = barQuery.getResultList(); for (final Bar bar : barList) { - System.out.println("Bar Id:" + bar.getId()); + LOGGER.debug("Bar Id:{}", bar.getId()); for (final Foo foo : bar.getFooList()) { - System.out.println("FooName:" + foo.getName()); + LOGGER.debug("FooName:{}", foo.getName()); } } } @@ -97,7 +101,7 @@ public class FooServiceSortingIntegrationTest { final TypedQuery typedQuery = entityManager.createQuery(select); final List fooList = typedQuery.getResultList(); for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName() + "--------Id:" + foo.getId()); + LOGGER.debug("Name:{}-------Id:{}", foo.getName(), foo.getId()); } } @@ -111,7 +115,7 @@ public class FooServiceSortingIntegrationTest { final TypedQuery typedQuery = entityManager.createQuery(select); final List fooList = typedQuery.getResultList(); for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId()); + LOGGER.debug("Name:{}-------Id:{}", foo.getName(), foo.getId()); } } diff --git a/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java index 103321fc64..b19259d9df 100644 --- a/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/com/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java @@ -13,6 +13,8 @@ import com.baeldung.config.PersistenceJPAConfig; import com.baeldung.persistence.model.Foo; import org.junit.Test; import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; @@ -24,6 +26,8 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @DirtiesContext public class FooServiceSortingWitNullsManualIntegrationTest { + private static final Logger LOGGER = LoggerFactory.getLogger(FooServiceSortingWitNullsManualIntegrationTest.class); + @PersistenceContext private EntityManager entityManager; @@ -43,7 +47,7 @@ public class FooServiceSortingWitNullsManualIntegrationTest { final List fooList = sortQuery.getResultList(); assertNull(fooList.get(fooList.toArray().length - 1).getName()); for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName()); + LOGGER.debug("Name:{}", foo.getName()); } } @@ -57,7 +61,7 @@ public class FooServiceSortingWitNullsManualIntegrationTest { final List fooList = sortQuery.getResultList(); assertNull(fooList.get(0).getName()); for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName()); + LOGGER.debug("Name:{}", foo.getName()); } } diff --git a/persistence-modules/spring-jpa/src/test/resources/persistence-student.properties b/persistence-modules/spring-jpa/src/test/resources/persistence-student.properties index 3b6b580630..9ca389d6ab 100644 --- a/persistence-modules/spring-jpa/src/test/resources/persistence-student.properties +++ b/persistence-modules/spring-jpa/src/test/resources/persistence-student.properties @@ -2,7 +2,7 @@ jdbc.driverClassName=org.h2.Driver jdbc.url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1 hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=true +hibernate.show_sql=false hibernate.hbm2ddl.auto=create hibernate.cache.use_second_level_cache=false diff --git a/persistence-modules/spring-persistence-simple/pom.xml b/persistence-modules/spring-persistence-simple/pom.xml index 437a439b99..ec7c8bd3a0 100644 --- a/persistence-modules/spring-persistence-simple/pom.xml +++ b/persistence-modules/spring-persistence-simple/pom.xml @@ -92,7 +92,6 @@ 2.2 1.3 2.2.7.RELEASE - 1.4.200 0.23.0 diff --git a/pom.xml b/pom.xml index 2d38b5e37a..ad002650d7 100644 --- a/pom.xml +++ b/pom.xml @@ -7,6 +7,9 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + + spring-5-webflux-2 + parent-modules pom @@ -615,6 +618,7 @@ spring-5-reactive-oauth spring-5-reactive-security spring-5-webflux + spring-5-webflux-2 spring-activiti spring-akka @@ -794,6 +798,9 @@ **/*IntegrationTest.java **/*IntTest.java + + ${tutorialsproject.basedir}/logback-config.xml + @@ -1051,6 +1058,9 @@ **/*IntegrationTest.java **/*IntTest.java + + ${tutorialsproject.basedir}/logback-config.xml + @@ -1316,9 +1326,11 @@ core-java-modules/core-java-string-operations-3 core-java-modules/core-java-string-operations-4 core-java-modules/core-java-time-measurements + core-java-modules/core-java-networking-3 core-java-modules/multimodulemavenproject persistence-modules/sirix quarkus-vs-springboot + quarkus-jandex spring-boot-modules/spring-boot-cassandre testing-modules/testing-assertions @@ -1368,6 +1380,7 @@ core-java-modules/core-java-os core-java-modules/core-java-string-operations-3 core-java-modules/core-java-time-measurements + core-java-modules/core-java-networking-3 core-java-modules/multimodulemavenproject core-java-modules/core-java-strings persistence-modules/sirix @@ -1420,6 +1433,7 @@ 1.33 1.33 2.21.0 + 4.4 2.11.0 2.6 3.12.0 @@ -1442,7 +1456,7 @@ 3.13.0 1.18.20 - 1.4.197 + 1.4.200 diff --git a/quarkus-jandex/README.md b/quarkus-jandex/README.md new file mode 100644 index 0000000000..cca5fa7714 --- /dev/null +++ b/quarkus-jandex/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Quarkus Bean Discovery With Jandex Indexing](https://www.baeldung.com/quarkus-bean-discovery-index) diff --git a/quarkus-jandex/hello-app/.dockerignore b/quarkus-jandex/hello-app/.dockerignore new file mode 100644 index 0000000000..94810d006e --- /dev/null +++ b/quarkus-jandex/hello-app/.dockerignore @@ -0,0 +1,5 @@ +* +!target/*-runner +!target/*-runner.jar +!target/lib/* +!target/quarkus-app/* \ No newline at end of file diff --git a/quarkus-jandex/hello-app/.gitignore b/quarkus-jandex/hello-app/.gitignore new file mode 100644 index 0000000000..bdf57ce3b4 --- /dev/null +++ b/quarkus-jandex/hello-app/.gitignore @@ -0,0 +1,39 @@ +#Maven +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +release.properties + +# Eclipse +.project +.classpath +.settings/ +bin/ + +# IntelliJ +.idea +*.ipr +*.iml +*.iws + +# NetBeans +nb-configuration.xml + +# Visual Studio Code +.vscode +.factorypath + +# OSX +.DS_Store + +# Vim +*.swp +*.swo + +# patch +*.orig +*.rej + +# Local environment +.env diff --git a/quarkus-jandex/hello-app/.mvn/wrapper/MavenWrapperDownloader.java b/quarkus-jandex/hello-app/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000000..c39041cdf6 --- /dev/null +++ b/quarkus-jandex/hello-app/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,114 @@ +/* + * Copyright 2007-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if (mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if (mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if (!outputFile.getParentFile().exists()) { + if (!outputFile.getParentFile().mkdirs()) { + System.out.println("- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/quarkus-jandex/hello-app/.mvn/wrapper/maven-wrapper.properties b/quarkus-jandex/hello-app/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000..ffdc10e59f --- /dev/null +++ b/quarkus-jandex/hello-app/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.1/apache-maven-3.8.1-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/quarkus-jandex/hello-app/README.md b/quarkus-jandex/hello-app/README.md new file mode 100644 index 0000000000..769709eb00 --- /dev/null +++ b/quarkus-jandex/hello-app/README.md @@ -0,0 +1,51 @@ +# Hello App with Quarkus + +## Running the application in dev mode + +You can run your application in dev mode that enables live coding using: + +```shell script +./mvnw compile quarkus:dev +``` + +You can then find the app using `http://localhost:8080`. + +> **_NOTE:_** Quarkus now ships with a Dev UI, which is available in dev mode only at http://localhost:8080/q/dev/. + +## Packaging and running the application + +The application can be packaged using: + +```shell script +./mvnw package +``` + +It produces the `quarkus-run.jar` file in the `target/quarkus-app/` directory. Be aware that it’s not an _über-jar_ as the dependencies are copied into the `target/quarkus-app/lib/` directory. + +The application is now runnable using `java -jar target/quarkus-app/quarkus-run.jar`. + +If you want to build an _über-jar_, execute the following command: + +```shell script +./mvnw package -Dquarkus.package.type=uber-jar +``` + +The application, packaged as an _über-jar_, is now runnable using `java -jar target/*-runner.jar`. + +## Creating a native executable + +You can create a native executable using: + +```shell script +./mvnw package -Pnative +``` + +Or, if you don't have GraalVM installed, you can run the native executable build in a container using: + +```shell script +./mvnw package -Pnative -Dquarkus.native.container-build=true +``` + +You can then execute your native executable with: `./target/quarkus-sample-1.0-SNAPSHOT-runner` + +If you want to learn more about building native executables, please consult https://quarkus.io/guides/maven-tooling.html. diff --git a/quarkus-jandex/hello-app/mvnw b/quarkus-jandex/hello-app/mvnw new file mode 100644 index 0000000000..a16b5431b4 --- /dev/null +++ b/quarkus-jandex/hello-app/mvnw @@ -0,0 +1,310 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/quarkus-jandex/hello-app/mvnw.cmd b/quarkus-jandex/hello-app/mvnw.cmd new file mode 100644 index 0000000000..c8d43372c9 --- /dev/null +++ b/quarkus-jandex/hello-app/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/quarkus-jandex/hello-app/pom.xml b/quarkus-jandex/hello-app/pom.xml new file mode 100644 index 0000000000..8da874a1c7 --- /dev/null +++ b/quarkus-jandex/hello-app/pom.xml @@ -0,0 +1,131 @@ + + + 4.0.0 + + + com.baeldung.quarkus + quarkus-jandex + 1.0.0-SNAPSHOT + + + hello-app + + + + io.quarkus + quarkus-resteasy + + + io.quarkus + quarkus-arc + + + io.quarkus + quarkus-junit5 + test + + + io.rest-assured + rest-assured + test + + + ${project.groupId} + hello-service + ${project.version} + + + ${project.groupId} + hello-sender-beans-xml + ${project.version} + + + ${project.groupId} + hello-sender-maven-plugin + ${project.version} + + + ${project.groupId} + hello-sender-application-properties + ${project.version} + + + ${project.groupId} + hello-sender-undetected + ${project.version} + + + + + + ${quarkus.platform.group-id} + quarkus-maven-plugin + ${quarkus.platform.version} + true + + + + build + generate-code + generate-code-tests + + + + + + maven-compiler-plugin + ${compiler-plugin.version} + + ${maven.compiler.parameters} + + + + maven-surefire-plugin + ${surefire-plugin.version} + + + org.jboss.logmanager.LogManager + ${maven.home} + + + + + + + + native + + + native + + + + + + maven-failsafe-plugin + ${surefire-plugin.version} + + + + integration-test + verify + + + + ${project.build.directory}/${project.build.finalName}-runner + org.jboss.logmanager.LogManager + ${maven.home} + + + + + + + + + native + + + + diff --git a/quarkus-jandex/hello-app/src/main/docker/Dockerfile.jvm b/quarkus-jandex/hello-app/src/main/docker/Dockerfile.jvm new file mode 100644 index 0000000000..3eb1b4de84 --- /dev/null +++ b/quarkus-jandex/hello-app/src/main/docker/Dockerfile.jvm @@ -0,0 +1,55 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode +# +# Before building the container image run: +# +# ./mvnw package +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.jvm -t quarkus/quarkus-sample-jvm . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/quarkus-sample-jvm +# +# If you want to include the debug port into your docker image +# you will have to expose the debug port (default 5005) like this : EXPOSE 8080 5005 +# +# Then run the container using : +# +# docker run -i --rm -p 8080:8080 -p 5005:5005 -e JAVA_ENABLE_DEBUG="true" quarkus/quarkus-sample-jvm +# +### +FROM registry.access.redhat.com/ubi8/ubi-minimal:8.4 + +ARG JAVA_PACKAGE=java-11-openjdk-headless +ARG RUN_JAVA_VERSION=1.3.8 +ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en' +# Install java and the run-java script +# Also set up permissions for user `1001` +RUN microdnf install curl ca-certificates ${JAVA_PACKAGE} \ + && microdnf update \ + && microdnf clean all \ + && mkdir /deployments \ + && chown 1001 /deployments \ + && chmod "g+rwX" /deployments \ + && chown 1001:root /deployments \ + && curl https://repo1.maven.org/maven2/io/fabric8/run-java-sh/${RUN_JAVA_VERSION}/run-java-sh-${RUN_JAVA_VERSION}-sh.sh -o /deployments/run-java.sh \ + && chown 1001 /deployments/run-java.sh \ + && chmod 540 /deployments/run-java.sh \ + && echo "securerandom.source=file:/dev/urandom" >> /etc/alternatives/jre/conf/security/java.security + +# Configure the JAVA_OPTIONS, you can add -XshowSettings:vm to also display the heap size. +ENV JAVA_OPTIONS="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager" +# We make four distinct layers so if there are application changes the library layers can be re-used +COPY --chown=1001 target/quarkus-app/lib/ /deployments/lib/ +COPY --chown=1001 target/quarkus-app/*.jar /deployments/ +COPY --chown=1001 target/quarkus-app/app/ /deployments/app/ +COPY --chown=1001 target/quarkus-app/quarkus/ /deployments/quarkus/ + +EXPOSE 8080 +USER 1001 + +ENTRYPOINT [ "/deployments/run-java.sh" ] + diff --git a/quarkus-jandex/hello-app/src/main/docker/Dockerfile.legacy-jar b/quarkus-jandex/hello-app/src/main/docker/Dockerfile.legacy-jar new file mode 100644 index 0000000000..f32188a45d --- /dev/null +++ b/quarkus-jandex/hello-app/src/main/docker/Dockerfile.legacy-jar @@ -0,0 +1,51 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode +# +# Before building the container image run: +# +# ./mvnw package -Dquarkus.package.type=legacy-jar +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.legacy-jar -t quarkus/quarkus-sample-legacy-jar . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/quarkus-sample-legacy-jar +# +# If you want to include the debug port into your docker image +# you will have to expose the debug port (default 5005) like this : EXPOSE 8080 5005 +# +# Then run the container using : +# +# docker run -i --rm -p 8080:8080 -p 5005:5005 -e JAVA_ENABLE_DEBUG="true" quarkus/quarkus-sample-legacy-jar +# +### +FROM registry.access.redhat.com/ubi8/ubi-minimal:8.4 + +ARG JAVA_PACKAGE=java-11-openjdk-headless +ARG RUN_JAVA_VERSION=1.3.8 +ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en' +# Install java and the run-java script +# Also set up permissions for user `1001` +RUN microdnf install curl ca-certificates ${JAVA_PACKAGE} \ + && microdnf update \ + && microdnf clean all \ + && mkdir /deployments \ + && chown 1001 /deployments \ + && chmod "g+rwX" /deployments \ + && chown 1001:root /deployments \ + && curl https://repo1.maven.org/maven2/io/fabric8/run-java-sh/${RUN_JAVA_VERSION}/run-java-sh-${RUN_JAVA_VERSION}-sh.sh -o /deployments/run-java.sh \ + && chown 1001 /deployments/run-java.sh \ + && chmod 540 /deployments/run-java.sh \ + && echo "securerandom.source=file:/dev/urandom" >> /etc/alternatives/jre/conf/security/java.security + +# Configure the JAVA_OPTIONS, you can add -XshowSettings:vm to also display the heap size. +ENV JAVA_OPTIONS="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager" +COPY target/lib/* /deployments/lib/ +COPY target/*-runner.jar /deployments/app.jar + +EXPOSE 8080 +USER 1001 + +ENTRYPOINT [ "/deployments/run-java.sh" ] diff --git a/quarkus-jandex/hello-app/src/main/docker/Dockerfile.native b/quarkus-jandex/hello-app/src/main/docker/Dockerfile.native new file mode 100644 index 0000000000..4fa16507fe --- /dev/null +++ b/quarkus-jandex/hello-app/src/main/docker/Dockerfile.native @@ -0,0 +1,27 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode +# +# Before building the container image run: +# +# ./mvnw package -Pnative +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.native -t quarkus/quarkus-sample . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/quarkus-sample +# +### +FROM registry.access.redhat.com/ubi8/ubi-minimal:8.4 +WORKDIR /work/ +RUN chown 1001 /work \ + && chmod "g+rwX" /work \ + && chown 1001:root /work +COPY --chown=1001:root target/*-runner /work/application + +EXPOSE 8080 +USER 1001 + +CMD ["./application", "-Dquarkus.http.host=0.0.0.0"] diff --git a/quarkus-jandex/hello-app/src/main/docker/Dockerfile.native-distroless b/quarkus-jandex/hello-app/src/main/docker/Dockerfile.native-distroless new file mode 100644 index 0000000000..86370b0a0b --- /dev/null +++ b/quarkus-jandex/hello-app/src/main/docker/Dockerfile.native-distroless @@ -0,0 +1,23 @@ +#### +# This Dockerfile is used in order to build a distroless container that runs the Quarkus application in native (no JVM) mode +# +# Before building the container image run: +# +# ./mvnw package -Pnative +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.native-distroless -t quarkus/quarkus-sample . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/quarkus-sample +# +### +FROM quay.io/quarkus/quarkus-distroless-image:1.0 +COPY target/*-runner /application + +EXPOSE 8080 +USER nonroot + +CMD ["./application", "-Dquarkus.http.host=0.0.0.0"] diff --git a/quarkus-jandex/hello-app/src/main/java/com/baeldung/quarkus/hello/HelloResource.java b/quarkus-jandex/hello-app/src/main/java/com/baeldung/quarkus/hello/HelloResource.java new file mode 100644 index 0000000000..1867527327 --- /dev/null +++ b/quarkus-jandex/hello-app/src/main/java/com/baeldung/quarkus/hello/HelloResource.java @@ -0,0 +1,26 @@ +package com.baeldung.quarkus.hello; + +import com.baeldung.quarkus.hello.service.HelloService; + +import javax.inject.Inject; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +@Path("/hello") +public class HelloResource { + + @Inject + HelloService service; + + @GET + @Produces(MediaType.TEXT_PLAIN) + public String hello() { + StringBuilder sb = new StringBuilder(); + sb.append("Those are saying hello:\n=======================\n\n"); + service.sendHello(s -> sb.append(" - ").append(s).append("\n")); + return sb.toString(); + } + +} diff --git a/quarkus-jandex/hello-app/src/main/resources/META-INF/resources/index.html b/quarkus-jandex/hello-app/src/main/resources/META-INF/resources/index.html new file mode 100644 index 0000000000..ba625a1420 --- /dev/null +++ b/quarkus-jandex/hello-app/src/main/resources/META-INF/resources/index.html @@ -0,0 +1,14 @@ + + + + + qHello App + + + +

Hello App

+ +This app demonstrates how Quarkus resolves CDI managed beans. You can find the output of all resolved beans by invoking the Hello Resource. + + + diff --git a/quarkus-jandex/hello-app/src/main/resources/application.properties b/quarkus-jandex/hello-app/src/main/resources/application.properties new file mode 100644 index 0000000000..95ff9889c7 --- /dev/null +++ b/quarkus-jandex/hello-app/src/main/resources/application.properties @@ -0,0 +1,2 @@ +quarkus.index-dependency.hello-sender.group-id=com.baeldung.quarkus +quarkus.index-dependency.hello-sender.artifact-id=hello-sender-application-properties diff --git a/quarkus-jandex/hello-sender-application-properties/pom.xml b/quarkus-jandex/hello-sender-application-properties/pom.xml new file mode 100644 index 0000000000..01784b44f4 --- /dev/null +++ b/quarkus-jandex/hello-sender-application-properties/pom.xml @@ -0,0 +1,26 @@ + + + + com.baeldung.quarkus + quarkus-jandex + 1.0.0-SNAPSHOT + + 4.0.0 + + hello-sender-application-properties + + + + io.quarkus + quarkus-arc + + + ${project.groupId} + hello-service + ${project.version} + + + + diff --git a/quarkus-jandex/hello-sender-application-properties/src/main/java/com/baeldung/quarkus/hello/sender/applicationproperties/ApplicationPropertiesHelloSender.java b/quarkus-jandex/hello-sender-application-properties/src/main/java/com/baeldung/quarkus/hello/sender/applicationproperties/ApplicationPropertiesHelloSender.java new file mode 100644 index 0000000000..ffd495e92e --- /dev/null +++ b/quarkus-jandex/hello-sender-application-properties/src/main/java/com/baeldung/quarkus/hello/sender/applicationproperties/ApplicationPropertiesHelloSender.java @@ -0,0 +1,15 @@ +package com.baeldung.quarkus.hello.sender.applicationproperties; + +import com.baeldung.quarkus.hello.service.HelloRetrieving; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.event.Observes; + +@ApplicationScoped +public class ApplicationPropertiesHelloSender { + + public void sendHello(@Observes HelloRetrieving event) { + event.getHelloReceiver().accept("Hi, I was detected by inserting this module's groupId and artifactId into the app's application.properties file."); + } + +} diff --git a/quarkus-jandex/hello-sender-beans-xml/pom.xml b/quarkus-jandex/hello-sender-beans-xml/pom.xml new file mode 100644 index 0000000000..30cabcc91d --- /dev/null +++ b/quarkus-jandex/hello-sender-beans-xml/pom.xml @@ -0,0 +1,26 @@ + + + + com.baeldung.quarkus + quarkus-jandex + 1.0.0-SNAPSHOT + + 4.0.0 + + hello-sender-beans-xml + + + + io.quarkus + quarkus-arc + + + ${project.groupId} + hello-service + ${project.version} + + + + diff --git a/quarkus-jandex/hello-sender-beans-xml/src/main/java/com/baeldung/quarkus/hello/sender/beansxml/BeansXmlHelloSender.java b/quarkus-jandex/hello-sender-beans-xml/src/main/java/com/baeldung/quarkus/hello/sender/beansxml/BeansXmlHelloSender.java new file mode 100644 index 0000000000..bed6a7793d --- /dev/null +++ b/quarkus-jandex/hello-sender-beans-xml/src/main/java/com/baeldung/quarkus/hello/sender/beansxml/BeansXmlHelloSender.java @@ -0,0 +1,15 @@ +package com.baeldung.quarkus.hello.sender.beansxml; + +import com.baeldung.quarkus.hello.service.HelloRetrieving; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.event.Observes; + +@ApplicationScoped +public class BeansXmlHelloSender { + + public void sendHello(@Observes HelloRetrieving event) { + event.getHelloReceiver().accept("Hi, I was detected using an empty META-INF/beans.xml file."); + } + +} diff --git a/quarkus-jandex/hello-sender-beans-xml/src/main/resources/META-INF/beans.xml b/quarkus-jandex/hello-sender-beans-xml/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000000..e69de29bb2 diff --git a/quarkus-jandex/hello-sender-maven-plugin/pom.xml b/quarkus-jandex/hello-sender-maven-plugin/pom.xml new file mode 100644 index 0000000000..ad226f38dd --- /dev/null +++ b/quarkus-jandex/hello-sender-maven-plugin/pom.xml @@ -0,0 +1,46 @@ + + + + com.baeldung.quarkus + quarkus-jandex + 1.0.0-SNAPSHOT + + 4.0.0 + + hello-sender-maven-plugin + + + + io.quarkus + quarkus-arc + + + ${project.groupId} + hello-service + ${project.version} + + + + + + + + org.jboss.jandex + jandex-maven-plugin + 1.2.1 + + + make-index + + + jandex + + + + + + + + diff --git a/quarkus-jandex/hello-sender-maven-plugin/src/main/java/com/baeldung/quarkus/hello/sender/mavenplugin/MavenPluginHelloSender.java b/quarkus-jandex/hello-sender-maven-plugin/src/main/java/com/baeldung/quarkus/hello/sender/mavenplugin/MavenPluginHelloSender.java new file mode 100644 index 0000000000..ca08eef5ac --- /dev/null +++ b/quarkus-jandex/hello-sender-maven-plugin/src/main/java/com/baeldung/quarkus/hello/sender/mavenplugin/MavenPluginHelloSender.java @@ -0,0 +1,15 @@ +package com.baeldung.quarkus.hello.sender.mavenplugin; + +import com.baeldung.quarkus.hello.service.HelloRetrieving; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.event.Observes; + +@ApplicationScoped +public class MavenPluginHelloSender { + + public void sendHello(@Observes HelloRetrieving event) { + event.getHelloReceiver().accept("Hi, I was detected using the Jandex Maven Plugin."); + } + +} diff --git a/quarkus-jandex/hello-sender-undetected/pom.xml b/quarkus-jandex/hello-sender-undetected/pom.xml new file mode 100644 index 0000000000..0d8cb29a98 --- /dev/null +++ b/quarkus-jandex/hello-sender-undetected/pom.xml @@ -0,0 +1,26 @@ + + + + com.baeldung.quarkus + quarkus-jandex + 1.0.0-SNAPSHOT + + 4.0.0 + + hello-sender-undetected + + + + io.quarkus + quarkus-arc + + + ${project.groupId} + hello-service + ${project.version} + + + + diff --git a/quarkus-jandex/hello-sender-undetected/src/main/java/com/baeldung/quarkus/hello/sender/undetected/UndetectedHelloSender.java b/quarkus-jandex/hello-sender-undetected/src/main/java/com/baeldung/quarkus/hello/sender/undetected/UndetectedHelloSender.java new file mode 100644 index 0000000000..a39e610b2a --- /dev/null +++ b/quarkus-jandex/hello-sender-undetected/src/main/java/com/baeldung/quarkus/hello/sender/undetected/UndetectedHelloSender.java @@ -0,0 +1,15 @@ +package com.baeldung.quarkus.hello.sender.undetected; + +import com.baeldung.quarkus.hello.service.HelloRetrieving; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.event.Observes; + +@ApplicationScoped +public class UndetectedHelloSender { + + public void sendHello(@Observes HelloRetrieving event) { + event.getHelloReceiver().accept("Hi, I do not create a Jandex index, so I should not get detected."); + } + +} diff --git a/quarkus-jandex/hello-service/pom.xml b/quarkus-jandex/hello-service/pom.xml new file mode 100644 index 0000000000..274423c526 --- /dev/null +++ b/quarkus-jandex/hello-service/pom.xml @@ -0,0 +1,21 @@ + + + + com.baeldung.quarkus + quarkus-jandex + 1.0.0-SNAPSHOT + + 4.0.0 + + hello-service + + + + io.quarkus + quarkus-arc + + + + diff --git a/quarkus-jandex/hello-service/src/main/java/com/baeldung/quarkus/hello/service/HelloRetrieving.java b/quarkus-jandex/hello-service/src/main/java/com/baeldung/quarkus/hello/service/HelloRetrieving.java new file mode 100644 index 0000000000..513e2ff245 --- /dev/null +++ b/quarkus-jandex/hello-service/src/main/java/com/baeldung/quarkus/hello/service/HelloRetrieving.java @@ -0,0 +1,17 @@ +package com.baeldung.quarkus.hello.service; + +import java.util.function.Consumer; + +public class HelloRetrieving { + + private final Consumer helloReceiver; + + public HelloRetrieving(Consumer helloReceiver) { + this.helloReceiver = helloReceiver; + } + + public Consumer getHelloReceiver() { + return helloReceiver; + } + +} diff --git a/quarkus-jandex/hello-service/src/main/java/com/baeldung/quarkus/hello/service/HelloService.java b/quarkus-jandex/hello-service/src/main/java/com/baeldung/quarkus/hello/service/HelloService.java new file mode 100644 index 0000000000..4b93d2f12f --- /dev/null +++ b/quarkus-jandex/hello-service/src/main/java/com/baeldung/quarkus/hello/service/HelloService.java @@ -0,0 +1,18 @@ +package com.baeldung.quarkus.hello.service; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.event.Event; +import javax.inject.Inject; +import java.util.function.Consumer; + +@ApplicationScoped +public class HelloService { + + @Inject + Event helloRetrievingEvent; + + public void sendHello(Consumer target) { + helloRetrievingEvent.fire(new HelloRetrieving(target)); + } + +} diff --git a/quarkus-jandex/hello-service/src/main/resources/META-INF/beans.xml b/quarkus-jandex/hello-service/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000000..e69de29bb2 diff --git a/quarkus-jandex/pom.xml b/quarkus-jandex/pom.xml new file mode 100644 index 0000000000..eb7f308599 --- /dev/null +++ b/quarkus-jandex/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + com.baeldung.quarkus + quarkus-jandex + 1.0.0-SNAPSHOT + pom + + + hello-service + hello-sender-beans-xml + hello-sender-maven-plugin + hello-sender-application-properties + hello-sender-undetected + hello-app + + + + + + ${quarkus.platform.group-id} + ${quarkus.platform.artifact-id} + ${quarkus.platform.version} + pom + import + + + + + + 3.8.1 + true + 11 + 11 + UTF-8 + UTF-8 + quarkus-bom + io.quarkus.platform + 2.4.2.Final + 3.0.0-M5 + + + diff --git a/spf4j/spf4j-aspects-app/pom.xml b/spf4j/spf4j-aspects-app/pom.xml index c4940b9c97..09ca41ea47 100644 --- a/spf4j/spf4j-aspects-app/pom.xml +++ b/spf4j/spf4j-aspects-app/pom.xml @@ -9,10 +9,9 @@ jar - com.baeldung - parent-modules + com.baeldung.spf4j + spf4j 1.0.0-SNAPSHOT - ../../ diff --git a/spf4j/spf4j-core-app/pom.xml b/spf4j/spf4j-core-app/pom.xml index 28c104afe1..2f7f3745f1 100644 --- a/spf4j/spf4j-core-app/pom.xml +++ b/spf4j/spf4j-core-app/pom.xml @@ -9,10 +9,9 @@ jar - com.baeldung - parent-modules + com.baeldung.spf4j + spf4j 1.0.0-SNAPSHOT - ../../ diff --git a/spring-5-data-reactive/pom.xml b/spring-5-data-reactive/pom.xml index 3a9651de39..c145992737 100644 --- a/spring-5-data-reactive/pom.xml +++ b/spring-5-data-reactive/pom.xml @@ -72,7 +72,6 @@ com.h2database h2 - ${h2.version} org.apache.httpcomponents @@ -135,7 +134,6 @@ 1.0.0.RELEASE 0.8.1.RELEASE 4.5.2 - 1.4.200 1.5.23 3.3.1.RELEASE diff --git a/spring-5-reactive-2/pom.xml b/spring-5-reactive-2/pom.xml index 0758365932..e48d42a863 100644 --- a/spring-5-reactive-2/pom.xml +++ b/spring-5-reactive-2/pom.xml @@ -75,9 +75,45 @@ + + + integration-lite-first + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + ${project.basedir}/src/test/resources/logback-test.xml + + + + + + + + integration-lite-second + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + ${project.basedir}/src/test/resources/logback-test.xml + + + + + + + + 1.0.1.RELEASE 2.24.0 - \ No newline at end of file diff --git a/spring-5-reactive-client/pom.xml b/spring-5-reactive-client/pom.xml index 136f31b49e..f665d5c9a6 100644 --- a/spring-5-reactive-client/pom.xml +++ b/spring-5-reactive-client/pom.xml @@ -148,14 +148,49 @@ + + + integration-lite-first + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + ${project.basedir}/src/test/resources/logback-test.xml + + + + + + + + integration-lite-second + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + ${project.basedir}/src/test/resources/logback-test.xml + + + + + + + + 1.0.1.RELEASE 1.1.3 1.0 1.0 - 4.1 1.1.6 4.0.1 - \ No newline at end of file diff --git a/spring-5-reactive-security/pom.xml b/spring-5-reactive-security/pom.xml index 267a683fa7..140c6b8296 100644 --- a/spring-5-reactive-security/pom.xml +++ b/spring-5-reactive-security/pom.xml @@ -123,7 +123,6 @@ 1.1.3 1.0 1.0 - 4.1 3.1.6.RELEASE
diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml index 408573198b..b9456c7181 100644 --- a/spring-5-reactive/pom.xml +++ b/spring-5-reactive/pom.xml @@ -153,7 +153,6 @@ 1.1.3 1.0 1.0 - 4.1
\ No newline at end of file diff --git a/spring-5-webflux-2/README.md b/spring-5-webflux-2/README.md new file mode 100644 index 0000000000..0222ddbaa4 --- /dev/null +++ b/spring-5-webflux-2/README.md @@ -0,0 +1,7 @@ +## Spring 5 WebFlux 2 + +This module contains articles about Spring 5 WebFlux + +## Relevant articles: + +- [Spring Webflux and @Cacheable Annotation](https://www.baeldung.com/spring-webflux-cacheable) \ No newline at end of file diff --git a/spring-5-webflux-2/pom.xml b/spring-5-webflux-2/pom.xml new file mode 100644 index 0000000000..c90fcbe3d9 --- /dev/null +++ b/spring-5-webflux-2/pom.xml @@ -0,0 +1,102 @@ + + + 4.0.0 + spring-5-webflux-2 + spring-5-webflux-2 + http://www.baeldung.com + 1.0-SNAPSHOT + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + + + org.junit + junit-bom + ${junit-jupiter.version} + pom + import + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.jupiter + junit-jupiter + + + org.junit.jupiter + junit-jupiter-api + + + org.junit.platform + junit-plaform-commons + + + + + io.projectreactor.addons + reactor-extra + 3.4.5 + + + com.github.ben-manes.caffeine + caffeine + 2.9.2 + + + org.springframework.boot + spring-boot-starter-data-mongodb-reactive + + + io.projectreactor + reactor-test + test + + + org.testcontainers + mongodb + 1.16.2 + test + + + com.squareup.okhttp3 + mockwebserver + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/Item.java b/spring-5-webflux-2/src/main/java/caching/Item.java similarity index 96% rename from spring-5-webflux/src/main/java/com/baeldung/spring/caching/Item.java rename to spring-5-webflux-2/src/main/java/caching/Item.java index 7b79ff7503..627eeef740 100644 --- a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/Item.java +++ b/spring-5-webflux-2/src/main/java/caching/Item.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.caching; +package caching; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemRepository.java b/spring-5-webflux-2/src/main/java/caching/ItemRepository.java similarity index 85% rename from spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemRepository.java rename to spring-5-webflux-2/src/main/java/caching/ItemRepository.java index 27c97de36a..d69edaf5df 100644 --- a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemRepository.java +++ b/spring-5-webflux-2/src/main/java/caching/ItemRepository.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.caching; +package caching; import org.springframework.data.mongodb.repository.ReactiveMongoRepository; import org.springframework.stereotype.Repository; diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemService.java b/spring-5-webflux-2/src/main/java/caching/ItemService.java similarity index 96% rename from spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemService.java rename to spring-5-webflux-2/src/main/java/caching/ItemService.java index b24b54521e..85d7005831 100644 --- a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/ItemService.java +++ b/spring-5-webflux-2/src/main/java/caching/ItemService.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.caching; +package caching; import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.LoadingCache; diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/SpringWebfluxCachingApplication.java b/spring-5-webflux-2/src/main/java/caching/SpringWebfluxCachingApplication.java similarity index 93% rename from spring-5-webflux/src/main/java/com/baeldung/spring/caching/SpringWebfluxCachingApplication.java rename to spring-5-webflux-2/src/main/java/caching/SpringWebfluxCachingApplication.java index 5266e33775..df648fe6a3 100644 --- a/spring-5-webflux/src/main/java/com/baeldung/spring/caching/SpringWebfluxCachingApplication.java +++ b/spring-5-webflux-2/src/main/java/caching/SpringWebfluxCachingApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.caching; +package caching; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-5-webflux/src/main/resources/application-cache.properties b/spring-5-webflux-2/src/main/resources/application-cache.properties similarity index 100% rename from spring-5-webflux/src/main/resources/application-cache.properties rename to spring-5-webflux-2/src/main/resources/application-cache.properties diff --git a/spring-5-webflux-2/src/main/resources/logback.xml b/spring-5-webflux-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..48b68c6bf1 --- /dev/null +++ b/spring-5-webflux-2/src/main/resources/logback.xml @@ -0,0 +1,31 @@ + + + + + + %black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C{1.}): %msg%n%throwable + + + + + + netty-access.log + + %msg%n + + + + + + + + + + + + + + + + diff --git a/spring-5-webflux/src/test/java/com/baeldung/spring/caching/MonoFluxResultCachingLiveTest.java b/spring-5-webflux-2/src/test/java/caching/MonoFluxResultCachingLiveTest.java similarity index 98% rename from spring-5-webflux/src/test/java/com/baeldung/spring/caching/MonoFluxResultCachingLiveTest.java rename to spring-5-webflux-2/src/test/java/caching/MonoFluxResultCachingLiveTest.java index 322b3c5aa5..daf8367209 100644 --- a/spring-5-webflux/src/test/java/com/baeldung/spring/caching/MonoFluxResultCachingLiveTest.java +++ b/spring-5-webflux-2/src/test/java/caching/MonoFluxResultCachingLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.caching; +package caching; import org.junit.jupiter.api.Test; diff --git a/spring-5-webflux-2/src/test/resources/logback-test.xml b/spring-5-webflux-2/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..12cedf5952 --- /dev/null +++ b/spring-5-webflux-2/src/test/resources/logback-test.xml @@ -0,0 +1,13 @@ + + + + + + %black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C{1.}): %msg%n%throwable + + + + + + + diff --git a/spring-5-webflux/README.md b/spring-5-webflux/README.md index 889f211fc6..bd667468fb 100644 --- a/spring-5-webflux/README.md +++ b/spring-5-webflux/README.md @@ -11,4 +11,3 @@ This module contains articles about Spring 5 WebFlux - [Spring MVC Async vs Spring WebFlux](https://www.baeldung.com/spring-mvc-async-vs-webflux) - [Set a Timeout in Spring 5 Webflux WebClient](https://www.baeldung.com/spring-webflux-timeout) - [Guide to Retry in Spring WebFlux](https://www.baeldung.com/spring-webflux-retry) -- [Spring Webflux and @Cacheable Annotation](https://www.baeldung.com/spring-webflux-cacheable) diff --git a/spring-5-webflux/pom.xml b/spring-5-webflux/pom.xml index d6afb686fc..69de83c227 100644 --- a/spring-5-webflux/pom.xml +++ b/spring-5-webflux/pom.xml @@ -66,31 +66,11 @@ - - io.projectreactor.addons - reactor-extra - 3.4.5 - - - com.github.ben-manes.caffeine - caffeine - 2.9.2 - - - org.springframework.boot - spring-boot-starter-data-mongodb-reactive - io.projectreactor reactor-test test - - org.testcontainers - mongodb - 1.16.2 - test - com.squareup.okhttp3 mockwebserver diff --git a/spring-5/pom.xml b/spring-5/pom.xml index 5799f3bc8f..1ac696e7bd 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -142,7 +142,6 @@ 1.0 1.5.6 - 4.1 ${project.build.directory}/generated-snippets 4.0.3 diff --git a/spring-batch-2/README.md b/spring-batch-2/README.md index 08bf1933db..9b5d59f0b9 100644 --- a/spring-batch-2/README.md +++ b/spring-batch-2/README.md @@ -1,3 +1,5 @@ ### Relevant Articles: - [Spring Boot With Spring Batch](https://www.baeldung.com/spring-boot-spring-batch) +- [How to Trigger and Stop a Scheduled Spring Batch Job](https://www.baeldung.com/spring-batch-start-stop-job) +- More articles [[<-- prev]](/spring-batch) diff --git a/spring-batch-2/pom.xml b/spring-batch-2/pom.xml index c429c272bd..12d31aca14 100644 --- a/spring-batch-2/pom.xml +++ b/spring-batch-2/pom.xml @@ -22,10 +22,8 @@ spring-boot-starter-batch - org.hsqldb - hsqldb - ${hsqldb.version} - runtime + com.h2database + h2 org.springframework.boot @@ -44,11 +42,17 @@ ${spring.batch.version} test + + org.awaitility + awaitility + ${awaitility.version} + test + 4.3.0 - 2.5.1 + 3.1.1 \ No newline at end of file diff --git a/spring-batch/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java b/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java similarity index 69% rename from spring-batch/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java rename to spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java index cff4e96c89..c830a41855 100644 --- a/spring-batch/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java +++ b/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java @@ -11,26 +11,20 @@ import org.springframework.batch.core.configuration.annotation.EnableBatchProces import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.core.launch.JobLauncher; -import org.springframework.batch.core.launch.support.SimpleJobLauncher; -import org.springframework.batch.core.repository.JobRepository; -import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.item.file.FlatFileItemReader; import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder; import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper; -import org.springframework.batch.support.transaction.ResourcelessTransactionManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; -import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.scheduling.support.ScheduledMethodRunnable; -import javax.sql.DataSource; import java.util.Date; import java.util.IdentityHashMap; import java.util.List; @@ -58,13 +52,16 @@ public class SpringBatchScheduler { @Autowired private StepBuilderFactory stepBuilderFactory; + @Autowired + private JobLauncher jobLauncher; + @Scheduled(fixedRate = 2000) public void launchJob() throws Exception { Date date = new Date(); logger.debug("scheduler starts at " + date); if (enabled.get()) { - JobExecution jobExecution = jobLauncher().run(job(), new JobParametersBuilder().addDate("launchDate", date) - .toJobParameters()); + JobExecution jobExecution = jobLauncher.run(job(), new JobParametersBuilder().addDate("launchDate", date) + .toJobParameters()); batchRunCounter.incrementAndGet(); logger.debug("Batch job ends with status as " + jobExecution.getStatus()); } @@ -110,56 +107,33 @@ public class SpringBatchScheduler { @Bean public Job job() { - return jobBuilderFactory.get("job") - .start(readBooks()) - .build(); - } - - @Bean - public JobLauncher jobLauncher() throws Exception { - SimpleJobLauncher jobLauncher = new SimpleJobLauncher(); - jobLauncher.setJobRepository(jobRepository()); - jobLauncher.afterPropertiesSet(); - return jobLauncher; - } - - @Bean - public JobRepository jobRepository() throws Exception { - JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); - factory.setDataSource(dataSource()); - factory.setTransactionManager(new ResourcelessTransactionManager()); - return factory.getObject(); - } - - @Bean - public DataSource dataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("org.sqlite.JDBC"); - dataSource.setUrl("jdbc:sqlite:repository.sqlite"); - return dataSource; + return jobBuilderFactory + .get("job") + .start(readBooks()) + .build(); } @Bean protected Step readBooks() { return stepBuilderFactory.get("readBooks") - . chunk(2) - .reader(reader()) - .writer(writer()) - .build(); + . chunk(2) + .reader(reader()) + .writer(writer()) + .build(); } @Bean public FlatFileItemReader reader() { return new FlatFileItemReaderBuilder().name("bookItemReader") - .resource(new ClassPathResource("books.csv")) - .delimited() - .names(new String[] { "id", "name" }) - .fieldSetMapper(new BeanWrapperFieldSetMapper() { - { - setTargetType(Book.class); - } - }) - .build(); + .resource(new ClassPathResource("books.csv")) + .delimited() + .names(new String[] { "id", "name" }) + .fieldSetMapper(new BeanWrapperFieldSetMapper() { + { + setTargetType(Book.class); + } + }) + .build(); } @Bean diff --git a/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchSchedulerApplication.java b/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchSchedulerApplication.java new file mode 100644 index 0000000000..349a359efb --- /dev/null +++ b/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchSchedulerApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.batchscheduler; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBatchSchedulerApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBatchSchedulerApplication.class, args); + } + +} diff --git a/spring-batch/src/main/java/com/baeldung/batchscheduler/model/Book.java b/spring-batch-2/src/main/java/com/baeldung/batchscheduler/model/Book.java similarity index 98% rename from spring-batch/src/main/java/com/baeldung/batchscheduler/model/Book.java rename to spring-batch-2/src/main/java/com/baeldung/batchscheduler/model/Book.java index 8ee986c729..7deedeb63e 100644 --- a/spring-batch/src/main/java/com/baeldung/batchscheduler/model/Book.java +++ b/spring-batch-2/src/main/java/com/baeldung/batchscheduler/model/Book.java @@ -3,7 +3,7 @@ package com.baeldung.batchscheduler.model; public class Book { private int id; private String name; - + public Book() {} public Book(int id, String name) { @@ -27,7 +27,7 @@ public class Book { public void setName(String name) { this.name = name; } - + public String toString() { return "Book [id=" + id + ", name=" + name + "]"; } diff --git a/spring-batch/src/main/resources/books.csv b/spring-batch-2/src/main/resources/books.csv similarity index 100% rename from spring-batch/src/main/resources/books.csv rename to spring-batch-2/src/main/resources/books.csv diff --git a/spring-batch/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java b/spring-batch-2/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java similarity index 76% rename from spring-batch/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java rename to spring-batch-2/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java index 81877fbc39..61e5a1dd74 100644 --- a/spring-batch/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java +++ b/spring-batch-2/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java @@ -4,32 +4,40 @@ import com.baeldung.batchscheduler.SpringBatchScheduler; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.batch.test.context.SpringBatchTest; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.PropertySource; import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; import static org.awaitility.Awaitility.await; import static java.util.concurrent.TimeUnit.*; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = SpringBatchScheduler.class) +@SpringBatchTest +@SpringBootTest +@DirtiesContext +@PropertySource("classpath:application.properties") +@RunWith(SpringRunner.class) public class SpringBatchSchedulerIntegrationTest { @Autowired private ApplicationContext context; @Test - public void stopJobsWhenSchedulerDisabled() throws Exception { + public void stopJobsWhenSchedulerDisabled() { SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class); await().untilAsserted(() -> Assert.assertEquals(2, schedulerBean.getBatchRunCounter() - .get())); + .get())); schedulerBean.stop(); await().atLeast(3, SECONDS); Assert.assertEquals(2, schedulerBean.getBatchRunCounter() - .get()); + .get()); } @Test @@ -37,24 +45,24 @@ public class SpringBatchSchedulerIntegrationTest { ScheduledAnnotationBeanPostProcessor bean = context.getBean(ScheduledAnnotationBeanPostProcessor.class); SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class); await().untilAsserted(() -> Assert.assertEquals(2, schedulerBean.getBatchRunCounter() - .get())); + .get())); bean.postProcessBeforeDestruction(schedulerBean, "SpringBatchScheduler"); await().atLeast(3, SECONDS); Assert.assertEquals(2, schedulerBean.getBatchRunCounter() - .get()); + .get()); } @Test public void stopJobSchedulerWhenFutureTasksCancelled() throws Exception { SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class); await().untilAsserted(() -> Assert.assertEquals(2, schedulerBean.getBatchRunCounter() - .get())); + .get())); schedulerBean.cancelFutureSchedulerTasks(); await().atLeast(3, SECONDS); Assert.assertEquals(2, schedulerBean.getBatchRunCounter() - .get()); + .get()); } diff --git a/spring-batch/README.md b/spring-batch/README.md index 3a89459629..b87a2149a0 100644 --- a/spring-batch/README.md +++ b/spring-batch/README.md @@ -7,8 +7,8 @@ This module contains articles about Spring Batch - [Introduction to Spring Batch](https://www.baeldung.com/introduction-to-spring-batch) - [Spring Batch using Partitioner](https://www.baeldung.com/spring-batch-partitioner) - [Spring Batch – Tasklets vs Chunks](https://www.baeldung.com/spring-batch-tasklet-chunk) -- [How to Trigger and Stop a Scheduled Spring Batch Job](https://www.baeldung.com/spring-batch-start-stop-job) - [Configuring Skip Logic in Spring Batch](https://www.baeldung.com/spring-batch-skip-logic) - [Testing a Spring Batch Job](https://www.baeldung.com/spring-batch-testing-job) - [Configuring Retry Logic in Spring Batch](https://www.baeldung.com/spring-batch-retry-logic) - [Conditional Flow in Spring Batch](https://www.baeldung.com/spring-batch-conditional-flow) +- More articles [[next -->]](/spring-batch-2) diff --git a/spring-batch/pom.xml b/spring-batch/pom.xml index 9879a4777f..32126fec9b 100644 --- a/spring-batch/pom.xml +++ b/spring-batch/pom.xml @@ -82,12 +82,6 @@ hsqldb runtime - - org.awaitility - awaitility - ${awaitility.version} - test - @@ -97,7 +91,6 @@ 4.1 2.3.1 2.12.3 - 3.1.1 \ No newline at end of file diff --git a/spring-batch/repository.sqlite b/spring-batch/repository.sqlite index a2b87ffa00..b6a954554c 100644 Binary files a/spring-batch/repository.sqlite and b/spring-batch/repository.sqlite differ diff --git a/spring-boot-modules/spring-boot-angular/pom.xml b/spring-boot-modules/spring-boot-angular/pom.xml index d713510cff..10885d5320 100644 --- a/spring-boot-modules/spring-boot-angular/pom.xml +++ b/spring-boot-modules/spring-boot-angular/pom.xml @@ -31,7 +31,6 @@ com.h2database h2 - ${h2.version} runtime diff --git a/spring-boot-modules/spring-boot-basic-customization-2/README.md b/spring-boot-modules/spring-boot-basic-customization-2/README.md index 0e688bda2a..9488618ca5 100644 --- a/spring-boot-modules/spring-boot-basic-customization-2/README.md +++ b/spring-boot-modules/spring-boot-basic-customization-2/README.md @@ -7,3 +7,4 @@ This module contains articles about Spring Boot customization 2 - [DispatcherServlet and web.xml in Spring Boot](https://www.baeldung.com/spring-boot-dispatcherservlet-web-xml) - [XML Defined Beans in Spring Boot](https://www.baeldung.com/spring-boot-xml-beans) - [What Is OncePerRequestFilter?](https://www.baeldung.com/spring-onceperrequestfilter) + - [Spring Boot Exit Codes](https://www.baeldung.com/spring-boot-exit-codes) diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/event/ExitCodeEventDemoApplication.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/exitcode/event/ExitCodeEventDemoApplication.java similarity index 100% rename from spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/event/ExitCodeEventDemoApplication.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/exitcode/event/ExitCodeEventDemoApplication.java diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/exception/ExitCodeExceptionMapperDemoApplication.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/exitcode/exception/ExitCodeExceptionMapperDemoApplication.java similarity index 100% rename from spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/exception/ExitCodeExceptionMapperDemoApplication.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/exitcode/exception/ExitCodeExceptionMapperDemoApplication.java diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/exceptionexitgen/ExceptionExitCodeGeneratorApplication.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/exitcode/exceptionexitgen/ExceptionExitCodeGeneratorApplication.java similarity index 100% rename from spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/exceptionexitgen/ExceptionExitCodeGeneratorApplication.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/exitcode/exceptionexitgen/ExceptionExitCodeGeneratorApplication.java diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/exceptionexitgen/FailedToStartException.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/exitcode/exceptionexitgen/FailedToStartException.java similarity index 100% rename from spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/exceptionexitgen/FailedToStartException.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/exitcode/exceptionexitgen/FailedToStartException.java diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/generator/ExitCodeGeneratorDemoApplication.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/exitcode/generator/ExitCodeGeneratorDemoApplication.java similarity index 100% rename from spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/generator/ExitCodeGeneratorDemoApplication.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/exitcode/generator/ExitCodeGeneratorDemoApplication.java diff --git a/spring-boot-modules/spring-boot-basic-customization/README.md b/spring-boot-modules/spring-boot-basic-customization/README.md index 6c067fc5a1..a3d9f1b1fc 100644 --- a/spring-boot-modules/spring-boot-basic-customization/README.md +++ b/spring-boot-modules/spring-boot-basic-customization/README.md @@ -11,4 +11,3 @@ This module contains articles about Spring Boot customization - [Spring Boot: Configuring a Main Class](https://www.baeldung.com/spring-boot-main-class) - [How to Define a Spring Boot Filter?](https://www.baeldung.com/spring-boot-add-filter) - [Guide to the Favicon in Spring Boot](https://www.baeldung.com/spring-boot-favicon) - - [Spring Boot Exit Codes](https://www.baeldung.com/spring-boot-exit-codes) diff --git a/spring-boot-modules/spring-boot-camel/pom.xml b/spring-boot-modules/spring-boot-camel/pom.xml index 0069dfdbff..5d5e2ce6bd 100644 --- a/spring-boot-modules/spring-boot-camel/pom.xml +++ b/spring-boot-modules/spring-boot-camel/pom.xml @@ -9,10 +9,9 @@ spring-boot-camel - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT diff --git a/spring-boot-modules/spring-boot-cassandre/pom.xml b/spring-boot-modules/spring-boot-cassandre/pom.xml index 14849e50d7..1f2931a2bf 100644 --- a/spring-boot-modules/spring-boot-cassandre/pom.xml +++ b/spring-boot-modules/spring-boot-cassandre/pom.xml @@ -9,10 +9,9 @@ Cassandre trading bot tutorial - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter/pom.xml b/spring-boot-modules/spring-boot-custom-starter/greeter/pom.xml index f96880b1cf..5c0580d29a 100644 --- a/spring-boot-modules/spring-boot-custom-starter/greeter/pom.xml +++ b/spring-boot-modules/spring-boot-custom-starter/greeter/pom.xml @@ -8,10 +8,9 @@ greeter - com.baeldung - parent-boot-2 + com.baeldung.spring-boot-modules + spring-boot-custom-starter 0.0.1-SNAPSHOT - ../../../parent-boot-2 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/application/pom.xml b/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/application/pom.xml index 1c26ec32d3..a00c3a3c57 100644 --- a/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/application/pom.xml +++ b/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/application/pom.xml @@ -9,9 +9,8 @@ com.baeldung - parent-boot-2 + parent-multi-module 0.0.1-SNAPSHOT - ../../../../parent-boot-2 diff --git a/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/library/pom.xml b/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/library/pom.xml index 5d45de0d1d..6e7b3ce78a 100644 --- a/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/library/pom.xml +++ b/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/library/pom.xml @@ -9,9 +9,8 @@ com.baeldung - parent-boot-2 + parent-multi-module 0.0.1-SNAPSHOT - ../../../../parent-boot-2 diff --git a/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/pom.xml b/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/pom.xml index 2a483a8fef..4bc8434d43 100644 --- a/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/pom.xml +++ b/spring-boot-modules/spring-boot-custom-starter/parent-multi-module/pom.xml @@ -8,6 +8,12 @@ 0.0.1-SNAPSHOT pom + + com.baeldung.spring-boot-modules + spring-boot-custom-starter + 0.0.1-SNAPSHOT + + library application diff --git a/spring-boot-modules/spring-boot-data/pom.xml b/spring-boot-modules/spring-boot-data/pom.xml index c57dad49f4..7e0f764cf2 100644 --- a/spring-boot-modules/spring-boot-data/pom.xml +++ b/spring-boot-modules/spring-boot-data/pom.xml @@ -35,7 +35,6 @@ com.h2database h2 - ${h2.version} org.springframework.boot diff --git a/spring-boot-modules/spring-boot-groovy/pom.xml b/spring-boot-modules/spring-boot-groovy/pom.xml index ea9f3231cd..820bb0fd7a 100644 --- a/spring-boot-modules/spring-boot-groovy/pom.xml +++ b/spring-boot-modules/spring-boot-groovy/pom.xml @@ -10,10 +10,9 @@ Spring Boot Todo Application with Groovy - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java index 895ac8c562..78023aff8f 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java +++ b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java @@ -1,24 +1,19 @@ package com.baeldung.keycloak; import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver; -import org.keycloak.adapters.springsecurity.KeycloakSecurityComponents; +import org.keycloak.adapters.springsecurity.KeycloakConfiguration; import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider; import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper; import org.springframework.security.core.session.SessionRegistryImpl; import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy; import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy; -@Configuration -@EnableWebSecurity -@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class) +@KeycloakConfiguration class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter { // Submits the KeycloakAuthenticationProvider to the AuthenticationManager @Autowired diff --git a/spring-boot-modules/spring-boot-libraries/pom.xml b/spring-boot-modules/spring-boot-libraries/pom.xml index eee469ea46..97fde60a16 100644 --- a/spring-boot-modules/spring-boot-libraries/pom.xml +++ b/spring-boot-modules/spring-boot-libraries/pom.xml @@ -82,7 +82,6 @@ com.h2database h2 - ${h2.version} @@ -239,7 +238,6 @@ 2.2.4 2.3.2 0.23.0 - 1.4.200 2.1.0 1.5-beta1 2.1 diff --git a/spring-boot-modules/spring-boot-mvc-2/README.md b/spring-boot-modules/spring-boot-mvc-2/README.md index f9becb721f..0d0e05daf0 100644 --- a/spring-boot-modules/spring-boot-mvc-2/README.md +++ b/spring-boot-modules/spring-boot-mvc-2/README.md @@ -7,7 +7,6 @@ This module contains articles about Spring Web MVC in Spring Boot projects. - [Functional Controllers in Spring MVC](https://www.baeldung.com/spring-mvc-functional-controllers) - [Specify an Array of Strings as Body Parameters in Swagger](https://www.baeldung.com/swagger-body-array-of-strings) - [Swagger @ApiParam vs @ApiModelProperty](https://www.baeldung.com/swagger-apiparam-vs-apimodelproperty) -- [ETags for REST with Spring](https://www.baeldung.com/etags-for-rest-with-spring) - [Testing REST with multiple MIME types](https://www.baeldung.com/testing-rest-api-with-multiple-media-types) - [Testing Web APIs with Postman Collections](https://www.baeldung.com/postman-testing-collections) - [Spring Boot Consuming and Producing JSON](https://www.baeldung.com/spring-boot-json) diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/Foo.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/Foo.java new file mode 100644 index 0000000000..a8e379fc79 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/Foo.java @@ -0,0 +1,93 @@ +package com.baeldung.mime; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Version; +import java.io.Serializable; + +@Entity +public class Foo implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + @Column(nullable = false) + private String name; + + @Version + private long version; + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + + this.name = name; + } + + // API + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public long getVersion() { + return version; + } + + public void setVersion(long version) { + this.version = version; + } + + // + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Foo other = (Foo) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Foo [name=").append(name).append("]"); + return builder.toString(); + } +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/FooController.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/FooController.java new file mode 100644 index 0000000000..d7da9bd849 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/FooController.java @@ -0,0 +1,36 @@ +package com.baeldung.mime; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; + +import javax.servlet.http.HttpServletResponse; + +@RestController +@RequestMapping(value = "/foos") +public class FooController { + + @Autowired + private FooDao fooDao; + + @GetMapping(value = "/{id}") + public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) { + return fooDao.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); + } + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) { + return fooDao.save(resource); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/FooDao.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/FooDao.java new file mode 100644 index 0000000000..9fc99e1124 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/mime/FooDao.java @@ -0,0 +1,8 @@ +package com.baeldung.mime; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface FooDao extends CrudRepository{ +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/FooLiveTest.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/FooLiveTest.java index e65b106ead..86dd4915b4 100644 --- a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/FooLiveTest.java +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/FooLiveTest.java @@ -14,15 +14,12 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.baeldung.etag.Foo; -import com.baeldung.etag.WebConfig; - import io.restassured.RestAssured; import io.restassured.response.Response; @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes= WebConfig.class, webEnvironment = WebEnvironment.RANDOM_PORT) -@ComponentScan({"com.baeldung.mime", "com.baeldung.etag"}) +@SpringBootTest(classes = FooController.class, webEnvironment = WebEnvironment.RANDOM_PORT) +@ComponentScan({"com.baeldung.mime"}) @EnableAutoConfiguration @ActiveProfiles("test") public class FooLiveTest { @@ -47,12 +44,12 @@ public class FooLiveTest { createAsUri(resource); } - private final String createAsUri(final Foo resource) { + private String createAsUri(final Foo resource) { final Response response = createAsResponse(resource); return getURL() + "/" + response.getBody().as(Foo.class).getId(); } - private final Response createAsResponse(final Foo resource) { + private Response createAsResponse(final Foo resource) { final String resourceAsString = marshaller.encode(resource); return RestAssured.given() diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/JacksonMarshaller.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/JacksonMarshaller.java index 9dee0ef2cd..c6d14a9427 100644 --- a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/JacksonMarshaller.java +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/JacksonMarshaller.java @@ -7,7 +7,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; -import com.baeldung.etag.Foo; +import com.baeldung.mime.Foo; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/XStreamMarshaller.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/XStreamMarshaller.java index 2c67694e83..8a4188ceca 100644 --- a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/XStreamMarshaller.java +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/XStreamMarshaller.java @@ -4,7 +4,7 @@ import java.util.List; import org.springframework.http.MediaType; -import com.baeldung.etag.Foo; +import com.baeldung.mime.Foo; import com.thoughtworks.xstream.XStream; public final class XStreamMarshaller implements IMarshaller { diff --git a/spring-boot-modules/spring-boot-mvc-3/README.md b/spring-boot-modules/spring-boot-mvc-3/README.md index f9c6989b3c..fa24ac11ed 100644 --- a/spring-boot-modules/spring-boot-mvc-3/README.md +++ b/spring-boot-modules/spring-boot-mvc-3/README.md @@ -10,4 +10,5 @@ This module contains articles about Spring Web MVC in Spring Boot projects. - [Differences in @Valid and @Validated Annotations in Spring](https://www.baeldung.com/spring-valid-vs-validated) - [CharacterEncodingFilter In SpringBoot](https://www.baeldung.com/spring-boot-characterencodingfilter) - [HandlerInterceptors vs. Filters in Spring MVC](https://www.baeldung.com/spring-mvc-handlerinterceptor-vs-filter) +- [ETags for REST with Spring](https://www.baeldung.com/etags-for-rest-with-spring) - More articles: [[prev -->]](/spring-boot-modules/spring-boot-mvc-2) diff --git a/spring-boot-modules/spring-boot-mvc-3/pom.xml b/spring-boot-modules/spring-boot-mvc-3/pom.xml index dee217862d..43a492786e 100644 --- a/spring-boot-modules/spring-boot-mvc-3/pom.xml +++ b/spring-boot-modules/spring-boot-mvc-3/pom.xml @@ -27,6 +27,14 @@ org.springframework.boot spring-boot-starter-thymeleaf + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + commons-io commons-io diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/Foo.java b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/Foo.java similarity index 99% rename from spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/Foo.java rename to spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/Foo.java index e553ca1b72..9790bca663 100644 --- a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/Foo.java +++ b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/Foo.java @@ -1,13 +1,12 @@ package com.baeldung.etag; -import java.io.Serializable; - import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Version; +import java.io.Serializable; @Entity public class Foo implements Serializable { diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooController.java b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/FooController.java similarity index 99% rename from spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooController.java rename to spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/FooController.java index 58f366501d..d40a5e7809 100644 --- a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooController.java +++ b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/FooController.java @@ -1,7 +1,5 @@ package com.baeldung.etag; -import javax.servlet.http.HttpServletResponse; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -16,6 +14,8 @@ import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ResponseStatusException; +import javax.servlet.http.HttpServletResponse; + @RestController @RequestMapping(value = "/foos") public class FooController { diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooDao.java b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/FooDao.java similarity index 100% rename from spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooDao.java rename to spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/FooDao.java diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/SpringBootEtagApplication.java b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/SpringBootEtagApplication.java similarity index 100% rename from spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/SpringBootEtagApplication.java rename to spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/SpringBootEtagApplication.java diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/WebConfig.java b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/WebConfig.java similarity index 100% rename from spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/WebConfig.java rename to spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/etag/WebConfig.java diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/resources/WEB-INF/web.xml b/spring-boot-modules/spring-boot-mvc-3/src/main/resources/WEB-INF/web.xml similarity index 100% rename from spring-boot-modules/spring-boot-mvc-2/src/main/resources/WEB-INF/web.xml rename to spring-boot-modules/spring-boot-mvc-3/src/main/resources/WEB-INF/web.xml diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/etag/EtagIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-3/src/test/java/com/baeldung/etag/EtagIntegrationTest.java similarity index 99% rename from spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/etag/EtagIntegrationTest.java rename to spring-boot-modules/spring-boot-mvc-3/src/test/java/com/baeldung/etag/EtagIntegrationTest.java index 88c5ae1686..97de6d06f1 100644 --- a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/etag/EtagIntegrationTest.java +++ b/spring-boot-modules/spring-boot-mvc-3/src/test/java/com/baeldung/etag/EtagIntegrationTest.java @@ -1,10 +1,10 @@ package com.baeldung.etag; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.restassured.RestAssured; +import io.restassured.http.ContentType; +import io.restassured.response.Response; import org.assertj.core.util.Preconditions; import org.junit.Ignore; import org.junit.Test; @@ -18,12 +18,10 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.restassured.RestAssured; -import io.restassured.http.ContentType; -import io.restassured.response.Response; +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) diff --git a/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/pom.xml b/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/pom.xml index 496004b0e2..b1c44de9a9 100644 --- a/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/pom.xml +++ b/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/pom.xml @@ -9,10 +9,9 @@ jar - com.baeldung - parent-boot-2 + com.baeldung.spring-boot-modules + spring-boot-property-exp 0.0.1-SNAPSHOT - ../../../parent-boot-2 diff --git a/spring-boot-modules/spring-boot-react/pom.xml b/spring-boot-modules/spring-boot-react/pom.xml index 3e8a9a7bd1..d515aed6ce 100644 --- a/spring-boot-modules/spring-boot-react/pom.xml +++ b/spring-boot-modules/spring-boot-react/pom.xml @@ -25,7 +25,6 @@ com.h2database h2 - ${h2.version} runtime @@ -128,7 +127,6 @@ v14.18.0 v1.12.1 2.4.4 - 1.4.200 1.0.2
diff --git a/spring-boot-modules/spring-boot-validation/pom.xml b/spring-boot-modules/spring-boot-validation/pom.xml index 86e0a47d0d..fa4e8439e6 100644 --- a/spring-boot-modules/spring-boot-validation/pom.xml +++ b/spring-boot-modules/spring-boot-validation/pom.xml @@ -8,10 +8,9 @@ 0.0.1-SNAPSHOT - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT diff --git a/spring-boot-rest-2/README.md b/spring-boot-rest-2/README.md index 41270d58ea..985aa97a86 100644 --- a/spring-boot-rest-2/README.md +++ b/spring-boot-rest-2/README.md @@ -2,3 +2,4 @@ - [Get All Endpoints in Spring Boot](https://www.baeldung.com/spring-boot-get-all-endpoints) - [HTTP PUT vs. POST in REST API](https://www.baeldung.com/rest-http-put-vs-post) +- [415 Unsupported MediaType in Spring Application](https://www.baeldung.com/spring-415-unsupported-mediatype) diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/UnsupportedMediaTypeApplication.java b/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/UnsupportedMediaTypeApplication.java new file mode 100644 index 0000000000..2bf6bb33cd --- /dev/null +++ b/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/UnsupportedMediaTypeApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.unsupportedmediatype; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class UnsupportedMediaTypeApplication { + + public static void main(String[] args) { + SpringApplication.run(UnsupportedMediaTypeApplication.class, args); + } + +} diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/User.java b/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/User.java new file mode 100644 index 0000000000..765149dad5 --- /dev/null +++ b/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/User.java @@ -0,0 +1,66 @@ +package com.baeldung.unsupportedmediatype; + +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; + +@XmlRootElement +public class User implements Serializable { + private Integer id; + private String name; + private Integer age; + private String address; + + public User(){ + } + + public User(Integer id, String name, Integer age, String address) { + this.id = id; + this.name = name; + this.age = age; + this.address = address; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + @Override + public String toString() { + return "User{" + + "id=" + id + + ", name='" + name + '\'' + + ", age=" + age + + ", address='" + address + '\'' + + '}'; + } + + +} diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/UserController.java b/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/UserController.java new file mode 100644 index 0000000000..a20043619a --- /dev/null +++ b/spring-boot-rest-2/src/main/java/com/baeldung/unsupportedmediatype/UserController.java @@ -0,0 +1,29 @@ +package com.baeldung.unsupportedmediatype; + +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.*; + +import java.util.Collections; +import java.util.List; + +@RestController +@RequestMapping("/user") +public class UserController { + + @GetMapping(value = "/") + List getAllUsers(){ + return Collections.singletonList(new User(1, "Andy", 28, "14th Street")); + } + + @GetMapping(value = "/{user-id}") + User getUser(@PathVariable("user-id") Integer userId){ + return new User(userId, "Andy", 28, "14th Street"); + } + + @PostMapping(value = "/", consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) + void AddUser(@RequestBody User user){ + // Adding the User in the repository + } + + +} \ No newline at end of file diff --git a/spring-boot-rest-2/src/test/java/com/baeldung/unsupportedmediatype/ApplicationUnitTest.java b/spring-boot-rest-2/src/test/java/com/baeldung/unsupportedmediatype/ApplicationUnitTest.java new file mode 100644 index 0000000000..498ad9d537 --- /dev/null +++ b/spring-boot-rest-2/src/test/java/com/baeldung/unsupportedmediatype/ApplicationUnitTest.java @@ -0,0 +1,58 @@ +package com.baeldung.unsupportedmediatype; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringRunner.class) +@WebMvcTest(UserController.class) +public class ApplicationUnitTest { + @Autowired + private MockMvc mockMvc; + + @Test + public void JsonTestCase() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.post("/user/") + .contentType(MediaType.APPLICATION_JSON_VALUE) + .content( "{\n" + + " \"name\": \"Andy\",\n" + + " \"age\": 1,\n" + + " \"address\": \"Hello world\"\n" + + "}")) + .andExpect(status().isOk()); + } + + @Test + public void JsonFailTestCase() throws Exception {// Because no content-type added + mockMvc.perform(MockMvcRequestBuilders.post("/user/") + .content( "{\n" + + " \"name\": \"Andy\",\n" + + " \"age\": 1,\n" + + " \"address\": \"Hello world\"\n" + + "}")) + .andExpect(status().isUnsupportedMediaType()); + } + + @Test + public void XmlTestCase() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.post("/user/") + .contentType(MediaType.APPLICATION_XML_VALUE) + .content("Andy1
Hello world
")) + .andExpect(status().isOk()); + } + + @Test + public void StringFailTestCase() throws Exception { // Because content-type is not supported + mockMvc.perform(MockMvcRequestBuilders.post("/user/") + .contentType(MediaType.TEXT_PLAIN_VALUE) + .content("Andy1
Hello world
")) + .andExpect(status().isUnsupportedMediaType()); + } +} diff --git a/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml b/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml index 8e7b87c220..8248884632 100644 --- a/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml +++ b/spring-cloud/spring-cloud-zookeeper/Greeting/pom.xml @@ -68,16 +68,6 @@ spring-boot-starter-test ${spring-boot.version} - - org.hamcrest - hamcrest-core - ${hamcrest-core.version} - test -
- - 1.3 - - \ No newline at end of file diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-ui/pom.xml b/spring-cloud/spring-cloud-zuul/spring-zuul-ui/pom.xml index 7c3f668473..c071b8863a 100644 --- a/spring-cloud/spring-cloud-zuul/spring-zuul-ui/pom.xml +++ b/spring-cloud/spring-cloud-zuul/spring-zuul-ui/pom.xml @@ -27,11 +27,6 @@ spring-test test - - org.hamcrest - hamcrest - test - org.mockito mockito-core diff --git a/spring-core-2/pom.xml b/spring-core-2/pom.xml index dda23c4ea4..19e7fb5f28 100644 --- a/spring-core-2/pom.xml +++ b/spring-core-2/pom.xml @@ -129,11 +129,6 @@ spring-test test - - org.hamcrest - hamcrest - test - org.mockito mockito-core diff --git a/spring-core/README.md b/spring-core/README.md index b8d46f6b34..3f0fe4b4e4 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -11,5 +11,6 @@ This module contains articles about core Spring functionality - [Spring Application Context Events](https://www.baeldung.com/spring-context-events) - [What is a Spring Bean?](https://www.baeldung.com/spring-bean) - [Spring PostConstruct and PreDestroy Annotations](https://www.baeldung.com/spring-postconstruct-predestroy) +- [Intro to the Spring ClassPathXmlApplicationContext](http://www.baeldung.com/spring-classpathxmlapplicationcontext) - More articles: [[next -->]](/spring-core-2) diff --git a/spring-core/src/test/java/com/baeldung/applicationcontext/README.md b/spring-core/src/test/java/com/baeldung/applicationcontext/README.md deleted file mode 100644 index 211007e0cf..0000000000 --- a/spring-core/src/test/java/com/baeldung/applicationcontext/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: -- [Introduction to Java Servlets](http://www.baeldung.com/intro-to-servlets) -- [Intro to the Spring ClassPathXmlApplicationContext](http://www.baeldung.com/spring-classpathxmlapplicationcontext) diff --git a/spring-security-modules/spring-security-web-boot-1/pom.xml b/spring-security-modules/spring-security-web-boot-1/pom.xml index a376a49b4c..3f6001686d 100644 --- a/spring-security-modules/spring-security-web-boot-1/pom.xml +++ b/spring-security-modules/spring-security-web-boot-1/pom.xml @@ -59,11 +59,6 @@ postgresql runtime - - org.hamcrest - hamcrest - test - org.springframework spring-test diff --git a/spring-security-modules/spring-security-web-boot-2/pom.xml b/spring-security-modules/spring-security-web-boot-2/pom.xml index ade644741d..91b6ff8724 100644 --- a/spring-security-modules/spring-security-web-boot-2/pom.xml +++ b/spring-security-modules/spring-security-web-boot-2/pom.xml @@ -59,11 +59,6 @@ postgresql runtime - - org.hamcrest - hamcrest - test - org.springframework spring-test diff --git a/spring-security-modules/spring-security-web-rest-custom/pom.xml b/spring-security-modules/spring-security-web-rest-custom/pom.xml index 85e50412ad..1403154767 100644 --- a/spring-security-modules/spring-security-web-rest-custom/pom.xml +++ b/spring-security-modules/spring-security-web-rest-custom/pom.xml @@ -116,11 +116,6 @@ ${commons-lang3.version} - - org.hamcrest - hamcrest - test - org.mockito mockito-core diff --git a/spring-security-modules/spring-session/spring-session-jdbc/pom.xml b/spring-security-modules/spring-session/spring-session-jdbc/pom.xml index 64bbce44f2..3cc2b8d18e 100644 --- a/spring-security-modules/spring-session/spring-session-jdbc/pom.xml +++ b/spring-security-modules/spring-session/spring-session-jdbc/pom.xml @@ -28,7 +28,6 @@ com.h2database h2 - ${h2.version} runtime diff --git a/spring-web-modules/spring-rest-query-language/pom.xml b/spring-web-modules/spring-rest-query-language/pom.xml index c5a8c172f3..65f28f5be0 100644 --- a/spring-web-modules/spring-rest-query-language/pom.xml +++ b/spring-web-modules/spring-rest-query-language/pom.xml @@ -181,11 +181,6 @@ spring-test test - - org.hamcrest - hamcrest - test - org.mockito mockito-core diff --git a/spring-web-modules/spring-rest-simple/pom.xml b/spring-web-modules/spring-rest-simple/pom.xml index 69d88d6456..2f8d6eac27 100644 --- a/spring-web-modules/spring-rest-simple/pom.xml +++ b/spring-web-modules/spring-rest-simple/pom.xml @@ -120,11 +120,6 @@ ${com.squareup.okhttp3.version} - - org.hamcrest - hamcrest - test - org.mockito mockito-core diff --git a/spring-web-modules/spring-rest-testing/pom.xml b/spring-web-modules/spring-rest-testing/pom.xml index dc5fdcd323..93942e97b6 100644 --- a/spring-web-modules/spring-rest-testing/pom.xml +++ b/spring-web-modules/spring-rest-testing/pom.xml @@ -165,11 +165,6 @@ spring-test test - - org.hamcrest - hamcrest - test - org.mockito mockito-core diff --git a/spring-web-modules/spring-resttemplate/pom.xml b/spring-web-modules/spring-resttemplate/pom.xml index 3066a82242..5cac186fad 100644 --- a/spring-web-modules/spring-resttemplate/pom.xml +++ b/spring-web-modules/spring-resttemplate/pom.xml @@ -108,11 +108,6 @@ ${com.squareup.okhttp3.version} - - org.hamcrest - hamcrest - test - org.mockito mockito-core diff --git a/spring-websockets/README.md b/spring-websockets/README.md index 7d69c21b78..88a97850b5 100644 --- a/spring-websockets/README.md +++ b/spring-websockets/README.md @@ -7,3 +7,4 @@ This module contains articles about Spring WebSockets. - [A Quick Example of Spring Websockets’ @SendToUser Annotation](https://www.baeldung.com/spring-websockets-sendtouser) - [Scheduled WebSocket Push with Spring Boot](https://www.baeldung.com/spring-boot-scheduled-websocket) - [Test WebSocket APIs With Postman](https://www.baeldung.com/postman-websocket-apis) +- [Debugging WebSockets](https://www.baeldung.com/debug-websockets) diff --git a/spring-websockets/pom.xml b/spring-websockets/pom.xml index a28ef8749a..28c875d50d 100644 --- a/spring-websockets/pom.xml +++ b/spring-websockets/pom.xml @@ -1,7 +1,7 @@ + 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"> 4.0.0 spring-websockets spring-websockets diff --git a/spring-websockets/src/main/java/com/baeldung/debugwebsockets/StockTicksController.java b/spring-websockets/src/main/java/com/baeldung/debugwebsockets/StockTicksController.java new file mode 100644 index 0000000000..0942657c33 --- /dev/null +++ b/spring-websockets/src/main/java/com/baeldung/debugwebsockets/StockTicksController.java @@ -0,0 +1,39 @@ +package com.baeldung.debugwebsockets; + +import org.springframework.messaging.simp.SimpMessagingTemplate; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Controller; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; + +@Controller +public class StockTicksController { + private final SimpMessagingTemplate simpMessagingTemplate; + + public StockTicksController(SimpMessagingTemplate simpMessagingTemplate) { + this.simpMessagingTemplate = simpMessagingTemplate; + } + + @Scheduled(fixedRate = 3000) + public void sendTicks() { + simpMessagingTemplate.convertAndSend("/topic/ticks", getStockTicks()); + } + + private Map getStockTicks() { + Map ticks = new HashMap<>(); + ticks.put("AAPL", getRandomTick()); + ticks.put("GOOGL", getRandomTick()); + ticks.put("MSFT", getRandomTick()); + ticks.put("TSLA", getRandomTick()); + ticks.put("AMZN", getRandomTick()); + ticks.put("HPE", getRandomTick()); + + return ticks; + } + + private int getRandomTick() { + return ThreadLocalRandom.current().nextInt(-100, 100 + 1); + } +} \ No newline at end of file diff --git a/spring-websockets/src/main/java/com/baeldung/debugwebsockets/StompClientSessionHandler.java b/spring-websockets/src/main/java/com/baeldung/debugwebsockets/StompClientSessionHandler.java new file mode 100644 index 0000000000..535be79cee --- /dev/null +++ b/spring-websockets/src/main/java/com/baeldung/debugwebsockets/StompClientSessionHandler.java @@ -0,0 +1,31 @@ +package com.baeldung.debugwebsockets; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.messaging.simp.stomp.StompHeaders; +import org.springframework.messaging.simp.stomp.StompSession; +import org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter; + +import java.lang.reflect.Type; +import java.util.Map; + +public class StompClientSessionHandler extends StompSessionHandlerAdapter { + private static final Logger logger = LoggerFactory.getLogger("StompClientSessionHandler"); + + @Override + public void afterConnected(StompSession session, StompHeaders connectedHeaders) { + logger.info("New session established. Session Id -> {}", session.getSessionId()); + session.subscribe("/topic/ticks", this); + logger.info("Subscribed to topic: /topic/ticks"); + } + + @Override + public void handleFrame(StompHeaders headers, Object payload) { + logger.info("Payload -> {}", payload); + } + + @Override + public Type getPayloadType(StompHeaders headers) { + return Map.class; + } +} diff --git a/spring-websockets/src/main/java/com/baeldung/debugwebsockets/StompWebSocketClient.java b/spring-websockets/src/main/java/com/baeldung/debugwebsockets/StompWebSocketClient.java new file mode 100644 index 0000000000..0cbe32bf65 --- /dev/null +++ b/spring-websockets/src/main/java/com/baeldung/debugwebsockets/StompWebSocketClient.java @@ -0,0 +1,24 @@ +package com.baeldung.debugwebsockets; + +import org.springframework.messaging.converter.MappingJackson2MessageConverter; +import org.springframework.messaging.simp.stomp.StompSessionHandler; +import org.springframework.web.socket.client.WebSocketClient; +import org.springframework.web.socket.client.standard.StandardWebSocketClient; +import org.springframework.web.socket.messaging.WebSocketStompClient; + +import java.util.Scanner; + +public class StompWebSocketClient { + + private static final String URL = "ws://localhost:8080/stock-ticks/websocket"; + + public static void main(String[] args) { + WebSocketClient client = new StandardWebSocketClient(); + WebSocketStompClient stompClient = new WebSocketStompClient(client); + stompClient.setMessageConverter(new MappingJackson2MessageConverter()); + StompSessionHandler sessionHandler = new StompClientSessionHandler(); + stompClient.connect(URL, sessionHandler); + + new Scanner(System.in).nextLine(); + } +} diff --git a/spring-websockets/src/main/java/com/baeldung/debugwebsockets/WebsocketApplication.java b/spring-websockets/src/main/java/com/baeldung/debugwebsockets/WebsocketApplication.java new file mode 100644 index 0000000000..1d0d6950d3 --- /dev/null +++ b/spring-websockets/src/main/java/com/baeldung/debugwebsockets/WebsocketApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.debugwebsockets; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class WebsocketApplication { + + public static void main(String[] args) { + SpringApplication.run(WebsocketApplication.class, args); + } + +} diff --git a/spring-websockets/src/main/java/com/baeldung/debugwebsockets/WebsocketConfiguration.java b/spring-websockets/src/main/java/com/baeldung/debugwebsockets/WebsocketConfiguration.java new file mode 100644 index 0000000000..3735e7359b --- /dev/null +++ b/spring-websockets/src/main/java/com/baeldung/debugwebsockets/WebsocketConfiguration.java @@ -0,0 +1,25 @@ +package com.baeldung.debugwebsockets; + +import org.springframework.context.annotation.Configuration; +import org.springframework.messaging.simp.config.MessageBrokerRegistry; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; +import org.springframework.web.socket.config.annotation.StompEndpointRegistry; +import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; + +@Configuration +@EnableWebSocketMessageBroker +@EnableScheduling +public class WebsocketConfiguration implements WebSocketMessageBrokerConfigurer { + @Override + public void configureMessageBroker(MessageBrokerRegistry config) { + config.enableSimpleBroker("/topic"); + config.setApplicationDestinationPrefixes("/app"); + } + + @Override + public void registerStompEndpoints(StompEndpointRegistry registry) { + registry.addEndpoint("/stock-ticks").setAllowedOriginPatterns("*").withSockJS(); + } + +} diff --git a/spring-websockets/src/test/java/com/baeldung/debugwebsockets/WebSocketIntegrationTest.java b/spring-websockets/src/test/java/com/baeldung/debugwebsockets/WebSocketIntegrationTest.java new file mode 100644 index 0000000000..bdc283b9e4 --- /dev/null +++ b/spring-websockets/src/test/java/com/baeldung/debugwebsockets/WebSocketIntegrationTest.java @@ -0,0 +1,114 @@ +package com.baeldung.debugwebsockets; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.messaging.converter.MappingJackson2MessageConverter; +import org.springframework.messaging.simp.stomp.StompCommand; +import org.springframework.messaging.simp.stomp.StompFrameHandler; +import org.springframework.messaging.simp.stomp.StompHeaders; +import org.springframework.messaging.simp.stomp.StompSession; +import org.springframework.messaging.simp.stomp.StompSessionHandler; +import org.springframework.web.socket.client.WebSocketClient; +import org.springframework.web.socket.client.standard.StandardWebSocketClient; +import org.springframework.web.socket.messaging.WebSocketStompClient; + +import java.lang.reflect.Type; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +/** + * This should be part of integration test suite. + * The test starts the server and then connects to the WebSocket. Then verifies if the messages are received from the + * WebSocket. + * This test is inspired from: https://github.com/spring-guides/gs-messaging-stomp-websocket/blob/main/complete/src/test/java/com/example/messagingstompwebsocket/GreetingIntegrationTests.java + */ +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +class WebSocketIntegrationTest{ + WebSocketClient client; + WebSocketStompClient stompClient; + @LocalServerPort + private int port; + private static final Logger logger= LoggerFactory.getLogger(WebSocketIntegrationTest.class); + + @BeforeEach + public void setup() { + logger.info("Setting up the tests ..."); + client = new StandardWebSocketClient(); + stompClient = new WebSocketStompClient(client); + stompClient.setMessageConverter(new MappingJackson2MessageConverter()); + } + + @Test + void givenWebSocket_whenMessage_thenVerifyMessage() throws Exception { + final CountDownLatch latch = new CountDownLatch(1); + final AtomicReference failure = new AtomicReference<>(); + StompSessionHandler sessionHandler = new StompSessionHandler() { + @Override + public Type getPayloadType(StompHeaders headers) { + return null; + } + + @Override + public void handleFrame(StompHeaders headers, Object payload) { + } + + @Override + public void afterConnected(StompSession session, StompHeaders connectedHeaders) { + logger.info("Connected to the WebSocket ..."); + session.subscribe("/topic/ticks", new StompFrameHandler() { + @Override + public Type getPayloadType(StompHeaders headers) { + return Map.class; + } + + @Override + public void handleFrame(StompHeaders headers, Object payload) { + try { + + assertThat(payload).isNotNull(); + assertThat(payload).isInstanceOf(Map.class); + + @SuppressWarnings("unchecked") + Map map = (Map) payload; + + assertThat(map).containsKey("HPE"); + assertThat(map.get("HPE")).isInstanceOf(Integer.class); + } catch (Throwable t) { + failure.set(t); + logger.error("There is an exception ", t); + } finally { + session.disconnect(); + latch.countDown(); + } + + } + }); + } + + @Override + public void handleException(StompSession session, StompCommand command, StompHeaders headers, byte[] payload, Throwable exception) { + } + + @Override + public void handleTransportError(StompSession session, Throwable exception) { + } + }; + stompClient.connect("ws://localhost:{port}/stock-ticks/websocket", sessionHandler, this.port); + if (latch.await(20, TimeUnit.SECONDS)) { + if (failure.get() != null) { + fail("Assertion Failed", failure.get()); + } + } else { + fail("Could not receive the message on time"); + } + } +} diff --git a/testing-modules/junit-5-basics/pom.xml b/testing-modules/junit-5-basics/pom.xml index 62dc4321a8..4dcba2db96 100644 --- a/testing-modules/junit-5-basics/pom.xml +++ b/testing-modules/junit-5-basics/pom.xml @@ -124,6 +124,7 @@ 5.0.6.RELEASE + 1.4.197 \ No newline at end of file diff --git a/testing-modules/selenium-junit-testng/pom.xml b/testing-modules/selenium-junit-testng/pom.xml index 0bf6f0726d..dfa19c48d4 100644 --- a/testing-modules/selenium-junit-testng/pom.xml +++ b/testing-modules/selenium-junit-testng/pom.xml @@ -31,11 +31,6 @@ testng ${testng.version} - - org.hamcrest - hamcrest-all - ${hamcrest-all.version} - ru.yandex.qatools.ashot ashot diff --git a/testing-modules/spring-testing-2/README.md b/testing-modules/spring-testing-2/README.md index 16b47adeac..434388d683 100644 --- a/testing-modules/spring-testing-2/README.md +++ b/testing-modules/spring-testing-2/README.md @@ -3,3 +3,4 @@ - [Guide to @DynamicPropertySource in Spring](https://www.baeldung.com/spring-dynamicpropertysource) - [Concurrent Test Execution in Spring 5](https://www.baeldung.com/spring-5-concurrent-tests) - [Spring 5 Testing with @EnabledIf Annotation](https://www.baeldung.com/spring-5-enabledIf) +- [The Spring TestExecutionListener](https://www.baeldung.com/spring-testexecutionlistener) diff --git a/testing-modules/spring-testing-2/pom.xml b/testing-modules/spring-testing-2/pom.xml index f3e4f098b4..82a9ed9599 100644 --- a/testing-modules/spring-testing-2/pom.xml +++ b/testing-modules/spring-testing-2/pom.xml @@ -26,7 +26,6 @@ com.h2database h2 - ${h2.version} org.postgresql diff --git a/testing-modules/spring-testing/src/main/java/com/baeldung/testexecutionlisteners/AdditionService.java b/testing-modules/spring-testing-2/src/main/java/com/baeldung/testexecutionlisteners/AdditionService.java similarity index 100% rename from testing-modules/spring-testing/src/main/java/com/baeldung/testexecutionlisteners/AdditionService.java rename to testing-modules/spring-testing-2/src/main/java/com/baeldung/testexecutionlisteners/AdditionService.java diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/testexecutionlisteners/AdditionServiceUnitTest.java b/testing-modules/spring-testing-2/src/test/java/com/baeldung/testexecutionlisteners/AdditionServiceUnitTest.java similarity index 92% rename from testing-modules/spring-testing/src/test/java/com/baeldung/testexecutionlisteners/AdditionServiceUnitTest.java rename to testing-modules/spring-testing-2/src/test/java/com/baeldung/testexecutionlisteners/AdditionServiceUnitTest.java index bbe537a3ce..6c5d08f478 100644 --- a/testing-modules/spring-testing/src/test/java/com/baeldung/testexecutionlisteners/AdditionServiceUnitTest.java +++ b/testing-modules/spring-testing-2/src/test/java/com/baeldung/testexecutionlisteners/AdditionServiceUnitTest.java @@ -1,7 +1,5 @@ package com.baeldung.testexecutionlisteners; -import static org.junit.Assert.assertThat; - import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; @@ -9,9 +7,12 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; +import static org.hamcrest.MatcherAssert.assertThat; + @RunWith(SpringRunner.class) @ContextConfiguration(classes = AdditionService.class) public class AdditionServiceUnitTest { + @Autowired private AdditionService additionService; diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/testexecutionlisteners/CustomTestExecutionListener.java b/testing-modules/spring-testing-2/src/test/java/com/baeldung/testexecutionlisteners/CustomTestExecutionListener.java similarity index 100% rename from testing-modules/spring-testing/src/test/java/com/baeldung/testexecutionlisteners/CustomTestExecutionListener.java rename to testing-modules/spring-testing-2/src/test/java/com/baeldung/testexecutionlisteners/CustomTestExecutionListener.java diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithMergeModeUnitTest.java b/testing-modules/spring-testing-2/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithMergeModeUnitTest.java similarity index 93% rename from testing-modules/spring-testing/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithMergeModeUnitTest.java rename to testing-modules/spring-testing-2/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithMergeModeUnitTest.java index 44937aa755..de1501c54d 100644 --- a/testing-modules/spring-testing/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithMergeModeUnitTest.java +++ b/testing-modules/spring-testing-2/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithMergeModeUnitTest.java @@ -1,7 +1,5 @@ package com.baeldung.testexecutionlisteners; -import static org.junit.Assert.assertThat; - import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; @@ -11,11 +9,14 @@ import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.TestExecutionListeners.MergeMode; import org.springframework.test.context.junit4.SpringRunner; +import static org.hamcrest.MatcherAssert.assertThat; + @RunWith(SpringRunner.class) -@TestExecutionListeners(value = { CustomTestExecutionListener.class }, +@TestExecutionListeners(value = { CustomTestExecutionListener.class }, mergeMode = MergeMode.MERGE_WITH_DEFAULTS) @ContextConfiguration(classes = AdditionService.class) public class TestExecutionListenersWithMergeModeUnitTest { + @Autowired private AdditionService additionService; diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithoutMergeModeUnitTest.java b/testing-modules/spring-testing-2/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithoutMergeModeUnitTest.java similarity index 94% rename from testing-modules/spring-testing/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithoutMergeModeUnitTest.java rename to testing-modules/spring-testing-2/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithoutMergeModeUnitTest.java index e25ab9f381..b4cc861c29 100644 --- a/testing-modules/spring-testing/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithoutMergeModeUnitTest.java +++ b/testing-modules/spring-testing-2/src/test/java/com/baeldung/testexecutionlisteners/TestExecutionListenersWithoutMergeModeUnitTest.java @@ -1,7 +1,5 @@ package com.baeldung.testexecutionlisteners; -import static org.junit.Assert.assertThat; - import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; @@ -11,11 +9,14 @@ import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; +import static org.hamcrest.MatcherAssert.assertThat; + @RunWith(SpringRunner.class) @TestExecutionListeners(value = {CustomTestExecutionListener.class, DependencyInjectionTestExecutionListener.class}) @ContextConfiguration(classes = AdditionService.class) public class TestExecutionListenersWithoutMergeModeUnitTest { + @Autowired private AdditionService additionService; diff --git a/testing-modules/spring-testing/README.md b/testing-modules/spring-testing/README.md index a4de9c5c57..2427dfabbe 100644 --- a/testing-modules/spring-testing/README.md +++ b/testing-modules/spring-testing/README.md @@ -7,4 +7,3 @@ - [Using SpringJUnit4ClassRunner with Parameterized](https://www.baeldung.com/springjunit4classrunner-parameterized) - [Override Properties in Spring’s Tests](https://www.baeldung.com/spring-tests-override-properties) - [A Quick Guide to @DirtiesContext](https://www.baeldung.com/spring-dirtiescontext) -- [The Spring TestExecutionListener](https://www.baeldung.com/spring-testexecutionlistener) diff --git a/testing-modules/testing-assertions/pom.xml b/testing-modules/testing-assertions/pom.xml index 12af95b575..09f4291b78 100644 --- a/testing-modules/testing-assertions/pom.xml +++ b/testing-modules/testing-assertions/pom.xml @@ -18,12 +18,6 @@ logback-classic ${logback.version} - - org.hamcrest - hamcrest-all - ${hamcrest-all.version} - test - org.apache.commons commons-collections4 @@ -32,8 +26,4 @@ - - 4.4 - - \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/pom.xml b/video-tutorials/jackson-annotations/pom.xml index 29f457964b..eaec50c1f7 100644 --- a/video-tutorials/jackson-annotations/pom.xml +++ b/video-tutorials/jackson-annotations/pom.xml @@ -116,7 +116,6 @@ 2.9.6 2.8.0 - 4.1 3.0.1 3.0.0 diff --git a/xml/pom.xml b/xml/pom.xml index 968682ee38..0764c9d145 100644 --- a/xml/pom.xml +++ b/xml/pom.xml @@ -355,7 +355,6 @@ 1.2.0 2.0.6 1.6.2 - 4.1 1.2.4.5 2.3.1 1.4.2