diff --git a/apache-poi-2/README.md b/apache-poi-2/README.md index e31c219819..d810c40815 100644 --- a/apache-poi-2/README.md +++ b/apache-poi-2/README.md @@ -6,4 +6,5 @@ This module contains articles about Apache POI - [Adding a Column to an Excel Sheet Using Apache POI](https://www.baeldung.com/java-excel-add-column) - [Add an Image to a Cell in an Excel File With Java](https://www.baeldung.com/java-add-image-excel) +- [Numeric Format Using POI](https://www.baeldung.com/apache-poi-numeric-format) - More articles: [[<-- prev]](/apache-poi) diff --git a/apache-poi-2/src/main/java/com/baeldung/poi/excel/newcolumn/numeric/ExcelNumericFormat.java b/apache-poi-2/src/main/java/com/baeldung/poi/excel/newcolumn/numeric/ExcelNumericFormat.java new file mode 100644 index 0000000000..02148c783b --- /dev/null +++ b/apache-poi-2/src/main/java/com/baeldung/poi/excel/newcolumn/numeric/ExcelNumericFormat.java @@ -0,0 +1,19 @@ +package com.baeldung.poi.excel.newcolumn.numeric; + +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.DataFormat; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Workbook; + +public class ExcelNumericFormat { + + public static void applyNumericFormat(Workbook outWorkbook, Row row, Cell cell, Double value, String styleFormat) { + CellStyle style = outWorkbook.createCellStyle(); + DataFormat format = outWorkbook.createDataFormat(); + style.setDataFormat(format.getFormat(styleFormat)); + cell.setCellValue(value); + cell.setCellStyle(style); + } + +} diff --git a/apache-poi-2/src/test/java/com/baeldung/poi/excel/newcolumn/numeric/NumberCellValueUnitTest.java b/apache-poi-2/src/test/java/com/baeldung/poi/excel/newcolumn/numeric/NumberCellValueUnitTest.java new file mode 100644 index 0000000000..ae1090fd69 --- /dev/null +++ b/apache-poi-2/src/test/java/com/baeldung/poi/excel/newcolumn/numeric/NumberCellValueUnitTest.java @@ -0,0 +1,105 @@ +package com.baeldung.poi.excel.newcolumn.numeric; + +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.usermodel.Cell; +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.Test; +import org.junit.jupiter.api.Assertions; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.text.DecimalFormat; + +public class NumberCellValueUnitTest { + + @Test + public void decimalDisplay_whenAddedDouble_thenNumericCellCreated() throws IOException { + File file = new File("number_test.xlsx"); + try (Workbook outWorkbook = new XSSFWorkbook()) { + Sheet sheet = outWorkbook.createSheet("Numeric Sheet"); + Row row = sheet.createRow(0); + Cell cell = row.createCell(0); + ExcelNumericFormat.applyNumericFormat(outWorkbook, row, cell, 10.251, "0.00"); + FileOutputStream fileOut = new FileOutputStream(file); + outWorkbook.write(fileOut); + fileOut.close(); + } + try (Workbook inWorkbook = new XSSFWorkbook("number_test.xlsx")) { + Sheet sheet = inWorkbook.cloneSheet(0); + Row row = sheet.getRow(0); + Assertions.assertEquals(10.251, row.getCell(0) + .getNumericCellValue()); + file.delete(); + } + } + + @Test + public void decimalRoundedDisplay_whenAddedDouble_thenNumericCellCreated() throws IOException { + File file = new File("number_test.xlsx"); + try (Workbook outWorkbook = new XSSFWorkbook()) { + Sheet sheet = outWorkbook.createSheet("Numeric Sheet"); + Row row = sheet.createRow(0); + Cell cell = row.createCell(0); + ExcelNumericFormat.applyNumericFormat(outWorkbook, row, cell, 10.251123, "#,##0.0000"); + FileOutputStream fileOut = new FileOutputStream(file); + outWorkbook.write(fileOut); + fileOut.close(); + } + try (Workbook inWorkbook = new XSSFWorkbook("number_test.xlsx")) { + Sheet sheet = inWorkbook.cloneSheet(0); + Row row = sheet.getRow(0); + Assertions.assertEquals(10.251123, row.getCell(0) + .getNumericCellValue()); + file.delete(); + } + } + + @Test + public void decimalDisplayInXLS_whenAddedDouble_thenNumericCellCreated() throws IOException { + File file = new File("number_test.xls"); + try (Workbook outWorkbook = new HSSFWorkbook()) { + Sheet sheet = outWorkbook.createSheet("Numeric Sheet"); + Row row = sheet.createRow(0); + Cell cell = row.createCell(0); + ExcelNumericFormat.applyNumericFormat(outWorkbook, row, cell, 10.251, "0.00"); + FileOutputStream fileOut = new FileOutputStream(file); + outWorkbook.write(fileOut); + fileOut.close(); + } + try (Workbook inWorkbook = new HSSFWorkbook(new FileInputStream(file))) { + Sheet sheet = inWorkbook.cloneSheet(0); + Row row = sheet.getRow(0); + Assertions.assertEquals(10.251, row.getCell(0) + .getNumericCellValue()); + file.delete(); + } + } + + @Test + public void decimalValue_whenAddedDouble_thenNumericCellCreated() throws IOException { + File file = new File("number_test.xlsx"); + try (Workbook outWorkbook = new XSSFWorkbook()) { + Sheet sheet = outWorkbook.createSheet("Numeric Sheet"); + Row row = sheet.createRow(0); + Cell cell = row.createCell(0); + DecimalFormat df = new DecimalFormat("#,###.##"); + ExcelNumericFormat.applyNumericFormat(outWorkbook, row, cell, Double.valueOf(df.format(10.251)), "#,###.##"); + + FileOutputStream fileOut = new FileOutputStream(file); + outWorkbook.write(fileOut); + fileOut.close(); + } + try (Workbook inWorkbook = new XSSFWorkbook("number_test.xlsx")) { + Sheet sheet = inWorkbook.cloneSheet(0); + Row row = sheet.getRow(0); + Assertions.assertEquals(10.25, row.getCell(0) + .getNumericCellValue()); + file.delete(); + } + } +} \ No newline at end of file diff --git a/apache-poi/src/main/java/com/baeldung/poi/excel/multilinetext/MultilineText.java b/apache-poi/src/main/java/com/baeldung/poi/excel/multilinetext/MultilineText.java index 2e0cc5770e..231d7b8968 100644 --- a/apache-poi/src/main/java/com/baeldung/poi/excel/multilinetext/MultilineText.java +++ b/apache-poi/src/main/java/com/baeldung/poi/excel/multilinetext/MultilineText.java @@ -2,7 +2,6 @@ package com.baeldung.poi.excel.multilinetext; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.Row; public class MultilineText { public void formatMultilineText(Cell cell, int cellNumber) { diff --git a/aws-lambda/todo-reminder/ToDoFunction/pom.xml b/aws-lambda/todo-reminder/ToDoFunction/pom.xml index c17ff8bf15..c847907c9b 100644 --- a/aws-lambda/todo-reminder/ToDoFunction/pom.xml +++ b/aws-lambda/todo-reminder/ToDoFunction/pom.xml @@ -111,7 +111,7 @@ 11.2 5.0.1 1.2.0 - 3.3.0 + 4.1.0 3.19.0 5.8.1 diff --git a/aws/pom.xml b/aws/pom.xml index 7c363eb400..a57dd6690e 100644 --- a/aws/pom.xml +++ b/aws/pom.xml @@ -20,12 +20,6 @@ aws-java-sdk ${aws-java-sdk.version} - - org.mockito - mockito-core - ${mockito-core.version} - test - com.amazonaws aws-lambda-java-core @@ -111,7 +105,6 @@ 1.1.0 2.8.0 1.11.290 - 2.21.0 1.11.86 https://s3-us-west-2.amazonaws.com/dynamodb-local/release 1.10.L001 diff --git a/core-java-modules/core-java-11-2/README.md b/core-java-modules/core-java-11-2/README.md index 93920864cc..0a46fac19e 100644 --- a/core-java-modules/core-java-11-2/README.md +++ b/core-java-modules/core-java-11-2/README.md @@ -9,3 +9,4 @@ This module contains articles about Java 11 core features - [New Features in Java 11](https://www.baeldung.com/java-11-new-features) - [Getting the Java Version at Runtime](https://www.baeldung.com/get-java-version-runtime) - [Invoking a SOAP Web Service in Java](https://www.baeldung.com/java-soap-web-service) +- [Java HTTPS Client Certificate Authentication](https://www.baeldung.com/java-https-client-certificate-authentication) 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 f6ea266676..ed2dcaf695 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 @@ -2,12 +2,21 @@ package com.baeldung.java9.modules; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.Matchers.*; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.collection.IsEmptyCollection.empty; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import java.lang.module.ModuleDescriptor; -import java.lang.module.ModuleDescriptor.*; + +import java.lang.module.ModuleDescriptor.Builder; +import java.lang.module.ModuleDescriptor.Exports; +import java.lang.module.ModuleDescriptor.Opens; +import java.lang.module.ModuleDescriptor.Provides; +import java.lang.module.ModuleDescriptor.Requires; import java.sql.Date; import java.sql.Driver; import java.util.HashMap; @@ -16,7 +25,7 @@ import java.util.stream.Collectors; import org.junit.Before; import org.junit.Test; -import org.junit.Ignore; + public class ModuleAPIUnitTest { @@ -28,14 +37,9 @@ public class ModuleAPIUnitTest { @Before public void setUp() { - Class hashMapClass = HashMap.class; - javaBaseModule = hashMapClass.getModule(); - - Class dateClass = Date.class; - javaSqlModule = dateClass.getModule(); - - Class personClass = Person.class; - module = personClass.getModule(); + javaBaseModule = HashMap.class.getModule(); + javaSqlModule = Date.class.getModule(); + module = Person.class.getModule(); } @Test @@ -111,7 +115,6 @@ 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(); @@ -120,7 +123,7 @@ public class ModuleAPIUnitTest { .map(Provides::service) .collect(Collectors.toSet()); - assertThat(javaBaseProvidesService, contains("java.nio.file.spi.FileSystemProvider")); + assertThat(javaBaseProvidesService, hasItem("java.nio.file.spi.FileSystemProvider")); assertThat(javaSqlProvides, empty()); } @@ -132,15 +135,14 @@ public class ModuleAPIUnitTest { .map(Exports::source) .collect(Collectors.toSet()); - assertThat(javaSqlExportsSource, hasItems("java.sql", "javax.sql")); + assertThat(javaSqlExportsSource, hasItems("java.sql", "javax.sql")); } @Test public void givenModules_whenAccessingModuleDescriptorUses_thenUsesAreReturned() { - Set javaBaseUses = javaBaseModule.getDescriptor().uses(); Set javaSqlUses = javaSqlModule.getDescriptor().uses(); - assertThat(javaSqlUses, contains("java.sql.Driver")); + assertThat(javaSqlUses, hasItem("java.sql.Driver")); } @Test diff --git a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/iteration/MapIteration.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/iteration/MapIteration.java index b0c32e1487..2d8b17e5e7 100644 --- a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/iteration/MapIteration.java +++ b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/iteration/MapIteration.java @@ -17,22 +17,45 @@ public class MapIteration { System.out.println("Iterating Keys of Map Using KeySet"); mapIteration.iterateKeys(map); + System.out.println("Iterating Values of Map Using values()"); + mapIteration.iterateValues(map); + System.out.println("Iterating Map Using Entry Set"); mapIteration.iterateUsingEntrySet(map); System.out.println("Iterating Using Iterator and Map Entry"); mapIteration.iterateUsingIteratorAndEntry(map); + System.out.println("Iterating Using Iterator and KeySet"); + mapIteration.iterateUsingIteratorAndKeySet(map); + + System.out.println("Iterating values Using Iterator and values()"); + mapIteration.iterateUsingIteratorAndValues(map); + System.out.println("Iterating Using KeySet and For Each"); mapIteration.iterateUsingKeySetAndForeach(map); System.out.println("Iterating Map Using Lambda Expression"); mapIteration.iterateUsingLambda(map); + System.out.println("Iterating Map By Keys Using Lambda Expression"); + mapIteration.iterateByKeysUsingLambda(map); + + System.out.println("Iterating values Using Lambda Expression"); + mapIteration.iterateValuesUsingLambda(map); + System.out.println("Iterating Using Stream API"); mapIteration.iterateUsingStreamAPI(map); } + public void iterateUsingIteratorAndValues(Map map) { + Iterator iterator = map.values().iterator(); + while (iterator.hasNext()) { + Integer value = iterator.next(); + System.out.println("value :" + value); + } + } + public void iterateUsingEntrySet(Map map) { for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() + ":" + entry.getValue()); @@ -43,6 +66,14 @@ public class MapIteration { map.forEach((k, v) -> System.out.println((k + ":" + v))); } + public void iterateByKeysUsingLambda(Map map) { + map.keySet().forEach(k -> System.out.println((k + ":" + map.get(k)))); + } + + public void iterateValuesUsingLambda(Map map) { + map.values().forEach(v -> System.out.println(("value: " + v))); + } + public void iterateUsingIteratorAndEntry(Map map) { Iterator> iterator = map.entrySet() .iterator(); @@ -52,6 +83,14 @@ public class MapIteration { } } + public void iterateUsingIteratorAndKeySet(Map map) { + Iterator iterator = map.keySet().iterator(); + while (iterator.hasNext()) { + String key = iterator.next(); + System.out.println(key + ":" + map.get(key)); + } + } + public void iterateUsingKeySetAndForeach(Map map) { for (String key : map.keySet()) { System.out.println(key + ":" + map.get(key)); @@ -68,7 +107,12 @@ public class MapIteration { for (String key : map.keySet()) { System.out.println(key); } + } + public void iterateValues(Map map) { + for (Integer value : map.values()) { + System.out.println(value); + } } } \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/volatilekeywordthreadsafety/VolatileVarNotThreadSafe.java b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/volatilekeywordthreadsafety/VolatileVarNotThreadSafe.java new file mode 100644 index 0000000000..cf9b7fd20b --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/volatilekeywordthreadsafety/VolatileVarNotThreadSafe.java @@ -0,0 +1,47 @@ +package com.baeldung.volatilekeywordthreadsafety; + +import org.slf4j.LoggerFactory; +import org.slf4j.Logger; + +public class VolatileVarNotThreadSafe { + + private static final Logger LOG = LoggerFactory.getLogger(VolatileVarNotThreadSafe.class); + private static volatile int count = 0; + private static final int MAX_LIMIT = 1000; + + public static void increment() { + count++; + } + + public static int getCount() { + return count; + } + + public static void main(String[] args) throws InterruptedException { + Thread t1 = new Thread(new Runnable() { + @Override + public void run() { + for(int index=0; index 0); + } +} diff --git a/core-java-modules/core-java-exceptions-3/pom.xml b/core-java-modules/core-java-exceptions-3/pom.xml index 18dc52932e..455f769757 100644 --- a/core-java-modules/core-java-exceptions-3/pom.xml +++ b/core-java-modules/core-java-exceptions-3/pom.xml @@ -24,6 +24,22 @@ + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + + + + + + + + + 1.4.191 diff --git a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/unknownsourcestacktrace/Main.java b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/unknownsourcestacktrace/Main.java new file mode 100644 index 0000000000..0806a4bf80 --- /dev/null +++ b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/unknownsourcestacktrace/Main.java @@ -0,0 +1,25 @@ +package com.baeldung.unknownsourcestacktrace; + +import com.baeldung.unknownsourcestacktrace.dto.User; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class Main { + private static final Logger logger = LoggerFactory.getLogger(Main.class); + private static final int SHORT_NAME_LIMIT = 10; + + public static void main(String[] args) { + User user = new User(); + user.setName("Tom"); + + logger.info(getGreetingMessage(user.getName())); + } + + private static String getGreetingMessage(String name) { + return "Welcome " + getShortenedName(name) + "!"; + } + + private static String getShortenedName(String name) { + return name.substring(0, SHORT_NAME_LIMIT); + } +} diff --git a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/unknownsourcestacktrace/dto/User.java b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/unknownsourcestacktrace/dto/User.java new file mode 100644 index 0000000000..997631ea46 --- /dev/null +++ b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/unknownsourcestacktrace/dto/User.java @@ -0,0 +1,13 @@ +package com.baeldung.unknownsourcestacktrace.dto; + +public class User { + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/core-java-modules/core-java-io-4/README.md b/core-java-modules/core-java-io-4/README.md index c837e2bffc..0ce69237bb 100644 --- a/core-java-modules/core-java-io-4/README.md +++ b/core-java-modules/core-java-io-4/README.md @@ -5,4 +5,5 @@ This module contains articles about core Java input and output (IO) ### Relevant Articles: - [Java File Separator vs File Path Separator](https://www.baeldung.com/java-file-vs-file-path-separator) +- [Simulate touch Command in Java](https://www.baeldung.com/java-simulate-touch-command) - [[<-- Prev]](/core-java-modules/core-java-io-3) diff --git a/core-java-modules/core-java-io-4/src/main/java/com/baeldung/iostreams/InputSequenceHandler.java b/core-java-modules/core-java-io-4/src/main/java/com/baeldung/iostreams/InputSequenceHandler.java new file mode 100644 index 0000000000..7b09c3cc72 --- /dev/null +++ b/core-java-modules/core-java-io-4/src/main/java/com/baeldung/iostreams/InputSequenceHandler.java @@ -0,0 +1,45 @@ +package com.baeldung.iostreams; + +import java.io.*; +import java.util.List; +import java.util.Vector; + +public class InputSequenceHandler { + + private SequenceInputStream sequenceInputStream; + + public InputSequenceHandler(Vector inputStreams) { + sequenceInputStream = new SequenceInputStream(inputStreams.elements()); + } + + public InputSequenceHandler(String file1, String file2) throws FileNotFoundException { + sequenceInputStream = new SequenceInputStream(new FileInputStream(file1), new FileInputStream(file2)); + } + + public InputSequenceHandler(List fileNames) throws FileNotFoundException { + Vector inputStreams = new Vector<>(); + + for (String fileName: fileNames) { + inputStreams.add(new FileInputStream(fileName)); + } + sequenceInputStream = new SequenceInputStream(inputStreams.elements()); + } + + + public int read() throws IOException { + return sequenceInputStream.read(); + } + + public String readAsString() throws IOException { + StringBuilder stringBuilder = new StringBuilder(); + int readByte; + while ((readByte = sequenceInputStream.read()) != -1) { + stringBuilder.append((char) readByte); + } + return stringBuilder.toString(); + } + + public void close() throws IOException { + sequenceInputStream.close(); + } +} diff --git a/core-java-modules/core-java-io-4/src/test/java/com/baeldung/iostreams/InputSequenceUnitTest.java b/core-java-modules/core-java-io-4/src/test/java/com/baeldung/iostreams/InputSequenceUnitTest.java new file mode 100644 index 0000000000..5ee8f8542d --- /dev/null +++ b/core-java-modules/core-java-io-4/src/test/java/com/baeldung/iostreams/InputSequenceUnitTest.java @@ -0,0 +1,77 @@ +package com.baeldung.iostreams; + +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.SequenceInputStream; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.Vector; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class InputSequenceUnitTest { + + private static final String FILE1 = "iostreams/File1.txt"; + private static final String FILE2 = "iostreams/File2.txt"; + private static final String FILE3 = "iostreams/File3.txt"; + + private static final String FILE1_AND_FILE2_CONTENT = "InputSequenceUnitTest"; + private static final String ALL_FILES_CONTENT = "InputSequenceUnitTest is Success"; + + @Test + public void givenTwoFiles_readAsString() throws URISyntaxException, IOException { + String file1 = Paths.get(ClassLoader.getSystemResource(FILE1).toURI()).toString(); + String file2 = Paths.get(ClassLoader.getSystemResource(FILE2).toURI()).toString(); + InputSequenceHandler inputSequenceHandler = new InputSequenceHandler(file1, file2); + String stringValue = inputSequenceHandler.readAsString(); + inputSequenceHandler.close(); + assertEquals(stringValue, FILE1_AND_FILE2_CONTENT); + } + + @Test + public void givenFileList_readAsString() throws URISyntaxException, IOException { + List filesList = new ArrayList<>(); + filesList.add(Paths.get(ClassLoader.getSystemResource(FILE1).toURI()).toString()); + filesList.add(Paths.get(ClassLoader.getSystemResource(FILE2).toURI()).toString()); + filesList.add(Paths.get(ClassLoader.getSystemResource(FILE3).toURI()).toString()); + InputSequenceHandler inputSequenceHandler = new InputSequenceHandler(filesList); + String stringValue = inputSequenceHandler.readAsString(); + inputSequenceHandler.close(); + assertEquals(stringValue, ALL_FILES_CONTENT); + } + + @Test + public void givenVectorOfInputStreams_readAsString() throws IOException { + String[] strings = {"Testing", "Leads", "to", "failure", + "and", "failure", "leads", "to", "understanding"}; + Vector inputStreamVector = new Vector<>(); + StringBuilder stringBuilder = new StringBuilder(); + for (String string: strings) { + inputStreamVector.add(new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8))); + stringBuilder.append(string); + } + InputSequenceHandler inputSequenceHandler = new InputSequenceHandler(inputStreamVector); + String combinedString = inputSequenceHandler.readAsString(); + inputSequenceHandler.close(); + assertEquals(stringBuilder.toString(), combinedString); + } + + @Test + public void givenTwoStrings_readCombinedValue() throws IOException { + InputStream first = new ByteArrayInputStream("One".getBytes()); + InputStream second = new ByteArrayInputStream("Magic".getBytes()); + SequenceInputStream sequenceInputStream = new SequenceInputStream(first, second); + StringBuilder stringBuilder = new StringBuilder(); + int byteValue; + while ((byteValue = sequenceInputStream.read()) != -1) { + stringBuilder.append((char) byteValue); + } + assertEquals("OneMagic", stringBuilder.toString()); + } +} diff --git a/core-java-modules/core-java-io-4/src/test/resources/iostreams/File1.txt b/core-java-modules/core-java-io-4/src/test/resources/iostreams/File1.txt new file mode 100644 index 0000000000..fa17a296b5 --- /dev/null +++ b/core-java-modules/core-java-io-4/src/test/resources/iostreams/File1.txt @@ -0,0 +1 @@ +InputSequence \ No newline at end of file diff --git a/core-java-modules/core-java-io-4/src/test/resources/iostreams/File2.txt b/core-java-modules/core-java-io-4/src/test/resources/iostreams/File2.txt new file mode 100644 index 0000000000..0eb8734500 --- /dev/null +++ b/core-java-modules/core-java-io-4/src/test/resources/iostreams/File2.txt @@ -0,0 +1 @@ +UnitTest \ No newline at end of file diff --git a/core-java-modules/core-java-io-4/src/test/resources/iostreams/File3.txt b/core-java-modules/core-java-io-4/src/test/resources/iostreams/File3.txt new file mode 100644 index 0000000000..2f237d7c44 --- /dev/null +++ b/core-java-modules/core-java-io-4/src/test/resources/iostreams/File3.txt @@ -0,0 +1 @@ + is Success \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-constructors/README.md b/core-java-modules/core-java-lang-oop-constructors/README.md index d3d05d31bf..6083f1d0df 100644 --- a/core-java-modules/core-java-lang-oop-constructors/README.md +++ b/core-java-modules/core-java-lang-oop-constructors/README.md @@ -9,3 +9,4 @@ This module contains article about constructors in Java - [Private Constructors in Java](https://www.baeldung.com/java-private-constructors) - [Throwing Exceptions in Constructors](https://www.baeldung.com/java-constructors-exceptions) - [Constructors in Java Abstract Classes](https://www.baeldung.com/java-abstract-classes-constructors) +- [Java Implicit Super Constructor is Undefined Error](https://www.baeldung.com/java-implicit-super-constructor-is-undefined-error) diff --git a/core-java-modules/core-java-lang-oop-types-2/README.md b/core-java-modules/core-java-lang-oop-types-2/README.md index e1ce057035..c5e2a75f25 100644 --- a/core-java-modules/core-java-lang-oop-types-2/README.md +++ b/core-java-modules/core-java-lang-oop-types-2/README.md @@ -5,4 +5,4 @@ This module contains articles about types in Java ### Relevant Articles: - [Convert an Array of Primitives to an Array of Objects](https://www.baeldung.com/java-primitive-array-to-object-array) -- [Check if an Enum Value Exists in Java](https://www.baeldung.com/java-find-enum-by-criteria) +- [Check if an Enum Value Exists in Java](https://www.baeldung.com/java-search-enum-values) diff --git a/core-java-modules/core-java-lang-operators-2/pom.xml b/core-java-modules/core-java-lang-operators-2/pom.xml index 724dad95ee..c36250f1ae 100644 --- a/core-java-modules/core-java-lang-operators-2/pom.xml +++ b/core-java-modules/core-java-lang-operators-2/pom.xml @@ -15,6 +15,11 @@ + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + org.projectlombok lombok diff --git a/core-java-modules/core-java-lang-operators-2/src/test/java/com/baeldung/getbit/GetABitFromIntegralValueUnitTest.java b/core-java-modules/core-java-lang-operators-2/src/test/java/com/baeldung/getbit/GetABitFromIntegralValueUnitTest.java new file mode 100644 index 0000000000..61f9885a91 --- /dev/null +++ b/core-java-modules/core-java-lang-operators-2/src/test/java/com/baeldung/getbit/GetABitFromIntegralValueUnitTest.java @@ -0,0 +1,78 @@ +package com.baeldung.getbit; + +import org.junit.Test; + +import java.math.BigInteger; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class GetABitFromIntegralValueUnitTest { + @Test + public void givenAByte_whenUsingAHardCodedMask_thenGetBitValue() { + byte val1 = 0b0110_0100; + byte val2 = 0b0110_0010; + byte mask = 0b0000_0100; + boolean isSet1 = (val1 & mask) > 0; + boolean isSet2 = (val2 & mask) > 0; + + assertTrue(isSet1); + assertFalse(isSet2); + } + + @Test + public void givenAnIntValue_whenUsingACalculatedMask_thenGetBitValue() { + int val = 0b0110_0100; + int pos = 2; + int mask = 1 << pos; + boolean isSet = (val & mask) > 0; + + assertTrue(isSet); + } + + @Test + public void givenAnIntValue_whenUsingALeftShiftedValue1_thenGetBitValue() { + int val = 0b0110_0100; + int pos = 2; + boolean isSet = ((val << (31 - pos)) < 0); + + assertTrue(isSet); + } + + @Test + public void givenAnIntValue_whenUsingALeftShiftedValue2_thenGetBitValue() { + int val = 0b0110_0100; + int pos = 2; + boolean isSet = ((val << (~pos & 31)) < 0); + + assertTrue(isSet); + } + + @Test + public void givenAnIntValue_whenUsingALeftShiftedValue3_thenGetBitValue() { + int val = 0b0110_0100; + int pos = 2; + boolean isSet = ((val << ~pos) < 0); + + assertTrue(isSet); + } + + @Test + public void givenAnIntValue_whenUsingARightShiftedValue_thenGetBitValue() { + int val = 0b0110_0100; + int pos = 2; + boolean isSet = ((val >> pos) & 1) == 1; + + assertTrue(isSet); + } + + @Test + public void givenAnIntValue_whenUsingBigInteger_thenGetBitValue() { + int val = 0b0110_0100; + int pos = 2; + boolean isSet = BigInteger.valueOf(val).testBit(pos); + + assertTrue(isSet); + } + +} diff --git a/core-java-modules/core-java-serialization/src/main/java/com/baeldung/serialization/Customer.java b/core-java-modules/core-java-serialization/src/main/java/com/baeldung/serialization/Customer.java new file mode 100644 index 0000000000..51587b6c86 --- /dev/null +++ b/core-java-modules/core-java-serialization/src/main/java/com/baeldung/serialization/Customer.java @@ -0,0 +1,35 @@ +package com.baeldung.serialization; + +import java.io.Serializable; + +public class Customer implements Serializable { + private static final long serialVersionUID = 1L; + + private long id; + private volatile String name; + private Address address; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } +} diff --git a/core-java-modules/core-java-serialization/src/main/java/com/baeldung/util/MySerializationUtils.java b/core-java-modules/core-java-serialization/src/main/java/com/baeldung/util/MySerializationUtils.java index bfaa91313c..568a503476 100644 --- a/core-java-modules/core-java-serialization/src/main/java/com/baeldung/util/MySerializationUtils.java +++ b/core-java-modules/core-java-serialization/src/main/java/com/baeldung/util/MySerializationUtils.java @@ -29,7 +29,7 @@ public class MySerializationUtils { public static boolean isSerializable(Class it) { boolean serializable = it.isPrimitive() || it.isInterface() || Serializable.class.isAssignableFrom(it); if (!serializable) { - return serializable; + return false; } Field[] declaredFields = it.getDeclaredFields(); for (Field field : declaredFields) { @@ -37,8 +37,10 @@ public class MySerializationUtils { continue; } Class fieldType = field.getType(); - return isSerializable(fieldType); + if (!isSerializable(fieldType)) { + return false; + } } - return serializable; + return true; } } diff --git a/core-java-modules/core-java-serialization/src/test/java/com/baeldung/serialization/SerializationUnitTest.java b/core-java-modules/core-java-serialization/src/test/java/com/baeldung/serialization/SerializationUnitTest.java index a8c4009386..dde9beb2bb 100644 --- a/core-java-modules/core-java-serialization/src/test/java/com/baeldung/serialization/SerializationUnitTest.java +++ b/core-java-modules/core-java-serialization/src/test/java/com/baeldung/serialization/SerializationUnitTest.java @@ -107,5 +107,7 @@ public class SerializationUnitTest { assertFalse(MySerializationUtils.isSerializable(Address.class)); assertTrue(MySerializationUtils.isSerializable(Person.class)); assertTrue(MySerializationUtils.isSerializable(Integer.class)); + assertFalse(MySerializationUtils.isSerializable(Customer.class)); + assertTrue(MySerializationUtils.isSerializable(Employee.class)); } } diff --git a/core-java-modules/core-java-string-conversions-2/src/test/java/com/baeldung/stringtofloat/StringToFloatConversionUnitTest.java b/core-java-modules/core-java-string-conversions-2/src/test/java/com/baeldung/stringtofloat/StringToFloatConversionUnitTest.java new file mode 100644 index 0000000000..5780946bca --- /dev/null +++ b/core-java-modules/core-java-string-conversions-2/src/test/java/com/baeldung/stringtofloat/StringToFloatConversionUnitTest.java @@ -0,0 +1,187 @@ +package com.baeldung.stringtofloat; + +import org.junit.jupiter.api.Test; + +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.text.ParseException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class StringToFloatConversionUnitTest { + + @Test + public void givenFloat_whenStringConcatenation_thenReturnString() { + Float givenFloat = 1.25f; + + String result = givenFloat + ""; + + assertEquals("1.25", result); + } + + @Test + public void givenFloatPrimitive_whenStringConcatenation_thenReturnString() { + float givenFloat = 1.25f; + + String result = givenFloat + ""; + + assertEquals("1.25", result); + } + + @Test + public void givenNullFloat_whenStringConcatenation_thenReturnNullString() { + Float givenFloat = null; + + String result = givenFloat + ""; + + assertEquals("null", result); + } + + @Test + public void givenFloat_whenToString_thenReturnString() { + Float givenFloat = 1.25f; + + String result = Float.toString(givenFloat); + + assertEquals("1.25", result); + } + + @Test + public void givenNullFloat_whenToString_thenThrowNullPointerException() { + Float givenFloat = null; + + assertThrows(NullPointerException.class, () -> Float.toString(givenFloat)); + } + + @Test + public void givenFloat_whenValueOf_thenReturnString() { + Float givenFloat = 1.25f; + + String result = String.valueOf(givenFloat); + + assertEquals("1.25", result); + } + + @Test + public void givenNullFloat_whenValueOf_thenReturnNullString() { + Float givenFloat = null; + + String result = String.valueOf(givenFloat); + + assertEquals("null", result); + } + + @Test + public void givenFloat_whenDecimalFormat_thenReturnString() { + Float givenFloat = 1.25f; + + String result = new DecimalFormat("#.0000").format(givenFloat); + + assertEquals("1.2500", result); + } + + @Test + public void givenFloat_whenDecimalFormat_thenReturnWholeNumberString() { + Float givenFloat = 1.0025f; + + String result = new DecimalFormat("#.##").format(givenFloat); + + assertEquals("1", result); + } + + @Test + public void givenNullFloat_whenDecimalFormat_thenThrowIllegalArgumentException() { + Float givenFloat = null; + + assertThrows(IllegalArgumentException.class, () -> new DecimalFormat("#.000").format(givenFloat)); + } + + @Test + public void givenFloat_whenStringFormat_thenReturnString() { + Float givenFloat = 1.25f; + + String result = String.format("%f", givenFloat); + + assertEquals("1.250000", result); + } + + @Test + public void givenFloat_whenStringFormatWithDecimalLimit_thenReturnRoundedString() { + Float givenFloat = 1.256f; + + String result = String.format("%.2f", givenFloat); + + assertEquals("1.26", result); + } + + @Test + public void givenNullFloat_whenStringFormatWithDecimalLimit_thenReturnNullString() { + Float givenFloat = null; + + String result = String.format("%f", givenFloat); + + assertEquals("null", result); + } + + @Test + public void givenString_whenParseFloat_thenReturnFloat() { + String givenString = "1.25"; + + float result = Float.parseFloat(givenString); + + assertEquals(1.25f, result); + } + + @Test + public void givenNullString_whenParseFloat_thenThrowNullPointerException() { + String givenString = null; + + assertThrows(NullPointerException.class, () -> Float.parseFloat(givenString)); + } + + @Test + public void givenNonParsableString_whenParseFloat_thenThrowNumberFormatException() { + String givenString = "1.23x"; + + assertThrows(NumberFormatException.class, () -> Float.parseFloat(givenString)); + } + + @Test + public void givenString_whenValueOf_thenReturnFloat() { + String givenString = "1.25"; + + Float result = Float.valueOf(givenString); + + assertEquals(1.25f, result); + } + + @Test + public void givenNonParsableString_whenValueOf_thenThrowNumberFormatException() { + String givenString = "1.25x"; + + assertThrows(NumberFormatException.class, () -> Float.valueOf(givenString)); + } + + @Test + public void givenString_whenConstructor_thenReturnFloat() { + String givenString = "1.25"; + + Float result = new Float(givenString); + + assertEquals(1.25f, result); + } + + @Test + public void givenString_whenDecimalFormat_thenReturnFloat() throws ParseException { + String givenString = "1,250"; + DecimalFormatSymbols symbols = new DecimalFormatSymbols(); + symbols.setDecimalSeparator(','); + DecimalFormat decimalFormat = new DecimalFormat("#.000"); + decimalFormat.setDecimalFormatSymbols(symbols); + + Float result = decimalFormat.parse(givenString).floatValue(); + + assertEquals(1.25f, result); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-string-operations-4/src/main/java/com/baeldung/split/SplitStringEveryNthChar.java b/core-java-modules/core-java-string-operations-4/src/main/java/com/baeldung/split/SplitStringEveryNthChar.java new file mode 100644 index 0000000000..3ac31d012a --- /dev/null +++ b/core-java-modules/core-java-string-operations-4/src/main/java/com/baeldung/split/SplitStringEveryNthChar.java @@ -0,0 +1,51 @@ +package com.baeldung.split; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import com.google.common.base.Splitter; +import com.google.common.collect.ImmutableList; + +public class SplitStringEveryNthChar { + + public static List usingSplitMethod(String text, int n) { + String[] results = text.split("(?<=\\G.{" + n + "})"); + + return Arrays.asList(results); + } + + public static List usingSubstringMethod(String text, int n) { + List results = new ArrayList<>(); + int length = text.length(); + + for (int i = 0; i < length; i += n) { + results.add(text.substring(i, Math.min(length, i + n))); + } + + return results; + } + + public static List usingPattern(String text, int n) { + List results = new ArrayList<>(); + + Pattern pattern = Pattern.compile(".{1," + n + "}"); + Matcher matcher = pattern.matcher(text); + while (matcher.find()) { + String match = text.substring(matcher.start(), matcher.end()); + results.add(match); + } + + return results; + } + + public static List usingGuava(String text, int n) { + Iterable parts = Splitter.fixedLength(n) + .split(text); + + return ImmutableList.copyOf(parts); + } + +} diff --git a/core-java-modules/core-java-string-operations-4/src/test/java/com/baeldung/equalsvscontentequals/StringEqualsVsContentEqualsUnitTest.java b/core-java-modules/core-java-string-operations-4/src/test/java/com/baeldung/equalsvscontentequals/StringEqualsVsContentEqualsUnitTest.java new file mode 100644 index 0000000000..1b8c97d024 --- /dev/null +++ b/core-java-modules/core-java-string-operations-4/src/test/java/com/baeldung/equalsvscontentequals/StringEqualsVsContentEqualsUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.equalsvscontentequals; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class StringEqualsVsContentEqualsUnitTest { + + String actualString = "baeldung"; + String identicalString = "baeldung"; + CharSequence identicalStringInstance = "baeldung"; + CharSequence identicalStringBufferInstance = new StringBuffer("baeldung"); + + @Test + public void whenIdenticalTestString_thenBothTrue() { + assertTrue(actualString.equals(identicalString)); + assertTrue(actualString.contentEquals(identicalString)); + } + + @Test + public void whenSameContentButDifferentType_thenEqualsIsFalseAndContentEqualsIsTrue() { + assertTrue(actualString.equals(identicalStringInstance)); + assertTrue(actualString.contentEquals(identicalStringInstance)); + + assertFalse(actualString.equals(identicalStringBufferInstance)); + assertTrue(actualString.contentEquals(identicalStringBufferInstance)); + } + +} diff --git a/core-java-modules/core-java-string-operations-4/src/test/java/com/baeldung/split/SplitStringEveryNthCharUnitTest.java b/core-java-modules/core-java-string-operations-4/src/test/java/com/baeldung/split/SplitStringEveryNthCharUnitTest.java new file mode 100644 index 0000000000..03dcd5312e --- /dev/null +++ b/core-java-modules/core-java-string-operations-4/src/test/java/com/baeldung/split/SplitStringEveryNthCharUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.split; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.collection.IsIterableContainingInOrder.contains; + +import java.util.List; + +import org.junit.jupiter.api.Test; + +public class SplitStringEveryNthCharUnitTest { + + public static final String TEXT = "abcdefgh123456"; + + @Test + public void givenString_whenUsingSplit_thenSplit() { + List results = SplitStringEveryNthChar.usingSplitMethod(TEXT, 3); + + assertThat(results, contains("abc", "def", "gh1", "234", "56")); + } + + @Test + public void givenString_whenUsingSubstring_thenSplit() { + List results = SplitStringEveryNthChar.usingSubstringMethod(TEXT, 4); + + assertThat(results, contains("abcd", "efgh", "1234", "56")); + } + + @Test + public void givenString_whenUsingPattern_thenSplit() { + List results = SplitStringEveryNthChar.usingPattern(TEXT, 5); + + assertThat(results, contains("abcde", "fgh12", "3456")); + } + + @Test + public void givenString_whenUsingGuava_thenSplit() { + List results = SplitStringEveryNthChar.usingGuava(TEXT, 6); + + assertThat(results, contains("abcdef", "gh1234", "56")); + } + +} diff --git a/core-java-modules/core-java-time-measurements/pom.xml b/core-java-modules/core-java-time-measurements/pom.xml index 28959d0938..cb2fd9fb40 100644 --- a/core-java-modules/core-java-time-measurements/pom.xml +++ b/core-java-modules/core-java-time-measurements/pom.xml @@ -43,12 +43,6 @@ ${mockito-inline.version} test - - org.mockito - mockito-core - ${mockito-inline.version} - test - org.jmockit jmockit @@ -85,7 +79,7 @@ 1.18.22 1.8.9 1.44 - 4.0.0 + 4.1.0 \ No newline at end of file diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/javadoc/CodeSnippetFormatting.java b/core-java-modules/core-java/src/main/java/com/baeldung/javadoc/CodeSnippetFormatting.java new file mode 100644 index 0000000000..2bb9614e66 --- /dev/null +++ b/core-java-modules/core-java/src/main/java/com/baeldung/javadoc/CodeSnippetFormatting.java @@ -0,0 +1,154 @@ +package com.baeldung.javadoc; + +public class CodeSnippetFormatting { + + /** + * This is an example to show default behavior of code snippet formatting in Javadocs + * + * public class Application(){ + * + * } + * + */ + public void showCodeSnippetFormatting() { + // do nothing + } + + /** + * This is an example to show usage of HTML pre tag while code snippet formatting in Javadocs + * + *
+     * public class Application(){
+     *     List nums = new ArrayList<>();
+     * }
+     * 
+     * 
+ */ + public void showCodeSnippetFormattingUsingPRETag() { + // do nothing + } + + /** + * This is an example to show usage of HTML character entities while code snippet formatting in Javadocs + * + *
+     * public class Application(){
+     *     List<Integer> nums = new ArrayList<>();
+     * }
+     * 
+     * 
+ */ + public void showCodeSnippetFormattingUsingCharacterEntities() { + // do nothing + } + + /** + * This is an example to show usage of javadoc code tag while code snippet formatting in Javadocs + * + *
+     * 
+     * public class Application(){
+     *     {@code List nums = new ArrayList<>(); }
+     * }
+     *
+     * 
+ */ + public void showCodeSnippetFormattingUsingCodeTag() { + // do nothing + } + + /** + * This is an example to show issue faced while using annotations in Javadocs + * + *
+     * 
+     * public class Application(){
+     *            @Getter
+     *     {@code List nums = new ArrayList<>(); }
+     * }
+     *
+     * 
+ */ + public void showCodeSnippetFormattingIssueUsingCodeTag() { + // do nothing + } + + /** + * This is an example to show usage of javadoc code tag for handling '@' character + * + *
+     * 
+     * public class Application(){
+     *     {@code @Getter}
+     *     {@code List nums = new ArrayList<>(); }
+     * }
+     *
+     * 
+ */ + public void showCodeSnippetAnnotationFormattingUsingCodeTag() { + // do nothing + } + + + /** + * This is an example to show difference in javadoc literal and code tag + * + *

+ * + * {@literal @Getter} + * {@literal List nums = new ArrayList<>(); } + * + *
+ * {@code @Getter} + * {@code List nums = new ArrayList<>(); } + *

+ */ + public void showCodeSnippetCommentsFormattingUsingCodeAndLiteralTag() { + // do nothing + } + + /** + * This is an example to illustrate a basic jQuery code snippet embedded in documentation comments + *
+     * {@code }
+     * 
+ */ + public void showJSCodeSnippetUsingJavadoc() { + // do nothing + } + + /** + * This is an example to illustrate an HTML code snippet embedded in documentation comments + *
{@code
+     * 
+     * 
+     * 

Hello World!

+ * + * } + *
+ * + */ + public void showHTMLCodeSnippetUsingJavadoc() { + // do nothing + } + + /** + * This is an example to illustrate an HTML code snippet embedded in documentation comments + *
+     * 
+     * 
+     * 

Hello World!

+ * + * + *
+ * + */ + public void showHTMLCodeSnippetIssueUsingJavadoc() { + // do nothing + } + +} diff --git a/ddd/pom.xml b/ddd/pom.xml index cc5a173e85..3beb43bb35 100644 --- a/ddd/pom.xml +++ b/ddd/pom.xml @@ -86,11 +86,6 @@ spring-boot-starter-test test
- - org.mockito - mockito-core - test - de.flapdoodle.embed de.flapdoodle.embed.mongo diff --git a/ethereum/pom.xml b/ethereum/pom.xml index d2b05222c3..6c1a0e900f 100644 --- a/ethereum/pom.xml +++ b/ethereum/pom.xml @@ -191,7 +191,6 @@ 1.5.0-RELEASE 3.3.1 1.5.6.RELEASE - 2.21.0 2.4.0 2.0.4.RELEASE 3.1 diff --git a/jbang/hello.java b/jbang/hello.java new file mode 100755 index 0000000000..4a457b153b --- /dev/null +++ b/jbang/hello.java @@ -0,0 +1,11 @@ +///usr/bin/env jbang "$0" "$@" ; exit $? +// //DEPS + +import static java.lang.System.*; + +public class hello { + + public static void main(String... args) { + out.println("Hello World"); + } +} diff --git a/jbang/hellocli.java b/jbang/hellocli.java new file mode 100755 index 0000000000..8722cb27b8 --- /dev/null +++ b/jbang/hellocli.java @@ -0,0 +1,27 @@ +///usr/bin/env jbang "$0" "$@" ; exit $? +//DEPS info.picocli:picocli:4.5.0 + +import picocli.CommandLine; +import picocli.CommandLine.Command; +import picocli.CommandLine.Parameters; + +import java.util.concurrent.Callable; + +@Command(name = "hellocli", mixinStandardHelpOptions = true, version = "hellocli 0.1", + description = "hellocli made with jbang") +class hellocli implements Callable { + + @Parameters(index = "0", description = "The greeting to print", defaultValue = "World!") + private String greeting; + + public static void main(String... args) { + int exitCode = new CommandLine(new hellocli()).execute(args); + System.exit(exitCode); + } + + @Override + public Integer call() throws Exception { // your business logic goes here... + System.out.println("Hello " + greeting); + return 0; + } +} diff --git a/jbang/index.html b/jbang/index.html new file mode 100644 index 0000000000..bd34d026a3 --- /dev/null +++ b/jbang/index.html @@ -0,0 +1,18 @@ + + + + + + + JBang meets Quarkus + + + + + Go Say Hello! +

+ Powered by: + +

+ + \ No newline at end of file diff --git a/jbang/jbang-catalog.json b/jbang/jbang-catalog.json new file mode 100644 index 0000000000..2e30f0eb4a --- /dev/null +++ b/jbang/jbang-catalog.json @@ -0,0 +1,15 @@ +{ + "catalogs": {}, + "aliases": { + "hello": { + "script-ref": "hello.java" + }, + "hellocli": { + "script-ref": "hellocli.java" + }, + "jbangquarkus": { + "script-ref": "jbangquarkus.java" + } + }, + "templates": {} +} \ No newline at end of file diff --git a/jbang/jbangquarkus.java b/jbang/jbangquarkus.java new file mode 100755 index 0000000000..9e3cb5f69a --- /dev/null +++ b/jbang/jbangquarkus.java @@ -0,0 +1,21 @@ +///usr/bin/env jbang "$0" "$@" ; exit $? +// Update the Quarkus version to what you want here or run jbang with +// `-Dquarkus.version=` to override it. +//DEPS io.quarkus:quarkus-bom:${quarkus.version:2.4.0.Final}@pom +//DEPS io.quarkus:quarkus-resteasy +//JAVAC_OPTIONS -parameters + +//FILES META-INF/resources/index.html=index.html + +import javax.enterprise.context.ApplicationScoped; +import javax.ws.rs.GET; +import javax.ws.rs.Path; + +@Path("/hello") +@ApplicationScoped +public class jbangquarkus { + @GET + public String sayHello() { + return "Hello from Quarkus with jbang.dev"; + } +} diff --git a/jhipster/jhipster-microservice/gateway-app/src/test/java/com/gateway/web/rest/AccountResourceIntegrationTest.java b/jhipster/jhipster-microservice/gateway-app/src/test/java/com/gateway/web/rest/AccountResourceIntegrationTest.java index 607c69ebd1..6eab576561 100644 --- a/jhipster/jhipster-microservice/gateway-app/src/test/java/com/gateway/web/rest/AccountResourceIntegrationTest.java +++ b/jhipster/jhipster-microservice/gateway-app/src/test/java/com/gateway/web/rest/AccountResourceIntegrationTest.java @@ -26,7 +26,7 @@ import org.springframework.transaction.annotation.Transactional; import java.util.*; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Matchers.anyObject; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -64,7 +64,7 @@ public class AccountResourceIntegrationTest { @Before public void setup() { MockitoAnnotations.initMocks(this); - doNothing().when(mockMailService).sendActivationEmail(anyObject()); + doNothing().when(mockMailService).sendActivationEmail(any()); AccountResource accountResource = new AccountResource(userRepository, userService, mockMailService); diff --git a/jhipster/jhipster-monolithic/src/test/java/com/baeldung/web/rest/AccountResourceIntegrationTest.java b/jhipster/jhipster-monolithic/src/test/java/com/baeldung/web/rest/AccountResourceIntegrationTest.java index 9644ae488c..a6a104ba63 100644 --- a/jhipster/jhipster-monolithic/src/test/java/com/baeldung/web/rest/AccountResourceIntegrationTest.java +++ b/jhipster/jhipster-monolithic/src/test/java/com/baeldung/web/rest/AccountResourceIntegrationTest.java @@ -26,7 +26,7 @@ import org.springframework.transaction.annotation.Transactional; import java.util.*; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Matchers.anyObject; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -64,7 +64,7 @@ public class AccountResourceIntegrationTest { @Before public void setup() { MockitoAnnotations.initMocks(this); - doNothing().when(mockMailService).sendActivationEmail(anyObject()); + doNothing().when(mockMailService).sendActivationEmail(any()); AccountResource accountResource = new AccountResource(userRepository, userService, mockMailService); diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/util/JWTDecoderUtil.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/util/JWTDecoderUtil.java index 922d5c0ce5..0fbf7637dd 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/util/JWTDecoderUtil.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/util/JWTDecoderUtil.java @@ -11,7 +11,7 @@ import static io.jsonwebtoken.SignatureAlgorithm.HS256; public class JWTDecoderUtil { public static String decodeJWTToken(String token) { - Base64.Decoder decoder = Base64.getDecoder(); + Base64.Decoder decoder = Base64.getUrlDecoder(); String[] chunks = token.split("\\."); @@ -22,7 +22,7 @@ public class JWTDecoderUtil { } public static String decodeJWTToken(String token, String secretKey) throws Exception { - Base64.Decoder decoder = Base64.getDecoder(); + Base64.Decoder decoder = Base64.getUrlDecoder(); String[] chunks = token.split("\\."); diff --git a/linux-bash/command-line-arguments/src/main/bash/README.md b/linux-bash/command-line-arguments/src/main/bash/README.md index 27d89fff99..015d121617 100644 --- a/linux-bash/command-line-arguments/src/main/bash/README.md +++ b/linux-bash/command-line-arguments/src/main/bash/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [How to Use Command Line Arguments in a Bash Script](https://www.baeldung.com/linux/use-command-line-arguments-in-bash-script) +- [Concatenate Two Strings to Build a Complete Path in Linux](https://www.baeldung.com/linux/concatenate-strings-to-build-path) diff --git a/lombok/README.md b/lombok/README.md index b8073ff621..69b547f10c 100644 --- a/lombok/README.md +++ b/lombok/README.md @@ -15,3 +15,4 @@ This module contains articles about Project Lombok. - [Using Lombok’s @Accessors Annotation](https://www.baeldung.com/lombok-accessors) - [Omitting Getter or Setter in Lombok](https://www.baeldung.com/lombok-omit-getter-setter) - [Declaring Val and Var Variables in Lombok](https://www.baeldung.com/java-lombok-val-var) +- [Lombok Using @With Annotations](https://www.baeldung.com/lombok-with-annotations) diff --git a/lombok/lombok.config b/lombok/lombok.config new file mode 100644 index 0000000000..6f1b2fffea --- /dev/null +++ b/lombok/lombok.config @@ -0,0 +1,8 @@ +import lombok_feature.config + +config.stopBubbling = true +lombok.anyconstructor.addconstructorproperties=false +lombok.addLombokGeneratedAnnotation = true +lombok.addSuppressWarnings = false + + diff --git a/lombok/lombok_feature.config b/lombok/lombok_feature.config new file mode 100644 index 0000000000..01b41e1504 --- /dev/null +++ b/lombok/lombok_feature.config @@ -0,0 +1 @@ +lombok.experimental.flagUsage = warning \ No newline at end of file diff --git a/lombok/pom.xml b/lombok/pom.xml index 2daaf9f438..4a78c5422c 100644 --- a/lombok/pom.xml +++ b/lombok/pom.xml @@ -26,6 +26,11 @@ hibernate-jpa-2.1-api ${hibernate-jpa-2.1-api.version}
+ + org.jetbrains + annotations + 23.0.0 +
@@ -70,7 +75,7 @@ 1.0.0.Final - 1.18.10.0 + 1.18.20.0 \ No newline at end of file diff --git a/lombok/src/main/java/com/baeldung/lombok/configexamples/Account.java b/lombok/src/main/java/com/baeldung/lombok/configexamples/Account.java new file mode 100644 index 0000000000..2442f9fa4b --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/configexamples/Account.java @@ -0,0 +1,40 @@ +package com.baeldung.lombok.configexamples; + +import lombok.*; +import lombok.extern.java.Log; + +import java.util.logging.Level; + +import static java.lang.Math.abs; + +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +@Log +public class Account { + + @NonNull + private Double balance = 0.; + @NonNull + private String accountHolder = ""; + + public Account addBalance(double amount) { + if (amount < 0) { + throw new IllegalArgumentException("Can not add negative amount"); + } + + this.balance += amount; + return this; + } + + public Account withdraw(double amount) { + if (this.balance - abs(amount) < 0) { + domainLog.log(Level.INFO, String.format("Transaction denied for account holder: %s", this.accountHolder)); + throw new IllegalArgumentException(String.format("Not enough balance, you have %.2f", this.balance)); + } + + this.balance -= abs(amount); + return this; + } +} \ No newline at end of file diff --git a/lombok/src/main/java/com/baeldung/lombok/configexamples/TransactionLog.java b/lombok/src/main/java/com/baeldung/lombok/configexamples/TransactionLog.java new file mode 100644 index 0000000000..61a7a94a16 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/configexamples/TransactionLog.java @@ -0,0 +1,13 @@ +package com.baeldung.lombok.configexamples; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.experimental.Accessors; + +@AllArgsConstructor +@Getter +@Accessors(prefix = {"op"}) +public class TransactionLog { + double amount; + String description; +} diff --git a/lombok/src/main/java/com/baeldung/lombok/configexamples/lombok.config b/lombok/src/main/java/com/baeldung/lombok/configexamples/lombok.config new file mode 100644 index 0000000000..824d11a92f --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/configexamples/lombok.config @@ -0,0 +1,6 @@ +clear lombok.experimental.flagUsage + +lombok.anyconstructor.addconstructorproperties=true +lombok.addNullAnnotations = jetbrains +lombok.accessors.chain = true +lombok.log.fieldName = domainLog \ No newline at end of file diff --git a/lombok/src/test/java/com/baeldung/lombok/configexamples/AccountUnitTest.java b/lombok/src/test/java/com/baeldung/lombok/configexamples/AccountUnitTest.java new file mode 100644 index 0000000000..c030acf905 --- /dev/null +++ b/lombok/src/test/java/com/baeldung/lombok/configexamples/AccountUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.lombok.configexamples; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class AccountUnitTest { + + @Test + void should_initialize_account() { + Account myAccount = new Account() + .setBalance(2000.00) + .setAccountHolder("John Snow"); + + assertEquals(2000.00, myAccount.getBalance()); + assertEquals("John Snow", myAccount.getAccountHolder()); + } + + @Test + void should_throw_error_when_balance_becomes_negative() { + Account myAccount = new Account() + .setBalance(20.00) + .setAccountHolder("John Snow"); + + assertThrows(IllegalArgumentException.class, () -> myAccount.withdraw(100.00)); + } + + @Test + void should_throw_no_error_when_balance_becomes_zero() { + Account myAccount = new Account() + .setBalance(20.00) + .setAccountHolder("John Snow"); + + myAccount.withdraw(20.00); + + assertEquals(0.00, myAccount.getBalance()); + } + + @Test + void should_update_balance_properly() { + Account myAccount = new Account() + .setBalance(20.00) + .setAccountHolder("John Snow"); + + myAccount.withdraw(5.00).withdraw(10.00); + + assertEquals(5.00, myAccount.getBalance()); + } +} \ No newline at end of file diff --git a/metrics/pom.xml b/metrics/pom.xml index 6ac1761ca0..abdfb14dc6 100644 --- a/metrics/pom.xml +++ b/metrics/pom.xml @@ -78,7 +78,7 @@ com.netflix.spectator spectator-api - 0.132.0 + 1.0.11 @@ -92,4 +92,4 @@ 1.1.0 - \ No newline at end of file + diff --git a/metrics/src/test/java/com/baeldung/metrics/spectator/SpectatorMetersUnitTest.java b/metrics/src/test/java/com/baeldung/metrics/spectator/SpectatorMetersUnitTest.java new file mode 100644 index 0000000000..d27ffec6af --- /dev/null +++ b/metrics/src/test/java/com/baeldung/metrics/spectator/SpectatorMetersUnitTest.java @@ -0,0 +1,221 @@ +package com.baeldung.metrics.spectator; + +import com.netflix.spectator.api.*; +import com.netflix.spectator.api.patterns.LongTaskTimer; +import com.netflix.spectator.api.patterns.PolledMeter; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class SpectatorMetersUnitTest { + @Test + public void spectatorCounterTest(){ + + class MyListProcessor { + private final Counter insertCounter; + private final Counter removeCounter; + List requestList = new ArrayList(); + + private MyListProcessor(Registry registry){ + insertCounter = registry.counter("list.insert.count"); + removeCounter = registry.counter("list.remove.count"); + } + + private void addToList(String element){ + requestList.add(element); + insertCounter.increment(); + } + + private void removeFromList(){ + requestList.remove(0); + removeCounter.increment(); + } + } + + MyListProcessor myListProcessor = new MyListProcessor(new DefaultRegistry()); + myListProcessor.addToList("element1"); + myListProcessor.addToList("element2"); + myListProcessor.addToList("element3"); + myListProcessor.removeFromList(); + + assertEquals(3, myListProcessor.insertCounter.count()); + assertEquals(1, myListProcessor.removeCounter.count()); + + } + + @Test + public void spectatorTimerTest() throws Exception { + + class MyRequestProcessor { + private final Timer requestLatency; + + private MyRequestProcessor(Registry registry) { + requestLatency = registry.timer("app.request.latency"); + } + + private String processRequest(int input) throws Exception { + return requestLatency.record(() -> handleRequest(input)); + + } + + private String handleRequest(int input) throws InterruptedException { + try { + Thread.sleep(input); + return "Done"; + } catch (InterruptedException e) { + e.printStackTrace(); + throw e; + } + } + } + + MyRequestProcessor myRequestProcessor = new MyRequestProcessor(new DefaultRegistry()); + myRequestProcessor.processRequest(3000); + assertEquals(1, myRequestProcessor.requestLatency.count()); + assertThat(myRequestProcessor.requestLatency.totalTime()).isBetween(3000000000L, 4000000000L); + } + + @Test + public void spectatorLongTaskTimerTest() throws Exception { + + class MyRequestProcessor { + private final LongTaskTimer refreshDuration; + private long duration; + + private MyRequestProcessor(Registry registry) { + refreshDuration = LongTaskTimer.get(registry, registry.createId("metadata.refreshDuration")); + } + + private String processRequest(int input) throws Exception { + final long taskId = refreshDuration.start(); + try { + Thread.sleep(input); + return "Done"; + + } catch (InterruptedException e) { + e.printStackTrace(); + throw e; + } finally { + refreshDuration.stop(taskId); + } + + } + } + + MyRequestProcessor myRequestProcessor = new MyRequestProcessor(new DefaultRegistry()); + myRequestProcessor.processRequest(3000); + System.out.println(myRequestProcessor.refreshDuration.measure()); + System.out.println(myRequestProcessor.duration); + System.out.println(myRequestProcessor.refreshDuration.duration()); + } + + @Test + public void spectatorGauges_polledMeter_Test(){ + class MyList { + + private List list = new ArrayList();; + private AtomicInteger listSize = new AtomicInteger(0); + + private MyList(Registry registry) { + PolledMeter.using(registry) + .withName("list.size") + .monitorValue(listSize); + } + + private void addToList(String element){ + list.add(element); + listSize.incrementAndGet(); + } + private void removeFromList(){ + list.remove(0); + listSize.decrementAndGet(); + } + private int size(){ + return list.size(); + } + } + + MyList myList = new MyList(new DefaultRegistry()); + myList.addToList("element1"); + myList.addToList("element2"); + myList.addToList("element3"); + myList.addToList("element4"); + myList.removeFromList(); + assertEquals(myList.size(), myList.listSize.get()); + } + + @Test + public void spectatorGauges_ActiveGauges_Test(){ + class MyList { + + private List list = new ArrayList();; + private AtomicInteger listSize = new AtomicInteger(0); + private Gauge gauge; + + private MyList(Registry registry) { + gauge = registry.gauge("list.size"); + } + + private void addToList(String element){ + list.add(element); + listSize.incrementAndGet(); + gauge.set(listSize.get()); + } + private void removeFromList(){ + list.remove(0); + listSize.decrementAndGet(); + gauge.set(listSize.get()); + } + private int size(){ + return list.size(); + } + } + + MyList myList = new MyList(new DefaultRegistry()); + myList.addToList("element1"); + myList.addToList("element2"); + myList.addToList("element3"); + myList.addToList("element4"); + myList.removeFromList(); + assertEquals(3.0, myList.gauge.value()); + } + + @Test + public void spectatorDistributionSummaryTest() throws Exception { + + class MyRequestProcessor { + private final DistributionSummary distributionSummary; + + private MyRequestProcessor(Registry registry) { + distributionSummary = registry.distributionSummary("app.request.size"); + } + + private void processRequest(String input) throws Exception { + distributionSummary.record((long) input.length()); + handleRequest(); + } + + private void handleRequest() throws InterruptedException { + try { + Thread.sleep(3000); + return; + } catch (InterruptedException e) { + e.printStackTrace(); + throw e; + } + } + } + + MyRequestProcessor myRequestProcessor = new MyRequestProcessor(new DefaultRegistry()); + myRequestProcessor.processRequest("This is my sample input."); + assertEquals(1, myRequestProcessor.distributionSummary.count()); + assertEquals("This is my sample input.".length(), (int) myRequestProcessor.distributionSummary.totalAmount()); + } + +} + diff --git a/micronaut/README.md b/micronaut/README.md index 86ed705a9f..1ab31d0c0c 100644 --- a/micronaut/README.md +++ b/micronaut/README.md @@ -4,3 +4,4 @@ This module contains articles about Micronaut. ### Relevant Articles: - [Introduction to Micronaut Framework](https://www.baeldung.com/micronaut) +- [Micronaut vs. Spring Boot](https://www.baeldung.com/micronaut-vs-spring-boot) diff --git a/micronaut/src/main/java/com/baeldung/micronaut/vs/springboot/CompareApplication.java b/micronaut/src/main/java/com/baeldung/micronaut/vs/springboot/CompareApplication.java index 3375c302c2..4654526b28 100644 --- a/micronaut/src/main/java/com/baeldung/micronaut/vs/springboot/CompareApplication.java +++ b/micronaut/src/main/java/com/baeldung/micronaut/vs/springboot/CompareApplication.java @@ -4,6 +4,6 @@ import io.micronaut.runtime.Micronaut; public class CompareApplication { public static void main(String[] args) { - Micronaut.run(CompareApplication.class); + Micronaut.run(CompareApplication.class); } } diff --git a/micronaut/src/main/java/com/baeldung/micronaut/vs/springboot/client/ArithmeticClient.java b/micronaut/src/main/java/com/baeldung/micronaut/vs/springboot/client/ArithmeticClient.java index eb314d8a1d..4d5c752215 100644 --- a/micronaut/src/main/java/com/baeldung/micronaut/vs/springboot/client/ArithmeticClient.java +++ b/micronaut/src/main/java/com/baeldung/micronaut/vs/springboot/client/ArithmeticClient.java @@ -6,18 +6,18 @@ import io.micronaut.http.client.annotation.Client; @Client("/math") public interface ArithmeticClient { - @Get("/sum/{number1}/{number2}") - String sum(float number1, float number2); - - @Get("/subtract/{number1}/{number2}") - String subtract(float number1, float number2); - - @Get("/multiply/{number1}/{number2}") - String multiply(float number1, float number2); - - @Get("/divide/{number1}/{number2}") - String divide(float number1, float number2); - - @Get("/memory") - String memory(); + @Get("/sum/{number1}/{number2}") + String sum(float number1, float number2); + + @Get("/subtract/{number1}/{number2}") + String subtract(float number1, float number2); + + @Get("/multiply/{number1}/{number2}") + String multiply(float number1, float number2); + + @Get("/divide/{number1}/{number2}") + String divide(float number1, float number2); + + @Get("/memory") + String memory(); } diff --git a/micronaut/src/main/java/com/baeldung/micronaut/vs/springboot/client/ArithmeticClientImpl.java b/micronaut/src/main/java/com/baeldung/micronaut/vs/springboot/client/ArithmeticClientImpl.java index 1a9cad7981..6b7ae900be 100644 --- a/micronaut/src/main/java/com/baeldung/micronaut/vs/springboot/client/ArithmeticClientImpl.java +++ b/micronaut/src/main/java/com/baeldung/micronaut/vs/springboot/client/ArithmeticClientImpl.java @@ -8,34 +8,39 @@ import io.micronaut.http.client.annotation.Client; @Singleton public class ArithmeticClientImpl { - private RxHttpClient httpClient; + private RxHttpClient httpClient; - public ArithmeticClientImpl(@Client("/") RxHttpClient httpClient) { - this.httpClient = httpClient; + public ArithmeticClientImpl(@Client("/") RxHttpClient httpClient) { + this.httpClient = httpClient; } public String sum(float number1, float number2) { - HttpRequest req = HttpRequest.GET("/math/sum/" + number1 + "/" + number2); - return httpClient.retrieve(req).blockingFirst(); - } - + HttpRequest req = HttpRequest.GET("/math/sum/" + number1 + "/" + number2); + return httpClient.retrieve(req) + .blockingFirst(); + } + public String subtract(float number1, float number2) { - HttpRequest req = HttpRequest.GET("/math/subtract/" + number1 + "/" + number2); - return httpClient.retrieve(req).blockingFirst(); - } - + HttpRequest req = HttpRequest.GET("/math/subtract/" + number1 + "/" + number2); + return httpClient.retrieve(req) + .blockingFirst(); + } + public String multiply(float number1, float number2) { - HttpRequest req = HttpRequest.GET("/math/multiply/" + number1 + "/" + number2); - return httpClient.retrieve(req).blockingFirst(); - } - + HttpRequest req = HttpRequest.GET("/math/multiply/" + number1 + "/" + number2); + return httpClient.retrieve(req) + .blockingFirst(); + } + public String divide(float number1, float number2) { - HttpRequest req = HttpRequest.GET("/math/divide/" + number1 + "/" + number2); - return httpClient.retrieve(req).blockingFirst(); - } - + HttpRequest req = HttpRequest.GET("/math/divide/" + number1 + "/" + number2); + return httpClient.retrieve(req) + .blockingFirst(); + } + public String memory() { - HttpRequest req = HttpRequest.GET("/math/memory"); - return httpClient.retrieve(req).blockingFirst(); - } + HttpRequest req = HttpRequest.GET("/math/memory"); + return httpClient.retrieve(req) + .blockingFirst(); + } } diff --git a/micronaut/src/main/java/com/baeldung/micronaut/vs/springboot/controller/ArithmeticController.java b/micronaut/src/main/java/com/baeldung/micronaut/vs/springboot/controller/ArithmeticController.java index 930bdba029..5bc0e865e1 100644 --- a/micronaut/src/main/java/com/baeldung/micronaut/vs/springboot/controller/ArithmeticController.java +++ b/micronaut/src/main/java/com/baeldung/micronaut/vs/springboot/controller/ArithmeticController.java @@ -14,45 +14,45 @@ import io.micronaut.http.annotation.Get; public class ArithmeticController { @Inject private ArithmeticService arithmeticService; - + @Get("/sum/{number1}/{number2}") public float getSum(float number1, float number2) { - return arithmeticService.add(number1, number2); + return arithmeticService.add(number1, number2); } - + @Get("/subtract/{number1}/{number2}") public float getDifference(float number1, float number2) { - return arithmeticService.subtract(number1, number2); + return arithmeticService.subtract(number1, number2); } - + @Get("/multiply/{number1}/{number2}") public float getMultiplication(float number1, float number2) { - return arithmeticService.multiply(number1, number2); + return arithmeticService.multiply(number1, number2); } - + @Get("/divide/{number1}/{number2}") public float getDivision(float number1, float number2) { - return arithmeticService.divide(number1, number2); + return arithmeticService.divide(number1, number2); } - + @Get("/memory") public String getMemoryStatus() { - MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); - String memoryStats = ""; - - String init = String.format("Initial: %.2f GB \n", - (double)memoryBean.getHeapMemoryUsage().getInit() /1073741824); - String usedHeap = String.format("Used: %.2f GB \n", - (double)memoryBean.getHeapMemoryUsage().getUsed() /1073741824); - String maxHeap = String.format("Max: %.2f GB \n", - (double)memoryBean.getHeapMemoryUsage().getMax() /1073741824); - String committed = String.format("Committed: %.2f GB \n", - (double)memoryBean.getHeapMemoryUsage().getCommitted() /1073741824); - memoryStats += init; - memoryStats += usedHeap; - memoryStats += maxHeap; - memoryStats += committed; - - return memoryStats; + MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); + String memoryStats = ""; + + String init = String.format("Initial: %.2f GB \n", (double) memoryBean.getHeapMemoryUsage() + .getInit() / 1073741824); + String usedHeap = String.format("Used: %.2f GB \n", (double) memoryBean.getHeapMemoryUsage() + .getUsed() / 1073741824); + String maxHeap = String.format("Max: %.2f GB \n", (double) memoryBean.getHeapMemoryUsage() + .getMax() / 1073741824); + String committed = String.format("Committed: %.2f GB \n", (double) memoryBean.getHeapMemoryUsage() + .getCommitted() / 1073741824); + memoryStats += init; + memoryStats += usedHeap; + memoryStats += maxHeap; + memoryStats += committed; + + return memoryStats; } } diff --git a/micronaut/src/main/java/com/baeldung/micronaut/vs/springboot/service/ArithmeticService.java b/micronaut/src/main/java/com/baeldung/micronaut/vs/springboot/service/ArithmeticService.java index 663f96b3b5..e0e4680495 100644 --- a/micronaut/src/main/java/com/baeldung/micronaut/vs/springboot/service/ArithmeticService.java +++ b/micronaut/src/main/java/com/baeldung/micronaut/vs/springboot/service/ArithmeticService.java @@ -5,21 +5,21 @@ import javax.inject.Singleton; @Singleton public class ArithmeticService { public float add(float number1, float number2) { - return number1 + number2; + return number1 + number2; } - + public float subtract(float number1, float number2) { - return number1 - number2; + return number1 - number2; } - + public float multiply(float number1, float number2) { - return number1 * number2; + return number1 * number2; } - + public float divide(float number1, float number2) { - if (number2 == 0) { - throw new IllegalArgumentException("'number2' cannot be zero"); - } - return number1 / number2; + if (number2 == 0) { + throw new IllegalArgumentException("'number2' cannot be zero"); + } + return number1 / number2; } } diff --git a/micronaut/src/test/java/com/baeldung/micronaut/vs/springboot/ArithmeticClientUnitTest.java b/micronaut/src/test/java/com/baeldung/micronaut/vs/springboot/ArithmeticClientUnitTest.java index abf10d6f5e..9a1b095d22 100644 --- a/micronaut/src/test/java/com/baeldung/micronaut/vs/springboot/ArithmeticClientUnitTest.java +++ b/micronaut/src/test/java/com/baeldung/micronaut/vs/springboot/ArithmeticClientUnitTest.java @@ -13,49 +13,49 @@ import org.junit.Test; import com.baeldung.micronaut.vs.springboot.client.ArithmeticClientImpl; - public class ArithmeticClientUnitTest { - private EmbeddedServer server; + private EmbeddedServer server; private ArithmeticClientImpl client; @Before public void setup() { server = ApplicationContext.run(EmbeddedServer.class); - client = server.getApplicationContext().getBean(ArithmeticClientImpl.class); + client = server.getApplicationContext() + .getBean(ArithmeticClientImpl.class); } @After public void cleanup() { server.stop(); } - + @Test public void givenTwoNumbers_whenAdd_thenCorrectAnswerReturned() { - String expected = Float.valueOf(10 + 20).toString(); - assertEquals(expected, client.sum(10, 20)); + String expected = Float.valueOf(10 + 20).toString(); + assertEquals(expected, client.sum(10, 20)); } - + @Test public void givenTwoNumbers_whenSubtract_thenCorrectAnswerReturned() { - String expected = Float.valueOf(20 - 10).toString(); - assertEquals(expected, client.subtract(20, 10)); + String expected = Float.valueOf(20 - 10).toString(); + assertEquals(expected, client.subtract(20, 10)); } - + @Test public void givenTwoNumbers_whenMultiply_thenCorrectAnswerReturned() { - String expected = Float.valueOf(10 * 20).toString(); - assertEquals(expected, client.multiply(10, 20)); + String expected = Float.valueOf(10 * 20).toString(); + assertEquals(expected, client.multiply(10, 20)); } - + @Test public void givenTwoNumbers_whenDivide_thenCorrectAnswerReturned() { - String expected = Float.valueOf(30 / 10).toString(); - assertEquals(expected, client.divide(30, 10)); + String expected = Float.valueOf(30 / 10).toString(); + assertEquals(expected, client.divide(30, 10)); } - + @Test public void whenMemory_thenCorrectAnswerReturned() { - String expected = "Initial:"; - assertThat(client.memory(), containsString(expected)); + String expected = "Initial:"; + assertThat(client.memory(), containsString(expected)); } } diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index 42081fa115..109bf3b64f 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -88,10 +88,8 @@ 3.3.0 1.0.22.RELEASE - 2.5.4 + 2.6.1 1.9.1 - - 3.4.0 \ No newline at end of file diff --git a/patterns/clean-architecture/pom.xml b/patterns/clean-architecture/pom.xml index 7b244e4a5e..5938b0e596 100644 --- a/patterns/clean-architecture/pom.xml +++ b/patterns/clean-architecture/pom.xml @@ -40,11 +40,6 @@ - - org.mockito - mockito-core - test - org.junit.platform junit-platform-engine diff --git a/patterns/hexagonal-architecture/pom.xml b/patterns/hexagonal-architecture/pom.xml index 9dfc113d03..b18bd49aec 100644 --- a/patterns/hexagonal-architecture/pom.xml +++ b/patterns/hexagonal-architecture/pom.xml @@ -36,11 +36,6 @@ - - org.mockito - mockito-core - test - diff --git a/persistence-modules/hibernate-exceptions/README.md b/persistence-modules/hibernate-exceptions/README.md index 7c4f96280e..2e5a98c2f8 100644 --- a/persistence-modules/hibernate-exceptions/README.md +++ b/persistence-modules/hibernate-exceptions/README.md @@ -4,3 +4,4 @@ - [Hibernate Error “No Persistence Provider for EntityManager”](https://www.baeldung.com/hibernate-no-persistence-provider) - [TransactionRequiredException Error](https://www.baeldung.com/jpa-transaction-required-exception) - [Hibernate’s “Object References an Unsaved Transient Instance” Error](https://www.baeldung.com/hibernate-unsaved-transient-instance-error) +- [EntityNotFoundException in Hibernate](https://www.baeldung.com/hibernate-entitynotfoundexception) diff --git a/persistence-modules/hibernate-exceptions/pom.xml b/persistence-modules/hibernate-exceptions/pom.xml index 89e1f4ca7e..cabace17b9 100644 --- a/persistence-modules/hibernate-exceptions/pom.xml +++ b/persistence-modules/hibernate-exceptions/pom.xml @@ -29,6 +29,11 @@ jaxb-api ${jaxb.version} + + com.h2database + h2 + ${h2.version} + diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Category.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Category.java similarity index 100% rename from persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Category.java rename to persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Category.java diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Item.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Item.java similarity index 100% rename from persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Item.java rename to persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Item.java diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitynotfoundexception/User.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/User.java similarity index 100% rename from persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitynotfoundexception/User.java rename to persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/User.java diff --git a/persistence-modules/hibernate-exceptions/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-exceptions/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..4e83a57f48 --- /dev/null +++ b/persistence-modules/hibernate-exceptions/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,23 @@ + + + + EntityManager EntityNotFoundException persistence unit + com.baeldung.hibernate.entitynotfoundexception.Category + com.baeldung.hibernate.entitynotfoundexception.Item + com.baeldung.hibernate.entitynotfoundexception.User + true + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitynotfoundexception/EntityNotFoundExceptionIntegrationTest.java b/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/entitynotfoundexception/EntityNotFoundExceptionIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitynotfoundexception/EntityNotFoundExceptionIntegrationTest.java rename to persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/entitynotfoundexception/EntityNotFoundExceptionIntegrationTest.java diff --git a/persistence-modules/hibernate-jpa/README.md b/persistence-modules/hibernate-jpa/README.md index bb079b1705..5599140732 100644 --- a/persistence-modules/hibernate-jpa/README.md +++ b/persistence-modules/hibernate-jpa/README.md @@ -13,5 +13,4 @@ This module contains articles specific to use of Hibernate as a JPA implementati - [Enabling Transaction Locks in Spring Data JPA](https://www.baeldung.com/java-jpa-transaction-locks) - [JPA/Hibernate Persistence Context](https://www.baeldung.com/jpa-hibernate-persistence-context) - [Quick Guide to EntityManager#getReference()](https://www.baeldung.com/jpa-entity-manager-get-reference) -- [JPA Entities and the Serializable Interface](https://www.baeldung.com/jpa-entities-serializable) -- [EntityNotFoundException in Hibernate](https://www.baeldung.com/hibernate-entitynotfoundexception) +- [JPA Entities and the Serializable Interface](https://www.baeldung.com/jpa-entities-serializable) \ No newline at end of file diff --git a/persistence-modules/hibernate-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/persistence.xml index e895ac6ba9..12b41a4973 100644 --- a/persistence-modules/hibernate-jpa/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/persistence.xml @@ -120,21 +120,4 @@ - - EntityManager EntityNotFoundException persistence unit - com.baeldung.hibernate.entitynotfoundexception.Category - com.baeldung.hibernate.entitynotfoundexception.Item - com.baeldung.hibernate.entitynotfoundexception.User - true - - - - - - - - - - - \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/test/resources/application.properties b/persistence-modules/spring-boot-persistence-mongodb/src/test/resources/application.properties new file mode 100644 index 0000000000..ac8c1cf2d2 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/test/resources/application.properties @@ -0,0 +1 @@ +spring.mongodb.embedded.version=3.5.5 \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence/pom.xml b/persistence-modules/spring-boot-persistence/pom.xml index deac0c2a57..58b4dd8b9e 100644 --- a/persistence-modules/spring-boot-persistence/pom.xml +++ b/persistence-modules/spring-boot-persistence/pom.xml @@ -37,11 +37,6 @@ org.springframework.boot spring-boot-starter-test - - org.mockito - mockito-core - test - com.h2database h2 diff --git a/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/boot/ddd/event/AggregateEventsIntegrationTest.java b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/boot/ddd/event/AggregateEventsIntegrationTest.java index ac607063b2..5481d4644d 100644 --- a/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/boot/ddd/event/AggregateEventsIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/boot/ddd/event/AggregateEventsIntegrationTest.java @@ -3,7 +3,7 @@ package com.baeldung.boot.ddd.event; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.verifyNoInteractions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -51,7 +51,7 @@ class AggregateEventsIntegrationTest { .domainOperation(); // then - verifyZeroInteractions(eventHandler); + verifyNoInteractions(eventHandler); } @BeforeEach diff --git a/persistence-modules/spring-data-jpa-query-2/pom.xml b/persistence-modules/spring-data-jpa-query-2/pom.xml index 96585d9325..ebdbc2d2d9 100644 --- a/persistence-modules/spring-data-jpa-query-2/pom.xml +++ b/persistence-modules/spring-data-jpa-query-2/pom.xml @@ -30,10 +30,6 @@ com.fasterxml.jackson.core jackson-databind - - org.hibernate - hibernate-envers - javax.transaction jta @@ -56,12 +52,10 @@ org.hibernate hibernate-core - ${hibernate.version} org.hibernate hibernate-envers - ${hibernate.version} org.springframework @@ -84,8 +78,6 @@ 9.0.0.M26 1.1 21.0 - - 5.2.10.Final \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Bar.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Bar.java index c7f05254cc..0ceb2d5626 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Bar.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Bar.java @@ -1,8 +1,14 @@ package com.baeldung.persistence.model; -import java.io.Serializable; -import java.util.Date; -import java.util.Set; +import com.google.common.collect.Sets; +import org.hibernate.annotations.OrderBy; +import org.hibernate.envers.Audited; +import org.jboss.logging.Logger; +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedBy; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.CascadeType; import javax.persistence.Column; @@ -17,17 +23,9 @@ import javax.persistence.OneToMany; import javax.persistence.PrePersist; import javax.persistence.PreRemove; import javax.persistence.PreUpdate; - -import org.hibernate.annotations.OrderBy; -import org.hibernate.envers.Audited; -import org.jboss.logging.Logger; -import org.springframework.data.annotation.CreatedBy; -import org.springframework.data.annotation.CreatedDate; -import org.springframework.data.annotation.LastModifiedBy; -import org.springframework.data.annotation.LastModifiedDate; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; - -import com.google.common.collect.Sets; +import java.io.Serializable; +import java.util.Date; +import java.util.Set; @Entity @NamedQuery(name = "Bar.findAll", query = "SELECT b FROM Bar b") @@ -35,11 +33,11 @@ import com.google.common.collect.Sets; @EntityListeners(AuditingEntityListener.class) public class Bar implements Serializable { - private static Logger logger = Logger.getLogger(Bar.class); + private static final Logger LOGGER = Logger.getLogger(Bar.class); public enum OPERATION { INSERT, UPDATE, DELETE; - private String value; + private final String value; OPERATION() { value = toString(); @@ -70,7 +68,7 @@ public class Bar implements Serializable { private String name; @OneToMany(mappedBy = "bar", cascade = CascadeType.ALL, fetch = FetchType.LAZY) - @OrderBy(clause = "NAME DESC") + @OrderBy(clause = "name DESC") // @NotAudited private Set fooSet = Sets.newHashSet(); @@ -102,7 +100,6 @@ public class Bar implements Serializable { public Bar(final String name) { super(); - this.name = name; } @@ -202,35 +199,31 @@ public class Bar implements Serializable { return false; final Bar other = (Bar) obj; if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; + return other.name == null; + } else + return name.equals(other.name); } @Override public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Bar [name=").append(name).append("]"); - return builder.toString(); + return "Bar [name=" + name + "]"; } @PrePersist public void onPrePersist() { - logger.info("@PrePersist"); + LOGGER.info("@PrePersist"); audit(OPERATION.INSERT); } @PreUpdate public void onPreUpdate() { - logger.info("@PreUpdate"); + LOGGER.info("@PreUpdate"); audit(OPERATION.UPDATE); } @PreRemove public void onPreRemove() { - logger.info("@PreRemove"); + LOGGER.info("@PreRemove"); audit(OPERATION.DELETE); } diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Foo.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Foo.java index d36a1e58cf..eec15c5e56 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Foo.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/persistence/model/Foo.java @@ -16,7 +16,10 @@ import javax.persistence.NamedNativeQuery; import org.hibernate.envers.Audited; -@NamedNativeQueries({ @NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) }) +@NamedNativeQueries({ + @NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), + @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) +}) @Entity @Audited // @Proxy(lazy = false) @@ -89,17 +92,13 @@ public class Foo implements Serializable { 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; + return other.name == null; + } else + return name.equals(other.name); } @Override public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Foo [name=").append(name).append("]"); - return builder.toString(); + return "Foo [name=" + name + "]"; } } diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java index 444324dafc..09d44956b3 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java @@ -1,17 +1,14 @@ package com.baeldung.persistence.audit; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.List; - +import com.baeldung.persistence.model.Bar; +import com.baeldung.persistence.model.Foo; +import com.baeldung.persistence.service.IBarAuditableService; +import com.baeldung.persistence.service.IFooAuditableService; +import com.baeldung.spring.config.PersistenceTestConfig; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.junit.After; -import org.junit.AfterClass; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; @@ -23,28 +20,17 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; -import com.baeldung.persistence.model.Bar; -import com.baeldung.persistence.model.Foo; -import com.baeldung.persistence.service.IBarAuditableService; -import com.baeldung.persistence.service.IFooAuditableService; -import com.baeldung.spring.config.PersistenceTestConfig; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) public class EnversFooBarAuditIntegrationTest { - private static Logger logger = LoggerFactory.getLogger(EnversFooBarAuditIntegrationTest.class); - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - logger.info("setUpBeforeClass()"); - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - logger.info("tearDownAfterClass()"); - } + private static final Logger LOGGER = LoggerFactory.getLogger(EnversFooBarAuditIntegrationTest.class); @Autowired @Qualifier("fooHibernateAuditableService") @@ -60,15 +46,15 @@ public class EnversFooBarAuditIntegrationTest { private Session session; @Before - public void setUp() throws Exception { - logger.info("setUp()"); + public void setUp() { + LOGGER.info("setUp()"); makeRevisions(); session = sessionFactory.openSession(); } @After - public void tearDown() throws Exception { - logger.info("tearDown()"); + public void tearDown() { + LOGGER.info("tearDown()"); session.close(); } @@ -97,14 +83,12 @@ public class EnversFooBarAuditIntegrationTest { // REV #3: update BAR private void rev3(final Bar bar) { - bar.setName("BAR1"); barService.update(bar); } // REV #4: insert FOO3 & update BAR private void rev4(final Bar bar) { - final Foo foo3 = new Foo("FOO3"); foo3.setBar(bar); fooService.create(foo3); diff --git a/persistence-modules/spring-data-jpa-repo-2/README.md b/persistence-modules/spring-data-jpa-repo-2/README.md index 0a690fe5a5..be5bab1b56 100644 --- a/persistence-modules/spring-data-jpa-repo-2/README.md +++ b/persistence-modules/spring-data-jpa-repo-2/README.md @@ -3,4 +3,5 @@ ### Relevant Articles: - [Introduction to Spring Data JPA](https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) - [Performance Difference Between save() and saveAll() in Spring Data](https://www.baeldung.com/spring-data-save-saveall) -- More articles: [[<-- prev]](/spring-data-jpa-repo/) +- [LIKE Queries in Spring JPA Repositories](https://www.baeldung.com/spring-jpa-like-queries) +- More articles: [[<-- prev]](../spring-data-jpa-repo) diff --git a/persistence-modules/spring-data-jpa-repo-2/pom.xml b/persistence-modules/spring-data-jpa-repo-2/pom.xml index 12e178dd49..3109cb5192 100644 --- a/persistence-modules/spring-data-jpa-repo-2/pom.xml +++ b/persistence-modules/spring-data-jpa-repo-2/pom.xml @@ -14,7 +14,10 @@ - + + org.springframework.boot + spring-boot-starter-web + javax.persistence javax.persistence-api @@ -31,7 +34,7 @@ com.h2database h2 - + com.google.guava guava diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/like/LikeApplication.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/like/LikeApplication.java similarity index 85% rename from persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/like/LikeApplication.java rename to persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/like/LikeApplication.java index 311aea3001..26a5723977 100644 --- a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/like/LikeApplication.java +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/like/LikeApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.like; +package com.baeldung.spring.data.persistence.like; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/like/model/Movie.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/like/model/Movie.java similarity index 94% rename from persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/like/model/Movie.java rename to persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/like/model/Movie.java index bba8bd35c4..f500b61a8a 100644 --- a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/like/model/Movie.java +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/like/model/Movie.java @@ -1,4 +1,4 @@ -package com.baeldung.like.model; +package com.baeldung.spring.data.persistence.like.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/like/repository/MovieRepository.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/like/repository/MovieRepository.java similarity index 90% rename from persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/like/repository/MovieRepository.java rename to persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/like/repository/MovieRepository.java index 241bdd3306..57befb5943 100644 --- a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/like/repository/MovieRepository.java +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/like/repository/MovieRepository.java @@ -1,17 +1,16 @@ -package com.baeldung.like.repository; - -import java.util.List; +package com.baeldung.spring.data.persistence.like.repository; +import com.baeldung.spring.data.persistence.like.model.Movie; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; -import com.baeldung.like.model.Movie; +import java.util.List; public interface MovieRepository extends CrudRepository { List findByTitleContaining(String title); - + List findByTitleLike(String title); List findByTitleContains(String title); @@ -23,17 +22,17 @@ public interface MovieRepository extends CrudRepository { List findByDirectorEndsWith(String director); List findByTitleContainingIgnoreCase(String title); - + List findByRatingNotContaining(String rating); - + List findByDirectorNotLike(String director); - + @Query("SELECT m FROM Movie m WHERE m.title LIKE %:title%") List searchByTitleLike(@Param("title") String title); - + @Query("SELECT m FROM Movie m WHERE m.rating LIKE ?1%") List searchByRatingStartsWith(String rating); - + //Escaping works in SpringBoot >= 2.4.1 //@Query("SELECT m FROM Movie m WHERE m.director LIKE %?#{escape([0])} escape ?#{escapeCharacter()}") @Query("SELECT m FROM Movie m WHERE m.director LIKE %:#{[0]}") diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/resources/persistence.properties b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/persistence.properties index 339859a6e8..05cb7a13b9 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/main/resources/persistence.properties +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/persistence.properties @@ -2,7 +2,7 @@ jdbc.driverClassName=org.h2.Driver jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 jdbc.user=sa -jdbc.pass= +jdbc.pass=sa # hibernate.X hibernate.hbm2ddl.auto=create-drop diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/like/MovieRepositoryIntegrationTest.java similarity index 91% rename from persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java rename to persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/like/MovieRepositoryIntegrationTest.java index cc96b638ab..291926c127 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/like/MovieRepositoryIntegrationTest.java @@ -1,7 +1,7 @@ -package com.baeldung.like; +package com.baeldung.spring.data.persistence.like; -import com.baeldung.like.model.Movie; -import com.baeldung.like.repository.MovieRepository; +import com.baeldung.spring.data.persistence.like.model.Movie; +import com.baeldung.spring.data.persistence.like.repository.MovieRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -9,6 +9,7 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.junit4.SpringRunner; +import javax.sql.DataSource; import java.util.List; import static org.junit.Assert.assertEquals; @@ -22,11 +23,14 @@ public class MovieRepositoryIntegrationTest { @Autowired private MovieRepository movieRepository; + @Autowired + private DataSource dataSource; + @Test public void givenPartialTitle_WhenFindByTitleContaining_ThenMoviesShouldReturn() { List results = movieRepository.findByTitleContaining("in"); assertEquals(3, results.size()); - + results = movieRepository.findByTitleLike("%in%"); assertEquals(3, results.size()); @@ -60,25 +64,25 @@ public class MovieRepositoryIntegrationTest { List results = movieRepository.searchByTitleLike("in"); assertEquals(3, results.size()); } - + @Test public void givenStartOfRating_SearchFindByRatingStartsWith_ThenMoviesShouldReturn() { List results = movieRepository.searchByRatingStartsWith("PG"); assertEquals(6, results.size()); } - + @Test public void givenLastName_WhenSearchByDirectorEndsWith_ThenMoviesShouldReturn() { List results = movieRepository.searchByDirectorEndsWith("Burton"); assertEquals(1, results.size()); } - + @Test public void givenPartialRating_findByRatingNotContaining_ThenMoviesShouldReturn() { List results = movieRepository.findByRatingNotContaining("PG"); assertEquals(1, results.size()); } - + @Test public void givenPartialDirector_WhenFindByDirectorNotLike_ThenMoviesShouldReturn() { List results = movieRepository.findByDirectorNotLike("An%"); diff --git a/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/repository/FooServiceIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/repository/FooServiceIntegrationTest.java index 141844fa11..21990afb5e 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/repository/FooServiceIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/repository/FooServiceIntegrationTest.java @@ -7,6 +7,8 @@ import org.springframework.dao.DataIntegrityViolationException; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; +import javax.sql.DataSource; + @RunWith(SpringRunner.class) @ContextConfiguration(classes = PersistenceConfig.class) public class FooServiceIntegrationTest { @@ -14,6 +16,9 @@ public class FooServiceIntegrationTest { @Autowired private IFooService service; + @Autowired + private DataSource dataSource; + @Test(expected = DataIntegrityViolationException.class) public final void whenInvalidEntityIsCreated_thenDataException() { service.create(new Foo()); diff --git a/persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-cleanup.sql b/persistence-modules/spring-data-jpa-repo-2/src/test/resources/test-movie-cleanup.sql similarity index 100% rename from persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-cleanup.sql rename to persistence-modules/spring-data-jpa-repo-2/src/test/resources/test-movie-cleanup.sql diff --git a/persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-data.sql b/persistence-modules/spring-data-jpa-repo-2/src/test/resources/test-movie-data.sql similarity index 100% rename from persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-data.sql rename to persistence-modules/spring-data-jpa-repo-2/src/test/resources/test-movie-data.sql diff --git a/persistence-modules/spring-data-jpa-repo/README.md b/persistence-modules/spring-data-jpa-repo/README.md index 1a95340a97..43097a8c1e 100644 --- a/persistence-modules/spring-data-jpa-repo/README.md +++ b/persistence-modules/spring-data-jpa-repo/README.md @@ -5,13 +5,12 @@ This module contains articles about repositories in Spring Data JPA ### Relevant Articles: - [Case Insensitive Queries with Spring Data Repository](https://www.baeldung.com/spring-data-case-insensitive-queries) - [Derived Query Methods in Spring Data JPA Repositories](https://www.baeldung.com/spring-data-derived-queries) -- [LIKE Queries in Spring JPA Repositories](https://www.baeldung.com/spring-jpa-like-queries) - [Spring Data – CrudRepository save() Method](https://www.baeldung.com/spring-data-crud-repository-save) - [Spring Data JPA – Adding a Method in All Repositories](https://www.baeldung.com/spring-data-jpa-method-in-all-repositories) - [Spring Data Composable Repositories](https://www.baeldung.com/spring-data-composable-repositories) - [Spring Data JPA Repository Populators](https://www.baeldung.com/spring-data-jpa-repository-populators) - [Calling Stored Procedures from Spring Data JPA Repositories](https://www.baeldung.com/spring-data-jpa-stored-procedures) -- More articles: [[--> next]](/spring-data-jpa-repo-2/) +- More articles: [[--> next]](../spring-data-jpa-repo-2) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/persistence-modules/spring-data-mongodb-reactive/pom.xml b/persistence-modules/spring-data-mongodb-reactive/pom.xml index 2220418ac3..e7ecc49c2d 100644 --- a/persistence-modules/spring-data-mongodb-reactive/pom.xml +++ b/persistence-modules/spring-data-mongodb-reactive/pom.xml @@ -123,7 +123,7 @@ - 5.2.2.RELEASE + 5.3.13 4.5.2 3.3.1.RELEASE diff --git a/persistence-modules/spring-data-mongodb-reactive/src/main/resources/application.properties b/persistence-modules/spring-data-mongodb-reactive/src/main/resources/application.properties new file mode 100644 index 0000000000..ac8c1cf2d2 --- /dev/null +++ b/persistence-modules/spring-data-mongodb-reactive/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.mongodb.embedded.version=3.5.5 \ No newline at end of file diff --git a/persistence-modules/spring-mybatis/pom.xml b/persistence-modules/spring-mybatis/pom.xml index 4eda66e1a9..eb0ebd723d 100644 --- a/persistence-modules/spring-mybatis/pom.xml +++ b/persistence-modules/spring-mybatis/pom.xml @@ -78,11 +78,11 @@ - 5.3.8 + 5.3.13 - 2.0.2 + 2.0.6 3.5.2 - 2.1.0 + 2.2.0 1.4.197 diff --git a/persistence-modules/spring-persistence-simple/pom.xml b/persistence-modules/spring-persistence-simple/pom.xml index ec7c8bd3a0..d9b832df2d 100644 --- a/persistence-modules/spring-persistence-simple/pom.xml +++ b/persistence-modules/spring-persistence-simple/pom.xml @@ -76,12 +76,6 @@ test ${spring-boot-starter.version} - - org.mockito - mockito-core - ${mockito.version} - test - @@ -94,8 +88,6 @@ 2.2.7.RELEASE 0.23.0 - - 3.3.3 \ No newline at end of file diff --git a/pom.xml b/pom.xml index 1560e99d98..7e7ddd758c 100644 --- a/pom.xml +++ b/pom.xml @@ -652,6 +652,7 @@ spring-data-rest-querydsl spring-di spring-di-2 + spring-di-3 spring-drools spring-ejb @@ -1416,7 +1417,7 @@ 3.21.0 2.2 1.3 - 3.3.0 + 4.1.0 1.11.20 diff --git a/quarkus/pom.xml b/quarkus/pom.xml index 22f5e0e991..9342b1a4af 100644 --- a/quarkus/pom.xml +++ b/quarkus/pom.xml @@ -37,6 +37,12 @@ pom import + + org.mockito + mockito-core + ${mockito.version} + test + @@ -94,6 +100,11 @@ rest-assured test + + org.mockito + mockito-core + test + @@ -172,6 +183,7 @@ 1.7.0.Final 1.18.6 + 3.3.0 \ No newline at end of file diff --git a/spring-5-reactive-client/pom.xml b/spring-5-reactive-client/pom.xml index f665d5c9a6..5fb41a7d6b 100644 --- a/spring-5-reactive-client/pom.xml +++ b/spring-5-reactive-client/pom.xml @@ -94,7 +94,7 @@ com.github.tomakehurst wiremock-standalone - 2.26.0 + ${wiremock-standalone.version} test @@ -110,13 +110,13 @@ org.mockito mockito-junit-jupiter - 2.23.0 + ${mockito.version} test io.projectreactor reactor-test - 3.2.10.RELEASE + ${reactor-test.version} test @@ -192,5 +192,7 @@ 1.0 1.1.6 4.0.1 + 3.2.10.RELEASE + 2.26.0 \ No newline at end of file diff --git a/spring-aop/pom.xml b/spring-aop/pom.xml index cbec4ef35b..0d48c479ca 100644 --- a/spring-aop/pom.xml +++ b/spring-aop/pom.xml @@ -32,11 +32,6 @@ spring-boot-starter-test test - - org.mockito - mockito-core - test - diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index b0a9f41acc..29da696494 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -19,6 +19,7 @@ spring-boot spring-boot-1 + spring-boot-2 spring-boot-admin spring-boot-angular spring-boot-annotations @@ -70,6 +71,7 @@ spring-boot-swagger spring-boot-swagger-jwt spring-boot-testing + spring-boot-testing-2 spring-boot-vue spring-boot-actuator spring-boot-data-2 diff --git a/spring-boot-modules/spring-boot-2/.mvn/wrapper/MavenWrapperDownloader.java b/spring-boot-modules/spring-boot-2/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000000..b901097f2d --- /dev/null +++ b/spring-boot-modules/spring-boot-2/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,117 @@ +/* + * 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 + * + * http://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/spring-boot-modules/spring-boot-2/.mvn/wrapper/maven-wrapper.properties b/spring-boot-modules/spring-boot-2/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000..642d572ce9 --- /dev/null +++ b/spring-boot-modules/spring-boot-2/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-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/spring-boot-modules/spring-boot-2/README.md b/spring-boot-modules/spring-boot-2/README.md new file mode 100644 index 0000000000..7ea97f80c5 --- /dev/null +++ b/spring-boot-modules/spring-boot-2/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Speed up Spring Boot Startup Time](https://www.baeldung.com/spring-boot-startup-speed) diff --git a/spring-boot-modules/spring-boot-2/mvnw b/spring-boot-modules/spring-boot-2/mvnw new file mode 100644 index 0000000000..41c0f0c23d --- /dev/null +++ b/spring-boot-modules/spring-boot-2/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 +# +# http://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/spring-boot-modules/spring-boot-2/mvnw.cmd b/spring-boot-modules/spring-boot-2/mvnw.cmd new file mode 100644 index 0000000000..86115719e5 --- /dev/null +++ b/spring-boot-modules/spring-boot-2/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 http://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/spring-boot-modules/spring-boot-2/pom.xml b/spring-boot-modules/spring-boot-2/pom.xml new file mode 100644 index 0000000000..f3973605ad --- /dev/null +++ b/spring-boot-modules/spring-boot-2/pom.xml @@ -0,0 +1,69 @@ + + + 4.0.0 + spring-boot-2 + jar + Module for Spring Boot version 2.x + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + 2.14.1 + 11 + 11 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-security + + + org.apache.logging.log4j + log4j-core + ${log4j2.version} + + + org.springframework + spring-context-indexer + 5.3.13 + true + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + springStartupApp + com.baeldung.springStart.SpringStartApplication + + + + + repackage + + + + + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-2/src/main/java/com/baeldung/springStart/SpringStartApplication.java b/spring-boot-modules/spring-boot-2/src/main/java/com/baeldung/springStart/SpringStartApplication.java new file mode 100644 index 0000000000..f149a4c67e --- /dev/null +++ b/spring-boot-modules/spring-boot-2/src/main/java/com/baeldung/springStart/SpringStartApplication.java @@ -0,0 +1,19 @@ +package com.baeldung.springStart; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.actuate.autoconfigure.metrics.JvmMetricsAutoConfiguration; +import org.springframework.boot.actuate.autoconfigure.metrics.LogbackMetricsAutoConfiguration; +import org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; + +@SpringBootApplication +//@EnableAutoConfiguration(exclude = {JacksonAutoConfiguration.class, JvmMetricsAutoConfiguration.class, +// LogbackMetricsAutoConfiguration.class, MetricsAutoConfiguration.class}) +public class SpringStartApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringStartApplication.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-2/src/main/resources/application.properties b/spring-boot-modules/spring-boot-2/src/main/resources/application.properties new file mode 100644 index 0000000000..4a5f46a7b1 --- /dev/null +++ b/spring-boot-modules/spring-boot-2/src/main/resources/application.properties @@ -0,0 +1,3 @@ +spring.main.lazy-initialization=true +logging.level.org.springframework.boot.autoconfigure=DEBUG +spring.jmx.enabled=false \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-annotations-2/README.md b/spring-boot-modules/spring-boot-annotations-2/README.md index 991c771986..ec72620b37 100644 --- a/spring-boot-modules/spring-boot-annotations-2/README.md +++ b/spring-boot-modules/spring-boot-annotations-2/README.md @@ -5,4 +5,5 @@ This module contains articles about Spring Boot annotations ### Relevant Articles: - [Spring Conditional Annotations](https://www.baeldung.com/spring-conditional-annotations) +- [Guide to @SpringBootConfiguration in Spring Boot](https://www.baeldung.com/springbootconfiguration-annotation) - More articles: [[<-- prev]](/spring-boot-modules/spring-boot-annotations) diff --git a/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/Application.java b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/springbootconfiguration/Application.java similarity index 100% rename from spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/Application.java rename to spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/springbootconfiguration/Application.java diff --git a/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonService.java b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/springbootconfiguration/PersonService.java similarity index 100% rename from spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonService.java rename to spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/springbootconfiguration/PersonService.java diff --git a/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonServiceImpl.java b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/springbootconfiguration/PersonServiceImpl.java similarity index 100% rename from spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonServiceImpl.java rename to spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/springbootconfiguration/PersonServiceImpl.java diff --git a/spring-boot-modules/spring-boot-annotations-2/src/main/resources/application.properties b/spring-boot-modules/spring-boot-annotations-2/src/main/resources/application.properties new file mode 100644 index 0000000000..ba17f62cd0 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations-2/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.main.web-application-type=none \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/springbootconfiguration/SpringContextTest.java b/spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/springbootconfiguration/SpringContextTest.java new file mode 100644 index 0000000000..11bbad8bb2 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/springbootconfiguration/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung.springbootconfiguration; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void contextLoads() { + } +} diff --git a/spring-boot-modules/spring-boot-artifacts-2/README.md b/spring-boot-modules/spring-boot-artifacts-2/README.md index 35f9cfab32..5d0a6ebcd1 100644 --- a/spring-boot-modules/spring-boot-artifacts-2/README.md +++ b/spring-boot-modules/spring-boot-artifacts-2/README.md @@ -5,3 +5,5 @@ This module contains articles about configuring the Spring Boot build process 2. ### Relevant Articles: - [Difference Between spring-boot:repackage and Maven package](https://www.baeldung.com/spring-boot-repackage-vs-mvn-package) +- [Intro to Spring Boot Starters](https://www.baeldung.com/spring-boot-starters) +- More articles: [[<-- prev]](/spring-boot-modules/spring-boot-artifacts) diff --git a/spring-boot-modules/spring-boot-artifacts/README.md b/spring-boot-modules/spring-boot-artifacts/README.md index cb77cfad4d..ffe044c51b 100644 --- a/spring-boot-modules/spring-boot-artifacts/README.md +++ b/spring-boot-modules/spring-boot-artifacts/README.md @@ -5,9 +5,9 @@ This module contains articles about configuring the Spring Boot build process. ### Relevant Articles: - [Spring Boot Dependency Management with a Custom Parent](https://www.baeldung.com/spring-boot-dependency-management-custom-parent) - [Create a Fat Jar App with Spring Boot](https://www.baeldung.com/deployable-fat-jar-spring-boot) - - [Intro to Spring Boot Starters](https://www.baeldung.com/spring-boot-starters) - [Introduction to WebJars](https://www.baeldung.com/maven-webjars) - [A Quick Guide to Maven Wrapper](https://www.baeldung.com/maven-wrapper) - [Running a Spring Boot App with Maven vs an Executable War/Jar](https://www.baeldung.com/spring-boot-run-maven-vs-executable-jar) - [Injecting Git Information Into Spring](https://www.baeldung.com/spring-git-information) - [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar) + - More articles: [[next -->]](/spring-boot-modules/spring-boot-artifacts-2) diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java index 42da61fe14..2bc1b8a55c 100644 --- a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java @@ -15,6 +15,7 @@ public class FilterConfig { registrationBean.setFilter(new RequestResponseLoggingFilter()); registrationBean.addUrlPatterns("/users/*"); + registrationBean.setOrder(2); return registrationBean; diff --git a/spring-boot-modules/spring-boot-bootstrap/README.md b/spring-boot-modules/spring-boot-bootstrap/README.md index 02ec52f755..5787f3262d 100644 --- a/spring-boot-modules/spring-boot-bootstrap/README.md +++ b/spring-boot-modules/spring-boot-bootstrap/README.md @@ -9,5 +9,4 @@ This module contains articles about bootstrapping Spring Boot applications. - [Deploy a Spring Boot Application to Google App Engine](https://www.baeldung.com/spring-boot-google-app-engine) - [Deploy a Spring Boot Application to OpenShift](https://www.baeldung.com/spring-boot-deploy-openshift) - [Deploy a Spring Boot Application to AWS Beanstalk](https://www.baeldung.com/spring-boot-deploy-aws-beanstalk) -- [Guide to @SpringBootConfiguration in Spring Boot](https://www.baeldung.com/springbootconfiguration-annotation) - [Implement Health Checks in OpenShift](https://www.baeldung.com/ops/openshift-health-checks) diff --git a/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java b/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java index 57eec935f6..956892729e 100644 --- a/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java +++ b/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java @@ -14,6 +14,6 @@ public class MyStompSessionHandlerIntegrationTest { MyStompSessionHandler sessionHandler = new MyStompSessionHandler(); sessionHandler.afterConnected(mockSession, mockHeader); Mockito.verify(mockSession).subscribe("/topic/messages", sessionHandler); - Mockito.verify(mockSession).send(Mockito.anyString(), Mockito.anyObject()); + Mockito.verify(mockSession).send(Mockito.anyString(), Mockito.any()); } } diff --git a/spring-boot-modules/spring-boot-crud/pom.xml b/spring-boot-modules/spring-boot-crud/pom.xml index 0a8e57be17..7acaa49e87 100644 --- a/spring-boot-modules/spring-boot-crud/pom.xml +++ b/spring-boot-modules/spring-boot-crud/pom.xml @@ -33,11 +33,6 @@ org.springframework.boot spring-boot-starter-test - - org.mockito - mockito-core - test - com.h2database h2 diff --git a/spring-boot-modules/spring-boot-environment/pom.xml b/spring-boot-modules/spring-boot-environment/pom.xml index 2cda396a9b..d63b291ea4 100644 --- a/spring-boot-modules/spring-boot-environment/pom.xml +++ b/spring-boot-modules/spring-boot-environment/pom.xml @@ -140,7 +140,7 @@ 18.0 3.1.7 4.5.8 - 2020.0.0 + 2021.0.0 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/prefix/PrefixController.java b/spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/prefix/PrefixController.java index 00b728c7ae..dc6b0cd513 100644 --- a/spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/prefix/PrefixController.java +++ b/spring-boot-modules/spring-boot-environment/src/main/java/com/baeldung/prefix/PrefixController.java @@ -1,6 +1,7 @@ package com.baeldung.prefix; -import org.springframework.beans.factory.annotation.Value; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @@ -8,12 +9,12 @@ import org.springframework.web.bind.annotation.GetMapping; @Controller public class PrefixController { - @Value(value = "${server.port}") - private int serverPort; + @Autowired + private Environment environment; @GetMapping("/prefix") public String getServerPortInfo(final Model model) { - model.addAttribute("serverPort", serverPort); + model.addAttribute("serverPort", environment.getProperty("server.port")); return "prefix"; } } diff --git a/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/JobRunrSpringBootApp.java b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/JobRunrSpringBootApp.java index 061dba15bf..3821332132 100644 --- a/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/JobRunrSpringBootApp.java +++ b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/JobRunrSpringBootApp.java @@ -1,15 +1,11 @@ package com.baeldung; import com.baeldung.jobrunr.service.SampleJobService; -import org.jobrunr.jobs.mappers.JobMapper; import org.jobrunr.scheduling.JobScheduler; import org.jobrunr.scheduling.cron.Cron; -import org.jobrunr.storage.InMemoryStorageProvider; -import org.jobrunr.storage.StorageProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; import javax.annotation.PostConstruct; @@ -23,13 +19,6 @@ public class JobRunrSpringBootApp { SpringApplication.run(JobRunrSpringBootApp.class, args); } - @Bean - public StorageProvider storageProvider(JobMapper jobMapper) { - InMemoryStorageProvider storageProvider = new InMemoryStorageProvider(); - storageProvider.setJobMapper(jobMapper); - return storageProvider; - } - @PostConstruct public void scheduleRecurrently() { jobScheduler.scheduleRecurrently(Cron.every5minutes(), x -> x.executeSampleJob("a recurring job")); diff --git a/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/config/StorageProviderConfig.java b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/config/StorageProviderConfig.java new file mode 100644 index 0000000000..e4b8cf12d7 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/config/StorageProviderConfig.java @@ -0,0 +1,18 @@ +package com.baeldung.config; + +import org.jobrunr.jobs.mappers.JobMapper; +import org.jobrunr.storage.InMemoryStorageProvider; +import org.jobrunr.storage.StorageProvider; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class StorageProviderConfig { + + @Bean + public StorageProvider storageProvider(JobMapper jobMapper) { + InMemoryStorageProvider storageProvider = new InMemoryStorageProvider(); + storageProvider.setJobMapper(jobMapper); + return storageProvider; + } +} diff --git a/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/micronaut/vs/springboot/CompareApplication.java b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/micronaut/vs/springboot/CompareApplication.java index 5bf1e0a57c..14908ae108 100644 --- a/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/micronaut/vs/springboot/CompareApplication.java +++ b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/micronaut/vs/springboot/CompareApplication.java @@ -7,7 +7,7 @@ import org.springframework.context.annotation.ComponentScan; @EnableAutoConfiguration @ComponentScan("com.baeldung.micronaut.vs.springboot") public class CompareApplication { - public static void main(final String[] args) { + public static void main(final String[] args) { SpringApplication.run(CompareApplication.class, args); } } diff --git a/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/micronaut/vs/springboot/controller/ArithmeticController.java b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/micronaut/vs/springboot/controller/ArithmeticController.java index 2bb8046f66..54b2680dca 100644 --- a/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/micronaut/vs/springboot/controller/ArithmeticController.java +++ b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/micronaut/vs/springboot/controller/ArithmeticController.java @@ -42,7 +42,8 @@ public class ArithmeticController { MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); String memoryStats = ""; - String init = String.format("Initial: %.2f GB \n", + String init = String.format( + "Initial: %.2f GB \n", (double)memoryBean.getHeapMemoryUsage().getInit() /1073741824); String usedHeap = String.format("Used: %.2f GB \n", (double)memoryBean.getHeapMemoryUsage().getUsed() /1073741824); diff --git a/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/micronaut/vs/springboot/service/ArithmeticService.java b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/micronaut/vs/springboot/service/ArithmeticService.java index 485cfd4d8c..0ed84b63c5 100644 --- a/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/micronaut/vs/springboot/service/ArithmeticService.java +++ b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/micronaut/vs/springboot/service/ArithmeticService.java @@ -4,22 +4,22 @@ import org.springframework.stereotype.Service; @Service public class ArithmeticService { - public float add(float number1, float number2) { - return number1 + number2; + public float add(float number1, float number2) { + return number1 + number2; } - + public float subtract(float number1, float number2) { - return number1 - number2; + return number1 - number2; } - + public float multiply(float number1, float number2) { - return number1 * number2; + return number1 * number2; } - + public float divide(float number1, float number2) { - if (number2 == 0) { - throw new IllegalArgumentException("'number2' cannot be zero"); - } - return number1 / number2; + if (number2 == 0) { + throw new IllegalArgumentException("'number2' cannot be zero"); + } + return number1 / number2; } } diff --git a/spring-boot-modules/spring-boot-mvc-3/src/test/java/com/baeldung/micronaut/vs/springboot/controller/ArithmeticControllerUnitTest.java b/spring-boot-modules/spring-boot-mvc-3/src/test/java/com/baeldung/micronaut/vs/springboot/controller/ArithmeticControllerUnitTest.java index 8734faef54..6b08bfbd9c 100644 --- a/spring-boot-modules/spring-boot-mvc-3/src/test/java/com/baeldung/micronaut/vs/springboot/controller/ArithmeticControllerUnitTest.java +++ b/spring-boot-modules/spring-boot-mvc-3/src/test/java/com/baeldung/micronaut/vs/springboot/controller/ArithmeticControllerUnitTest.java @@ -19,50 +19,50 @@ import com.baeldung.micronaut.vs.springboot.CompareApplication; @SpringBootTest(classes = CompareApplication.class) @AutoConfigureMockMvc public class ArithmeticControllerUnitTest { - @Autowired + @Autowired private MockMvc mockMvc; - - @Test - public void givenTwoNumbers_whenAdd_thenCorrectAnswerReturned() throws Exception { - Float expected = Float.valueOf(10 + 20); - this.mockMvc.perform(MockMvcRequestBuilders.get("/math/sum/10/20") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string(expected.toString())); - } - - @Test - public void givenTwoNumbers_whenSubtract_thenCorrectAnswerReturned() throws Exception { - Float expected = Float.valueOf(20 - 10); - this.mockMvc.perform(MockMvcRequestBuilders.get("/math/subtract/20/10") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string(expected.toString())); - } - @Test - public void givenTwoNumbers_whenMultiply_thenCorrectAnswerReturned() throws Exception { - Float expected = Float.valueOf(20 * 10); - this.mockMvc.perform(MockMvcRequestBuilders.get("/math/multiply/20/10") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string(expected.toString())); - } - - @Test - public void givenTwoNumbers_whenDivide_thenCorrectAnswerReturned() throws Exception { - Float expected = Float.valueOf(20 / 10); - this.mockMvc.perform(MockMvcRequestBuilders.get("/math/divide/20/10") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string(expected.toString())); - } - - @Test - public void whenMemory_thenMemoryStringReturned() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.get("/math/memory") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string(containsString("Initial:"))); - } + @Test + public void givenTwoNumbers_whenAdd_thenCorrectAnswerReturned() throws Exception { + Float expected = Float.valueOf(10 + 20); + this.mockMvc.perform(MockMvcRequestBuilders.get("/math/sum/10/20") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string(expected.toString())); + } + + @Test + public void givenTwoNumbers_whenSubtract_thenCorrectAnswerReturned() throws Exception { + Float expected = Float.valueOf(20 - 10); + this.mockMvc.perform(MockMvcRequestBuilders.get("/math/subtract/20/10") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string(expected.toString())); + } + + @Test + public void givenTwoNumbers_whenMultiply_thenCorrectAnswerReturned() throws Exception { + Float expected = Float.valueOf(20 * 10); + this.mockMvc.perform(MockMvcRequestBuilders.get("/math/multiply/20/10") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string(expected.toString())); + } + + @Test + public void givenTwoNumbers_whenDivide_thenCorrectAnswerReturned() throws Exception { + Float expected = Float.valueOf(20 / 10); + this.mockMvc.perform(MockMvcRequestBuilders.get("/math/divide/20/10") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string(expected.toString())); + } + + @Test + public void whenMemory_thenMemoryStringReturned() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/math/memory") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("Initial:"))); + } } diff --git a/spring-boot-modules/spring-boot-mvc/src/main/resources/application.properties b/spring-boot-modules/spring-boot-mvc/src/main/resources/application.properties index 7f399bb11d..a24a95c8e7 100644 --- a/spring-boot-modules/spring-boot-mvc/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-mvc/src/main/resources/application.properties @@ -1 +1,2 @@ -spring.thymeleaf.view-names=thymeleaf/* \ No newline at end of file +spring.thymeleaf.view-names=thymeleaf/* +spring.mvc.pathmatch.matching-strategy=ant_path_matcher \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/pom.xml b/spring-boot-modules/spring-boot-properties/pom.xml index 8cbaccdac5..3c7e13036e 100644 --- a/spring-boot-modules/spring-boot-properties/pom.xml +++ b/spring-boot-modules/spring-boot-properties/pom.xml @@ -122,7 +122,7 @@ - 2020.0.3 + 2021.0.0 1.10 20.0 @ diff --git a/spring-boot-modules/spring-boot-runtime/pom.xml b/spring-boot-modules/spring-boot-runtime/pom.xml index d42ae303a7..2f25c28b06 100644 --- a/spring-boot-modules/spring-boot-runtime/pom.xml +++ b/spring-boot-modules/spring-boot-runtime/pom.xml @@ -95,7 +95,7 @@ 2.2 18.0 3.1.7 - 3.0.2 + 3.1.0 4.5.8 diff --git a/spring-boot-modules/spring-boot-springdoc/pom.xml b/spring-boot-modules/spring-boot-springdoc/pom.xml index 10bd9a7534..b766aac3d4 100644 --- a/spring-boot-modules/spring-boot-springdoc/pom.xml +++ b/spring-boot-modules/spring-boot-springdoc/pom.xml @@ -40,7 +40,6 @@ org.hibernate hibernate-core - ${hibernate.version} @@ -207,10 +206,9 @@ - 5.2.10.Final 1.5.2 1.5.6 - 1.4.0 + 1.6.0 ${project.build.directory}/generated-snippets diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/resources/application.properties b/spring-boot-modules/spring-boot-springdoc/src/main/resources/application.properties index 0eecfbb1c4..9e83617bad 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-springdoc/src/main/resources/application.properties @@ -11,4 +11,6 @@ spring.datasource.url=jdbc:h2:mem:springdoc ## for com.baeldung.restdocopenapi ## springdoc.version=@springdoc.version@ spring.jpa.hibernate.ddl-auto=none -###################################### \ No newline at end of file +###################################### + +spring.mvc.pathmatch.matching-strategy=ant_path_matcher \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-swagger/README.md b/spring-boot-modules/spring-boot-swagger/README.md index f94ae75c41..ef33be8e07 100644 --- a/spring-boot-modules/spring-boot-swagger/README.md +++ b/spring-boot-modules/spring-boot-swagger/README.md @@ -2,3 +2,4 @@ - [Hiding Endpoints From Swagger Documentation in Spring Boot](https://www.baeldung.com/spring-swagger-hiding-endpoints) - [Swagger @Api Description Is Deprecated](https://www.baeldung.com/java-swagger-api-description-deprecated) +- [Generate PDF from Swagger API Documentation](https://www.baeldung.com/swagger-generate-pdf) diff --git a/spring-boot-modules/spring-boot-testing-2/.gitignore b/spring-boot-modules/spring-boot-testing-2/.gitignore new file mode 100644 index 0000000000..da7c2c5c0a --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/.gitignore @@ -0,0 +1,5 @@ +/target/ +.settings/ +.classpath +.project + diff --git a/spring-boot-modules/spring-boot-testing-2/README.md b/spring-boot-modules/spring-boot-testing-2/README.md new file mode 100644 index 0000000000..33664a4448 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/README.md @@ -0,0 +1,12 @@ +## Spring Boot Testing + +This module contains articles about Spring Boot testing + +### The Course + +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: + +- [Setting the Log Level in Spring Boot when Testing](https://www.baeldung.com/spring-boot-testing-log-level) +- More articles: [[<-- prev]](../spring-boot-testing) \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing-2/pom.xml b/spring-boot-modules/spring-boot-testing-2/pom.xml new file mode 100644 index 0000000000..d1000156c6 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/pom.xml @@ -0,0 +1,33 @@ + + + 4.0.0 + spring-boot-testing-2 + spring-boot-testing-2 + jar + This is simple boot application for demonstrating testing features. + + + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + + + com.baeldung.boot.Application + + + diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/boot/Application.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/boot/Application.java new file mode 100644 index 0000000000..a78bb0410b --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/boot/Application.java @@ -0,0 +1,12 @@ +package com.baeldung.boot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/component/OtherComponent.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/component/OtherComponent.java similarity index 100% rename from spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/component/OtherComponent.java rename to spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/component/OtherComponent.java diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/testloglevel/TestLogLevelApplication.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/testloglevel/TestLogLevelApplication.java similarity index 100% rename from spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/testloglevel/TestLogLevelApplication.java rename to spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/testloglevel/TestLogLevelApplication.java diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/testloglevel/TestLogLevelController.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/testloglevel/TestLogLevelController.java similarity index 100% rename from spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/testloglevel/TestLogLevelController.java rename to spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/testloglevel/TestLogLevelController.java diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/resources/application.properties b/spring-boot-modules/spring-boot-testing-2/src/main/resources/application.properties new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/boot/SpringContextTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/boot/SpringContextTest.java new file mode 100644 index 0000000000..f3c8b9a954 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/boot/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung.boot; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackMultiProfileTestLogLevelIntegrationTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/testloglevel/LogbackMultiProfileTestLogLevelIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackMultiProfileTestLogLevelIntegrationTest.java rename to spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/testloglevel/LogbackMultiProfileTestLogLevelIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackTestLogLevelIntegrationTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/testloglevel/LogbackTestLogLevelIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackTestLogLevelIntegrationTest.java rename to spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/testloglevel/LogbackTestLogLevelIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/TestLogLevelWithProfileIntegrationTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/testloglevel/TestLogLevelWithProfileIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/TestLogLevelWithProfileIntegrationTest.java rename to spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/testloglevel/TestLogLevelWithProfileIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-testing/src/test/resources/application-logback-test.properties b/spring-boot-modules/spring-boot-testing-2/src/test/resources/application-logback-test.properties similarity index 100% rename from spring-boot-modules/spring-boot-testing/src/test/resources/application-logback-test.properties rename to spring-boot-modules/spring-boot-testing-2/src/test/resources/application-logback-test.properties diff --git a/spring-boot-modules/spring-boot-testing/src/test/resources/application-logback-test2.properties b/spring-boot-modules/spring-boot-testing-2/src/test/resources/application-logback-test2.properties similarity index 100% rename from spring-boot-modules/spring-boot-testing/src/test/resources/application-logback-test2.properties rename to spring-boot-modules/spring-boot-testing-2/src/test/resources/application-logback-test2.properties diff --git a/spring-boot-modules/spring-boot-testing/src/test/resources/application-logging-test.properties b/spring-boot-modules/spring-boot-testing-2/src/test/resources/application-logging-test.properties similarity index 100% rename from spring-boot-modules/spring-boot-testing/src/test/resources/application-logging-test.properties rename to spring-boot-modules/spring-boot-testing-2/src/test/resources/application-logging-test.properties diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/resources/application.properties b/spring-boot-modules/spring-boot-testing-2/src/test/resources/application.properties new file mode 100644 index 0000000000..2b406d1c6e --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/test/resources/application.properties @@ -0,0 +1,3 @@ +# logging.level.com.baeldung.testloglevel=DEBUG + +# logging.level.root=INFO diff --git a/spring-boot-modules/spring-boot-testing/src/test/resources/logback-multiprofile.xml b/spring-boot-modules/spring-boot-testing-2/src/test/resources/logback-multiprofile.xml similarity index 100% rename from spring-boot-modules/spring-boot-testing/src/test/resources/logback-multiprofile.xml rename to spring-boot-modules/spring-boot-testing-2/src/test/resources/logback-multiprofile.xml diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/resources/logback-test.xml b/spring-boot-modules/spring-boot-testing-2/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..0528aa88f3 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/test/resources/logback-test.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + diff --git a/spring-boot-modules/spring-boot-testing/README.md b/spring-boot-modules/spring-boot-testing/README.md index 058c78c9bb..4d23c32422 100644 --- a/spring-boot-modules/spring-boot-testing/README.md +++ b/spring-boot-modules/spring-boot-testing/README.md @@ -10,9 +10,9 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Testing with Spring and Spock](https://www.baeldung.com/spring-spock-testing) - [Exclude Auto-Configuration Classes in Spring Boot Tests](https://www.baeldung.com/spring-boot-exclude-auto-configuration-test) -- [Setting the Log Level in Spring Boot when Testing](https://www.baeldung.com/spring-boot-testing-log-level) - [Embedded Redis Server with Spring Boot Test](https://www.baeldung.com/spring-embedded-redis) - [Testing Spring Boot @ConfigurationProperties](https://www.baeldung.com/spring-boot-testing-configurationproperties) - [Prevent ApplicationRunner or CommandLineRunner Beans From Executing During Junit Testing](https://www.baeldung.com/spring-junit-prevent-runner-beans-testing-execution) - [Testing in Spring Boot](https://www.baeldung.com/spring-boot-testing) - [Fixing the NoSuchMethodError JUnit Error](https://www.baeldung.com/junit-nosuchmethoderror) +- More articles: [[more -->]](../spring-boot-testing-2) \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/test/resources/logback-test.xml b/spring-boot-modules/spring-boot-testing/src/test/resources/logback-test.xml index 0528aa88f3..9553dcad41 100644 --- a/spring-boot-modules/spring-boot-testing/src/test/resources/logback-test.xml +++ b/spring-boot-modules/spring-boot-testing/src/test/resources/logback-test.xml @@ -9,5 +9,4 @@ - diff --git a/spring-boot-rest/pom.xml b/spring-boot-rest/pom.xml index 72d4ecfaa6..1244d290b5 100644 --- a/spring-boot-rest/pom.xml +++ b/spring-boot-rest/pom.xml @@ -88,7 +88,7 @@ com.baeldung.SpringBootRestApplication 27.0.1-jre 1.4.11.1 - 2.3.5 + 2.4.5 \ No newline at end of file diff --git a/spring-boot-rest/src/main/java/com/baeldung/springpagination/controller/PostRestController.java b/spring-boot-rest/src/main/java/com/baeldung/springpagination/controller/PostRestController.java index c52960b365..500de17e1e 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/springpagination/controller/PostRestController.java +++ b/spring-boot-rest/src/main/java/com/baeldung/springpagination/controller/PostRestController.java @@ -19,6 +19,7 @@ import org.springframework.web.bind.annotation.ResponseStatus; import java.text.ParseException; import java.util.List; +import java.util.Objects; import java.util.stream.Collectors; @Controller @@ -65,7 +66,11 @@ public class PostRestController { @PutMapping(value = "/{id}") @ResponseStatus(HttpStatus.OK) - public void updatePost(@RequestBody PostDto postDto) throws ParseException { + public void updatePost(@PathVariable("id") Long id, @RequestBody PostDto postDto) throws ParseException { + if(!Objects.equals(id, postDto.getId())){ + throw new IllegalArgumentException("IDs don't match"); + } + Post post = convertToEntity(postDto); postService.updatePost(post); } diff --git a/spring-cloud-bus/pom.xml b/spring-cloud-bus/pom.xml index 88bb766047..2eab7d52a9 100644 --- a/spring-cloud-bus/pom.xml +++ b/spring-cloud-bus/pom.xml @@ -34,7 +34,7 @@ - 2020.0.3 + 2021.0.0 \ No newline at end of file diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 65b623febd..1b6b18cd6b 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -79,7 +79,7 @@ - 2020.0.3 + 2021.0.0 2.2.3.RELEASE 2.2.3.RELEASE 1.4.7.RELEASE diff --git a/spring-cloud/spring-cloud-config/pom.xml b/spring-cloud/spring-cloud-config/pom.xml index 4eda3dda0a..db26d67358 100644 --- a/spring-cloud/spring-cloud-config/pom.xml +++ b/spring-cloud/spring-cloud-config/pom.xml @@ -34,7 +34,7 @@ - 2020.0.3 + 2021.0.0 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/pom.xml b/spring-cloud/spring-cloud-kubernetes/pom.xml index d8894eb36f..837e2aabfb 100644 --- a/spring-cloud/spring-cloud-kubernetes/pom.xml +++ b/spring-cloud/spring-cloud-kubernetes/pom.xml @@ -38,7 +38,7 @@ - 2020.0.3 + 2021.0.0 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-ribbon-client/pom.xml b/spring-cloud/spring-cloud-ribbon-client/pom.xml index 2c2bce4bcd..666a6fa9fc 100644 --- a/spring-cloud/spring-cloud-ribbon-client/pom.xml +++ b/spring-cloud/spring-cloud-ribbon-client/pom.xml @@ -47,7 +47,7 @@ - 2020.0.3 + 2021.0.0 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-ribbon-client/src/main/java/com/baeldung/spring/cloud/ribbon/client/RestTemplateConfiguration.java b/spring-cloud/spring-cloud-ribbon-client/src/main/java/com/baeldung/spring/cloud/ribbon/client/RestTemplateConfiguration.java new file mode 100644 index 0000000000..c69168fc74 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-client/src/main/java/com/baeldung/spring/cloud/ribbon/client/RestTemplateConfiguration.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.ribbon.client; + +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; + +@Configuration +public class RestTemplateConfiguration { + + @LoadBalanced + @Bean + RestTemplate getRestTemplate() { + return new RestTemplate(); + } +} diff --git a/spring-cloud/spring-cloud-ribbon-client/src/main/java/com/baeldung/spring/cloud/ribbon/client/ServerLocationApp.java b/spring-cloud/spring-cloud-ribbon-client/src/main/java/com/baeldung/spring/cloud/ribbon/client/ServerLocationApp.java index 6105e2c489..b7b92d114d 100644 --- a/spring-cloud/spring-cloud-ribbon-client/src/main/java/com/baeldung/spring/cloud/ribbon/client/ServerLocationApp.java +++ b/spring-cloud/spring-cloud-ribbon-client/src/main/java/com/baeldung/spring/cloud/ribbon/client/ServerLocationApp.java @@ -3,9 +3,7 @@ package com.baeldung.spring.cloud.ribbon.client; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.netflix.ribbon.RibbonClient; -import org.springframework.context.annotation.Bean; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @@ -15,19 +13,12 @@ import org.springframework.web.client.RestTemplate; @RibbonClient(name = "ping-a-server", configuration = RibbonConfiguration.class) public class ServerLocationApp { - @LoadBalanced - @Bean - RestTemplate getRestTemplate() { - return new RestTemplate(); - } - @Autowired RestTemplate restTemplate; @RequestMapping("/server-location") public String serverLocation() { - String servLoc = this.restTemplate.getForObject("http://ping-server/locaus", String.class); - return servLoc; + return this.restTemplate.getForObject("http://ping-server/locaus", String.class); } public static void main(String[] args) { diff --git a/spring-cloud/spring-cloud-ribbon-client/src/test/java/com/baeldung/spring/cloud/ribbon/client/ServerLocationAppIntegrationTest.java b/spring-cloud/spring-cloud-ribbon-client/src/test/java/com/baeldung/spring/cloud/ribbon/client/ServerLocationAppIntegrationTest.java index 4134880fa6..2ad9ca4797 100644 --- a/spring-cloud/spring-cloud-ribbon-client/src/test/java/com/baeldung/spring/cloud/ribbon/client/ServerLocationAppIntegrationTest.java +++ b/spring-cloud/spring-cloud-ribbon-client/src/test/java/com/baeldung/spring/cloud/ribbon/client/ServerLocationAppIntegrationTest.java @@ -1,6 +1,5 @@ package com.baeldung.spring.cloud.ribbon.client; -import static org.assertj.core.api.BDDAssertions.then; import static org.junit.Assert.assertEquals; import org.junit.After; @@ -13,7 +12,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; @@ -43,7 +41,7 @@ public class ServerLocationAppIntegrationTest { private TestRestTemplate testRestTemplate; @Test - public void loadBalancingServersTest() throws InterruptedException { + public void loadBalancingServersTest() { ResponseEntity response = this.testRestTemplate.getForEntity("http://localhost:" + this.port + "/server-location", String.class); assertEquals(response.getBody(), "Australia"); } diff --git a/spring-cloud/spring-cloud-security/pom.xml b/spring-cloud/spring-cloud-security/pom.xml index d9072af91b..362a70eaeb 100644 --- a/spring-cloud/spring-cloud-security/pom.xml +++ b/spring-cloud/spring-cloud-security/pom.xml @@ -34,7 +34,7 @@ - 2020.0.3 + 2021.0.0 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-task/pom.xml b/spring-cloud/spring-cloud-task/pom.xml index 0cfc62bdbb..2047ce0e21 100644 --- a/spring-cloud/spring-cloud-task/pom.xml +++ b/spring-cloud/spring-cloud-task/pom.xml @@ -48,8 +48,8 @@ - 2020.0.3 - 2.3.3 + 2021.0.0 + 2.4.0 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/java/com/baeldung/SpringContextTest.java index 32224bf91b..e1a4255579 100644 --- a/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/java/com/baeldung/SpringContextTest.java +++ b/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/java/com/baeldung/SpringContextTest.java @@ -3,7 +3,7 @@ package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer; +import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -12,7 +12,7 @@ import com.baeldung.task.TaskDemo; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootApplication -@ContextConfiguration(classes = { JobConfiguration.class, TaskDemo.class }, initializers = { ConfigFileApplicationContextInitializer.class }) +@ContextConfiguration(classes = { JobConfiguration.class, TaskDemo.class }, initializers = { ConfigDataApplicationContextInitializer.class }) public class SpringContextTest { @Test diff --git a/spring-cloud/spring-cloud-zookeeper/pom.xml b/spring-cloud/spring-cloud-zookeeper/pom.xml index 79eabf74f0..3fb899ec47 100644 --- a/spring-cloud/spring-cloud-zookeeper/pom.xml +++ b/spring-cloud/spring-cloud-zookeeper/pom.xml @@ -18,8 +18,4 @@ HelloWorld - - 5.2.7.RELEASE - - \ No newline at end of file diff --git a/spring-cloud/spring-cloud-zuul/pom.xml b/spring-cloud/spring-cloud-zuul/pom.xml index 0590774bef..668f6e6c2a 100644 --- a/spring-cloud/spring-cloud-zuul/pom.xml +++ b/spring-cloud/spring-cloud-zuul/pom.xml @@ -35,7 +35,7 @@ org.springframework.cloud spring-cloud-dependencies - ${spring-cloud.version} + ${spring-cloud-dependencies.version} pom import @@ -81,7 +81,7 @@ - 2020.0.3 + 2021.0.0 2.2.7.RELEASE diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/pom.xml b/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/pom.xml index d2b28643fa..2969b5eed9 100644 --- a/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/pom.xml +++ b/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/pom.xml @@ -43,6 +43,7 @@ 2.2.0.RELEASE 2.4.7 + 2020.0.4 \ 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 c071b8863a..3e32a91a41 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.mockito - mockito-core - test - diff --git a/spring-core-2/pom.xml b/spring-core-2/pom.xml index 19e7fb5f28..a4cae17c20 100644 --- a/spring-core-2/pom.xml +++ b/spring-core-2/pom.xml @@ -129,11 +129,6 @@ spring-test test - - org.mockito - mockito-core - test - net.javacrumbs.shedlock diff --git a/spring-di-2/README.md b/spring-di-2/README.md index f41976c3f0..5989e6269b 100644 --- a/spring-di-2/README.md +++ b/spring-di-2/README.md @@ -9,4 +9,6 @@ This module contains articles about dependency injection with Spring - [Spring – Injecting Collections](https://www.baeldung.com/spring-injecting-collections) - [Wiring in Spring: @Autowired, @Resource and @Inject](https://www.baeldung.com/spring-annotations-resource-inject-autowire) - [Injecting Spring Beans into Unmanaged Objects](https://www.baeldung.com/spring-inject-bean-into-unmanaged-objects) -- More articles: [[<-- prev]](/spring-di) +- [Constructor Dependency Injection in Spring](https://www.baeldung.com/constructor-injection-in-spring) +- [Circular Dependencies in Spring](https://www.baeldung.com/circular-dependencies-in-spring) +- More articles: [[<-- prev]](../spring-di)[[more -->]](../spring-di-3) diff --git a/spring-di-2/pom.xml b/spring-di-2/pom.xml index 7d3f4c7b33..0e57c6ef92 100644 --- a/spring-di-2/pom.xml +++ b/spring-di-2/pom.xml @@ -14,37 +14,41 @@ ../parent-spring-5 + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + - org.springframework - spring-test - ${spring.version} + org.springframework.boot + spring-boot-starter-web org.springframework.boot spring-boot-starter-data-jpa - ${spring-boot.version} - - - org.springframework.boot - spring-boot-starter-web - ${spring-boot.version} org.springframework spring-aspects - ${spring.version} - - - org.projectlombok - lombok - ${lombok.version} javax.inject javax.inject ${javax.inject.version} + + + org.springframework.boot + spring-boot-starter-test + @@ -74,7 +78,7 @@ - 2.3.1.RELEASE + 2.6.1 1.11 1 diff --git a/spring-di/src/main/java/com/baeldung/circulardependency/CircularDependencyA.java b/spring-di-2/src/main/java/com/baeldung/circulardependency/CircularDependencyA.java similarity index 100% rename from spring-di/src/main/java/com/baeldung/circulardependency/CircularDependencyA.java rename to spring-di-2/src/main/java/com/baeldung/circulardependency/CircularDependencyA.java diff --git a/spring-di/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java b/spring-di-2/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java similarity index 100% rename from spring-di/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java rename to spring-di-2/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java diff --git a/spring-di/src/main/java/com/baeldung/constructordi/Config.java b/spring-di-2/src/main/java/com/baeldung/constructordi/Config.java similarity index 99% rename from spring-di/src/main/java/com/baeldung/constructordi/Config.java rename to spring-di-2/src/main/java/com/baeldung/constructordi/Config.java index 07568018f3..d3c6b2d231 100644 --- a/spring-di/src/main/java/com/baeldung/constructordi/Config.java +++ b/spring-di-2/src/main/java/com/baeldung/constructordi/Config.java @@ -1,11 +1,10 @@ package com.baeldung.constructordi; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - import com.baeldung.constructordi.domain.Engine; import com.baeldung.constructordi.domain.Transmission; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan("com.baeldung.constructordi") diff --git a/spring-di/src/main/java/com/baeldung/constructordi/SpringRunner.java b/spring-di-2/src/main/java/com/baeldung/constructordi/SpringRunner.java similarity index 99% rename from spring-di/src/main/java/com/baeldung/constructordi/SpringRunner.java rename to spring-di-2/src/main/java/com/baeldung/constructordi/SpringRunner.java index abbe97a4bd..75a1af47ee 100644 --- a/spring-di/src/main/java/com/baeldung/constructordi/SpringRunner.java +++ b/spring-di-2/src/main/java/com/baeldung/constructordi/SpringRunner.java @@ -1,11 +1,10 @@ package com.baeldung.constructordi; +import com.baeldung.constructordi.domain.Car; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -import com.baeldung.constructordi.domain.Car; - public class SpringRunner { public static void main(String[] args) { Car toyota = getCarFromXml(); diff --git a/spring-di/src/main/java/com/baeldung/constructordi/domain/Car.java b/spring-di-2/src/main/java/com/baeldung/constructordi/domain/Car.java similarity index 85% rename from spring-di/src/main/java/com/baeldung/constructordi/domain/Car.java rename to spring-di-2/src/main/java/com/baeldung/constructordi/domain/Car.java index 9f68ba5cd9..bbe9b669d8 100644 --- a/spring-di/src/main/java/com/baeldung/constructordi/domain/Car.java +++ b/spring-di-2/src/main/java/com/baeldung/constructordi/domain/Car.java @@ -5,8 +5,9 @@ import org.springframework.stereotype.Component; @Component public class Car { - private Engine engine; - private Transmission transmission; + + private final Engine engine; + private final Transmission transmission; @Autowired public Car(Engine engine, Transmission transmission) { diff --git a/spring-di/src/main/java/com/baeldung/constructordi/domain/Engine.java b/spring-di-2/src/main/java/com/baeldung/constructordi/domain/Engine.java similarity index 81% rename from spring-di/src/main/java/com/baeldung/constructordi/domain/Engine.java rename to spring-di-2/src/main/java/com/baeldung/constructordi/domain/Engine.java index f2987988eb..ed9c1f4d1c 100644 --- a/spring-di/src/main/java/com/baeldung/constructordi/domain/Engine.java +++ b/spring-di-2/src/main/java/com/baeldung/constructordi/domain/Engine.java @@ -1,8 +1,9 @@ package com.baeldung.constructordi.domain; public class Engine { - private String type; - private int volume; + + private final String type; + private final int volume; public Engine(String type, int volume) { this.type = type; diff --git a/spring-di/src/main/java/com/baeldung/constructordi/domain/Transmission.java b/spring-di-2/src/main/java/com/baeldung/constructordi/domain/Transmission.java similarity index 88% rename from spring-di/src/main/java/com/baeldung/constructordi/domain/Transmission.java rename to spring-di-2/src/main/java/com/baeldung/constructordi/domain/Transmission.java index 85271e1f2a..00060e4921 100644 --- a/spring-di/src/main/java/com/baeldung/constructordi/domain/Transmission.java +++ b/spring-di-2/src/main/java/com/baeldung/constructordi/domain/Transmission.java @@ -1,7 +1,8 @@ package com.baeldung.constructordi.domain; public class Transmission { - private String type; + + private final String type; public Transmission(String type) { this.type = type; diff --git a/spring-di/src/main/resources/constructordi.xml b/spring-di-2/src/main/resources/constructordi.xml similarity index 100% rename from spring-di/src/main/resources/constructordi.xml rename to spring-di-2/src/main/resources/constructordi.xml diff --git a/spring-di/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java similarity index 100% rename from spring-di/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java rename to spring-di-2/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java diff --git a/spring-di/src/test/java/com/baeldung/circulardependency/TestConfig.java b/spring-di-2/src/test/java/com/baeldung/circulardependency/TestConfig.java similarity index 100% rename from spring-di/src/test/java/com/baeldung/circulardependency/TestConfig.java rename to spring-di-2/src/test/java/com/baeldung/circulardependency/TestConfig.java diff --git a/spring-di/src/test/java/com/baeldung/constructordi/ConstructorDependencyInjectionIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/constructordi/ConstructorDependencyInjectionIntegrationTest.java similarity index 99% rename from spring-di/src/test/java/com/baeldung/constructordi/ConstructorDependencyInjectionIntegrationTest.java rename to spring-di-2/src/test/java/com/baeldung/constructordi/ConstructorDependencyInjectionIntegrationTest.java index 7bd0ad0c86..4c4e622629 100644 --- a/spring-di/src/test/java/com/baeldung/constructordi/ConstructorDependencyInjectionIntegrationTest.java +++ b/spring-di-2/src/test/java/com/baeldung/constructordi/ConstructorDependencyInjectionIntegrationTest.java @@ -1,7 +1,6 @@ package com.baeldung.constructordi; -import static org.assertj.core.api.Assertions.assertThat; - +import com.baeldung.constructordi.domain.Car; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.context.ApplicationContext; @@ -11,7 +10,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; -import com.baeldung.constructordi.domain.Car; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = Config.class) diff --git a/spring-di-2/src/test/java/com/baeldung/di/aspectj/PersonUnitTest.java b/spring-di-2/src/test/java/com/baeldung/di/aspectj/PersonUnitTest.java index 72ccfbadf3..d0318e96b9 100644 --- a/spring-di-2/src/test/java/com/baeldung/di/aspectj/PersonUnitTest.java +++ b/spring-di-2/src/test/java/com/baeldung/di/aspectj/PersonUnitTest.java @@ -10,10 +10,12 @@ import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @ContextConfiguration(classes = AspectJConfig.class) public class PersonUnitTest { + @Test public void givenUnmanagedObjects_whenInjectingIdService_thenIdValueIsCorrectlySet() { PersonObject personObject = new PersonObject("Baeldung"); personObject.generateId(); + assertEquals(1, personObject.getId()); assertEquals("Baeldung", personObject.getName()); diff --git a/spring-di-3/README.md b/spring-di-3/README.md new file mode 100644 index 0000000000..9ab7789f37 --- /dev/null +++ b/spring-di-3/README.md @@ -0,0 +1,8 @@ +## Spring Dependency Injection + +This module contains articles about dependency injection with Spring + +### Relevant Articles + +- [@Lookup Annotation in Spring](https://www.baeldung.com/spring-lookup) +- More articles: [[<-- prev]](../spring-di-2) diff --git a/spring-di-3/pom.xml b/spring-di-3/pom.xml new file mode 100644 index 0000000000..0d4bbd01af --- /dev/null +++ b/spring-di-3/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + spring-di-3 + 1.0-SNAPSHOT + spring-di-3 + + + com.baeldung + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + + + + + 2.6.1 + + + \ No newline at end of file diff --git a/spring-di/src/main/java/com/baeldung/methodinjections/AppConfig.java b/spring-di-3/src/main/java/com/baeldung/methodinjections/AppConfig.java similarity index 99% rename from spring-di/src/main/java/com/baeldung/methodinjections/AppConfig.java rename to spring-di-3/src/main/java/com/baeldung/methodinjections/AppConfig.java index 7c1e209383..59c0e1543a 100644 --- a/spring-di/src/main/java/com/baeldung/methodinjections/AppConfig.java +++ b/spring-di-3/src/main/java/com/baeldung/methodinjections/AppConfig.java @@ -5,6 +5,5 @@ import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan(basePackages = "com.baeldung.methodinjections") - public class AppConfig { } diff --git a/spring-di/src/main/java/com/baeldung/methodinjections/Grader.java b/spring-di-3/src/main/java/com/baeldung/methodinjections/Grader.java similarity index 100% rename from spring-di/src/main/java/com/baeldung/methodinjections/Grader.java rename to spring-di-3/src/main/java/com/baeldung/methodinjections/Grader.java index 10dc77484c..f1b2bc7ea4 100644 --- a/spring-di/src/main/java/com/baeldung/methodinjections/Grader.java +++ b/spring-di-3/src/main/java/com/baeldung/methodinjections/Grader.java @@ -1,9 +1,9 @@ package com.baeldung.methodinjections; -import java.util.Collection; - import org.springframework.stereotype.Component; +import java.util.Collection; + @Component public class Grader { diff --git a/spring-di/src/main/java/com/baeldung/methodinjections/SchoolNotification.java b/spring-di-3/src/main/java/com/baeldung/methodinjections/SchoolNotification.java similarity index 95% rename from spring-di/src/main/java/com/baeldung/methodinjections/SchoolNotification.java rename to spring-di-3/src/main/java/com/baeldung/methodinjections/SchoolNotification.java index 752eb8893f..d9396f09b8 100644 --- a/spring-di/src/main/java/com/baeldung/methodinjections/SchoolNotification.java +++ b/spring-di-3/src/main/java/com/baeldung/methodinjections/SchoolNotification.java @@ -1,13 +1,13 @@ package com.baeldung.methodinjections; -import java.util.ArrayList; -import java.util.Collection; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; +import java.util.ArrayList; +import java.util.Collection; + @Component("schoolNotification") @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) public class SchoolNotification { @@ -19,7 +19,7 @@ public class SchoolNotification { public SchoolNotification(String name) { this.name = name; - this.marks = new ArrayList(); + this.marks = new ArrayList<>(); } public String addMark(Integer mark) { diff --git a/spring-di/src/main/java/com/baeldung/methodinjections/Student.java b/spring-di-3/src/main/java/com/baeldung/methodinjections/Student.java similarity index 100% rename from spring-di/src/main/java/com/baeldung/methodinjections/Student.java rename to spring-di-3/src/main/java/com/baeldung/methodinjections/Student.java diff --git a/spring-di/src/main/java/com/baeldung/methodinjections/StudentServices.java b/spring-di-3/src/main/java/com/baeldung/methodinjections/StudentServices.java similarity index 88% rename from spring-di/src/main/java/com/baeldung/methodinjections/StudentServices.java rename to spring-di-3/src/main/java/com/baeldung/methodinjections/StudentServices.java index 20d631b120..1bb9bda542 100644 --- a/spring-di/src/main/java/com/baeldung/methodinjections/StudentServices.java +++ b/spring-di-3/src/main/java/com/baeldung/methodinjections/StudentServices.java @@ -1,15 +1,15 @@ package com.baeldung.methodinjections; -import java.util.HashMap; -import java.util.Map; - import org.springframework.beans.factory.annotation.Lookup; import org.springframework.stereotype.Component; +import java.util.HashMap; +import java.util.Map; + @Component("studentService") public abstract class StudentServices { - private Map notes = new HashMap<>(); + private final Map notes = new HashMap<>(); @Lookup protected abstract SchoolNotification getNotification(String name); diff --git a/spring-di-3/src/main/resources/application.properties b/spring-di-3/src/main/resources/application.properties new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/spring-di-3/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/spring-di/src/main/resources/beans.xml b/spring-di-3/src/main/resources/beans.xml similarity index 100% rename from spring-di/src/main/resources/beans.xml rename to spring-di-3/src/main/resources/beans.xml diff --git a/spring-di-3/src/test/java/com/baeldung/methodinjections/StudentIntegrationTest.java b/spring-di-3/src/test/java/com/baeldung/methodinjections/StudentIntegrationTest.java new file mode 100644 index 0000000000..190a7d8773 --- /dev/null +++ b/spring-di-3/src/test/java/com/baeldung/methodinjections/StudentIntegrationTest.java @@ -0,0 +1,42 @@ +package com.baeldung.methodinjections; + +import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +public class StudentIntegrationTest { + + private ConfigurableApplicationContext context; + + @AfterEach + public void tearDown() { + context.close(); + } + + @Test + public void whenLookupMethodCalled_thenNewInstanceReturned() { + context = new AnnotationConfigApplicationContext(AppConfig.class); + + Student student1 = context.getBean("studentBean", Student.class); + Student student2 = context.getBean("studentBean", Student.class); + + assertEquals(student1, student2); + assertNotEquals(student1.getNotification("Alex"), student2.getNotification("Bethany")); + } + + @Test + public void whenAbstractGetterMethodInjects_thenNewInstanceReturned() { + context = new ClassPathXmlApplicationContext("beans.xml"); + + StudentServices services = context.getBean("studentServices", StudentServices.class); + + assertEquals("PASS", services.appendMark("Alex", 76)); + assertEquals("FAIL", services.appendMark("Bethany", 44)); + assertEquals("PASS", services.appendMark("Claire", 96)); + } +} diff --git a/spring-di-3/src/test/resources/logback-test.xml b/spring-di-3/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/spring-di-3/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/spring-di/README.md b/spring-di/README.md index d470768f16..7b1ebd41b9 100644 --- a/spring-di/README.md +++ b/spring-di/README.md @@ -5,13 +5,10 @@ This module contains articles about dependency injection with Spring ### Relevant Articles - [The Spring @Qualifier Annotation](https://www.baeldung.com/spring-qualifier-annotation) -- [Constructor Dependency Injection in Spring](https://www.baeldung.com/constructor-injection-in-spring) - [Spring Autowiring of Generic Types](https://www.baeldung.com/spring-autowire-generics) - [Guice vs Spring – Dependency Injection](https://www.baeldung.com/guice-spring-dependency-injection) - [Injecting Prototype Beans into a Singleton Instance in Spring](https://www.baeldung.com/spring-inject-prototype-bean-into-singleton) -- [@Lookup Annotation in Spring](https://www.baeldung.com/spring-lookup) - [Controlling Bean Creation Order with @DependsOn Annotation](https://www.baeldung.com/spring-depends-on) - [Unsatisfied Dependency in Spring](https://www.baeldung.com/spring-unsatisfied-dependency) -- [Circular Dependencies in Spring](https://www.baeldung.com/circular-dependencies-in-spring) - [XML-Based Injection in Spring](https://www.baeldung.com/spring-xml-injection) -- More articles: [[next -->]](/spring-di-2) +- More articles: [[next -->]](../spring-di-2) diff --git a/spring-di/src/test/java/com/baeldung/methodinjections/StudentIntegrationTest.java b/spring-di/src/test/java/com/baeldung/methodinjections/StudentIntegrationTest.java deleted file mode 100644 index 5d326a99dd..0000000000 --- a/spring-di/src/test/java/com/baeldung/methodinjections/StudentIntegrationTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.methodinjections; - -import org.junit.Assert; -import org.junit.Test; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class StudentIntegrationTest { - - @Test - public void whenLookupMethodCalled_thenNewInstanceReturned() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); - Student student1 = context.getBean("studentBean", Student.class); - Student student2 = context.getBean("studentBean", Student.class); - - Assert.assertEquals(student1, student2); - Assert.assertNotEquals(student1.getNotification("Alex"), student2.getNotification("Bethany")); - context.close(); - } - - @Test - public void whenAbstractGetterMethodInjects_thenNewInstanceReturned() { - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); - StudentServices services = context.getBean("studentServices", StudentServices.class); - - Assert.assertEquals("PASS", services.appendMark("Alex", 76)); - Assert.assertEquals("FAIL", services.appendMark("Bethany", 44)); - Assert.assertEquals("PASS", services.appendMark("Claire", 96)); - context.close(); - } -} diff --git a/spring-jenkins-pipeline/src/test/resources/application.properties b/spring-jenkins-pipeline/src/test/resources/application.properties index 4ee830556a..f97ea98811 100644 --- a/spring-jenkins-pipeline/src/test/resources/application.properties +++ b/spring-jenkins-pipeline/src/test/resources/application.properties @@ -1,2 +1,4 @@ #To use a randomly allocated free port during tests to avoid port conflict across tests spring.data.mongodb.port=0 + +spring.mongodb.embedded.version=3.5.5 diff --git a/spring-kafka/README.md b/spring-kafka/README.md index 0be741b393..5ff3cb625b 100644 --- a/spring-kafka/README.md +++ b/spring-kafka/README.md @@ -9,6 +9,7 @@ This module contains articles about Spring with Kafka - [Monitor the Consumer Lag in Apache Kafka](https://www.baeldung.com/java-kafka-consumer-lag) - [Send Large Messages With Kafka](https://www.baeldung.com/java-kafka-send-large-message) - [Configuring Kafka SSL Using Spring Boot](https://www.baeldung.com/spring-boot-kafka-ssl) +- [Kafka Streams With Spring Boot](https://www.baeldung.com/spring-boot-kafka-streams) ### Intro diff --git a/spring-kafka/pom.xml b/spring-kafka/pom.xml index 2801afffd7..22ef0297b5 100644 --- a/spring-kafka/pom.xml +++ b/spring-kafka/pom.xml @@ -70,6 +70,7 @@ 2.7.8 2.7.1 1.15.3 + 2.5.4 \ No newline at end of file diff --git a/spring-mockito/pom.xml b/spring-mockito/pom.xml index 0753935d0c..e0d7bee6f3 100644 --- a/spring-mockito/pom.xml +++ b/spring-mockito/pom.xml @@ -28,8 +28,4 @@ - - 2.24.0 - - \ No newline at end of file diff --git a/spring-quartz/pom.xml b/spring-quartz/pom.xml index 53b6962a60..e8919bfadb 100644 --- a/spring-quartz/pom.xml +++ b/spring-quartz/pom.xml @@ -54,8 +54,8 @@ - 2.3.0 - 0.9.5.2 + 2.3.2 + 0.9.5.5 \ No newline at end of file diff --git a/spring-quartz/src/main/resources/application.properties b/spring-quartz/src/main/resources/application.properties index 557349af2e..ffe90aadd5 100644 --- a/spring-quartz/src/main/resources/application.properties +++ b/spring-quartz/src/main/resources/application.properties @@ -2,7 +2,7 @@ using.spring.schedulerFactory=true spring.quartz.job-store-type=jdbc # Always create the Quartz database on startup -spring.quartz.jdbc.initialize-schema=always +spring.quartz.jdbc.initialize-schema=never spring.datasource.jdbc-url=jdbc:h2:mem:spring-quartz;DB_CLOSE_ON_EXIT=FALSE spring.datasource.driverClassName=org.h2.Driver diff --git a/spring-quartz/src/main/resources/quartz.properties b/spring-quartz/src/main/resources/quartz.properties index 662bb83eb0..8cecd7d3d3 100644 --- a/spring-quartz/src/main/resources/quartz.properties +++ b/spring-quartz/src/main/resources/quartz.properties @@ -20,3 +20,4 @@ org.quartz.dataSource.quartzDataSource.URL=jdbc:h2:mem:spring-quartz;INIT=RUNSCR org.quartz.dataSource.quartzDataSource.driver=org.h2.Driver org.quartz.dataSource.quartzDataSource.user=sa org.quartz.dataSource.quartzDataSource.password= +org.quartz.jdbc.initialize-schema=never diff --git a/spring-reactive/pom.xml b/spring-reactive/pom.xml index a4d375ea15..d31ee04d82 100644 --- a/spring-reactive/pom.xml +++ b/spring-reactive/pom.xml @@ -57,6 +57,43 @@ + + + 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 + + + + + + + + 3.4.12 1.2.2.RELEASE diff --git a/spring-reactive/src/test/java/com/baeldung/reactive/debugging/consumer/ConsumerFooServiceIntegrationTest.java b/spring-reactive/src/test/java/com/baeldung/reactive/debugging/consumer/ConsumerFooServiceIntegrationTest.java index 5cb1a69fbd..37e2ebe0ac 100644 --- a/spring-reactive/src/test/java/com/baeldung/reactive/debugging/consumer/ConsumerFooServiceIntegrationTest.java +++ b/spring-reactive/src/test/java/com/baeldung/reactive/debugging/consumer/ConsumerFooServiceIntegrationTest.java @@ -1,14 +1,6 @@ package com.baeldung.reactive.debugging.consumer; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.classic.spi.IThrowableProxy; -import com.baeldung.reactive.debugging.consumer.model.Foo; -import com.baeldung.reactive.debugging.consumer.service.FooService; -import com.baeldung.reactive.debugging.consumer.utils.ListAppender; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Hooks; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.Collection; @@ -16,7 +8,16 @@ import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; -import static org.assertj.core.api.Assertions.assertThat; +import com.baeldung.reactive.debugging.consumer.model.Foo; +import com.baeldung.reactive.debugging.consumer.service.FooService; +import com.baeldung.reactive.debugging.consumer.utils.ListAppender; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.classic.spi.IThrowableProxy; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Hooks; public class ConsumerFooServiceIntegrationTest { @@ -37,26 +38,26 @@ public class ConsumerFooServiceIntegrationTest { service.processFoo(flux); Collection allLoggedEntries = ListAppender.getEvents() - .stream() - .map(ILoggingEvent::getFormattedMessage) - .collect(Collectors.toList()); + .stream() + .map(ILoggingEvent::getFormattedMessage) + .collect(Collectors.toList()); Collection allSuppressedEntries = ListAppender.getEvents() - .stream() - .map(ILoggingEvent::getThrowableProxy) - .flatMap(t -> { - return Optional.ofNullable(t) - .map(IThrowableProxy::getSuppressed) - .map(Arrays::stream) - .orElse(Stream.empty()); - }) - .map(IThrowableProxy::getClassName) - .collect(Collectors.toList()); + .stream() + .map(ILoggingEvent::getThrowableProxy) + .flatMap(t -> { + return Optional.ofNullable(t) + .map(IThrowableProxy::getSuppressed) + .map(Arrays::stream) + .orElse(Stream.empty()); + }) + .map(IThrowableProxy::getClassName) + .collect(Collectors.toList()); assertThat(allLoggedEntries).anyMatch(entry -> entry.contains("The following error happened on processFoo method!")) - .anyMatch(entry -> entry.contains("| onSubscribe")) - .anyMatch(entry -> entry.contains("| cancel()")); + .anyMatch(entry -> entry.contains("| onSubscribe")) + .anyMatch(entry -> entry.contains("| cancel()")); assertThat(allSuppressedEntries) - .anyMatch(entry -> entry.contains("reactor.core.publisher.FluxOnAssembly$OnAssemblyException")); + .anyMatch(entry -> entry.contains("reactor.core.publisher.FluxOnAssembly$OnAssemblyException")); } } diff --git a/spring-reactive/src/test/java/com/baeldung/reactive/debugging/consumer/ConsumerFooServiceLiveTest.java b/spring-reactive/src/test/java/com/baeldung/reactive/debugging/consumer/ConsumerFooServiceLiveTest.java index c3ef67f534..ff6e4b2bd2 100644 --- a/spring-reactive/src/test/java/com/baeldung/reactive/debugging/consumer/ConsumerFooServiceLiveTest.java +++ b/spring-reactive/src/test/java/com/baeldung/reactive/debugging/consumer/ConsumerFooServiceLiveTest.java @@ -8,8 +8,8 @@ import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; /** * In order to run this live test, start the following classes: - * - com.baeldung.debugging.server.ServerDebuggingApplication - * - com.baeldung.debugging.consumer.ConsumerDebuggingApplication + * - com.baeldung.reactive.debugging.server.ServerDebuggingApplication + * - com.baeldung.reactive.debugging.consumer.ConsumerDebuggingApplication */ public class ConsumerFooServiceLiveTest { diff --git a/spring-reactive/src/test/java/com/baeldung/reactive/introduction/ReactorIntegrationTest.java b/spring-reactive/src/test/java/com/baeldung/reactive/introduction/ReactorIntegrationTest.java index e60d2e9b94..307cc2cfeb 100644 --- a/spring-reactive/src/test/java/com/baeldung/reactive/introduction/ReactorIntegrationTest.java +++ b/spring-reactive/src/test/java/com/baeldung/reactive/introduction/ReactorIntegrationTest.java @@ -101,7 +101,8 @@ public class ReactorIntegrationTest { Thread.sleep(1000); - assertThat(threadNames).containsExactly("parallel-1", "parallel-1", "parallel-1", "parallel-1"); + assertThat(threadNames).isNotEmpty(); + assertThat(threadNames).hasSize(4); } @Test diff --git a/spring-reactive/src/test/resources/logback-test.xml b/spring-reactive/src/test/resources/logback-test.xml index 8d4771e308..69c10177a9 100644 --- a/spring-reactive/src/test/resources/logback-test.xml +++ b/spring-reactive/src/test/resources/logback-test.xml @@ -1,12 +1,16 @@ - - - - [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n - + + + - - - + + + + + + \ No newline at end of file diff --git a/spring-scheduling/src/main/java/com/baeldung/scheduling/SpringSchedulingConfig.java b/spring-scheduling/src/main/java/com/baeldung/scheduling/SpringSchedulingConfig.java index 5d7f1cf88f..4bdfad3267 100644 --- a/spring-scheduling/src/main/java/com/baeldung/scheduling/SpringSchedulingConfig.java +++ b/spring-scheduling/src/main/java/com/baeldung/scheduling/SpringSchedulingConfig.java @@ -5,7 +5,9 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; @Configuration @EnableScheduling @@ -13,6 +15,14 @@ import org.springframework.scheduling.annotation.EnableScheduling; @PropertySource("classpath:springScheduled.properties") public class SpringSchedulingConfig { + @Bean + public TaskScheduler taskScheduler() { + ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler(); + threadPoolTaskScheduler.setPoolSize(5); + threadPoolTaskScheduler.setThreadNamePrefix("ThreadPoolTaskScheduler"); + return threadPoolTaskScheduler; + } + @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); diff --git a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/config/PasswordEncoderConfig.java b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/config/PasswordEncoderConfig.java new file mode 100644 index 0000000000..5df32d6392 --- /dev/null +++ b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/config/PasswordEncoderConfig.java @@ -0,0 +1,15 @@ +package com.baeldung.app.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class PasswordEncoderConfig { + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/config/WebSecurityConfig.java b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/config/WebSecurityConfig.java index 15af160135..c0abd3cec1 100644 --- a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/config/WebSecurityConfig.java +++ b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/config/WebSecurityConfig.java @@ -22,15 +22,11 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { } @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + public void configureGlobal(AuthenticationManagerBuilder auth, PasswordEncoder passwordEncoder) throws Exception { auth.inMemoryAuthentication() - .withUser("jim").password(passwordEncoder().encode("jim")).roles("USER", "ACTUATOR") - .and().withUser("pam").password(passwordEncoder().encode("pam")).roles("USER") - .and().withUser("michael").password(passwordEncoder().encode("michael")).roles("MANAGER"); - } - - @Bean - public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); + .withUser("jim").password(passwordEncoder.encode("jim")).roles("USER", "ACTUATOR") + .and().withUser("pam").password(passwordEncoder.encode("pam")).roles("USER") + .and().withUser("michael").password(passwordEncoder.encode("michael")).roles("MANAGER"); } + } diff --git a/spring-security-modules/spring-security-web-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/config/PasswordEncoderConfig.java b/spring-security-modules/spring-security-web-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/config/PasswordEncoderConfig.java new file mode 100644 index 0000000000..4c21b315fb --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/config/PasswordEncoderConfig.java @@ -0,0 +1,15 @@ +package com.baeldung.jdbcauthentication.h2.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class PasswordEncoderConfig { + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/spring-security-modules/spring-security-web-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java b/spring-security-modules/spring-security-web-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java index 50dc5b6958..49804e8458 100644 --- a/spring-security-modules/spring-security-web-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java +++ b/spring-security-modules/spring-security-web-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java @@ -1,19 +1,18 @@ package com.baeldung.jdbcauthentication.h2.config; -import javax.sql.DataSource; - import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; 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.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; +import javax.sql.DataSource; + @Configuration public class SecurityConfiguration extends WebSecurityConfigurerAdapter { + @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.authorizeRequests() @@ -32,20 +31,15 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { } @Autowired - private DataSource dataSource; - - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + public void configureGlobal(AuthenticationManagerBuilder auth, + DataSource dataSource, + PasswordEncoder passwordEncoder) throws Exception { auth.jdbcAuthentication() - .dataSource(dataSource) - .withDefaultSchema() - .withUser(User.withUsername("user") - .password(passwordEncoder().encode("pass")) - .roles("USER")); + .dataSource(dataSource) + .withDefaultSchema() + .withUser(User.withUsername("user") + .password(passwordEncoder.encode("pass")) + .roles("USER")); } - @Bean - public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } } \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-boot-3/README.md b/spring-security-modules/spring-security-web-boot-3/README.md index e95071b825..45fede7a4c 100644 --- a/spring-security-modules/spring-security-web-boot-3/README.md +++ b/spring-security-modules/spring-security-web-boot-3/README.md @@ -11,4 +11,5 @@ The "REST With Spring" Classes: http://github.learnspringsecurity.com - [Spring Security – Request Rejected Exception](https://www.baeldung.com/spring-security-request-rejected-exception) - [Spring Security – Cache Control Headers](https://www.baeldung.com/spring-security-cache-control-headers) - [Fixing 401s with CORS Preflights and Spring Security](https://www.baeldung.com/spring-security-cors-preflight) +- [Content Security Policy with Spring Security](https://www.baeldung.com/spring-security-csp) - More articles: [[<-- prev]](/spring-security-modules/spring-security-web-boot-2) diff --git a/spring-security-modules/spring-security-web-boot-3/pom.xml b/spring-security-modules/spring-security-web-boot-3/pom.xml index b26ca094be..5bfd07c8b5 100644 --- a/spring-security-modules/spring-security-web-boot-3/pom.xml +++ b/spring-security-modules/spring-security-web-boot-3/pom.xml @@ -1,7 +1,5 @@ - + 4.0.0 spring-security-web-boot-3 0.0.1-SNAPSHOT @@ -25,6 +23,25 @@ org.springframework.boot spring-boot-starter-web + + commons-io + commons-io + 2.11.0 + + + org.webjars + webjars-locator-core + + + org.webjars + bootstrap + 5.1.1 + + + org.webjars + jquery + 3.6.0 + org.springframework.boot spring-boot-starter-test diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/contentsecuritypolicy/ContentSecurityPolicyApplication.java b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/contentsecuritypolicy/ContentSecurityPolicyApplication.java new file mode 100644 index 0000000000..d009f64918 --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/contentsecuritypolicy/ContentSecurityPolicyApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.contentsecuritypolicy; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ContentSecurityPolicyApplication { + public static void main(String[] args) { + SpringApplication.run(ContentSecurityPolicyApplication.class, args); + } +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/contentsecuritypolicy/ContentSecurityPolicyController.java b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/contentsecuritypolicy/ContentSecurityPolicyController.java new file mode 100644 index 0000000000..f57833fd7b --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/contentsecuritypolicy/ContentSecurityPolicyController.java @@ -0,0 +1,23 @@ +package com.baeldung.contentsecuritypolicy; + +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +@RestController +public class ContentSecurityPolicyController { + private static final Logger logger = LoggerFactory.getLogger(ContentSecurityPolicyController.class); + + @PostMapping("/report") + public void report(HttpServletRequest request) throws IOException { + if (logger.isInfoEnabled()) { + logger.info("Report: {}", IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8)); + } + } +} diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/contentsecuritypolicy/ContentSecurityPolicySecurityConfiguration.java b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/contentsecuritypolicy/ContentSecurityPolicySecurityConfiguration.java new file mode 100644 index 0000000000..1593af9c66 --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/contentsecuritypolicy/ContentSecurityPolicySecurityConfiguration.java @@ -0,0 +1,26 @@ +package com.baeldung.contentsecuritypolicy; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.header.writers.StaticHeadersWriter; + +@Configuration +public class ContentSecurityPolicySecurityConfiguration extends WebSecurityConfigurerAdapter { + private static final String REPORT_TO = "{\"group\":\"csp-violation-report\",\"max_age\":2592000,\"endpoints\":[{\"url\":\"https://localhost:8080/report\"}]}"; + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf() + .disable() + .authorizeRequests() + .antMatchers("/**") + .permitAll() + .and() + .headers() + .addHeaderWriter(new StaticHeadersWriter("Report-To", REPORT_TO)) + .xssProtection() + .and() + .contentSecurityPolicy("form-action 'self'; report-uri /report; report-to csp-violation-report"); + } +} diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/resources/static/index.html b/spring-security-modules/spring-security-web-boot-3/src/main/resources/static/index.html new file mode 100644 index 0000000000..52ecb198df --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-3/src/main/resources/static/index.html @@ -0,0 +1,67 @@ + + + + Content Security Policy + + + + + + + + + + +
+
+ +
+
+ +
+
+
+
+
+
+

Login

+
+
+
+ + +
+
+
+ + +
+ +
+ +
+
+
+ +
+
+ +
+ + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/resources/static/main.css b/spring-security-modules/spring-security-web-boot-3/src/main/resources/static/main.css new file mode 100644 index 0000000000..dac839bc64 --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-3/src/main/resources/static/main.css @@ -0,0 +1,26 @@ +html, body{ + font-family: Raleway, serif; + background-color: #f5f5f5; +} +.navbar +{ + background-color: #63b175 !important; +} +.navbar-brand +{ + font-size: 1.75rem; + font-weight: bold; +} +/* +hr{ + border: 0px dotted rgba(249, 249, 249, 0.88); +}*/ + +hr { + border: 0; + border-bottom: 1px dashed #969595; + background: #969595; +} +label{ + font-weight: bold; +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-boot-3/src/test/java/com/baeldung/contentsecuritypolicy/ContentSecurityPolicyUnitTest.java b/spring-security-modules/spring-security-web-boot-3/src/test/java/com/baeldung/contentsecuritypolicy/ContentSecurityPolicyUnitTest.java new file mode 100644 index 0000000000..0e06a7ef35 --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-3/src/test/java/com/baeldung/contentsecuritypolicy/ContentSecurityPolicyUnitTest.java @@ -0,0 +1,64 @@ +package com.baeldung.contentsecuritypolicy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; + +import org.springframework.http.HttpStatus; + +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; + +import javax.servlet.http.HttpServletResponse; + +import java.util.Collection; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; + +@WebMvcTest +@AutoConfigureMockMvc +@DisplayName("Content Security Policy Unit Tests") +class ContentSecurityPolicyUnitTest { + + @Autowired + private MockMvc mockMvc; + + @Test + @DisplayName("Test to Check Bad URL") + void whenWrongUri_thenThrow404() throws Exception { + MvcResult result = mockMvc.perform(post("/reports").content("").contentType(MediaType.APPLICATION_JSON)).andReturn(); + + assertEquals(HttpStatus.NOT_FOUND.value(), result.getResponse().getStatus()); + } + + @Test + @DisplayName("Test to Check Page rendering") + void whenGet_thenRenderPage() throws Exception { + MvcResult result = mockMvc.perform(get("/").content("")).andReturn(); + + assertEquals(HttpStatus.OK.value(), result.getResponse().getStatus()); + assertEquals("text/html", MediaType.TEXT_HTML_VALUE); + } + + @Test + @DisplayName("Test to Check CSP headers") + void whenGet_thenCheckCspHeaders() throws Exception { + MvcResult result = mockMvc.perform(get("/").content("")).andReturn(); + HttpServletResponse response = result.getResponse(); + Collection headers = response.getHeaderNames(); + + assertNotNull(result); + assertNotNull(headers); + assertEquals(HttpStatus.OK.value(), response.getStatus()); + assertEquals("text/html", MediaType.TEXT_HTML_VALUE); + assertTrue(headers.contains("Report-To")); + assertTrue(headers.contains("Content-Security-Policy")); + } +} 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 1403154767..f435a4204e 100644 --- a/spring-security-modules/spring-security-web-rest-custom/pom.xml +++ b/spring-security-modules/spring-security-web-rest-custom/pom.xml @@ -115,12 +115,6 @@ commons-lang3 ${commons-lang3.version}
- - - org.mockito - mockito-core - test - diff --git a/spring-security-modules/spring-security-web-thymeleaf/src/main/java/com/baeldung/springsecuritythymeleaf/PasswordEncoderConfiguration.java b/spring-security-modules/spring-security-web-thymeleaf/src/main/java/com/baeldung/springsecuritythymeleaf/PasswordEncoderConfiguration.java new file mode 100644 index 0000000000..5ffe2c35f9 --- /dev/null +++ b/spring-security-modules/spring-security-web-thymeleaf/src/main/java/com/baeldung/springsecuritythymeleaf/PasswordEncoderConfiguration.java @@ -0,0 +1,15 @@ +package com.baeldung.springsecuritythymeleaf; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class PasswordEncoderConfiguration { + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/spring-security-modules/spring-security-web-thymeleaf/src/main/java/com/baeldung/springsecuritythymeleaf/SecurityConfiguration.java b/spring-security-modules/spring-security-web-thymeleaf/src/main/java/com/baeldung/springsecuritythymeleaf/SecurityConfiguration.java index f7f8cfb708..8e9047f629 100644 --- a/spring-security-modules/spring-security-web-thymeleaf/src/main/java/com/baeldung/springsecuritythymeleaf/SecurityConfiguration.java +++ b/spring-security-modules/spring-security-web-thymeleaf/src/main/java/com/baeldung/springsecuritythymeleaf/SecurityConfiguration.java @@ -8,6 +8,7 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @@ -32,19 +33,15 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { } @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + public void configureGlobal(AuthenticationManagerBuilder auth, PasswordEncoder passwordEncoder) throws Exception { auth.inMemoryAuthentication() .withUser("user") - .password(passwordEncoder().encode("password")) + .password(passwordEncoder.encode("password")) .roles("USER") .and() .withUser("admin") - .password(passwordEncoder().encode("admin")) + .password(passwordEncoder.encode("admin")) .roles("ADMIN"); } - - @Bean - public BCryptPasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } + } diff --git a/spring-security-modules/spring-security-web-thymeleaf/src/test/java/com/baeldung/springsecuritythymeleaf/ViewControllerIntegrationTest.java b/spring-security-modules/spring-security-web-thymeleaf/src/test/java/com/baeldung/springsecuritythymeleaf/ViewControllerIntegrationTest.java index c87d1bacc3..606a33dcf5 100644 --- a/spring-security-modules/spring-security-web-thymeleaf/src/test/java/com/baeldung/springsecuritythymeleaf/ViewControllerIntegrationTest.java +++ b/spring-security-modules/spring-security-web-thymeleaf/src/test/java/com/baeldung/springsecuritythymeleaf/ViewControllerIntegrationTest.java @@ -9,11 +9,13 @@ 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.context.annotation.Import; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; @RunWith(SpringRunner.class) @WebMvcTest +@Import(PasswordEncoderConfiguration.class) public class ViewControllerIntegrationTest { @Autowired diff --git a/spring-security-modules/spring-session/spring-session-mongodb/src/test/resources/application.properties b/spring-security-modules/spring-session/spring-session-mongodb/src/test/resources/application.properties index 4ee830556a..f97ea98811 100644 --- a/spring-security-modules/spring-session/spring-session-mongodb/src/test/resources/application.properties +++ b/spring-security-modules/spring-session/spring-session-mongodb/src/test/resources/application.properties @@ -1,2 +1,4 @@ #To use a randomly allocated free port during tests to avoid port conflict across tests spring.data.mongodb.port=0 + +spring.mongodb.embedded.version=3.5.5 diff --git a/spring-security-modules/spring-session/spring-session-redis/src/main/java/com/baeldung/spring/session/PasswordEncoderConfig.java b/spring-security-modules/spring-session/spring-session-redis/src/main/java/com/baeldung/spring/session/PasswordEncoderConfig.java new file mode 100644 index 0000000000..d9d0725204 --- /dev/null +++ b/spring-security-modules/spring-session/spring-session-redis/src/main/java/com/baeldung/spring/session/PasswordEncoderConfig.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.session; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class PasswordEncoderConfig { + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/spring-security-modules/spring-session/spring-session-redis/src/main/java/com/baeldung/spring/session/SecurityConfig.java b/spring-security-modules/spring-session/spring-session-redis/src/main/java/com/baeldung/spring/session/SecurityConfig.java index 678c98e7eb..d9476d7704 100644 --- a/spring-security-modules/spring-session/spring-session-redis/src/main/java/com/baeldung/spring/session/SecurityConfig.java +++ b/spring-security-modules/spring-session/spring-session-redis/src/main/java/com/baeldung/spring/session/SecurityConfig.java @@ -15,8 +15,8 @@ import org.springframework.security.crypto.password.PasswordEncoder; public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser("admin").password(passwordEncoder().encode("password")).roles("ADMIN"); + public void configureGlobal(AuthenticationManagerBuilder auth, PasswordEncoder passwordEncoder) throws Exception { + auth.inMemoryAuthentication().withUser("admin").password(passwordEncoder.encode("password")).roles("ADMIN"); } @Override @@ -24,8 +24,4 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { http.httpBasic().and().authorizeRequests().antMatchers("/").hasRole("ADMIN").anyRequest().authenticated(); } - @Bean - public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } } diff --git a/spring-web-modules/pom.xml b/spring-web-modules/pom.xml index 96aeb514a0..d66d9cb35a 100644 --- a/spring-web-modules/pom.xml +++ b/spring-web-modules/pom.xml @@ -30,6 +30,7 @@ spring-mvc-views spring-mvc-webflow spring-mvc-xml + spring-mvc-xml-2 spring-rest-angular spring-rest-http spring-rest-http-2 @@ -43,8 +44,10 @@ spring-thymeleaf spring-thymeleaf-2 spring-thymeleaf-3 + spring-thymeleaf-4 + spring-thymeleaf-5 spring-boot-jsp spring-web-url -
\ No newline at end of file +
diff --git a/spring-web-modules/spring-mvc-basics-3/README.md b/spring-web-modules/spring-mvc-basics-3/README.md index 391c8380ab..3f506f7467 100644 --- a/spring-web-modules/spring-mvc-basics-3/README.md +++ b/spring-web-modules/spring-mvc-basics-3/README.md @@ -5,9 +5,9 @@ This module contains articles about Spring MVC ## Relevant articles: - [How to Read HTTP Headers in Spring REST Controllers](https://www.baeldung.com/spring-rest-http-headers) - [A Custom Data Binder in Spring MVC](https://www.baeldung.com/spring-mvc-custom-data-binder) -- [Validating Lists in a Spring Controller](https://www.baeldung.com/spring-validate-list-controller) - [Spring Validation Message Interpolation](https://www.baeldung.com/spring-validation-message-interpolation) - [Using Enums as Request Parameters in Spring](https://www.baeldung.com/spring-enum-request-param) - [Guide to Flash Attributes in a Spring Web Application](https://www.baeldung.com/spring-web-flash-attributes) - [Reading HttpServletRequest Multiple Times in Spring](https://www.baeldung.com/spring-reading-httpservletrequest-multiple-times) -- More articles: [[<-- prev]](../spring-mvc-basics-2)[[more -->]](../spring-mvc-basics-4) +- [Intro to Spring Boot Starters](https://www.baeldung.com/spring-boot-starters) +- More articles: [[<-- prev]](../spring-mvc-basics-2)[[more -->]](../spring-mvc-basics-4) \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/README.md b/spring-web-modules/spring-mvc-basics-4/README.md index 50ceb724d1..e3211a87df 100644 --- a/spring-web-modules/spring-mvc-basics-4/README.md +++ b/spring-web-modules/spring-mvc-basics-4/README.md @@ -10,4 +10,5 @@ The "REST With Spring" Classes: https://bit.ly/restwithspring - [Spring Optional Path variables](https://www.baeldung.com/spring-optional-path-variables) - [JSON Parameters with Spring MVC](https://www.baeldung.com/spring-mvc-send-json-parameters) - [How to Set JSON Content Type In Spring MVC](https://www.baeldung.com/spring-mvc-set-json-content-type) -- More articles: [[<-- prev]](../spring-mvc-basics-3)[[more -->]](../spring-mvc-basics-5) +- [Validating Lists in a Spring Controller](https://www.baeldung.com/spring-validate-list-controller) +- More articles: [[<-- prev]](../spring-mvc-basics-3)[[next -->]](../spring-mvc-basics-5) diff --git a/spring-web-modules/spring-mvc-basics-4/pom.xml b/spring-web-modules/spring-mvc-basics-4/pom.xml index 067d1ed3b1..376e13ed72 100644 --- a/spring-web-modules/spring-mvc-basics-4/pom.xml +++ b/spring-web-modules/spring-mvc-basics-4/pom.xml @@ -23,6 +23,10 @@ org.springframework spring-web + + org.springframework.boot + spring-boot-starter-validation + javax.servlet javax.servlet-api diff --git a/spring-web-modules/spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/SpringListValidationApplication.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/SpringListValidationApplication.java similarity index 100% rename from spring-web-modules/spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/SpringListValidationApplication.java rename to spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/SpringListValidationApplication.java diff --git a/spring-web-modules/spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraint.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraint.java similarity index 100% rename from spring-web-modules/spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraint.java rename to spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraint.java diff --git a/spring-web-modules/spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraintValidator.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraintValidator.java similarity index 100% rename from spring-web-modules/spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraintValidator.java rename to spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraintValidator.java diff --git a/spring-web-modules/spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/controller/MovieController.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/controller/MovieController.java similarity index 100% rename from spring-web-modules/spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/controller/MovieController.java rename to spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/controller/MovieController.java diff --git a/spring-web-modules/spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/exception/ConstraintViolationExceptionHandler.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/exception/ConstraintViolationExceptionHandler.java similarity index 100% rename from spring-web-modules/spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/exception/ConstraintViolationExceptionHandler.java rename to spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/exception/ConstraintViolationExceptionHandler.java diff --git a/spring-web-modules/spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/model/Movie.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/model/Movie.java similarity index 100% rename from spring-web-modules/spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/model/Movie.java rename to spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/model/Movie.java diff --git a/spring-web-modules/spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/service/MovieService.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/service/MovieService.java similarity index 100% rename from spring-web-modules/spring-mvc-basics-3/src/main/java/com/baeldung/validation/listvalidation/service/MovieService.java rename to spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/service/MovieService.java diff --git a/spring-web-modules/spring-mvc-basics-3/src/test/java/com/baeldung/validation/listvalidation/MovieControllerIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/validation/listvalidation/MovieControllerIntegrationTest.java similarity index 100% rename from spring-web-modules/spring-mvc-basics-3/src/test/java/com/baeldung/validation/listvalidation/MovieControllerIntegrationTest.java rename to spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/validation/listvalidation/MovieControllerIntegrationTest.java diff --git a/spring-web-modules/spring-mvc-basics-5/src/main/resources/application.properties b/spring-web-modules/spring-mvc-basics-5/src/main/resources/application.properties index 935f91554b..c6d55580a3 100644 --- a/spring-web-modules/spring-mvc-basics-5/src/main/resources/application.properties +++ b/spring-web-modules/spring-mvc-basics-5/src/main/resources/application.properties @@ -1 +1,3 @@ server.servlet.context-path=/spring-mvc-basics + +spring.mvc.pathmatch.matching-strategy=ant-path-matcher diff --git a/spring-web-modules/spring-mvc-basics/src/main/resources/application.properties b/spring-web-modules/spring-mvc-basics/src/main/resources/application.properties index b8a9be0b40..d25df689e3 100644 --- a/spring-web-modules/spring-mvc-basics/src/main/resources/application.properties +++ b/spring-web-modules/spring-mvc-basics/src/main/resources/application.properties @@ -1,7 +1,8 @@ server.servlet.context-path=/spring-mvc-basics ### Content Negotiation (already defined programatically) -spring.mvc.pathmatch.use-suffix-pattern=true #spring.mvc.contentnegotiation.favor-path-extension=true #spring.mvc.contentnegotiation.favor-parameter=true #spring.mvc.contentnegotiation.parameter-name=mediaType +spring.mvc.pathmatch.use-suffix-pattern=true +spring.mvc.pathmatch.matching-strategy=ant-path-matcher \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-xml-2/.gitignore b/spring-web-modules/spring-mvc-xml-2/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-web-modules/spring-mvc-xml-2/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-xml-2/README.md b/spring-web-modules/spring-mvc-xml-2/README.md new file mode 100644 index 0000000000..05a6172fa1 --- /dev/null +++ b/spring-web-modules/spring-mvc-xml-2/README.md @@ -0,0 +1,14 @@ +## Spring MVC XML + +This module contains articles about Spring MVC with XML configuration + +### The Course + +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: + +- [Exploring SpringMVC’s Form Tag Library](https://www.baeldung.com/spring-mvc-form-tags) +- [Validating RequestParams and PathVariables in Spring](https://www.baeldung.com/spring-validate-requestparam-pathvariable) +- [Debugging the Spring MVC 404 “No mapping found for HTTP request” Error](https://www.baeldung.com/spring-mvc-404-error) +- More articles: [[<-- prev]](../spring-mvc-xml) diff --git a/spring-web-modules/spring-mvc-xml-2/pom.xml b/spring-web-modules/spring-mvc-xml-2/pom.xml new file mode 100644 index 0000000000..e65259d512 --- /dev/null +++ b/spring-web-modules/spring-mvc-xml-2/pom.xml @@ -0,0 +1,101 @@ + + + 4.0.0 + spring-mvc-xml-2 + 0.1-SNAPSHOT + spring-mvc-xml-2 + war + + + com.baeldung + spring-web-modules + 0.0.1-SNAPSHOT + + + + + + org.springframework + spring-web + ${org.springframework.version} + + + org.springframework + spring-webmvc + ${org.springframework.version} + + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + provided + + + javax.servlet + jstl + ${jstl.version} + runtime + + + org.hibernate.validator + hibernate-validator + ${hibernate-validator.version} + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + commons-io + commons-io + ${commons-io.version} + + + org.glassfish + javax.el + ${javax.el.version} + + + org.springframework.boot + spring-boot-starter-test + ${spring-boot.version} + test + + + + + spring-mvc-xml + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + + + + + 5.0.2.RELEASE + 1.5.10.RELEASE + 5.1.40 + 4.4.5 + 4.5.2 + 6.0.10.Final + 3.0.1-b08 + 19.0 + 1.6.1 + + + diff --git a/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/ClientWebConfig.java b/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/ClientWebConfig.java new file mode 100644 index 0000000000..a464717f5d --- /dev/null +++ b/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/ClientWebConfig.java @@ -0,0 +1,17 @@ +package com.baeldung.spring; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportResource; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@ImportResource("classpath:webMvcConfig.xml") +@Configuration +@ComponentScan +public class ClientWebConfig implements WebMvcConfigurer { + + public ClientWebConfig() { + super(); + } + +} \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java b/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/ClientWebConfigJava.java similarity index 96% rename from spring-web-modules/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java rename to spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/ClientWebConfigJava.java index 09c34ccc80..dc8db43e41 100644 --- a/spring-web-modules/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java +++ b/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/ClientWebConfigJava.java @@ -6,6 +6,7 @@ import java.util.ResourceBundle; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; import org.springframework.context.support.MessageSourceResourceBundle; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.validation.beanvalidation.MethodValidationPostProcessor; @@ -54,7 +55,7 @@ public class ClientWebConfigJava implements WebMvcConfigurer { return bean; } - + @Bean public MethodValidationPostProcessor methodValidationPostProcessor() { return new MethodValidationPostProcessor(); diff --git a/spring-web-modules/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ConstraintViolationExceptionHandler.java b/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/controller/ConstraintViolationExceptionHandler.java similarity index 100% rename from spring-web-modules/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ConstraintViolationExceptionHandler.java rename to spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/controller/ConstraintViolationExceptionHandler.java diff --git a/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/nomapping/GreetingController.java b/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/nomapping/GreetingController.java new file mode 100644 index 0000000000..5016113d30 --- /dev/null +++ b/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/nomapping/GreetingController.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.nomapping; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +public class GreetingController { + + @RequestMapping(value = "/greeting", method = RequestMethod.GET) + public String get(ModelMap model) { + model.addAttribute("message", "Hello, World!"); + return "greeting"; + } +} \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/RequestAndPathVariableValidationController.java b/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/paramsvalidation/RequestAndPathVariableValidationController.java similarity index 79% rename from spring-web-modules/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/RequestAndPathVariableValidationController.java rename to spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/paramsvalidation/RequestAndPathVariableValidationController.java index b77598c113..4768237871 100644 --- a/spring-web-modules/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/RequestAndPathVariableValidationController.java +++ b/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/paramsvalidation/RequestAndPathVariableValidationController.java @@ -1,12 +1,17 @@ -package com.baeldung.spring.controller; +package com.baeldung.spring.paramsvalidation; -import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.GetMapping; import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.*; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; + +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; @Controller @RequestMapping("/public/api/1") diff --git a/spring-web-modules/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Person.java b/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/taglibrary/Person.java similarity index 98% rename from spring-web-modules/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Person.java rename to spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/taglibrary/Person.java index 307a36b10f..ed2fa903ef 100644 --- a/spring-web-modules/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Person.java +++ b/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/taglibrary/Person.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.form; +package com.baeldung.spring.taglibrary; import java.util.List; diff --git a/spring-web-modules/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/PersonController.java b/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/taglibrary/PersonController.java similarity index 95% rename from spring-web-modules/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/PersonController.java rename to spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/taglibrary/PersonController.java index 71d9ad7845..0fcb66f2dd 100644 --- a/spring-web-modules/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/PersonController.java +++ b/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/taglibrary/PersonController.java @@ -1,14 +1,5 @@ -package com.baeldung.spring.controller; +package com.baeldung.spring.taglibrary; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.validation.Valid; - -import com.baeldung.spring.form.Person; -import com.baeldung.spring.validator.PersonValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; @@ -19,6 +10,12 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; +import javax.validation.Valid; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + @Controller public class PersonController { diff --git a/spring-web-modules/spring-mvc-xml/src/main/java/com/baeldung/spring/validator/PersonValidator.java b/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/taglibrary/PersonValidator.java similarity index 87% rename from spring-web-modules/spring-mvc-xml/src/main/java/com/baeldung/spring/validator/PersonValidator.java rename to spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/taglibrary/PersonValidator.java index cda756cdfc..9f437429ae 100644 --- a/spring-web-modules/spring-mvc-xml/src/main/java/com/baeldung/spring/validator/PersonValidator.java +++ b/spring-web-modules/spring-mvc-xml-2/src/main/java/com/baeldung/spring/taglibrary/PersonValidator.java @@ -1,6 +1,5 @@ -package com.baeldung.spring.validator; +package com.baeldung.spring.taglibrary; -import com.baeldung.spring.form.Person; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; diff --git a/spring-web-modules/spring-mvc-xml-2/src/main/resources/logback.xml b/spring-web-modules/spring-mvc-xml-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..56af2d397e --- /dev/null +++ b/spring-web-modules/spring-mvc-xml-2/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-xml-2/src/main/resources/messages.properties b/spring-web-modules/spring-mvc-xml-2/src/main/resources/messages.properties new file mode 100644 index 0000000000..a58f51db3e --- /dev/null +++ b/spring-web-modules/spring-mvc-xml-2/src/main/resources/messages.properties @@ -0,0 +1,3 @@ +required.name = Name is required! +NotEmpty.person.password = Password is required! + diff --git a/spring-web-modules/spring-mvc-xml-2/src/main/resources/webMvcConfig.xml b/spring-web-modules/spring-mvc-xml-2/src/main/resources/webMvcConfig.xml new file mode 100644 index 0000000000..5dcdef6ad4 --- /dev/null +++ b/spring-web-modules/spring-mvc-xml-2/src/main/resources/webMvcConfig.xml @@ -0,0 +1,40 @@ + + + + + + + + + image/jpeg + image/png + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-web-modules/spring-mvc-xml-2/src/main/webapp/WEB-INF/mvc-servlet.xml b/spring-web-modules/spring-mvc-xml-2/src/main/webapp/WEB-INF/mvc-servlet.xml new file mode 100644 index 0000000000..e27665da95 --- /dev/null +++ b/spring-web-modules/spring-mvc-xml-2/src/main/webapp/WEB-INF/mvc-servlet.xml @@ -0,0 +1,12 @@ + + + + + + + diff --git a/spring-web-modules/spring-mvc-xml-2/src/main/webapp/WEB-INF/view/greeting.jsp b/spring-web-modules/spring-mvc-xml-2/src/main/webapp/WEB-INF/view/greeting.jsp new file mode 100644 index 0000000000..ac17c75ab7 --- /dev/null +++ b/spring-web-modules/spring-mvc-xml-2/src/main/webapp/WEB-INF/view/greeting.jsp @@ -0,0 +1,9 @@ +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + Greeting + + +

${message}

+ + \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp b/spring-web-modules/spring-mvc-xml-2/src/main/webapp/WEB-INF/view/personForm.jsp similarity index 100% rename from spring-web-modules/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp rename to spring-web-modules/spring-mvc-xml-2/src/main/webapp/WEB-INF/view/personForm.jsp diff --git a/spring-web-modules/spring-mvc-xml/src/main/webapp/WEB-INF/view/personView.jsp b/spring-web-modules/spring-mvc-xml-2/src/main/webapp/WEB-INF/view/personView.jsp similarity index 100% rename from spring-web-modules/spring-mvc-xml/src/main/webapp/WEB-INF/view/personView.jsp rename to spring-web-modules/spring-mvc-xml-2/src/main/webapp/WEB-INF/view/personView.jsp diff --git a/spring-web-modules/spring-mvc-xml-2/src/main/webapp/WEB-INF/view/sample.jsp b/spring-web-modules/spring-mvc-xml-2/src/main/webapp/WEB-INF/view/sample.jsp new file mode 100644 index 0000000000..7cc14b5dcd --- /dev/null +++ b/spring-web-modules/spring-mvc-xml-2/src/main/webapp/WEB-INF/view/sample.jsp @@ -0,0 +1,7 @@ + + + + +

This is the body of the sample view

+ + \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-xml-2/src/main/webapp/WEB-INF/web.xml b/spring-web-modules/spring-mvc-xml-2/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..e704d2eba3 --- /dev/null +++ b/spring-web-modules/spring-mvc-xml-2/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,47 @@ + + + Spring MVC XML Application + + + + contextClass + + org.springframework.web.context.support.AnnotationConfigWebApplicationContext + + + + contextConfigLocation + com.baeldung.spring + + + + org.springframework.web.context.ContextLoaderListener + + + + + mvc + org.springframework.web.servlet.DispatcherServlet + 1 + + + mvc + / + + + + + 10 + + + index.jsp + + + + /errors + + diff --git a/spring-web-modules/spring-mvc-xml-2/src/main/webapp/index.jsp b/spring-web-modules/spring-mvc-xml-2/src/main/webapp/index.jsp new file mode 100644 index 0000000000..14872cf3ba --- /dev/null +++ b/spring-web-modules/spring-mvc-xml-2/src/main/webapp/index.jsp @@ -0,0 +1,15 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Spring MVC Examples + + + +

Spring MVC Examples

+ + + \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-xml-2/src/test/java/com/baeldung/SpringContextTest.java b/spring-web-modules/spring-mvc-xml-2/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..62e34859ee --- /dev/null +++ b/spring-web-modules/spring-mvc-xml-2/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.spring.ClientWebConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = ClientWebConfig.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-web-modules/spring-mvc-xml/src/test/java/com/baeldung/spring/controller/RequestAndPathVariableValidationControllerIntegrationTest.java b/spring-web-modules/spring-mvc-xml-2/src/test/java/com/baeldung/spring/paramsvalidation/RequestAndPathVariableValidationControllerIntegrationTest.java similarity index 90% rename from spring-web-modules/spring-mvc-xml/src/test/java/com/baeldung/spring/controller/RequestAndPathVariableValidationControllerIntegrationTest.java rename to spring-web-modules/spring-mvc-xml-2/src/test/java/com/baeldung/spring/paramsvalidation/RequestAndPathVariableValidationControllerIntegrationTest.java index c4332dd879..a71a024e62 100644 --- a/spring-web-modules/spring-mvc-xml/src/test/java/com/baeldung/spring/controller/RequestAndPathVariableValidationControllerIntegrationTest.java +++ b/spring-web-modules/spring-mvc-xml-2/src/test/java/com/baeldung/spring/paramsvalidation/RequestAndPathVariableValidationControllerIntegrationTest.java @@ -1,5 +1,6 @@ -package com.baeldung.spring.controller; +package com.baeldung.spring.paramsvalidation; +import com.baeldung.spring.ClientWebConfigJava; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -11,9 +12,6 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.spring.ClientWebConfig; -import com.baeldung.spring.ClientWebConfigJava; - import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -35,13 +33,13 @@ public class RequestAndPathVariableValidationControllerIntegrationTest { @Test public void getNameOfDayByNumberRequestParam_whenGetWithProperRequestParam_thenReturn200() throws Exception { mockMvc.perform(get("/public/api/1/name-for-day").param("dayOfWeek", Integer.toString(5))) - .andExpect(status().isOk()); + .andExpect(status().isOk()); } @Test public void getNameOfDayByNumberRequestParam_whenGetWithRequestParamOutOfRange_thenReturn400() throws Exception { mockMvc.perform(get("/public/api/1/name-for-day").param("dayOfWeek", Integer.toString(15))) - .andExpect(status().isBadRequest()); + .andExpect(status().isBadRequest()); } @Test @@ -52,7 +50,7 @@ public class RequestAndPathVariableValidationControllerIntegrationTest { @Test public void getNameOfDayByPathVariable_whenGetWithRequestParamOutOfRange_thenReturn400() throws Exception { mockMvc.perform(get("/public/api/1/name-for-day/{dayOfWeek}", Integer.toString(15))) - .andExpect(status().isBadRequest()); + .andExpect(status().isBadRequest()); } @Test @@ -63,7 +61,7 @@ public class RequestAndPathVariableValidationControllerIntegrationTest { @Test public void validStringRequestParam_whenGetWithTooLongRequestParam_thenReturn400() throws Exception { mockMvc.perform(get("/public/api/1/valid-name").param("name", "asdfghjklqw")) - .andExpect(status().isBadRequest()); + .andExpect(status().isBadRequest()); } @Test diff --git a/spring-web-modules/spring-mvc-xml/README.md b/spring-web-modules/spring-mvc-xml/README.md index 3fbea3626b..3260d91d94 100644 --- a/spring-web-modules/spring-mvc-xml/README.md +++ b/spring-web-modules/spring-mvc-xml/README.md @@ -12,12 +12,10 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Returning Image/Media Data with Spring MVC](https://www.baeldung.com/spring-mvc-image-media-data) - [Geolocation by IP in Java](https://www.baeldung.com/geolocation-by-ip-with-maxmind) - [Guide to JavaServer Pages (JSP)](https://www.baeldung.com/jsp) -- [Exploring SpringMVC’s Form Tag Library](https://www.baeldung.com/spring-mvc-form-tags) - [web.xml vs Initializer with Spring](https://www.baeldung.com/spring-xml-vs-java-config) - [A Java Web Application Without a web.xml](https://www.baeldung.com/java-web-app-without-web-xml) -- [Validating RequestParams and PathVariables in Spring](https://www.baeldung.com/spring-validate-requestparam-pathvariable) -- [Debugging the Spring MVC 404 “No mapping found for HTTP request” Error](https://www.baeldung.com/spring-mvc-404-error) - [Introduction to Servlets and Servlet Containers](https://www.baeldung.com/java-servlets-containers-intro) +- More articles: [[more -->]](../spring-mvc-xml-2) ## Spring MVC with XML Configuration Example Project diff --git a/spring-web-modules/spring-mvc-xml/pom.xml b/spring-web-modules/spring-mvc-xml/pom.xml index e67052e0cd..c814787ba7 100644 --- a/spring-web-modules/spring-mvc-xml/pom.xml +++ b/spring-web-modules/spring-mvc-xml/pom.xml @@ -39,11 +39,6 @@ ${jstl.version} runtime
- - org.hibernate.validator - hibernate-validator - ${hibernate-validator.version} - com.fasterxml.jackson.core diff --git a/spring-web-modules/spring-rest-query-language/pom.xml b/spring-web-modules/spring-rest-query-language/pom.xml index 65f28f5be0..c200852e27 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.mockito - mockito-core - test - diff --git a/spring-web-modules/spring-rest-simple/pom.xml b/spring-web-modules/spring-rest-simple/pom.xml index 2f8d6eac27..21c607ea1a 100644 --- a/spring-web-modules/spring-rest-simple/pom.xml +++ b/spring-web-modules/spring-rest-simple/pom.xml @@ -119,12 +119,6 @@ okhttp ${com.squareup.okhttp3.version} - - - org.mockito - mockito-core - test - org.springframework spring-test diff --git a/spring-web-modules/spring-rest-testing/pom.xml b/spring-web-modules/spring-rest-testing/pom.xml index 93942e97b6..4fc484d1d1 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.mockito - mockito-core - test - diff --git a/spring-web-modules/spring-resttemplate/pom.xml b/spring-web-modules/spring-resttemplate/pom.xml index 5cac186fad..93902bc81c 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.mockito - mockito-core - test - org.springframework spring-test diff --git a/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/mock/EmployeeServiceUnitTest.java b/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/mock/EmployeeServiceUnitTest.java index 9a992f390a..6e2072efe3 100644 --- a/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/mock/EmployeeServiceUnitTest.java +++ b/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/mock/EmployeeServiceUnitTest.java @@ -9,7 +9,7 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; diff --git a/spring-web-modules/spring-thymeleaf-2/README.md b/spring-web-modules/spring-thymeleaf-2/README.md index a8c067a443..488a0bdc2d 100644 --- a/spring-web-modules/spring-thymeleaf-2/README.md +++ b/spring-web-modules/spring-thymeleaf-2/README.md @@ -5,13 +5,10 @@ This module contains articles about Spring with Thymeleaf ## Relevant Articles: - [Working with Enums in Thymeleaf](https://www.baeldung.com/thymeleaf-enums) -- [Changing the Thymeleaf Template Directory in Spring Boot](https://www.baeldung.com/spring-thymeleaf-template-directory) - [Spring Request Parameters with Thymeleaf](https://www.baeldung.com/spring-thymeleaf-request-parameters) - [Thymeleaf lists Utility Object](https://www.baeldung.com/thymeleaf-lists-utility) - [Spring Path Variables with Thymeleaf](https://www.baeldung.com/spring-thymeleaf-path-variables) - [Working with Arrays in Thymeleaf](https://www.baeldung.com/thymeleaf-arrays) - [Working with Boolean in Thymeleaf](https://www.baeldung.com/thymeleaf-boolean) - [Working With Custom HTML Attributes in Thymeleaf](https://www.baeldung.com/thymeleaf-custom-html-attributes) -- [How to Create an Executable JAR with Maven](https://www.baeldung.com/executable-jar-with-maven) -- [Spring MVC Data and Thymeleaf](https://www.baeldung.com/spring-mvc-thymeleaf-data) - [[<-- prev]](/spring-thymeleaf) diff --git a/spring-web-modules/spring-thymeleaf-2/src/main/resources/templates-2/participants.html b/spring-web-modules/spring-thymeleaf-2/src/main/resources/templates-2/participants.html deleted file mode 100644 index f7e017e777..0000000000 --- a/spring-web-modules/spring-thymeleaf-2/src/main/resources/templates-2/participants.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - - -

Enter participant

-
- - - - - -
- - -

User Details

-

Details for user [[${id}]] ...

-
- -

Users

- -

- User [[${userId}]] -

-
- - diff --git a/spring-web-modules/spring-thymeleaf-3/README.md b/spring-web-modules/spring-thymeleaf-3/README.md index 76c54d3885..46ddd6c03f 100644 --- a/spring-web-modules/spring-thymeleaf-3/README.md +++ b/spring-web-modules/spring-thymeleaf-3/README.md @@ -11,3 +11,4 @@ This module contains articles about Spring with Thymeleaf - [Using Hidden Inputs with Spring and Thymeleaf](https://www.baeldung.com/spring-thymeleaf-hidden-inputs) - [Thymeleaf Variables](https://www.baeldung.com/thymeleaf-variables) - [Displaying Error Messages with Thymeleaf in Spring](https://www.baeldung.com/spring-thymeleaf-error-messages) +- [[next -->]](/spring-thymeleaf-4) diff --git a/spring-web-modules/spring-thymeleaf-4/README.md b/spring-web-modules/spring-thymeleaf-4/README.md new file mode 100644 index 0000000000..f8dc4c8b4e --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-4/README.md @@ -0,0 +1,27 @@ +## Spring Thymeleaf + +This module contains articles about Spring with Thymeleaf + +### Relevant Articles: +- [CSRF Protection with Spring MVC and Thymeleaf](https://www.baeldung.com/csrf-thymeleaf-with-spring-security) +- [Conditionals in Thymeleaf](https://www.baeldung.com/spring-thymeleaf-conditionals) +- [Iteration in Thymeleaf](https://www.baeldung.com/thymeleaf-iteration) +- [Spring with Thymeleaf Pagination for a List](https://www.baeldung.com/spring-thymeleaf-pagination) + +### Build the Project + +mvn clean install + +### Run the Project + +mvn cargo:run +- **note**: starts on port '8082' + +Access the pages using the URLs: + + - http://localhost:8082/spring-thymeleaf-4/ + - http://localhost:8082/spring-thymeleaf-4/addStudent/ + - http://localhost:8082/spring-thymeleaf-4/listStudents/ + +The first URL is the home page of the application. The home page has links to the second and third pages. + diff --git a/spring-web-modules/spring-thymeleaf-4/pom.xml b/spring-web-modules/spring-thymeleaf-4/pom.xml new file mode 100644 index 0000000000..44577078b0 --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-4/pom.xml @@ -0,0 +1,148 @@ + + + 4.0.0 + spring-thymeleaf-4 + spring-thymeleaf-4 + war + + + com.baeldung + parent-spring-5 + 0.0.1-SNAPSHOT + ../../parent-spring-5 + + + + + + org.springframework + spring-context + ${spring.version} + + + + commons-logging + commons-logging + + + + + org.springframework + spring-webmvc + ${spring.version} + + + org.springframework.data + spring-data-commons + ${spring-data.version} + + + javax.validation + validation-api + ${javax.validation-version} + + + org.hibernate.validator + hibernate-validator + ${hibernate-validator.version} + + + + org.springframework.security + spring-security-web + ${spring-security.version} + + + org.springframework.security + spring-security-config + ${spring-security.version} + + + + org.thymeleaf + thymeleaf + ${org.thymeleaf-version} + + + org.thymeleaf + thymeleaf-spring5 + ${org.thymeleaf-version} + + + nz.net.ultraq.thymeleaf + thymeleaf-layout-dialect + ${thymeleaf-layout-dialect.version} + + + org.thymeleaf.extras + thymeleaf-extras-java8time + ${org.thymeleaf.extras-version} + + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + provided + + + + org.springframework + spring-test + ${spring.version} + test + + + org.springframework.security + spring-security-test + ${spring-security.version} + test + + + + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + false + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty9x + embedded + + + + + + 8082 + + + + + + + + + 2.3.2.RELEASE + 3.0.11.RELEASE + 3.0.4.RELEASE + 2.4.1 + 2.0.1.Final + 6.0.11.Final + + 1.6.1 + + + \ No newline at end of file diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/config/InitSecurity.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/config/InitSecurity.java new file mode 100644 index 0000000000..956db4a0e5 --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/config/InitSecurity.java @@ -0,0 +1,11 @@ +package com.baeldung.thymeleaf.config; + +import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; + +public class InitSecurity extends AbstractSecurityWebApplicationInitializer { + + public InitSecurity() { + super(WebMVCSecurity.class); + + } +} diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/config/WebApp.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/config/WebApp.java new file mode 100644 index 0000000000..0913152bc3 --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/config/WebApp.java @@ -0,0 +1,36 @@ +package com.baeldung.thymeleaf.config; + +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; + +import javax.servlet.ServletRegistration.Dynamic; + +/** + * Java configuration file that is used for web application initialization + */ +public class WebApp extends AbstractAnnotationConfigDispatcherServletInitializer { + + public WebApp() { + super(); + } + + @Override + protected Class[] getRootConfigClasses() { + return null; + } + + @Override + protected Class[] getServletConfigClasses() { + return new Class[] { WebMVCConfig.class }; + } + + @Override + protected String[] getServletMappings() { + return new String[] { "/" }; + } + + @Override + protected void customizeRegistration(final Dynamic registration) { + super.customizeRegistration(registration); + } + +} diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java new file mode 100644 index 0000000000..50a555a017 --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java @@ -0,0 +1,115 @@ +package com.baeldung.thymeleaf.config; + +import com.baeldung.thymeleaf.formatter.NameFormatter; +import com.baeldung.thymeleaf.utils.ArrayUtil; +import nz.net.ultraq.thymeleaf.LayoutDialect; +import nz.net.ultraq.thymeleaf.decorators.strategies.GroupingStrategy; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Description; +import org.springframework.context.support.ResourceBundleMessageSource; +import org.springframework.format.FormatterRegistry; +import org.springframework.web.servlet.LocaleResolver; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; +import org.springframework.web.servlet.i18n.SessionLocaleResolver; +import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect; +import org.thymeleaf.spring5.ISpringTemplateEngine; +import org.thymeleaf.spring5.SpringTemplateEngine; +import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver; +import org.thymeleaf.spring5.view.ThymeleafViewResolver; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ITemplateResolver; + +import java.util.Locale; + +@Configuration +@EnableWebMvc +@ComponentScan({ "com.baeldung.thymeleaf" }) +/* + Java configuration file that is used for Spring MVC and Thymeleaf + configurations + */ +public class WebMVCConfig implements WebMvcConfigurer, ApplicationContextAware { + + private ApplicationContext applicationContext; + + @Override + public void setApplicationContext(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + @Bean + public ViewResolver htmlViewResolver() { + ThymeleafViewResolver resolver = new ThymeleafViewResolver(); + resolver.setTemplateEngine(templateEngine(htmlTemplateResolver())); + resolver.setContentType("text/html"); + resolver.setCharacterEncoding("UTF-8"); + resolver.setViewNames(ArrayUtil.array("*.html")); + return resolver; + } + + private ISpringTemplateEngine templateEngine(ITemplateResolver templateResolver) { + SpringTemplateEngine engine = new SpringTemplateEngine(); + engine.addDialect(new LayoutDialect(new GroupingStrategy())); + engine.addDialect(new Java8TimeDialect()); + engine.setTemplateResolver(templateResolver); + engine.setTemplateEngineMessageSource(messageSource()); + return engine; + } + + private ITemplateResolver htmlTemplateResolver() { + SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); + resolver.setApplicationContext(applicationContext); + resolver.setPrefix("/WEB-INF/views/"); + resolver.setCacheable(false); + resolver.setTemplateMode(TemplateMode.HTML); + return resolver; + } + + @Bean + @Description("Spring Message Resolver") + public ResourceBundleMessageSource messageSource() { + ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); + messageSource.setBasename("messages"); + return messageSource; + } + + @Bean + public LocaleResolver localeResolver() { + SessionLocaleResolver localeResolver = new SessionLocaleResolver(); + localeResolver.setDefaultLocale(new Locale("en")); + return localeResolver; + } + + @Bean + public LocaleChangeInterceptor localeChangeInterceptor() { + LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); + localeChangeInterceptor.setParamName("lang"); + return localeChangeInterceptor; + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(localeChangeInterceptor()); + } + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**", "/css/**") + .addResourceLocations("/WEB-INF/resources/", "/WEB-INF/css/"); + } + + @Override + @Description("Custom Conversion Service") + public void addFormatters(FormatterRegistry registry) { + registry.addFormatter(new NameFormatter()); + } +} diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java new file mode 100644 index 0000000000..ea51ca3cd9 --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java @@ -0,0 +1,43 @@ +package com.baeldung.thymeleaf.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) +public class WebMVCSecurity extends WebSecurityConfigurerAdapter { + + @Bean + @Override + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + public WebMVCSecurity() { + super(); + } + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication().withUser("user1").password("{noop}user1Pass").authorities("ROLE_USER"); + } + + @Override + public void configure(final WebSecurity web) throws Exception { + web.ignoring().antMatchers("/resources/**"); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + http.authorizeRequests().anyRequest().authenticated().and().httpBasic(); + } + +} diff --git a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/BookController.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/controller/BookController.java similarity index 99% rename from spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/BookController.java rename to spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/controller/BookController.java index d10caee9e7..194bf5825f 100644 --- a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/BookController.java +++ b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/controller/BookController.java @@ -1,22 +1,20 @@ package com.baeldung.thymeleaf.controller; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - +import com.baeldung.thymeleaf.model.Book; +import com.baeldung.thymeleaf.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; - import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; -import com.baeldung.thymeleaf.model.Book; -import com.baeldung.thymeleaf.service.BookService; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.IntStream; @Controller public class BookController { diff --git a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java similarity index 100% rename from spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java rename to spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java index 21f230c84c..8bbcd8fdb7 100644 --- a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java +++ b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java @@ -1,14 +1,14 @@ package com.baeldung.thymeleaf.controller; -import java.text.DateFormat; -import java.util.Date; -import java.util.Locale; - import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; +import java.text.DateFormat; +import java.util.Date; +import java.util.Locale; + /** * Handles requests for the application home page. * diff --git a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java similarity index 99% rename from spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java rename to spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java index 77cf02c902..99dd5501ae 100644 --- a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java +++ b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java @@ -1,9 +1,7 @@ package com.baeldung.thymeleaf.controller; -import java.util.List; - -import javax.validation.Valid; - +import com.baeldung.thymeleaf.model.Student; +import com.baeldung.thymeleaf.utils.StudentUtils; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; @@ -11,8 +9,8 @@ import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; -import com.baeldung.thymeleaf.model.Student; -import com.baeldung.thymeleaf.utils.StudentUtils; +import javax.validation.Valid; +import java.util.List; /** * Handles requests for the student model. diff --git a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/TeacherController.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/controller/TeacherController.java similarity index 99% rename from spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/TeacherController.java rename to spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/controller/TeacherController.java index 844d746084..c3a106f11a 100644 --- a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/TeacherController.java +++ b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/controller/TeacherController.java @@ -1,12 +1,11 @@ package com.baeldung.thymeleaf.controller; +import com.baeldung.thymeleaf.utils.TeacherUtils; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; -import com.baeldung.thymeleaf.utils.TeacherUtils; - @Controller public class TeacherController { diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/formatter/NameFormatter.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/formatter/NameFormatter.java new file mode 100644 index 0000000000..5fd5e88651 --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/formatter/NameFormatter.java @@ -0,0 +1,30 @@ +package com.baeldung.thymeleaf.formatter; + +import org.springframework.format.Formatter; +import org.thymeleaf.util.StringUtils; + +import java.text.ParseException; +import java.util.Locale; + +/** + * + * Name formatter class that implements the Spring Formatter interface. + * Formats a name(String) and return the value with spaces replaced by commas. + * + */ +public class NameFormatter implements Formatter { + + @Override + public String print(String input, Locale locale) { + return formatName(input, locale); + } + + @Override + public String parse(String input, Locale locale) throws ParseException { + return formatName(input, locale); + } + + private String formatName(String input, Locale locale) { + return StringUtils.replace(input, " ", ","); + } +} diff --git a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Book.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/model/Book.java similarity index 100% rename from spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Book.java rename to spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/model/Book.java diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/model/Student.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/model/Student.java new file mode 100644 index 0000000000..ca76cec986 --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/model/Student.java @@ -0,0 +1,59 @@ +package com.baeldung.thymeleaf.model; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import java.io.Serializable; + +/** + * + * Simple student POJO with few fields + * + */ +public class Student implements Serializable { + + private static final long serialVersionUID = -8582553475226281591L; + + @NotNull(message = "Student ID is required.") + @Min(value = 1000, message = "Student ID must be at least 4 digits.") + private Integer id; + + @NotNull(message = "Student name is required.") + private String name; + + @NotNull(message = "Student gender is required.") + private Character gender; + + private Float percentage; + + 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 Character getGender() { + return gender; + } + + public void setGender(Character gender) { + this.gender = gender; + } + + public Float getPercentage() { + return percentage; + } + + public void setPercentage(Float percentage) { + this.percentage = percentage; + } +} diff --git a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Teacher.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/model/Teacher.java similarity index 99% rename from spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Teacher.java rename to spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/model/Teacher.java index ad43590818..62f8a2938a 100644 --- a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Teacher.java +++ b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/model/Teacher.java @@ -1,11 +1,10 @@ package com.baeldung.thymeleaf.model; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; public class Teacher implements Serializable { diff --git a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/service/BookService.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/service/BookService.java similarity index 99% rename from spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/service/BookService.java rename to spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/service/BookService.java index 2aaa559251..a330a924bd 100644 --- a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/service/BookService.java +++ b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/service/BookService.java @@ -1,16 +1,15 @@ package com.baeldung.thymeleaf.service; -import java.util.Collections; -import java.util.List; - +import com.baeldung.thymeleaf.model.Book; +import com.baeldung.thymeleaf.utils.BookUtils; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; -import com.baeldung.thymeleaf.model.Book; -import com.baeldung.thymeleaf.utils.BookUtils; +import java.util.Collections; +import java.util.List; @Service public class BookService { diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/utils/ArrayUtil.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/utils/ArrayUtil.java new file mode 100644 index 0000000000..5c07476c9b --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/utils/ArrayUtil.java @@ -0,0 +1,8 @@ +package com.baeldung.thymeleaf.utils; + +public class ArrayUtil { + + public static String[] array(String... args) { + return args; + } +} \ No newline at end of file diff --git a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/BookUtils.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/utils/BookUtils.java similarity index 100% rename from spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/BookUtils.java rename to spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/utils/BookUtils.java index 3cd9e6a92e..0a23a1bdba 100644 --- a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/BookUtils.java +++ b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/utils/BookUtils.java @@ -1,11 +1,11 @@ package com.baeldung.thymeleaf.utils; +import com.baeldung.thymeleaf.model.Book; + import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; -import com.baeldung.thymeleaf.model.Book; - public class BookUtils { private static List books = new ArrayList(); diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/utils/StudentUtils.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/utils/StudentUtils.java new file mode 100644 index 0000000000..0e1165333d --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/utils/StudentUtils.java @@ -0,0 +1,34 @@ +package com.baeldung.thymeleaf.utils; + +import com.baeldung.thymeleaf.model.Student; + +import java.util.ArrayList; +import java.util.List; + +public class StudentUtils { + + private static List students = new ArrayList(); + + public static List buildStudents() { + if (students.isEmpty()) { + Student student1 = new Student(); + student1.setId(1001); + student1.setName("John Smith"); + student1.setGender('M'); + student1.setPercentage(Float.valueOf("80.45")); + + students.add(student1); + + Student student2 = new Student(); + student2.setId(1002); + student2.setName("Jane Williams"); + student2.setGender('F'); + student2.setPercentage(Float.valueOf("60.25")); + + students.add(student2); + } + + return students; + } + +} diff --git a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/TeacherUtils.java b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/utils/TeacherUtils.java similarity index 100% rename from spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/TeacherUtils.java rename to spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/utils/TeacherUtils.java index 1bb279cc92..f4b759e9df 100644 --- a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/TeacherUtils.java +++ b/spring-web-modules/spring-thymeleaf-4/src/main/java/com/baeldung/thymeleaf/utils/TeacherUtils.java @@ -1,10 +1,10 @@ package com.baeldung.thymeleaf.utils; +import com.baeldung.thymeleaf.model.Teacher; + import java.util.ArrayList; import java.util.List; -import com.baeldung.thymeleaf.model.Teacher; - public class TeacherUtils { private static List teachers = new ArrayList(); diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/resources/logback.xml b/spring-web-modules/spring-thymeleaf-4/src/main/resources/logback.xml new file mode 100644 index 0000000000..56af2d397e --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-4/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-web-modules/spring-thymeleaf-4/src/main/resources/messages_en.properties b/spring-web-modules/spring-thymeleaf-4/src/main/resources/messages_en.properties new file mode 100644 index 0000000000..b534d448b6 --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-4/src/main/resources/messages_en.properties @@ -0,0 +1,13 @@ +msg.id=ID +msg.name=Name +msg.gender=Gender +msg.percent=Percentage +welcome.message=Welcome Student !!! +msg.AddStudent=Add Student +msg.ListStudents=List Students +msg.Home=Home +msg.ListTeachers=List Teachers +msg.ListBooks=List Books with paging +msg.courses=Courses +msg.skills=Skills +msg.active=Active \ No newline at end of file diff --git a/spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/addStudent.html b/spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/addStudent.html similarity index 100% rename from spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/addStudent.html rename to spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/addStudent.html diff --git a/spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/csrfAttack.html b/spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/csrfAttack.html similarity index 100% rename from spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/csrfAttack.html rename to spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/csrfAttack.html diff --git a/spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/home.html b/spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/home.html similarity index 100% rename from spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/home.html rename to spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/home.html diff --git a/spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/listBooks.html b/spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/listBooks.html similarity index 100% rename from spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/listBooks.html rename to spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/listBooks.html diff --git a/spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html b/spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/listStudents.html similarity index 100% rename from spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html rename to spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/listStudents.html diff --git a/spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/listTeachers.html b/spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/listTeachers.html similarity index 100% rename from spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/listTeachers.html rename to spring-web-modules/spring-thymeleaf-4/src/main/webapp/WEB-INF/views/listTeachers.html diff --git a/spring-web-modules/spring-thymeleaf-4/src/test/java/com/baeldung/thymeleaf/SpringContextTest.java b/spring-web-modules/spring-thymeleaf-4/src/test/java/com/baeldung/thymeleaf/SpringContextTest.java new file mode 100644 index 0000000000..e2708330f2 --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-4/src/test/java/com/baeldung/thymeleaf/SpringContextTest.java @@ -0,0 +1,19 @@ +package com.baeldung.thymeleaf; + +import com.baeldung.thymeleaf.config.WebApp; +import com.baeldung.thymeleaf.config.WebMVCConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class }) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-web-modules/spring-thymeleaf-4/src/test/java/com/baeldung/thymeleaf/controller/ControllerIntegrationTest.java b/spring-web-modules/spring-thymeleaf-4/src/test/java/com/baeldung/thymeleaf/controller/ControllerIntegrationTest.java new file mode 100644 index 0000000000..cbbcdc0868 --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-4/src/test/java/com/baeldung/thymeleaf/controller/ControllerIntegrationTest.java @@ -0,0 +1,63 @@ +package com.baeldung.thymeleaf.controller; + +import com.baeldung.thymeleaf.config.WebApp; +import com.baeldung.thymeleaf.config.WebMVCConfig; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.RequestPostProcessor; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import javax.servlet.Filter; + +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class}) +public class ControllerIntegrationTest { + + @Autowired + WebApplicationContext wac; + + private MockMvc mockMvc; + + @Autowired + private Filter springSecurityFilterChain; + + private RequestPostProcessor testUser() { + return user("user1").password("user1Pass").roles("USER"); + } + + @Before + public void setup() { + mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build(); + } + + @Test + public void testTeachers() throws Exception { + mockMvc.perform(get("/listTeachers").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("listTeachers.html")); + } + + @Test + public void addStudentWithoutCSRF() throws Exception { + mockMvc.perform(post("/saveStudent").contentType(MediaType.APPLICATION_JSON).param("id", "1234567").param("name", "Joe").param("gender", "M").with(testUser())).andExpect(status().isForbidden()); + } + + @Test + public void addStudentWithCSRF() throws Exception { + mockMvc.perform(post("/saveStudent").contentType(MediaType.APPLICATION_JSON).param("id", "1234567").param("name", "Joe").param("gender", "M").with(testUser()).with(csrf())).andExpect(status().isOk()); + } +} diff --git a/spring-web-modules/spring-thymeleaf-4/src/test/java/com/baeldung/thymeleaf/security/csrf/CsrfEnabledIntegrationTest.java b/spring-web-modules/spring-thymeleaf-4/src/test/java/com/baeldung/thymeleaf/security/csrf/CsrfEnabledIntegrationTest.java new file mode 100644 index 0000000000..08a31cfa83 --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-4/src/test/java/com/baeldung/thymeleaf/security/csrf/CsrfEnabledIntegrationTest.java @@ -0,0 +1,62 @@ +package com.baeldung.thymeleaf.security.csrf; + +import com.baeldung.thymeleaf.config.InitSecurity; +import com.baeldung.thymeleaf.config.WebApp; +import com.baeldung.thymeleaf.config.WebMVCConfig; +import com.baeldung.thymeleaf.config.WebMVCSecurity; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.RequestPostProcessor; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import javax.servlet.Filter; + +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }) +public class CsrfEnabledIntegrationTest { + + @Autowired + WebApplicationContext wac; + @Autowired + MockHttpSession session; + + private MockMvc mockMvc; + + @Autowired + private Filter springSecurityFilterChain; + + private RequestPostProcessor testUser() { + return user("user1").password("user1Pass").roles("USER"); + } + + @Before + public void setup() { + mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build(); + } + + @Test + public void addStudentWithoutCSRF() throws Exception { + mockMvc.perform(post("/saveStudent").contentType(MediaType.APPLICATION_JSON).param("id", "1234567").param("name", "Joe").param("gender", "M").with(testUser())).andExpect(status().isForbidden()); + } + + @Test + public void addStudentWithCSRF() throws Exception { + mockMvc.perform(post("/saveStudent").contentType(MediaType.APPLICATION_JSON).param("id", "1234567").param("name", "Joe").param("gender", "M").with(testUser()).with(csrf())).andExpect(status().isOk()); + } + +} diff --git a/spring-web-modules/spring-thymeleaf-5/README.md b/spring-web-modules/spring-thymeleaf-5/README.md new file mode 100644 index 0000000000..7bbaa8b4db --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-5/README.md @@ -0,0 +1,10 @@ +## Spring Thymeleaf + +This module contains articles about Spring with Thymeleaf + +## Relevant Articles: + +- [Changing the Thymeleaf Template Directory in Spring Boot](https://www.baeldung.com/spring-thymeleaf-template-directory) +- [How to Create an Executable JAR with Maven](https://www.baeldung.com/executable-jar-with-maven) +- [Spring MVC Data and Thymeleaf](https://www.baeldung.com/spring-mvc-thymeleaf-data) +- [[<-- prev]](/spring-thymeleaf) diff --git a/spring-web-modules/spring-thymeleaf-5/pom.xml b/spring-web-modules/spring-thymeleaf-5/pom.xml new file mode 100644 index 0000000000..e7c54d83c9 --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-5/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + spring-thymeleaf-5 + spring-thymeleaf-5 + war + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-test + test + + + + + spring-thymeleaf-5 + + + + 2.2 + + + \ No newline at end of file diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/Application.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/Application.java new file mode 100644 index 0000000000..2ccca82497 --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/Application.java @@ -0,0 +1,11 @@ +package com.baeldung.thymeleaf; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-web-modules/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/ThymeleafConfig.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/ThymeleafConfig.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/ThymeleafConfig.java rename to spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/ThymeleafConfig.java diff --git a/spring-web-modules/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java rename to spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java diff --git a/spring-web-modules/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java rename to spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java diff --git a/spring-web-modules/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java rename to spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java diff --git a/spring-web-modules/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/templatedir/HelloController.java b/spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/templatedir/HelloController.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/templatedir/HelloController.java rename to spring-web-modules/spring-thymeleaf-5/src/main/java/com/baeldung/thymeleaf/templatedir/HelloController.java diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/resources/application.properties b/spring-web-modules/spring-thymeleaf-5/src/main/resources/application.properties new file mode 100644 index 0000000000..b09232bb1b --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-5/src/main/resources/application.properties @@ -0,0 +1 @@ +#spring.thymeleaf.prefix=classpath:/templates-2/ \ No newline at end of file diff --git a/spring-web-modules/spring-thymeleaf-2/src/main/resources/templates-2/hello.html b/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates-2/hello.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-2/src/main/resources/templates-2/hello.html rename to spring-web-modules/spring-thymeleaf-5/src/main/resources/templates-2/hello.html diff --git a/spring-web-modules/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-bean-data.html b/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/mvcdata/email-bean-data.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-bean-data.html rename to spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/mvcdata/email-bean-data.html diff --git a/spring-web-modules/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-model-attributes.html b/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/mvcdata/email-model-attributes.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-model-attributes.html rename to spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/mvcdata/email-model-attributes.html diff --git a/spring-web-modules/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-request-parameters.html b/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/mvcdata/email-request-parameters.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-request-parameters.html rename to spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/mvcdata/email-request-parameters.html diff --git a/spring-web-modules/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-servlet-context.html b/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/mvcdata/email-servlet-context.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-servlet-context.html rename to spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/mvcdata/email-servlet-context.html diff --git a/spring-web-modules/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-session-attributes.html b/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/mvcdata/email-session-attributes.html similarity index 100% rename from spring-web-modules/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-session-attributes.html rename to spring-web-modules/spring-thymeleaf-5/src/main/resources/templates/mvcdata/email-session-attributes.html diff --git a/spring-web-modules/spring-thymeleaf-2/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java b/spring-web-modules/spring-thymeleaf-5/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java similarity index 100% rename from spring-web-modules/spring-thymeleaf-2/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java rename to spring-web-modules/spring-thymeleaf-5/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java diff --git a/spring-web-modules/spring-thymeleaf-5/src/test/resources/logback-test.xml b/spring-web-modules/spring-thymeleaf-5/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-5/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/spring-web-modules/spring-thymeleaf/README.md b/spring-web-modules/spring-thymeleaf/README.md index 7c3d4cafa3..12eb97b4a2 100644 --- a/spring-web-modules/spring-thymeleaf/README.md +++ b/spring-web-modules/spring-thymeleaf/README.md @@ -4,15 +4,11 @@ This module contains articles about Spring with Thymeleaf ### Relevant Articles: - [Introduction to Using Thymeleaf in Spring](https://www.baeldung.com/thymeleaf-in-spring-mvc) -- [CSRF Protection with Spring MVC and Thymeleaf](https://www.baeldung.com/csrf-thymeleaf-with-spring-security) - [Thymeleaf: Custom Layout Dialect](https://www.baeldung.com/thymeleaf-spring-layouts) - [Spring and Thymeleaf 3: Expressions](https://www.baeldung.com/spring-thymeleaf-3-expressions) - [Spring MVC + Thymeleaf 3.0: New Features](https://www.baeldung.com/spring-thymeleaf-3) - [How to Work with Dates in Thymeleaf](https://www.baeldung.com/dates-in-thymeleaf) - [Working with Fragments in Thymeleaf](https://www.baeldung.com/spring-thymeleaf-fragments) -- [Conditionals in Thymeleaf](https://www.baeldung.com/spring-thymeleaf-conditionals) -- [Iteration in Thymeleaf](https://www.baeldung.com/thymeleaf-iteration) -- [Spring with Thymeleaf Pagination for a List](https://www.baeldung.com/spring-thymeleaf-pagination) - [[next -->]](/spring-thymeleaf-2) ### Build the Project @@ -24,13 +20,5 @@ mvn clean install mvn cargo:run - **note**: starts on port '8082' -Access the pages using the URLs: - - - http://localhost:8082/spring-thymeleaf/ - - http://localhost:8082/spring-thymeleaf/addStudent/ - - http://localhost:8082/spring-thymeleaf/listStudents/ - -The first URL is the home page of the application. The home page has links to the second and third pages. - ### Security The user/password required is: user1/user1Pass diff --git a/spring-web-modules/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java b/spring-web-modules/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java index 4a2a9974f1..462e9e8c21 100644 --- a/spring-web-modules/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java +++ b/spring-web-modules/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java @@ -59,10 +59,5 @@ public class ExpressionUtilityObjectsControllerIntegrationTest { public void testDates() throws Exception { mockMvc.perform(get("/dates").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("dates.html")); } - - @Test - public void testTeachers() throws Exception { - mockMvc.perform(get("/listTeachers").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("listTeachers.html")); - } } diff --git a/spring-web-modules/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/security/csrf/CsrfEnabledIntegrationTest.java b/spring-web-modules/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/security/csrf/CsrfEnabledIntegrationTest.java index a7c9fb4ae4..1160250877 100644 --- a/spring-web-modules/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/security/csrf/CsrfEnabledIntegrationTest.java +++ b/spring-web-modules/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/security/csrf/CsrfEnabledIntegrationTest.java @@ -49,16 +49,6 @@ public class CsrfEnabledIntegrationTest { mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build(); } - @Test - public void addStudentWithoutCSRF() throws Exception { - mockMvc.perform(post("/saveStudent").contentType(MediaType.APPLICATION_JSON).param("id", "1234567").param("name", "Joe").param("gender", "M").with(testUser())).andExpect(status().isForbidden()); - } - - @Test - public void addStudentWithCSRF() throws Exception { - mockMvc.perform(post("/saveStudent").contentType(MediaType.APPLICATION_JSON).param("id", "1234567").param("name", "Joe").param("gender", "M").with(testUser()).with(csrf())).andExpect(status().isOk()); - } - @Test public void htmlInliningTest() throws Exception { mockMvc.perform(get("/html").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("inliningExample.html")); diff --git a/testing-modules/junit-5/pom.xml b/testing-modules/junit-5/pom.xml index 7a511dfe7a..576800d979 100644 --- a/testing-modules/junit-5/pom.xml +++ b/testing-modules/junit-5/pom.xml @@ -16,6 +16,17 @@ ../ + + + + org.mockito + mockito-core + ${mockito.version} + test + + + + org.junit.platform @@ -76,7 +87,7 @@ org.mockito mockito-junit-jupiter - ${mockito.junit.jupiter.version} + ${mockito.version} test @@ -85,6 +96,11 @@ ${powermock.version} test + + org.mockito + mockito-core + test + @@ -119,11 +135,11 @@ - 2.23.0 2.8.2 - 2.0.0 + 2.0.9 5.0.1.RELEASE 3.0.0-M3 + 3.3.0 \ No newline at end of file diff --git a/testing-modules/mockito-2/pom.xml b/testing-modules/mockito-2/pom.xml index cff7598edc..ba81022c5c 100644 --- a/testing-modules/mockito-2/pom.xml +++ b/testing-modules/mockito-2/pom.xml @@ -29,8 +29,4 @@
- - 2.21.0 - - \ No newline at end of file diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/UnemploymentServiceImplUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/UnemploymentServiceImplUnitTest.java index 87093fc1ba..ef7a9ac1d9 100644 --- a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/UnemploymentServiceImplUnitTest.java +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/UnemploymentServiceImplUnitTest.java @@ -11,7 +11,7 @@ import java.util.stream.Stream; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) diff --git a/testing-modules/mockito-3/pom.xml b/testing-modules/mockito-3/pom.xml index 10130290df..e35416933b 100644 --- a/testing-modules/mockito-3/pom.xml +++ b/testing-modules/mockito-3/pom.xml @@ -24,8 +24,4 @@ - - 3.8.0 - - \ No newline at end of file diff --git a/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoConfigExamplesIntegrationTest.java b/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoConfigExamplesIntegrationTest.java index 5d3c009edc..b9df6a456c 100644 --- a/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoConfigExamplesIntegrationTest.java +++ b/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoConfigExamplesIntegrationTest.java @@ -7,8 +7,6 @@ import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.*; public class MockitoConfigExamplesIntegrationTest { diff --git a/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoConfigExamplesUnitTest.java b/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoConfigExamplesUnitTest.java index 389dc231c1..6a5f797b41 100644 --- a/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoConfigExamplesUnitTest.java +++ b/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoConfigExamplesUnitTest.java @@ -7,8 +7,6 @@ import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.*; import com.baeldung.mockito.MyList; diff --git a/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoMockIntegrationTest.java b/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoMockIntegrationTest.java index e8cbcc4e8c..944d41316d 100644 --- a/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoMockIntegrationTest.java +++ b/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoMockIntegrationTest.java @@ -4,7 +4,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.MockSettings; -import org.mockito.exceptions.verification.TooLittleActualInvocations; +import org.mockito.exceptions.verification.TooFewActualInvocations; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -42,7 +42,7 @@ public class MockitoMockIntegrationTest { when(listMock.add(anyString())).thenReturn(false); listMock.add(randomAlphabetic(6)); - thrown.expect(TooLittleActualInvocations.class); + thrown.expect(TooFewActualInvocations.class); thrown.expectMessage(containsString("myMock.add")); verify(listMock, times(2)).add(anyString()); diff --git a/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoMockUnitTest.java b/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoMockUnitTest.java index e1d99f80a2..27af3d8d1e 100644 --- a/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoMockUnitTest.java +++ b/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoMockUnitTest.java @@ -2,8 +2,6 @@ package com.baeldung.mockito; import static org.mockito.Mockito.*; -import com.baeldung.mockito.MyList; - import static org.junit.Assert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.containsString; @@ -13,7 +11,7 @@ import org.junit.Test; import org.junit.Rule; import org.junit.rules.ExpectedException; import org.mockito.MockSettings; -import org.mockito.exceptions.verification.TooLittleActualInvocations; +import org.mockito.exceptions.verification.TooFewActualInvocations; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -45,7 +43,7 @@ public class MockitoMockUnitTest { when(listMock.add(anyString())).thenReturn(false); listMock.add(randomAlphabetic(6)); - thrown.expect(TooLittleActualInvocations.class); + thrown.expect(TooFewActualInvocations.class); thrown.expectMessage(containsString("myMock.add")); verify(listMock, times(2)).add(anyString()); diff --git a/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoVerifyExamplesIntegrationTest.java b/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoVerifyExamplesIntegrationTest.java index b5075d7db2..6dfe7f9d6b 100644 --- a/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoVerifyExamplesIntegrationTest.java +++ b/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoVerifyExamplesIntegrationTest.java @@ -11,7 +11,6 @@ import java.util.List; import static org.hamcrest.Matchers.hasItem; import static org.junit.Assert.assertThat; -import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.*; public class MockitoVerifyExamplesIntegrationTest { @@ -35,7 +34,7 @@ public class MockitoVerifyExamplesIntegrationTest { @Test public final void givenNoInteractionWithMockOccurred_whenVerifyingInteractions_thenCorrect() { final List mockedList = mock(MyList.class); - verifyZeroInteractions(mockedList); + verifyNoInteractions(mockedList); } @Test diff --git a/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoVerifyExamplesUnitTest.java b/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoVerifyExamplesUnitTest.java index ca09f77d2d..f138256e72 100644 --- a/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoVerifyExamplesUnitTest.java +++ b/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoVerifyExamplesUnitTest.java @@ -2,7 +2,6 @@ package com.baeldung.mockito; import com.google.common.collect.Lists; -import com.baeldung.mockito.MyList; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; @@ -13,7 +12,6 @@ import java.util.List; import static org.hamcrest.Matchers.hasItem; import static org.junit.Assert.assertThat; -import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.*; public class MockitoVerifyExamplesUnitTest { @@ -37,7 +35,7 @@ public class MockitoVerifyExamplesUnitTest { @Test public final void givenNoInteractionWithMockOccurred_whenVerifyingInteractions_thenCorrect() { final List mockedList = mock(MyList.class); - verifyZeroInteractions(mockedList); + verifyNoInteractions(mockedList); } @Test diff --git a/testing-modules/mocks/pom.xml b/testing-modules/mocks/pom.xml index 3fabde037c..e25d6f3ce6 100644 --- a/testing-modules/mocks/pom.xml +++ b/testing-modules/mocks/pom.xml @@ -31,12 +31,6 @@ ${jukito.version} test - - org.mockito - mockito-core - ${mockito.version} - test - org.easymock easymock @@ -53,7 +47,6 @@ 0.15 1.5 - 2.21.0 3.5.1 1.41 1.1 diff --git a/testing-modules/mocks/src/test/java/com/baeldung/mockito/LoginControllerIntegrationTest.java b/testing-modules/mocks/src/test/java/com/baeldung/mockito/LoginControllerIntegrationTest.java index 98df2cf850..a42e6ae5e8 100644 --- a/testing-modules/mocks/src/test/java/com/baeldung/mockito/LoginControllerIntegrationTest.java +++ b/testing-modules/mocks/src/test/java/com/baeldung/mockito/LoginControllerIntegrationTest.java @@ -40,7 +40,7 @@ public class LoginControllerIntegrationTest { public void assertThatNoMethodHasBeenCalled() { loginController.login(null); // no method called - Mockito.verifyZeroInteractions(loginService); + Mockito.verifyNoInteractions(loginService); } @Test @@ -85,7 +85,7 @@ public class LoginControllerIntegrationTest { Assert.assertEquals("ERROR", login); Mockito.verify(loginService) .login(userForm); - Mockito.verifyZeroInteractions(loginService); + Mockito.verifyNoMoreInteractions(loginService); } @Test