bankTransfer = new ProducerRecord<>(BANK_TRANSFERS_TOPIC, createBankTransfer());
+ producer.send(bankTransfer).get();
+ }
+
+ private String createCardPayment() {
+ return "{\"paymentReference\":\"A184028KM0013790\", \"type\":\"card\", \"amount\":\"275\", \"currency\":\"GBP\"}";
+ }
+
+ private String createBankTransfer() {
+ return "{\"paymentReference\":\"19ae2-18mk73-009\", \"type\":\"bank\", \"amount\":\"150\", \"currency\":\"EUR\"}";
+ }
+}
diff --git a/apache-libraries-2/README.md b/apache-libraries-2/README.md
new file mode 100644
index 0000000000..cc910c5c2c
--- /dev/null
+++ b/apache-libraries-2/README.md
@@ -0,0 +1,2 @@
+## Relevant Articles
+- [Understanding XSLT Processing in Java](https://www.baeldung.com/java-extensible-stylesheet-language-transformations)
diff --git a/apache-libraries-2/pom.xml b/apache-libraries-2/pom.xml
new file mode 100644
index 0000000000..d188204208
--- /dev/null
+++ b/apache-libraries-2/pom.xml
@@ -0,0 +1,28 @@
+
+
+ 4.0.0
+ apache-libraries-2
+ 0.0.1-SNAPSHOT
+ apache-libraries-2
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+ javax.validation
+ validation-api
+ ${javax.validation.validation-api.version}
+
+
+
+
+ 2.0.1.Final
+
+
+
\ No newline at end of file
diff --git a/apache-libraries-2/src/main/java/com/baeldung/xslt/XSLTProcessor.java b/apache-libraries-2/src/main/java/com/baeldung/xslt/XSLTProcessor.java
new file mode 100644
index 0000000000..6bc0023485
--- /dev/null
+++ b/apache-libraries-2/src/main/java/com/baeldung/xslt/XSLTProcessor.java
@@ -0,0 +1,18 @@
+package com.baeldung.xslt;
+
+import javax.xml.transform.*;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+import java.io.File;
+
+public class XSLTProcessor {
+ public static void transformXMLUsingXSLT(String inputXMLPath, String xsltPath, String outputHTMLPath) throws TransformerException {
+ Source xmlSource = new StreamSource(new File(inputXMLPath));
+ Source xsltSource = new StreamSource(new File(xsltPath));
+ Result output = new StreamResult(new File(outputHTMLPath));
+
+ TransformerFactory transformerFactory = TransformerFactory.newInstance();
+ Transformer transformer = transformerFactory.newTransformer(xsltSource);
+ transformer.transform(xmlSource, output);
+ }
+}
diff --git a/apache-libraries-2/src/main/java/com/baeldung/xsltProcessing/XSLTProcessorWithParametersAndOption.java b/apache-libraries-2/src/main/java/com/baeldung/xsltProcessing/XSLTProcessorWithParametersAndOption.java
new file mode 100644
index 0000000000..07efab080d
--- /dev/null
+++ b/apache-libraries-2/src/main/java/com/baeldung/xsltProcessing/XSLTProcessorWithParametersAndOption.java
@@ -0,0 +1,31 @@
+package com.baeldung.xsltProcessing;
+
+import javax.xml.transform.*;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+import java.io.File;
+
+public class XSLTProcessorWithParametersAndOption {
+ public static void transformXMLWithParametersAndOption(
+ String inputXMLPath,
+ String xsltPath,
+ String outputHTMLPath,
+ String companyName,
+ boolean enableIndentation
+ ) throws TransformerException {
+ TransformerFactory transformerFactory = TransformerFactory.newInstance();
+ Source xsltSource = new StreamSource(new File(xsltPath));
+ Transformer transformer = transformerFactory.newTransformer(xsltSource);
+
+ transformer.setParameter("companyName", companyName);
+
+ if (enableIndentation) {
+ transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+ }
+
+ Source xmlSource = new StreamSource(new File(inputXMLPath));
+ Result outputResult = new StreamResult(new File(outputHTMLPath));
+
+ transformer.transform(xmlSource, outputResult);
+ }
+}
diff --git a/apache-libraries-2/src/main/java/com/baeldung/xsltProcessing/XSLTProcessorWithTemplate.java b/apache-libraries-2/src/main/java/com/baeldung/xsltProcessing/XSLTProcessorWithTemplate.java
new file mode 100644
index 0000000000..017fc0db8b
--- /dev/null
+++ b/apache-libraries-2/src/main/java/com/baeldung/xsltProcessing/XSLTProcessorWithTemplate.java
@@ -0,0 +1,21 @@
+package com.baeldung.xsltProcessing;
+
+import javax.xml.transform.*;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+import java.io.File;
+
+public class XSLTProcessorWithTemplate {
+ public static void transformXMLUsingTemplate(String inputXMLPath, String xsltPath, String outputHTMLPath) throws TransformerException {
+ TransformerFactory transformerFactory = TransformerFactory.newInstance();
+ Source xsltSource = new StreamSource(new File(xsltPath));
+ Templates templates = transformerFactory.newTemplates(xsltSource);
+
+ Transformer transformer = templates.newTransformer();
+
+ Source xmlSource = new StreamSource(new File(inputXMLPath));
+ Result outputResult = new StreamResult(new File(outputHTMLPath));
+
+ transformer.transform(xmlSource, outputResult);
+ }
+}
diff --git a/apache-libraries-2/src/main/resources/avroHttpRequest-schema.avsc b/apache-libraries-2/src/main/resources/avroHttpRequest-schema.avsc
new file mode 100644
index 0000000000..18179a9cde
--- /dev/null
+++ b/apache-libraries-2/src/main/resources/avroHttpRequest-schema.avsc
@@ -0,0 +1,47 @@
+{
+ "type":"record",
+ "name":"AvroHttpRequest",
+ "namespace":"com.baeldung.avro.model",
+ "fields":[
+ {
+ "name":"requestTime",
+ "type":"long"
+ },
+ {
+ "name":"clientIdentifier",
+ "type":{
+ "type":"record",
+ "name":"ClientIdentifier",
+ "fields":[
+ {
+ "name":"hostName",
+ "type":"string"
+ },
+ {
+ "name":"ipAddress",
+ "type":"string"
+ }
+ ]
+ }
+ },
+ {
+ "name":"employeeNames",
+ "type":{
+ "type":"array",
+ "items":"string"
+ },
+ "default":null
+ },
+ {
+ "name":"active",
+ "type":{
+ "type":"enum",
+ "name":"Active",
+ "symbols":[
+ "YES",
+ "NO"
+ ]
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/apache-libraries-2/src/main/resources/log4j2.xml b/apache-libraries-2/src/main/resources/log4j2.xml
new file mode 100644
index 0000000000..d1ea5173fa
--- /dev/null
+++ b/apache-libraries-2/src/main/resources/log4j2.xml
@@ -0,0 +1,18 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/annotations/annotation-processing/src/main/resources/logback.xml b/apache-libraries-2/src/main/resources/logback.xml
similarity index 100%
rename from annotations/annotation-processing/src/main/resources/logback.xml
rename to apache-libraries-2/src/main/resources/logback.xml
diff --git a/apache-libraries-2/src/test/java/com/baeldung/xslt/XSLTProcessorUnitTest.java b/apache-libraries-2/src/test/java/com/baeldung/xslt/XSLTProcessorUnitTest.java
new file mode 100644
index 0000000000..cbfbf78c87
--- /dev/null
+++ b/apache-libraries-2/src/test/java/com/baeldung/xslt/XSLTProcessorUnitTest.java
@@ -0,0 +1,29 @@
+package com.baeldung.xslt;
+
+import org.junit.jupiter.api.Test;
+
+import javax.xml.transform.TransformerException;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class XSLTProcessorUnitTest {
+
+ @Test
+ public void givenValidInputAndStylesheet_whenTransformingXML_thenOutputHTMLCreated() throws TransformerException, IOException {
+ // Given
+ String inputXMLPath = "src/test/resources/input.xml";
+ String xsltPath = "src/test/resources/stylesheet.xslt";
+ String outputHTMLPath = "src/test/resources/output.html";
+
+
+ XSLTProcessor.transformXMLUsingXSLT(inputXMLPath, xsltPath, outputHTMLPath);
+
+
+ Path outputFile = Paths.get(outputHTMLPath);
+ assertTrue(Files.exists(outputFile));
+ }
+}
diff --git a/apache-libraries-2/src/test/resources/input.xml b/apache-libraries-2/src/test/resources/input.xml
new file mode 100644
index 0000000000..e283680337
--- /dev/null
+++ b/apache-libraries-2/src/test/resources/input.xml
@@ -0,0 +1,11 @@
+
+
+
+ John Doe
+ 30
+
+
+ Jane Smith
+ 25
+
+
diff --git a/apache-libraries-2/src/test/resources/output.html b/apache-libraries-2/src/test/resources/output.html
new file mode 100644
index 0000000000..b75e73ca15
--- /dev/null
+++ b/apache-libraries-2/src/test/resources/output.html
@@ -0,0 +1,3 @@
+
+ Male person: John Doe, Age: 30
+ Female person: Jane Smith, Age: 25
diff --git a/apache-libraries-2/src/test/resources/stylesheet.xslt b/apache-libraries-2/src/test/resources/stylesheet.xslt
new file mode 100644
index 0000000000..9f07852a2a
--- /dev/null
+++ b/apache-libraries-2/src/test/resources/stylesheet.xslt
@@ -0,0 +1,22 @@
+
+
+
+
+
+ Male person:
+
+ , Age:
+
+
+
+
+
+
+ Female person:
+
+ , Age:
+
+
+
+
+
diff --git a/apache-poi-2/README.md b/apache-poi-2/README.md
index 0132147201..65641e7c37 100644
--- a/apache-poi-2/README.md
+++ b/apache-poi-2/README.md
@@ -13,4 +13,5 @@ This module contains articles about Apache POI.
- [Setting Formulas in Excel with Apache POI](https://www.baeldung.com/java-apache-poi-set-formulas)
- [Set the Date Format Using Apache POI](https://www.baeldung.com/java-apache-poi-date-format)
- [Replacing Variables in a Document Template with Java](https://www.baeldung.com/java-replace-pattern-word-document-doc-docx)
+- [Lock Header Rows With Apache POI](https://www.baeldung.com/java-apache-poi-lock-header-rows)
- More articles: [[<-- prev]](../apache-poi)
diff --git a/apache-poi-2/src/main/java/com/baeldung/poi/excel/locksheet/LockSheet.java b/apache-poi-2/src/main/java/com/baeldung/poi/excel/locksheet/LockSheet.java
new file mode 100644
index 0000000000..23df04065d
--- /dev/null
+++ b/apache-poi-2/src/main/java/com/baeldung/poi/excel/locksheet/LockSheet.java
@@ -0,0 +1,19 @@
+package com.baeldung.poi.excel.locksheet;
+
+import org.apache.poi.ss.usermodel.*;
+
+public class LockSheet {
+
+ public void lockFirstRow(Sheet sheet) {
+ sheet.createFreezePane(0, 1);
+ }
+
+ public void lockTwoRows(Sheet sheet) {
+ sheet.createFreezePane(0, 2);
+ }
+
+ public void lockFirstColumn(Sheet sheet) {
+ sheet.createFreezePane(1, 0);
+ }
+
+}
\ No newline at end of file
diff --git a/apache-poi-2/src/test/java/com/baeldung/poi/excel/locksheet/LockSheetUnitTest.java b/apache-poi-2/src/test/java/com/baeldung/poi/excel/locksheet/LockSheetUnitTest.java
new file mode 100644
index 0000000000..5fe8a9ea4b
--- /dev/null
+++ b/apache-poi-2/src/test/java/com/baeldung/poi/excel/locksheet/LockSheetUnitTest.java
@@ -0,0 +1,53 @@
+package com.baeldung.poi.excel.locksheet;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.io.IOException;
+
+import org.apache.poi.ss.usermodel.*;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+import org.junit.jupiter.api.*;
+
+class LockSheetUnitTest {
+
+ private LockSheet lockSheet;
+ private Workbook workbook;
+ private Sheet sheet;
+
+ @BeforeEach
+ void setup() {
+ workbook = new XSSFWorkbook();
+ sheet = workbook.createSheet();
+ Row row = sheet.createRow(0);
+ row.createCell(0).setCellValue("row 1 col 1");
+ row.createCell(1).setCellValue("row 1 col 2");
+ row = sheet.createRow(1);
+ row.createCell(0).setCellValue("row 2 col 1");
+ row.createCell(1).setCellValue("row 2 col 2");
+ lockSheet = new LockSheet();
+ }
+
+ @AfterEach
+ void cleanup() throws IOException {
+ workbook.close();
+ }
+
+ @Test
+ void whenLockFirstRow_thenFirstRowIsLocked() {
+ lockSheet.lockFirstRow(sheet);
+ assertEquals(sheet.getPaneInformation().getHorizontalSplitPosition(), 1);
+ }
+
+ @Test
+ void whenLockTwoRows_thenTwoRowsAreLocked() {
+ lockSheet.lockTwoRows(sheet);
+ assertEquals(sheet.getPaneInformation().getHorizontalSplitPosition(), 2);
+ }
+
+ @Test
+ void whenLockFirstColumn_thenFirstColumnIsLocked() {
+ lockSheet.lockFirstColumn(sheet);
+ assertEquals(sheet.getPaneInformation().getVerticalSplitPosition(), 1);
+ }
+
+}
\ No newline at end of file
diff --git a/apache-poi-3/README.md b/apache-poi-3/README.md
new file mode 100644
index 0000000000..9e9d6a94eb
--- /dev/null
+++ b/apache-poi-3/README.md
@@ -0,0 +1,3 @@
+## Relevant Articles
+- [How To Convert Excel Data Into List Of Java Objects](https://www.baeldung.com/java-convert-excel-data-into-list)
+- [Expand Columns with Apache POI](https://www.baeldung.com/java-apache-poi-expand-columns)
diff --git a/apache-poi-3/pom.xml b/apache-poi-3/pom.xml
new file mode 100644
index 0000000000..e6e85d1212
--- /dev/null
+++ b/apache-poi-3/pom.xml
@@ -0,0 +1,97 @@
+
+
+ 4.0.0
+ apache-poi-3
+ 0.0.1-SNAPSHOT
+ apache-poi-3
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+ org.apache.poi
+ poi-ooxml
+ ${poi.version}
+
+
+ org.apache.poi
+ poi-scratchpad
+ ${poi.version}
+
+
+
+ com.github.ozlerhakan
+ poiji
+ ${poiji.version}
+
+
+
+
+ org.apache.poi
+ poi
+ ${poi.version}
+
+
+
+ org.apache.poi
+ poi-ooxml-schemas
+ 4.1.2
+
+
+
+ org.apache.xmlbeans
+ xmlbeans
+ 5.1.1
+
+
+
+ org.apache.commons
+ commons-collections4
+ 4.4
+
+
+
+ org.dhatim
+ fastexcel
+ ${fastexcel.version}
+
+
+
+ org.dhatim
+ fastexcel-reader
+ ${fastexcel.version}
+
+
+
+ net.sourceforge.jexcelapi
+ jxl
+ ${jxl.version}
+
+
+
+ org.apache.logging.log4j
+ log4j-api
+ 2.17.1
+
+
+
+ org.apache.logging.log4j
+ log4j-core
+ 2.17.1
+
+
+
+
+ 5.2.3
+ 4.1.1
+ 0.15.7
+ 2.6.12
+
+
+
\ No newline at end of file
diff --git a/apache-poi-3/src/main/java/com/baeldung/convert/exceldatatolist/FoodInfo.java b/apache-poi-3/src/main/java/com/baeldung/convert/exceldatatolist/FoodInfo.java
new file mode 100644
index 0000000000..b8fe4522de
--- /dev/null
+++ b/apache-poi-3/src/main/java/com/baeldung/convert/exceldatatolist/FoodInfo.java
@@ -0,0 +1,54 @@
+package com.baeldung.convert.exceldatatolist;
+
+import com.poiji.annotation.ExcelCellName;
+
+public class FoodInfo {
+
+ @ExcelCellName("Category")
+ private String category; //food category
+ @ExcelCellName("Name")
+ private String name; // food name
+ @ExcelCellName("Measure")
+ private String measure;
+ @ExcelCellName("Calories")
+ private double calories; //amount of calories in kcal/measure
+
+ @Override
+ public String toString() {
+ return "FoodInfo{" + "category='" + category + '\'' + ", name='" + name + '\'' + ", measure='" + measure + '\'' + ", calories=" + calories + "} \n";
+ }
+
+
+ public String getCategory() {
+ return category;
+ }
+
+ public void setCategory(String category) {
+ this.category = category;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getMeasure() {
+ return measure;
+ }
+
+ public void setMeasure(String measure) {
+ this.measure = measure;
+ }
+
+ public double getCalories() {
+ return calories;
+ }
+
+ public void setCalories(double calories) {
+ this.calories = calories;
+ }
+
+}
diff --git a/apache-poi-3/src/main/java/com/baeldung/convert/exceldatatolist/fastexcel/ExcelDataToListOfObjectsFastExcel.java b/apache-poi-3/src/main/java/com/baeldung/convert/exceldatatolist/fastexcel/ExcelDataToListOfObjectsFastExcel.java
new file mode 100644
index 0000000000..87d31520e6
--- /dev/null
+++ b/apache-poi-3/src/main/java/com/baeldung/convert/exceldatatolist/fastexcel/ExcelDataToListOfObjectsFastExcel.java
@@ -0,0 +1,42 @@
+package com.baeldung.convert.exceldatatolist.fastexcel;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.stream.Stream;
+
+import org.dhatim.fastexcel.reader.ReadableWorkbook;
+import org.dhatim.fastexcel.reader.Row;
+import org.dhatim.fastexcel.reader.Sheet;
+
+import com.baeldung.convert.exceldatatolist.FoodInfo;
+
+public class ExcelDataToListOfObjectsFastExcel {
+ public static List excelDataToListOfObjets_withFastExcel(String fileLocation)throws IOException, NumberFormatException {
+ List foodData = new ArrayList();
+
+ try (FileInputStream file = new FileInputStream(fileLocation);
+ ReadableWorkbook wb = new ReadableWorkbook(file)) {
+ Sheet sheet = wb.getFirstSheet();
+ for (Row row:
+ sheet.read()
+ ) {
+ if(row.getRowNum() == 1) {
+ continue;
+ }
+ FoodInfo food = new FoodInfo();
+ food.setCategory(row.getCellText(0));
+ food.setName(row.getCellText(1));
+ food.setMeasure(row.getCellText(2));
+ food.setCalories(Double.parseDouble(row.getCellText(3)));
+
+ foodData.add(food);
+
+ }
+ }
+
+ return foodData;
+ }
+}
diff --git a/apache-poi-3/src/main/java/com/baeldung/convert/exceldatatolist/jexcelapi/ExcelDataToListOfObjectsJxl.java b/apache-poi-3/src/main/java/com/baeldung/convert/exceldatatolist/jexcelapi/ExcelDataToListOfObjectsJxl.java
new file mode 100644
index 0000000000..61ba5e4700
--- /dev/null
+++ b/apache-poi-3/src/main/java/com/baeldung/convert/exceldatatolist/jexcelapi/ExcelDataToListOfObjectsJxl.java
@@ -0,0 +1,37 @@
+package com.baeldung.convert.exceldatatolist.jexcelapi;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import com.baeldung.convert.exceldatatolist.FoodInfo;
+
+import jxl.Sheet;
+import jxl.Workbook;
+import jxl.read.biff.BiffException;
+
+public class ExcelDataToListOfObjectsJxl {
+ public static List excelDataToListOfObjets_withJxl(String fileLocation) throws IOException, BiffException {
+
+ List foodData = new ArrayList();
+
+ Workbook workbook = Workbook.getWorkbook(new File(fileLocation));
+ Sheet sheet = workbook.getSheet(0);
+
+ int rows = sheet.getRows();
+
+ for (int i = 1; i < rows; i++) {
+ FoodInfo foodInfo = new FoodInfo();
+
+ foodInfo.setCategory(sheet.getCell(0, i).getContents());
+ foodInfo.setName(sheet.getCell(1, i).getContents());
+ foodInfo.setMeasure(sheet.getCell(2, i).getContents());
+ foodInfo.setCalories(Double.parseDouble(sheet.getCell(3, i).getContents()));
+
+ foodData.add(foodInfo);
+
+ }
+ return foodData;
+ }
+}
diff --git a/apache-poi-3/src/main/java/com/baeldung/convert/exceldatatolist/poi/ExcelDataToListApachePOI.java b/apache-poi-3/src/main/java/com/baeldung/convert/exceldatatolist/poi/ExcelDataToListApachePOI.java
new file mode 100644
index 0000000000..8b568b889a
--- /dev/null
+++ b/apache-poi-3/src/main/java/com/baeldung/convert/exceldatatolist/poi/ExcelDataToListApachePOI.java
@@ -0,0 +1,39 @@
+package com.baeldung.convert.exceldatatolist.poi;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.poi.ss.usermodel.DataFormatter;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+
+import com.baeldung.convert.exceldatatolist.FoodInfo;
+
+public class ExcelDataToListApachePOI {
+ public static List excelDataToListOfObjets_withApachePOI(String fileLocation) throws IOException {
+ FileInputStream file = new FileInputStream(new File(fileLocation));
+ Workbook workbook = new XSSFWorkbook(file);
+ Sheet sheet = workbook.getSheetAt(0);
+ List foodData = new ArrayList();
+ DataFormatter dataFormatter = new DataFormatter();
+ for (int n = 1; n < sheet.getPhysicalNumberOfRows(); n++) {
+ Row row = sheet.getRow(n);
+ FoodInfo foodInfo = new FoodInfo();
+ int i = row.getFirstCellNum();
+
+ foodInfo.setCategory(dataFormatter.formatCellValue(row.getCell(i)));
+ foodInfo.setName(dataFormatter.formatCellValue(row.getCell(++i)));
+ foodInfo.setMeasure(dataFormatter.formatCellValue(row.getCell(++i)));
+ foodInfo.setCalories(Double.parseDouble(dataFormatter.formatCellValue(row.getCell(++i))));
+
+ foodData.add(foodInfo);
+
+ }
+ return foodData;
+ }
+}
diff --git a/apache-poi-3/src/main/java/com/baeldung/convert/exceldatatolist/poiji/ExcelDataToListOfObjectsPOIJI.java b/apache-poi-3/src/main/java/com/baeldung/convert/exceldatatolist/poiji/ExcelDataToListOfObjectsPOIJI.java
new file mode 100644
index 0000000000..be190d38f7
--- /dev/null
+++ b/apache-poi-3/src/main/java/com/baeldung/convert/exceldatatolist/poiji/ExcelDataToListOfObjectsPOIJI.java
@@ -0,0 +1,13 @@
+package com.baeldung.convert.exceldatatolist.poiji;
+
+import java.io.File;
+import java.util.List;
+
+import com.baeldung.convert.exceldatatolist.FoodInfo;
+import com.poiji.bind.Poiji;
+
+public class ExcelDataToListOfObjectsPOIJI {
+ public static List excelDataToListOfObjets_withPOIJI(String fileLocation){
+ return Poiji.fromExcel(new File(fileLocation), FoodInfo.class);
+ }
+}
diff --git a/apache-poi-3/src/main/resources/food_info.xls b/apache-poi-3/src/main/resources/food_info.xls
new file mode 100644
index 0000000000..1377d8e18d
Binary files /dev/null and b/apache-poi-3/src/main/resources/food_info.xls differ
diff --git a/apache-poi-3/src/main/resources/food_info.xlsx b/apache-poi-3/src/main/resources/food_info.xlsx
new file mode 100644
index 0000000000..c604ff367d
Binary files /dev/null and b/apache-poi-3/src/main/resources/food_info.xlsx differ
diff --git a/apache-poi-3/src/test/java/com/baeldung/convert/exceldatatolist/ExcelDataToListOfObjectsUnitTest.java b/apache-poi-3/src/test/java/com/baeldung/convert/exceldatatolist/ExcelDataToListOfObjectsUnitTest.java
new file mode 100644
index 0000000000..5d65c04b31
--- /dev/null
+++ b/apache-poi-3/src/test/java/com/baeldung/convert/exceldatatolist/ExcelDataToListOfObjectsUnitTest.java
@@ -0,0 +1,53 @@
+package com.baeldung.convert.exceldatatolist;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.IOException;
+import java.util.List;
+
+// import org.junit.jupiter.api.Test;
+// import static org.junit.jupiter.api.Assertions.*;
+import org.junit.Test;
+
+import com.baeldung.convert.exceldatatolist.fastexcel.ExcelDataToListOfObjectsFastExcel;
+import com.baeldung.convert.exceldatatolist.jexcelapi.ExcelDataToListOfObjectsJxl;
+import com.baeldung.convert.exceldatatolist.poi.ExcelDataToListApachePOI;
+import com.baeldung.convert.exceldatatolist.poiji.ExcelDataToListOfObjectsPOIJI;
+
+import jxl.read.biff.BiffException;
+
+public class ExcelDataToListOfObjectsUnitTest {
+
+ @Test
+ public void whenParsingExcelFileWithPOIJI_thenConvertsToList() throws IOException {
+ List foodInfoList = ExcelDataToListOfObjectsPOIJI.excelDataToListOfObjets_withPOIJI("src/main/resources/food_info.xlsx");
+
+ assertEquals("Beverages", foodInfoList.get(0).getCategory());
+ assertEquals("Dairy", foodInfoList.get(3).getCategory());
+ }
+
+ @Test
+ public void whenParsingExcelFileWithApachePOI_thenConvertsToList() throws IOException {
+ List foodInfoList = ExcelDataToListApachePOI.excelDataToListOfObjets_withApachePOI("src/main/resources/food_info.xlsx");
+
+ assertEquals("Beverages", foodInfoList.get(0).getCategory());
+ assertEquals("Dairy", foodInfoList.get(3).getCategory());
+ }
+
+ @Test
+ public void whenParsingExcelFileWithFastExcel_thenConvertsToList() throws IOException {
+ List foodInfoList = ExcelDataToListOfObjectsFastExcel.excelDataToListOfObjets_withFastExcel("src/main/resources/food_info.xlsx");
+
+ assertEquals("Beverages", foodInfoList.get(0).getCategory());
+ assertEquals("Dairy", foodInfoList.get(3).getCategory());
+ }
+
+ @Test
+ public void whenParsingExcelFileWithJxl_thenConvertsToList() throws IOException, BiffException {
+ List foodInfoList = ExcelDataToListOfObjectsJxl.excelDataToListOfObjets_withJxl("src/main/resources/food_info.xls");
+
+ assertEquals("Beverages", foodInfoList.get(0).getCategory());
+ assertEquals("Dairy", foodInfoList.get(3).getCategory());
+ }
+
+}
diff --git a/apache-poi-3/src/test/java/com/baeldung/poi/excel/expandcolumn/ExpandColumnUnitTest.java b/apache-poi-3/src/test/java/com/baeldung/poi/excel/expandcolumn/ExpandColumnUnitTest.java
new file mode 100644
index 0000000000..04d0aef211
--- /dev/null
+++ b/apache-poi-3/src/test/java/com/baeldung/poi/excel/expandcolumn/ExpandColumnUnitTest.java
@@ -0,0 +1,70 @@
+package com.baeldung.poi.excel.expandcolumn;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.io.IOException;
+
+import org.apache.poi.ss.usermodel.*;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+class ExpandColumnUnitTest {
+
+ private Workbook workbook;
+ private Sheet sheet;
+
+ @BeforeEach
+ void prepareSpreadsheet() {
+ workbook = new XSSFWorkbook();
+ sheet = workbook.createSheet();
+
+ Row headerRow = sheet.createRow(0);
+ Cell headerCell1 = headerRow.createCell(0);
+ headerCell1.setCellValue("Full Name");
+ Cell headerCell2 = headerRow.createCell(1);
+ headerCell2.setCellValue("Abbreviation");
+
+ Row dataRow = sheet.createRow(1);
+ Cell dataCell1 = dataRow.createCell(0);
+ dataCell1.setCellValue("Java Virtual Machine");
+ Cell dataCell2 = dataRow.createCell(1);
+ dataCell2.setCellValue("JVM");
+
+ dataRow = sheet.createRow(2);
+ dataCell1 = dataRow.createCell(0);
+ dataCell1.setCellValue("Java Runtime Environment");
+ dataCell2 = dataRow.createCell(1);
+ dataCell2.setCellValue("JRE");
+ }
+
+ @Test
+ void whenSetColumnWidth_thenColumnSetToTheSpecifiedWidth() {
+
+ Row row = sheet.getRow(2);
+ String cellValue = row.getCell(0).getStringCellValue();
+ int targetWidth = cellValue.length() * 256;
+
+ sheet.setColumnWidth(0, targetWidth);
+
+ assertEquals(targetWidth, sheet.getColumnWidth(0));
+ }
+
+ @Test
+ void whenAutoSizeColumn_thenColumnExpands() {
+
+ int originalWidth = sheet.getColumnWidth(0);
+
+ sheet.autoSizeColumn(0);
+
+ assertThat(sheet.getColumnWidth(0)).isGreaterThan(originalWidth);
+ }
+
+ @AfterEach
+ void cleanup() throws IOException {
+ workbook.close();
+ }
+
+}
\ No newline at end of file
diff --git a/apache-velocity/pom.xml b/apache-velocity/pom.xml
index a562ebeec0..f4b6de8872 100644
--- a/apache-velocity/pom.xml
+++ b/apache-velocity/pom.xml
@@ -63,7 +63,6 @@
4.5.2
1.7
2.0
- 3.3.2
\ No newline at end of file
diff --git a/asm/pom.xml b/asm/pom.xml
index f1e60d2560..4edfe86ae5 100644
--- a/asm/pom.xml
+++ b/asm/pom.xml
@@ -49,7 +49,6 @@
5.2
- 2.4
\ No newline at end of file
diff --git a/aws-modules/aws-dynamodb/.gitignore b/aws-modules/aws-dynamodb/.gitignore
new file mode 100644
index 0000000000..bf11a4cc38
--- /dev/null
+++ b/aws-modules/aws-dynamodb/.gitignore
@@ -0,0 +1,2 @@
+/target/
+.idea/
\ No newline at end of file
diff --git a/aws-modules/aws-dynamodb/README.md b/aws-modules/aws-dynamodb/README.md
new file mode 100644
index 0000000000..68a353e555
--- /dev/null
+++ b/aws-modules/aws-dynamodb/README.md
@@ -0,0 +1,7 @@
+## AWS DYNAMODB
+
+This module contains articles about AWS DynamoDB
+
+### Relevant articles
+- [Integration Testing with a Local DynamoDB Instance](https://www.baeldung.com/dynamodb-local-integration-tests)
+
diff --git a/aws-modules/aws-dynamodb/pom.xml b/aws-modules/aws-dynamodb/pom.xml
new file mode 100644
index 0000000000..37b88327f4
--- /dev/null
+++ b/aws-modules/aws-dynamodb/pom.xml
@@ -0,0 +1,87 @@
+
+
+ 4.0.0
+ aws-dynamodb
+ 0.1.0-SNAPSHOT
+ aws-dynamodb
+ jar
+
+
+ com.baeldung
+ aws-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+ com.amazonaws
+ aws-java-sdk
+ ${aws-java-sdk.version}
+
+
+ com.amazonaws
+ DynamoDBLocal
+ ${dynamodblocal.version}
+ test
+
+
+ commons-io
+ commons-io
+ ${commons-io.version}
+
+
+ com.google.code.gson
+ gson
+ ${gson.version}
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-shade-plugin
+ ${maven-shade-plugin.version}
+
+ false
+
+
+
+ package
+
+ shade
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-dependency-plugin
+ ${maven-plugins-version}
+
+
+ copy
+ compile
+
+ copy-dependencies
+
+
+
+ so,dll,dylib
+ native-libs
+
+
+
+
+
+
+
+
+ 2.8.0
+ 1.21.1
+ 3.1.1
+
+
+
\ No newline at end of file
diff --git a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/dynamodb/entity/ProductInfo.java b/aws-modules/aws-dynamodb/src/main/java/com/baeldung/dynamodb/entity/ProductInfo.java
similarity index 100%
rename from aws-modules/aws-miscellaneous/src/main/java/com/baeldung/dynamodb/entity/ProductInfo.java
rename to aws-modules/aws-dynamodb/src/main/java/com/baeldung/dynamodb/entity/ProductInfo.java
diff --git a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/dynamodb/repository/AbstractRepository.java b/aws-modules/aws-dynamodb/src/main/java/com/baeldung/dynamodb/repository/AbstractRepository.java
similarity index 100%
rename from aws-modules/aws-miscellaneous/src/main/java/com/baeldung/dynamodb/repository/AbstractRepository.java
rename to aws-modules/aws-dynamodb/src/main/java/com/baeldung/dynamodb/repository/AbstractRepository.java
diff --git a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/dynamodb/repository/ProductInfoRepository.java b/aws-modules/aws-dynamodb/src/main/java/com/baeldung/dynamodb/repository/ProductInfoRepository.java
similarity index 100%
rename from aws-modules/aws-miscellaneous/src/main/java/com/baeldung/dynamodb/repository/ProductInfoRepository.java
rename to aws-modules/aws-dynamodb/src/main/java/com/baeldung/dynamodb/repository/ProductInfoRepository.java
diff --git a/annotations/annotation-user/src/main/resources/logback.xml b/aws-modules/aws-dynamodb/src/main/resources/logback.xml
similarity index 100%
rename from annotations/annotation-user/src/main/resources/logback.xml
rename to aws-modules/aws-dynamodb/src/main/resources/logback.xml
diff --git a/aws-modules/aws-miscellaneous/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryIntegrationTest.java b/aws-modules/aws-dynamodb/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryIntegrationTest.java
similarity index 91%
rename from aws-modules/aws-miscellaneous/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryIntegrationTest.java
rename to aws-modules/aws-dynamodb/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryIntegrationTest.java
index 18f55544cd..e4dc0c65b8 100644
--- a/aws-modules/aws-miscellaneous/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryIntegrationTest.java
+++ b/aws-modules/aws-dynamodb/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryIntegrationTest.java
@@ -49,10 +49,10 @@ public class ProductInfoRepositoryIntegrationTest {
@BeforeClass
public static void setupClass() {
Properties testProperties = loadFromFileInClasspath("test.properties")
- .filter(properties -> !isEmpty(properties.getProperty(AWS_ACCESSKEY)))
- .filter(properties -> !isEmpty(properties.getProperty(AWS_SECRETKEY)))
- .filter(properties -> !isEmpty(properties.getProperty(DYNAMODB_ENDPOINT)))
- .orElseThrow(() -> new RuntimeException("Unable to get all of the required test property values"));
+ .filter(properties -> !isEmpty(properties.getProperty(AWS_ACCESSKEY)))
+ .filter(properties -> !isEmpty(properties.getProperty(AWS_SECRETKEY)))
+ .filter(properties -> !isEmpty(properties.getProperty(DYNAMODB_ENDPOINT)))
+ .orElseThrow(() -> new RuntimeException("Unable to get all of the required test property values"));
String amazonAWSAccessKey = testProperties.getProperty(AWS_ACCESSKEY);
String amazonAWSSecretKey = testProperties.getProperty(AWS_SECRETKEY);
diff --git a/aws-modules/aws-miscellaneous/src/test/java/com/baeldung/dynamodb/rule/LocalDbCreationRule.java b/aws-modules/aws-dynamodb/src/test/java/com/baeldung/dynamodb/rule/LocalDbCreationRule.java
similarity index 100%
rename from aws-modules/aws-miscellaneous/src/test/java/com/baeldung/dynamodb/rule/LocalDbCreationRule.java
rename to aws-modules/aws-dynamodb/src/test/java/com/baeldung/dynamodb/rule/LocalDbCreationRule.java
diff --git a/aws-modules/aws-miscellaneous/src/test/resources/test.properties b/aws-modules/aws-dynamodb/src/test/resources/test.properties
similarity index 100%
rename from aws-modules/aws-miscellaneous/src/test/resources/test.properties
rename to aws-modules/aws-dynamodb/src/test/resources/test.properties
diff --git a/aws-modules/aws-miscellaneous/pom.xml b/aws-modules/aws-miscellaneous/pom.xml
index 2fb7e397a0..4126256fb9 100644
--- a/aws-modules/aws-miscellaneous/pom.xml
+++ b/aws-modules/aws-miscellaneous/pom.xml
@@ -16,31 +16,9 @@
- com.amazonaws
- aws-java-sdk
- ${aws-java-sdk.version}
-
-
- com.amazonaws
- aws-lambda-java-core
- ${aws-lambda-java-core.version}
-
-
- commons-logging
- commons-logging
-
-
-
-
- com.amazonaws
- aws-lambda-java-events
- ${aws-lambda-java-events.version}
-
-
- commons-logging
- commons-logging
-
-
+ software.amazon.awssdk
+ aws-sdk-java
+ ${aws-java-sdk-v2.version}
commons-io
@@ -52,12 +30,6 @@
gson
${gson.version}
-
- com.amazonaws
- DynamoDBLocal
- ${dynamodblocal.version}
- test
-
@@ -101,8 +73,6 @@
- 1.3.0
- 1.1.0
2.8.0
1.21.1
1.10.L001
diff --git a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/ec2/EC2Application.java b/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/ec2/EC2Application.java
index 6755188fcd..e12a38e1de 100644
--- a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/ec2/EC2Application.java
+++ b/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/ec2/EC2Application.java
@@ -2,136 +2,148 @@ package com.baeldung.ec2;
import java.util.Arrays;
-import com.amazonaws.auth.AWSCredentials;
-import com.amazonaws.auth.AWSStaticCredentialsProvider;
-import com.amazonaws.auth.BasicAWSCredentials;
-import com.amazonaws.regions.Regions;
-import com.amazonaws.services.ec2.AmazonEC2;
-import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
-import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
-import com.amazonaws.services.ec2.model.CreateKeyPairRequest;
-import com.amazonaws.services.ec2.model.CreateKeyPairResult;
-import com.amazonaws.services.ec2.model.CreateSecurityGroupRequest;
-import com.amazonaws.services.ec2.model.DescribeInstancesRequest;
-import com.amazonaws.services.ec2.model.DescribeInstancesResult;
-import com.amazonaws.services.ec2.model.DescribeKeyPairsRequest;
-import com.amazonaws.services.ec2.model.DescribeKeyPairsResult;
-import com.amazonaws.services.ec2.model.IpPermission;
-import com.amazonaws.services.ec2.model.IpRange;
-import com.amazonaws.services.ec2.model.MonitorInstancesRequest;
-import com.amazonaws.services.ec2.model.RebootInstancesRequest;
-import com.amazonaws.services.ec2.model.RunInstancesRequest;
-import com.amazonaws.services.ec2.model.StartInstancesRequest;
-import com.amazonaws.services.ec2.model.StopInstancesRequest;
-import com.amazonaws.services.ec2.model.UnmonitorInstancesRequest;
+import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.ec2.Ec2Client;
+import software.amazon.awssdk.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
+import software.amazon.awssdk.services.ec2.model.CreateKeyPairRequest;
+import software.amazon.awssdk.services.ec2.model.CreateKeyPairResponse;
+import software.amazon.awssdk.services.ec2.model.CreateSecurityGroupRequest;
+import software.amazon.awssdk.services.ec2.model.DescribeInstancesRequest;
+import software.amazon.awssdk.services.ec2.model.DescribeInstancesResponse;
+import software.amazon.awssdk.services.ec2.model.DescribeKeyPairsRequest;
+import software.amazon.awssdk.services.ec2.model.DescribeKeyPairsResponse;
+import software.amazon.awssdk.services.ec2.model.IpPermission;
+import software.amazon.awssdk.services.ec2.model.IpRange;
+import software.amazon.awssdk.services.ec2.model.MonitorInstancesRequest;
+import software.amazon.awssdk.services.ec2.model.RebootInstancesRequest;
+import software.amazon.awssdk.services.ec2.model.RunInstancesRequest;
+import software.amazon.awssdk.services.ec2.model.RunInstancesResponse;
+import software.amazon.awssdk.services.ec2.model.StartInstancesRequest;
+import software.amazon.awssdk.services.ec2.model.StartInstancesResponse;
+import software.amazon.awssdk.services.ec2.model.StopInstancesRequest;
+import software.amazon.awssdk.services.ec2.model.UnmonitorInstancesRequest;
public class EC2Application {
- private static final AWSCredentials credentials;
-
- static {
- // put your accesskey and secretkey here
- credentials = new BasicAWSCredentials(
- "",
- ""
- );
- }
-
public static void main(String[] args) {
// Set up the client
- AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard()
- .withCredentials(new AWSStaticCredentialsProvider(credentials))
- .withRegion(Regions.US_EAST_1)
+ Ec2Client ec2Client = Ec2Client.builder()
+ .credentialsProvider(ProfileCredentialsProvider.create("default"))
+ .region(Region.US_EAST_1)
.build();
// Create a security group
- CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest().withGroupName("BaeldungSecurityGroup")
- .withDescription("Baeldung Security Group");
+ CreateSecurityGroupRequest createSecurityGroupRequest = CreateSecurityGroupRequest.builder()
+ .groupName("BaeldungSecurityGroup")
+ .description("Baeldung Security Group")
+ .build();
+
ec2Client.createSecurityGroup(createSecurityGroupRequest);
// Allow HTTP and SSH traffic
- IpRange ipRange1 = new IpRange().withCidrIp("0.0.0.0/0");
+ IpRange ipRange1 = IpRange.builder()
+ .cidrIp("0.0.0.0/0")
+ .build();
- IpPermission ipPermission1 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
- .withIpProtocol("tcp")
- .withFromPort(80)
- .withToPort(80);
+ IpPermission ipPermission1 = IpPermission.builder()
+ .ipRanges(Arrays.asList(ipRange1))
+ .ipProtocol("tcp")
+ .fromPort(80)
+ .toPort(80)
+ .build();
- IpPermission ipPermission2 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
- .withIpProtocol("tcp")
- .withFromPort(22)
- .withToPort(22);
+ IpPermission ipPermission2 = IpPermission.builder()
+ .ipRanges(Arrays.asList(ipRange1))
+ .ipProtocol("tcp")
+ .fromPort(22)
+ .toPort(22)
+ .build();
- AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest()
- .withGroupName("BaeldungSecurityGroup")
- .withIpPermissions(ipPermission1, ipPermission2);
+ AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = AuthorizeSecurityGroupIngressRequest
+ .builder()
+ .groupName("BaeldungSecurityGroup")
+ .ipPermissions(ipPermission1, ipPermission2)
+ .build();
ec2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);
// Create KeyPair
- CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest()
- .withKeyName("baeldung-key-pair");
- CreateKeyPairResult createKeyPairResult = ec2Client.createKeyPair(createKeyPairRequest);
- String privateKey = createKeyPairResult
- .getKeyPair()
- .getKeyMaterial(); // make sure you keep it, the private key, Amazon doesn't store the private key
+ CreateKeyPairRequest createKeyPairRequest = CreateKeyPairRequest.builder()
+ .keyName("baeldung-key-pair")
+ .build();
+
+ CreateKeyPairResponse createKeyPairResponse = ec2Client.createKeyPair(createKeyPairRequest);
+ String privateKey = createKeyPairResponse.keyMaterial();
+ // make sure you keep it, the private key, Amazon doesn't store the private key
// See what key-pairs you've got
- DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();
- DescribeKeyPairsResult describeKeyPairsResult = ec2Client.describeKeyPairs(describeKeyPairsRequest);
+ DescribeKeyPairsRequest describeKeyPairsRequest = DescribeKeyPairsRequest.builder()
+ .build();
+ DescribeKeyPairsResponse describeKeyPairsResponse = ec2Client.describeKeyPairs(describeKeyPairsRequest);
// Launch an Amazon Instance
- RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId("ami-97785bed") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html | https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/usingsharedamis-finding.html
- .withInstanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
- .withMinCount(1)
- .withMaxCount(1)
- .withKeyName("baeldung-key-pair") // optional - if not present, can't connect to instance
- .withSecurityGroups("BaeldungSecurityGroup");
+ RunInstancesRequest runInstancesRequest = RunInstancesRequest.builder()
+ .imageId("ami-97785bed")
+ .instanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
+ .minCount(1)
+ .maxCount(1)
+ .keyName("baeldung-key-pair") // optional - if not present, can't connect to instance
+ .securityGroups("BaeldungSecurityGroup")
+ .build();
- String yourInstanceId = ec2Client.runInstances(runInstancesRequest).getReservation().getInstances().get(0).getInstanceId();
+ RunInstancesResponse runInstancesResponse = ec2Client.runInstances(runInstancesRequest);
+ String yourInstanceId = runInstancesResponse.instances().get(0).instanceId();
// Start an Instance
- StartInstancesRequest startInstancesRequest = new StartInstancesRequest()
- .withInstanceIds(yourInstanceId);
+ StartInstancesRequest startInstancesRequest = StartInstancesRequest.builder()
+ .instanceIds(yourInstanceId)
+ .build();
+
+ StartInstancesResponse startInstancesResponse = ec2Client.startInstances(startInstancesRequest);
- ec2Client.startInstances(startInstancesRequest);
// Monitor Instances
- MonitorInstancesRequest monitorInstancesRequest = new MonitorInstancesRequest()
- .withInstanceIds(yourInstanceId);
+ MonitorInstancesRequest monitorInstancesRequest = MonitorInstancesRequest.builder()
+ .instanceIds(yourInstanceId)
+ .build();
+
ec2Client.monitorInstances(monitorInstancesRequest);
- UnmonitorInstancesRequest unmonitorInstancesRequest = new UnmonitorInstancesRequest()
- .withInstanceIds(yourInstanceId);
+ UnmonitorInstancesRequest unmonitorInstancesRequest = UnmonitorInstancesRequest.builder()
+ .instanceIds(yourInstanceId)
+ .build();
ec2Client.unmonitorInstances(unmonitorInstancesRequest);
// Reboot an Instance
-
- RebootInstancesRequest rebootInstancesRequest = new RebootInstancesRequest()
- .withInstanceIds(yourInstanceId);
+ RebootInstancesRequest rebootInstancesRequest = RebootInstancesRequest.builder()
+ .instanceIds(yourInstanceId)
+ .build();
ec2Client.rebootInstances(rebootInstancesRequest);
// Stop an Instance
- StopInstancesRequest stopInstancesRequest = new StopInstancesRequest()
- .withInstanceIds(yourInstanceId);
+ StopInstancesRequest stopInstancesRequest = StopInstancesRequest.builder()
+ .instanceIds(yourInstanceId)
+ .build();
+
ec2Client.stopInstances(stopInstancesRequest)
- .getStoppingInstances()
+ .stoppingInstances()
.get(0)
- .getPreviousState()
- .getName();
+ .previousState()
+ .name();
// Describe an Instance
- DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
- DescribeInstancesResult response = ec2Client.describeInstances(describeInstancesRequest);
- System.out.println(response.getReservations()
+ DescribeInstancesRequest describeInstancesRequest = DescribeInstancesRequest.builder().build();
+ DescribeInstancesResponse response = ec2Client.describeInstances(describeInstancesRequest);
+ System.out.println(response.reservations()
.get(0)
- .getInstances()
+ .instances()
.get(0)
- .getKernelId());
+ .kernelId());
}
}
diff --git a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/rds/AWSRDSService.java b/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/rds/AWSRDSService.java
index d4da92f30f..09309b92bb 100644
--- a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/rds/AWSRDSService.java
+++ b/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/rds/AWSRDSService.java
@@ -1,13 +1,5 @@
package com.baeldung.rds;
-import com.amazonaws.auth.AWSCredentialsProvider;
-import com.amazonaws.auth.AWSStaticCredentialsProvider;
-import com.amazonaws.auth.BasicAWSCredentials;
-import com.amazonaws.regions.Regions;
-import com.amazonaws.services.rds.AmazonRDS;
-import com.amazonaws.services.rds.AmazonRDSClientBuilder;
-import com.amazonaws.services.rds.model.*;
-
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
@@ -16,12 +8,22 @@ import java.util.Properties;
import java.util.UUID;
import java.util.logging.Logger;
+import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.rds.RdsClient;
+import software.amazon.awssdk.services.rds.model.CreateDbInstanceRequest;
+import software.amazon.awssdk.services.rds.model.CreateDbInstanceResponse;
+import software.amazon.awssdk.services.rds.model.DBInstance;
+import software.amazon.awssdk.services.rds.model.DeleteDbInstanceRequest;
+import software.amazon.awssdk.services.rds.model.DeleteDbInstanceResponse;
+import software.amazon.awssdk.services.rds.model.DescribeDbInstancesResponse;
+import software.amazon.awssdk.services.rds.model.Endpoint;
+
public class AWSRDSService {
final static Logger logger = Logger.getLogger(AWSRDSService.class.getName());
- private AWSCredentialsProvider credentials;
- private AmazonRDS amazonRDS;
+ private RdsClient rdsClient;
private String db_username;
private String db_password;
private String db_database;
@@ -34,22 +36,17 @@ public class AWSRDSService {
* **/
public AWSRDSService() throws IOException {
//Init RDS client with credentials and region.
- credentials = new
- AWSStaticCredentialsProvider(new
- BasicAWSCredentials("",
- ""));
- amazonRDS = AmazonRDSClientBuilder.standard().withCredentials(credentials)
- .withRegion(Regions.AP_SOUTHEAST_2).build();
Properties prop = new Properties();
InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties");
prop.load(input);
db_username = prop.getProperty("db_username");
db_password = prop.getProperty("db_password");
db_database = prop.getProperty("db_database");
- }
- public AWSRDSService(AmazonRDS amazonRDS){
- this.amazonRDS = amazonRDS;
+ rdsClient = RdsClient.builder()
+ .region(Region.AP_SOUTHEAST_2)
+ .credentialsProvider(ProfileCredentialsProvider.create("default"))
+ .build();
}
/**
@@ -60,29 +57,29 @@ public class AWSRDSService {
public String launchInstance() {
String identifier = "";
- CreateDBInstanceRequest request = new CreateDBInstanceRequest();
- // RDS instance name
- request.setDBInstanceIdentifier("Sydney");
- request.setEngine("postgres");
- request.setMultiAZ(false);
- request.setMasterUsername(db_username);
- request.setMasterUserPassword(db_password);
- request.setDBName(db_database);
- request.setStorageType("gp2");
- request.setAllocatedStorage(10);
+ CreateDbInstanceRequest instanceRequest = CreateDbInstanceRequest.builder()
+ .dbInstanceIdentifier("Sydney")
+ .engine("postgres")
+ .multiAZ(false)
+ .masterUsername(db_username)
+ .masterUserPassword(db_password)
+ .dbName(db_database)
+ .storageType("gp2")
+ .allocatedStorage(10)
+ .build();
- DBInstance instance = amazonRDS.createDBInstance(request);
+ CreateDbInstanceResponse createDbInstanceResponse = rdsClient.createDBInstance(instanceRequest);
// Information about the new RDS instance
- identifier = instance.getDBInstanceIdentifier();
- String status = instance.getDBInstanceStatus();
- Endpoint endpoint = instance.getEndpoint();
- String endpoint_url = "Endpoint URL not available yet.";
+ identifier = createDbInstanceResponse.dbInstance().dbInstanceIdentifier();
+ String status = createDbInstanceResponse.dbInstance().dbInstanceStatus();
+ Endpoint endpoint = createDbInstanceResponse.dbInstance().endpoint();
+ String endpointUrl = "Endpoint URL not available yet.";
if (endpoint != null) {
- endpoint_url = endpoint.toString();
+ endpointUrl = endpoint.toString();
}
logger.info(identifier + "\t" + status);
- logger.info(endpoint_url);
+ logger.info(endpointUrl);
return identifier;
@@ -90,44 +87,44 @@ public class AWSRDSService {
// Describe DB instances
public void listInstances() {
- DescribeDBInstancesResult result = amazonRDS.describeDBInstances();
- List instances = result.getDBInstances();
+ DescribeDbInstancesResponse response = rdsClient.describeDBInstances();
+ List instances = response.dbInstances();
for (DBInstance instance : instances) {
// Information about each RDS instance
- String identifier = instance.getDBInstanceIdentifier();
- String engine = instance.getEngine();
- String status = instance.getDBInstanceStatus();
- Endpoint endpoint = instance.getEndpoint();
- String endpoint_url = "Endpoint URL not available yet.";
+ String identifier = instance.dbInstanceIdentifier();
+ String engine = instance.engine();
+ String status = instance.dbInstanceStatus();
+ Endpoint endpoint = instance.endpoint();
+ String endpointUrl = "Endpoint URL not available yet.";
if (endpoint != null) {
- endpoint_url = endpoint.toString();
+ endpointUrl = endpoint.toString();
}
logger.info(identifier + "\t" + engine + "\t" + status);
- logger.info("\t" + endpoint_url);
+ logger.info("\t" + endpointUrl);
}
-
}
//Delete RDS instance
public void terminateInstance(String identifier) {
- DeleteDBInstanceRequest request = new DeleteDBInstanceRequest();
- request.setDBInstanceIdentifier(identifier);
- request.setSkipFinalSnapshot(true);
+ DeleteDbInstanceRequest request = DeleteDbInstanceRequest.builder()
+ .dbInstanceIdentifier(identifier)
+ .skipFinalSnapshot(true)
+ .build();
// Delete the RDS instance
- DBInstance instance = amazonRDS.deleteDBInstance(request);
+ DeleteDbInstanceResponse response = rdsClient.deleteDBInstance(request);
// Information about the RDS instance being deleted
- String status = instance.getDBInstanceStatus();
- Endpoint endpoint = instance.getEndpoint();
- String endpoint_url = "Endpoint URL not available yet.";
+ String status = response.dbInstance().dbInstanceStatus();
+ Endpoint endpoint = response.dbInstance().endpoint();
+ String endpointUrl = "Endpoint URL not available yet.";
if (endpoint != null) {
- endpoint_url = endpoint.toString();
+ endpointUrl = endpoint.toString();
}
logger.info(identifier + "\t" + status);
- logger.info(endpoint_url);
+ logger.info(endpointUrl);
}
diff --git a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/sqs/SQSApplication.java b/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/sqs/SQSApplication.java
index 978506a24f..3b78d73f60 100644
--- a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/sqs/SQSApplication.java
+++ b/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/sqs/SQSApplication.java
@@ -5,140 +5,190 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import com.amazonaws.auth.AWSCredentials;
-import com.amazonaws.auth.AWSStaticCredentialsProvider;
-import com.amazonaws.auth.BasicAWSCredentials;
-import com.amazonaws.regions.Regions;
-import com.amazonaws.services.sqs.AmazonSQSClientBuilder;
-import com.amazonaws.services.sqs.model.CreateQueueRequest;
-import com.amazonaws.services.sqs.model.DeleteMessageRequest;
-import com.amazonaws.services.sqs.model.GetQueueAttributesRequest;
-import com.amazonaws.services.sqs.model.GetQueueAttributesResult;
-import com.amazonaws.services.sqs.model.MessageAttributeValue;
-import com.amazonaws.services.sqs.model.ReceiveMessageRequest;
-import com.amazonaws.services.sqs.model.SendMessageBatchRequest;
-import com.amazonaws.services.sqs.model.SendMessageRequest;
-import com.amazonaws.services.sqs.model.SetQueueAttributesRequest;
-import com.amazonaws.services.sqs.model.SendMessageBatchRequestEntry;
-import com.amazonaws.services.sqs.model.Message;
-import com.amazonaws.services.sqs.AmazonSQS;
+import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.sqs.SqsClient;
+import software.amazon.awssdk.services.sqs.model.CreateQueueRequest;
+import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest;
+import software.amazon.awssdk.services.sqs.model.GetQueueAttributesRequest;
+import software.amazon.awssdk.services.sqs.model.GetQueueAttributesResponse;
+import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest;
+import software.amazon.awssdk.services.sqs.model.GetQueueUrlResponse;
+import software.amazon.awssdk.services.sqs.model.Message;
+import software.amazon.awssdk.services.sqs.model.MessageAttributeValue;
+import software.amazon.awssdk.services.sqs.model.QueueAttributeName;
+import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest;
+import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequest;
+import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequestEntry;
+import software.amazon.awssdk.services.sqs.model.SendMessageRequest;
+import software.amazon.awssdk.services.sqs.model.SetQueueAttributesRequest;
public class SQSApplication {
- private static final AWSCredentials credentials;
-
- static {
- // put your accesskey and secretkey here
- credentials = new BasicAWSCredentials(
- "",
- ""
- );
- }
+ private static final String STANDARD_QUEUE_NAME = "baeldung-queue";
+ private static final String FIFO_QUEUE_NAME = "baeldung-queue.fifo";
+ private static final String DEAD_LETTER_QUEUE_NAME = "baeldung-dead-letter-queue";
public static void main(String[] args) {
// Set up the client
- AmazonSQS sqs = AmazonSQSClientBuilder.standard()
- .withCredentials(new AWSStaticCredentialsProvider(credentials))
- .withRegion(Regions.US_EAST_1)
+ SqsClient sqsClient = SqsClient.builder()
+ .region(Region.US_EAST_1)
+ .credentialsProvider(ProfileCredentialsProvider.create())
.build();
// Create a standard queue
+ CreateQueueRequest createStandardQueueRequest = CreateQueueRequest.builder()
+ .queueName(STANDARD_QUEUE_NAME)
+ .build();
- CreateQueueRequest createStandardQueueRequest = new CreateQueueRequest("baeldung-queue");
- String standardQueueUrl = sqs.createQueue(createStandardQueueRequest)
- .getQueueUrl();
+ sqsClient.createQueue(createStandardQueueRequest);
+
+ System.out.println("\nGet queue url");
+
+ GetQueueUrlResponse getQueueUrlResponse = sqsClient.getQueueUrl(GetQueueUrlRequest.builder()
+ .queueName(STANDARD_QUEUE_NAME)
+ .build());
+ String standardQueueUrl = getQueueUrlResponse.queueUrl();
System.out.println(standardQueueUrl);
// Create a fifo queue
+ Map queueAttributes = new HashMap<>();
+ queueAttributes.put(QueueAttributeName.FIFO_QUEUE, "true");
+ queueAttributes.put(QueueAttributeName.CONTENT_BASED_DEDUPLICATION, "true");
- Map queueAttributes = new HashMap();
- queueAttributes.put("FifoQueue", "true");
- queueAttributes.put("ContentBasedDeduplication", "true");
+ CreateQueueRequest createFifoQueueRequest = CreateQueueRequest.builder()
+ .queueName(FIFO_QUEUE_NAME)
+ .attributes(queueAttributes)
+ .build();
- CreateQueueRequest createFifoQueueRequest = new CreateQueueRequest("baeldung-queue.fifo").withAttributes(queueAttributes);
- String fifoQueueUrl = sqs.createQueue(createFifoQueueRequest)
- .getQueueUrl();
+ sqsClient.createQueue(createFifoQueueRequest);
+
+ GetQueueUrlResponse getFifoQueueUrlResponse = sqsClient.getQueueUrl(GetQueueUrlRequest.builder()
+ .queueName(FIFO_QUEUE_NAME)
+ .build());
+
+ String fifoQueueUrl = getFifoQueueUrlResponse.queueUrl();
System.out.println(fifoQueueUrl);
// Set up a dead letter queue
+ CreateQueueRequest createDeadLetterQueueRequest = CreateQueueRequest.builder()
+ .queueName(DEAD_LETTER_QUEUE_NAME)
+ .build();
- String deadLetterQueueUrl = sqs.createQueue("baeldung-dead-letter-queue")
- .getQueueUrl();
+ String deadLetterQueueUrl = sqsClient.createQueue(createDeadLetterQueueRequest)
+ .queueUrl();
- GetQueueAttributesResult deadLetterQueueAttributes = sqs.getQueueAttributes(new GetQueueAttributesRequest(deadLetterQueueUrl).withAttributeNames("QueueArn"));
+ GetQueueAttributesRequest getQueueAttributesRequest = GetQueueAttributesRequest.builder()
+ .queueUrl(deadLetterQueueUrl)
+ .attributeNames(QueueAttributeName.QUEUE_ARN)
+ .build();
- String deadLetterQueueARN = deadLetterQueueAttributes.getAttributes()
+ GetQueueAttributesResponse deadLetterQueueAttributes = sqsClient.getQueueAttributes(getQueueAttributesRequest);
+
+ String deadLetterQueueARN = deadLetterQueueAttributes.attributes()
.get("QueueArn");
- SetQueueAttributesRequest queueAttributesRequest = new SetQueueAttributesRequest().withQueueUrl(standardQueueUrl)
- .addAttributesEntry("RedrivePolicy", "{\"maxReceiveCount\":\"2\", " + "\"deadLetterTargetArn\":\"" + deadLetterQueueARN + "\"}");
+ Map attributes = new HashMap<>();
+ attributes.put(QueueAttributeName.REDRIVE_POLICY, "{\"maxReceiveCount\":\"5\", \"deadLetterTargetArn\":\"" + deadLetterQueueARN + "\"}");
- sqs.setQueueAttributes(queueAttributesRequest);
+ SetQueueAttributesRequest queueAttributesRequest = SetQueueAttributesRequest.builder()
+ .queueUrl(standardQueueUrl)
+ .attributes(attributes)
+ .build();
+
+ sqsClient.setQueueAttributes(queueAttributesRequest);
// Send a message to a standard queue
Map messageAttributes = new HashMap<>();
+ MessageAttributeValue messageAttributeValue = MessageAttributeValue.builder()
+ .stringValue("This is an attribute")
+ .dataType("String")
+ .build();
- messageAttributes.put("AttributeOne", new MessageAttributeValue().withStringValue("This is an attribute")
- .withDataType("String"));
+ messageAttributes.put("AttributeOne", messageAttributeValue);
- SendMessageRequest sendMessageStandardQueue = new SendMessageRequest().withQueueUrl(standardQueueUrl)
- .withMessageBody("A simple message.")
- .withDelaySeconds(30) // Message will arrive in the queue after 30 seconds. We can use this only in standard queues
- .withMessageAttributes(messageAttributes);
+ SendMessageRequest sendMessageStandardQueue = SendMessageRequest.builder()
+ .queueUrl(standardQueueUrl)
+ .messageBody("A simple message.")
+ .delaySeconds(30) // Message will arrive in the queue after 30 seconds. We can use this only in standard queues
+ .messageAttributes(messageAttributes)
+ .build();
- sqs.sendMessage(sendMessageStandardQueue);
+ sqsClient.sendMessage(sendMessageStandardQueue);
// Send a message to a fifo queue
- SendMessageRequest sendMessageFifoQueue = new SendMessageRequest().withQueueUrl(fifoQueueUrl)
- .withMessageBody("FIFO Queue")
- .withMessageGroupId("baeldung-group-1")
- .withMessageAttributes(messageAttributes);
+ SendMessageRequest sendMessageFifoQueue = SendMessageRequest.builder()
+ .queueUrl(fifoQueueUrl)
+ .messageBody("FIFO Queue")
+ .messageGroupId("baeldung-group-1")
+ .messageAttributes(messageAttributes)
+ .build();
- sqs.sendMessage(sendMessageFifoQueue);
+ sqsClient.sendMessage(sendMessageFifoQueue);
// Send multiple messages
List messageEntries = new ArrayList<>();
- messageEntries.add(new SendMessageBatchRequestEntry().withId("id-1")
- .withMessageBody("batch-1")
- .withMessageGroupId("baeldung-group-1"));
- messageEntries.add(new SendMessageBatchRequestEntry().withId("id-2")
- .withMessageBody("batch-2")
- .withMessageGroupId("baeldung-group-1"));
+ SendMessageBatchRequestEntry messageBatchRequestEntry1 = SendMessageBatchRequestEntry.builder()
+ .id("id-1")
+ .messageBody("batch-1")
+ .messageGroupId("baeldung-group-1")
+ .build();
- SendMessageBatchRequest sendMessageBatchRequest = new SendMessageBatchRequest(fifoQueueUrl, messageEntries);
- sqs.sendMessageBatch(sendMessageBatchRequest);
+ SendMessageBatchRequestEntry messageBatchRequestEntry2 = SendMessageBatchRequestEntry.builder()
+ .id("id-2")
+ .messageBody("batch-2")
+ .messageGroupId("baeldung-group-1")
+ .build();
+
+ messageEntries.add(messageBatchRequestEntry1);
+ messageEntries.add(messageBatchRequestEntry2);
+
+ SendMessageBatchRequest sendMessageBatchRequest = SendMessageBatchRequest.builder()
+ .queueUrl(fifoQueueUrl)
+ .entries(messageEntries)
+ .build();
+
+ sqsClient.sendMessageBatch(sendMessageBatchRequest);
// Read a message from a queue
- ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(fifoQueueUrl).withWaitTimeSeconds(10) // Long polling;
- .withMaxNumberOfMessages(1); // Max is 10
+ ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder()
+ .waitTimeSeconds(10)
+ .maxNumberOfMessages(10)
+ .build();
- List sqsMessages = sqs.receiveMessage(receiveMessageRequest)
- .getMessages();
+ List sqsMessages = sqsClient.receiveMessage(receiveMessageRequest)
+ .messages();
sqsMessages.get(0)
- .getAttributes();
+ .attributes();
sqsMessages.get(0)
- .getBody();
+ .body();
// Delete a message from a queue
+ DeleteMessageRequest deleteMessageRequest = DeleteMessageRequest.builder()
+ .queueUrl(fifoQueueUrl)
+ .receiptHandle(sqsMessages.get(0)
+ .receiptHandle())
+ .build();
- sqs.deleteMessage(new DeleteMessageRequest().withQueueUrl(fifoQueueUrl)
- .withReceiptHandle(sqsMessages.get(0)
- .getReceiptHandle()));
+ sqsClient.deleteMessage(deleteMessageRequest);
// Monitoring
- GetQueueAttributesRequest getQueueAttributesRequest = new GetQueueAttributesRequest(standardQueueUrl).withAttributeNames("All");
- GetQueueAttributesResult getQueueAttributesResult = sqs.getQueueAttributes(getQueueAttributesRequest);
- System.out.println(String.format("The number of messages on the queue: %s", getQueueAttributesResult.getAttributes()
+ GetQueueAttributesRequest getQueueAttributesRequestForMonitoring = GetQueueAttributesRequest.builder()
+ .queueUrl(standardQueueUrl)
+ .build();
+
+ GetQueueAttributesResponse attributesResponse = sqsClient.getQueueAttributes(getQueueAttributesRequestForMonitoring);
+ System.out.println(String.format("The number of messages on the queue: %s", attributesResponse.attributes()
.get("ApproximateNumberOfMessages")));
- System.out.println(String.format("The number of messages in flight: %s", getQueueAttributesResult.getAttributes()
+ System.out.println(String.format("The number of messages in flight: %s", attributesResponse.attributes()
.get("ApproximateNumberOfMessagesNotVisible")));
}
diff --git a/aws-modules/aws-s3-update-object/pom.xml b/aws-modules/aws-s3-update-object/pom.xml
new file mode 100644
index 0000000000..3cf7b657b0
--- /dev/null
+++ b/aws-modules/aws-s3-update-object/pom.xml
@@ -0,0 +1,43 @@
+
+
+ 4.0.0
+ aws-s3-update-object
+ 0.0.1-SNAPSHOT
+ aws-s3-update-object
+ Project demonstrating overwriting of S3 objects
+
+ 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-test
+ test
+
+
+ com.amazonaws
+ aws-java-sdk
+ ${aws-java-sdk-version}
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+
+ 1.12.523
+
+
diff --git a/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/AwsS3UpdateObjectApplication.java b/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/AwsS3UpdateObjectApplication.java
new file mode 100644
index 0000000000..24866c287b
--- /dev/null
+++ b/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/AwsS3UpdateObjectApplication.java
@@ -0,0 +1,13 @@
+package com.baeldung.awss3updateobject;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class AwsS3UpdateObjectApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(AwsS3UpdateObjectApplication.class, args);
+ }
+
+}
diff --git a/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/controller/FileController.java b/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/controller/FileController.java
new file mode 100644
index 0000000000..e87358ef56
--- /dev/null
+++ b/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/controller/FileController.java
@@ -0,0 +1,24 @@
+package com.baeldung.awss3updateobject.controller;
+
+import com.baeldung.awss3updateobject.service.FileService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
+
+@RestController
+@RequestMapping("api/v1/file")
+public class FileController {
+
+ @Autowired
+ FileService fileService;
+
+ @PostMapping("/upload")
+ public String uploadFile(@RequestParam("file") MultipartFile multipartFile) throws Exception {
+ return this.fileService.uploadFile(multipartFile);
+ }
+
+ @PostMapping("/update")
+ public String updateFile(@RequestParam("file") MultipartFile multipartFile, @RequestParam("filePath") String exitingFilePath) throws Exception {
+ return this.fileService.updateFile(multipartFile, exitingFilePath);
+ }
+}
diff --git a/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/service/FileService.java b/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/service/FileService.java
new file mode 100644
index 0000000000..23eaad7913
--- /dev/null
+++ b/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/service/FileService.java
@@ -0,0 +1,80 @@
+package com.baeldung.awss3updateobject.service;
+
+import com.amazonaws.auth.AWSCredentials;
+import com.amazonaws.auth.AWSStaticCredentialsProvider;
+import com.amazonaws.auth.BasicAWSCredentials;
+import com.amazonaws.regions.Regions;
+import com.amazonaws.services.s3.AmazonS3;
+import com.amazonaws.services.s3.AmazonS3ClientBuilder;
+import com.amazonaws.services.s3.model.*;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.annotation.PostConstruct;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Map;
+
+@Service
+public class FileService {
+
+ private static final Logger logger = LoggerFactory.getLogger(FileService.class);
+
+ public AmazonS3 amazonS3;
+
+ @Value("${aws.s3bucket}")
+ public String awsS3Bucket;
+
+ @PostConstruct
+ private void init(){
+ AWSCredentials credentials = new BasicAWSCredentials(
+ "AWS AccessKey",
+ "AWS secretKey"
+ );
+ this.amazonS3 = AmazonS3ClientBuilder.standard()
+ .withRegion(Regions.fromName("us-east-1"))
+ .withCredentials(new AWSStaticCredentialsProvider(credentials))
+ .build();
+ }
+
+ public String uploadFile(MultipartFile multipartFile) throws Exception {
+ String key = "/documents/" + multipartFile.getOriginalFilename();
+ return this.uploadDocument(this.awsS3Bucket, key, multipartFile);
+ }
+
+ public String updateFile(MultipartFile multipartFile, String key) throws Exception {
+ return this.uploadDocument(this.awsS3Bucket, key, multipartFile);
+ }
+
+ private String uploadDocument(String s3bucket, String key, MultipartFile multipartFile) throws Exception {
+ try {
+ ObjectMetadata metadata = new ObjectMetadata();
+ metadata.setContentType(multipartFile.getContentType());
+ Map attributes = new HashMap<>();
+ attributes.put("document-content-size", String.valueOf(multipartFile.getSize()));
+ metadata.setUserMetadata(attributes);
+ InputStream documentStream = multipartFile.getInputStream();
+ PutObjectResult putObjectResult = this.amazonS3.putObject(new PutObjectRequest(s3bucket, key, documentStream, metadata));
+
+ S3Object s3Object = this.amazonS3.getObject(s3bucket, key);
+ logger.info("Last Modified: " + s3Object.getObjectMetadata().getLastModified());
+ return key;
+ } catch (AmazonS3Exception ex) {
+ if (ex.getErrorCode().equalsIgnoreCase("NoSuchBucket")) {
+ String msg = String.format("No bucket found with name %s", s3bucket);
+ throw new Exception(msg);
+ } else if (ex.getErrorCode().equalsIgnoreCase("AccessDenied")) {
+ String msg = String.format("Access denied to S3 bucket %s", s3bucket);
+ throw new Exception(msg);
+ }
+ throw ex;
+ } catch (IOException ex) {
+ String msg = String.format("Error saving file %s to AWS S3 bucket %s", key, s3bucket);
+ throw new Exception(msg);
+ }
+ }
+}
diff --git a/aws-modules/aws-s3-update-object/src/main/resources/application.properties b/aws-modules/aws-s3-update-object/src/main/resources/application.properties
new file mode 100644
index 0000000000..c840d970a8
--- /dev/null
+++ b/aws-modules/aws-s3-update-object/src/main/resources/application.properties
@@ -0,0 +1 @@
+aws.s3bucket=baeldung-documents;
diff --git a/aws-modules/aws-s3-update-object/src/test/java/com/baeldung/awss3updateobject/controller/FileControllerUnitTest.java b/aws-modules/aws-s3-update-object/src/test/java/com/baeldung/awss3updateobject/controller/FileControllerUnitTest.java
new file mode 100644
index 0000000000..823391c139
--- /dev/null
+++ b/aws-modules/aws-s3-update-object/src/test/java/com/baeldung/awss3updateobject/controller/FileControllerUnitTest.java
@@ -0,0 +1,62 @@
+package com.baeldung.awss3updateobject.controller;
+
+import com.baeldung.awss3updateobject.service.FileService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.mock.web.MockMultipartFile;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.web.multipart.MultipartFile;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.*;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
+
+public class FileControllerUnitTest {
+
+ private MockMvc mockMvc;
+
+ @Mock
+ private FileService fileService;
+
+ @InjectMocks
+ private FileController fileController;
+
+ @BeforeEach
+ public void setUp() {
+ MockitoAnnotations.openMocks(this);
+ this.mockMvc = MockMvcBuilders.standaloneSetup(fileController).build();
+ }
+
+ @Test
+ public void givenValidMultipartFile_whenUploadedViaEndpoint_thenCorrectPathIsReturned() throws Exception {
+ MockMultipartFile multipartFile = new MockMultipartFile("file", "test.txt", "text/plain", "sample file content".getBytes());
+ String expectedResult = "File Uploaded Successfully";
+
+ when(fileService.uploadFile(multipartFile)).thenReturn(expectedResult);
+
+ mockMvc.perform(multipart("/api/v1/file/upload").file(multipartFile))
+ .andExpect(status().isOk())
+ .andExpect(content().string(expectedResult));
+ }
+
+ @Test
+ public void givenValidMultipartFileAndExistingPath_whenUpdatedViaEndpoint_thenSamePathIsReturned() throws Exception {
+ MockMultipartFile multipartFile = new MockMultipartFile("file", "test.txt", "text/plain", "updated file content".getBytes());
+ String filePath = "some/path/to/file";
+ String expectedResult = "File Updated Successfully";
+
+ when(fileService.updateFile(multipartFile, filePath)).thenReturn(expectedResult);
+
+ mockMvc.perform(multipart("/api/v1/file/update")
+ .file(multipartFile)
+ .param("filePath", filePath))
+ .andExpect(status().isOk())
+ .andExpect(content().string(expectedResult));
+ }
+}
\ No newline at end of file
diff --git a/aws-modules/aws-s3-update-object/src/test/java/com/baeldung/awss3updateobject/service/FileServiceUnitTest.java b/aws-modules/aws-s3-update-object/src/test/java/com/baeldung/awss3updateobject/service/FileServiceUnitTest.java
new file mode 100644
index 0000000000..90ed77b148
--- /dev/null
+++ b/aws-modules/aws-s3-update-object/src/test/java/com/baeldung/awss3updateobject/service/FileServiceUnitTest.java
@@ -0,0 +1,99 @@
+package com.baeldung.awss3updateobject.service;
+
+import com.amazonaws.services.s3.AmazonS3;
+import com.amazonaws.services.s3.model.AmazonS3Exception;
+import com.amazonaws.services.s3.model.PutObjectRequest;
+import com.amazonaws.services.s3.model.S3Object;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.*;
+
+public class FileServiceUnitTest {
+
+ @Mock
+ private AmazonS3 amazonS3;
+
+ @Mock
+ private MultipartFile multipartFile;
+
+ @InjectMocks
+ private FileService fileService;
+
+ @BeforeEach
+ public void setup() {
+ MockitoAnnotations.openMocks(this);
+ fileService = new FileService();
+ fileService.awsS3Bucket = "test-bucket";
+ fileService.amazonS3 = amazonS3;
+ }
+
+ @Test
+ public void givenValidFile_whenUploaded_thenKeyMatchesDocumentPath() throws Exception {
+ when(multipartFile.getName()).thenReturn("testFile");
+ when(multipartFile.getOriginalFilename()).thenReturn("testFile");
+ when(multipartFile.getContentType()).thenReturn("application/pdf");
+ when(multipartFile.getSize()).thenReturn(1024L);
+ when(multipartFile.getInputStream()).thenReturn(mock(InputStream.class));
+
+ S3Object s3Object = new S3Object();
+ when(amazonS3.putObject(any())).thenReturn(null);
+ when(amazonS3.getObject(anyString(), anyString())).thenReturn(s3Object);
+
+ String key = fileService.uploadFile(multipartFile);
+
+ assertEquals("/documents/testFile", key);
+ }
+
+ @Test
+ public void givenValidFile_whenUploadFailsDueToNoBucket_thenExceptionIsThrown() throws Exception {
+ when(multipartFile.getName()).thenReturn("testFile");
+ when(multipartFile.getOriginalFilename()).thenReturn("testFile");
+ when(multipartFile.getContentType()).thenReturn("application/pdf");
+ when(multipartFile.getSize()).thenReturn(1024L);
+ when(multipartFile.getInputStream()).thenReturn(mock(InputStream.class));
+
+ AmazonS3Exception exception = new AmazonS3Exception("Test exception");
+ exception.setErrorCode("NoSuchBucket");
+ when(amazonS3.putObject(any(PutObjectRequest.class))).thenThrow(exception);
+
+ assertThrows(Exception.class, () -> fileService.uploadFile(multipartFile));
+ }
+
+ @Test
+ public void givenExistingFile_whenUpdated_thenSameKeyIsReturned() throws Exception {
+ when(multipartFile.getName()).thenReturn("testFile");
+ when(multipartFile.getContentType()).thenReturn("application/pdf");
+ when(multipartFile.getSize()).thenReturn(1024L);
+ when(multipartFile.getInputStream()).thenReturn(mock(InputStream.class));
+
+ S3Object s3Object = new S3Object();
+ when(amazonS3.putObject(any(PutObjectRequest.class))).thenReturn(null);
+ when(amazonS3.getObject(anyString(), anyString())).thenReturn(s3Object);
+
+ String key = "/documents/existingFile";
+ String resultKey = fileService.updateFile(multipartFile, key);
+
+ assertEquals(key, resultKey);
+ }
+
+ @Test
+ public void givenFileWithIOException_whenUpdated_thenExceptionIsThrown() throws Exception {
+ when(multipartFile.getName()).thenReturn("testFile");
+ when(multipartFile.getContentType()).thenReturn("application/pdf");
+ when(multipartFile.getSize()).thenReturn(1024L);
+ when(multipartFile.getInputStream()).thenThrow(new IOException("Test IO Exception"));
+
+ assertThrows(Exception.class, () -> fileService.updateFile(multipartFile, "/documents/existingFile"));
+ }
+}
\ No newline at end of file
diff --git a/aws-modules/aws-s3/README.md b/aws-modules/aws-s3/README.md
index 3389fdf454..9b862c8685 100644
--- a/aws-modules/aws-s3/README.md
+++ b/aws-modules/aws-s3/README.md
@@ -4,8 +4,10 @@ This module contains articles about Simple Storage Service (S3) on AWS
### Relevant articles
-- [AWS S3 with Java](https://www.baeldung.com/aws-s3-java)
+- [AWS S3 with Java](https://www.baeldung.com/java-aws-s3)
- [Multipart Uploads in Amazon S3 with Java](https://www.baeldung.com/aws-s3-multipart-upload)
- [Using the JetS3t Java Client With Amazon S3](https://www.baeldung.com/jets3t-amazon-s3)
- [Check if a Specified Key Exists in a Given S3 Bucket Using Java](https://www.baeldung.com/java-aws-s3-check-specified-key-exists)
-- [Listing All AWS S3 Objects in a Bucket Using Java](https://www.baeldung.com/java-aws-s3-list-bucket-objects)
\ No newline at end of file
+- [Listing All AWS S3 Objects in a Bucket Using Java](https://www.baeldung.com/java-aws-s3-list-bucket-objects)
+- [Update an Existing Amazon S3 Object Using Java](https://www.baeldung.com/java-update-amazon-s3-object)
+- [How To Rename Files and Folders in Amazon S3](https://www.baeldung.com/java-amazon-s3-rename-files-folders)
diff --git a/aws-modules/aws-s3/pom.xml b/aws-modules/aws-s3/pom.xml
index 157aeb671d..e2bc04964a 100644
--- a/aws-modules/aws-s3/pom.xml
+++ b/aws-modules/aws-s3/pom.xml
@@ -1,7 +1,7 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
aws-s3
0.1.0-SNAPSHOT
diff --git a/aws-modules/aws-s3/src/main/java/com/baeldung/s3/RenameObjectService.java b/aws-modules/aws-s3/src/main/java/com/baeldung/s3/RenameObjectService.java
new file mode 100644
index 0000000000..0ca586c73b
--- /dev/null
+++ b/aws-modules/aws-s3/src/main/java/com/baeldung/s3/RenameObjectService.java
@@ -0,0 +1,79 @@
+package com.baeldung.s3;
+
+import java.util.List;
+
+import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.s3.S3Client;
+import software.amazon.awssdk.services.s3.model.CopyObjectRequest;
+import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
+import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
+import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
+import software.amazon.awssdk.services.s3.model.S3Object;
+
+public class RenameObjectService {
+
+ private S3Client s3Client;
+
+ public RenameObjectService(S3Client s3Client) {
+ this.s3Client = s3Client;
+ }
+
+ public RenameObjectService() {
+ init();
+ }
+
+ public void init() {
+ this.s3Client = S3Client.builder()
+ .region(Region.US_EAST_1)
+ .credentialsProvider(ProfileCredentialsProvider.create("default"))
+ .build();
+ }
+
+ public void renameFile(String bucketName, String keyName, String destinationKeyName) {
+ CopyObjectRequest copyObjRequest = CopyObjectRequest.builder()
+ .sourceBucket(bucketName)
+ .sourceKey(keyName)
+ .destinationBucket(destinationKeyName)
+ .destinationKey(bucketName)
+ .build();
+ s3Client.copyObject(copyObjRequest);
+ DeleteObjectRequest deleteRequest = DeleteObjectRequest.builder()
+ .bucket(bucketName)
+ .key(keyName)
+ .build();
+ s3Client.deleteObject(deleteRequest);
+ }
+
+ public void renameFolder(String bucketName, String sourceFolderKey, String destinationFolderKey) {
+ ListObjectsV2Request listRequest = ListObjectsV2Request.builder()
+ .bucket(bucketName)
+ .prefix(sourceFolderKey)
+ .build();
+
+ ListObjectsV2Response listResponse = s3Client.listObjectsV2(listRequest);
+ List objects = listResponse.contents();
+
+ for (S3Object s3Object : objects) {
+ String newKey = destinationFolderKey + s3Object.key()
+ .substring(sourceFolderKey.length());
+
+ // Copy object to destination folder
+ CopyObjectRequest copyRequest = CopyObjectRequest.builder()
+ .sourceBucket(bucketName)
+ .sourceKey(s3Object.key())
+ .destinationBucket(bucketName)
+ .destinationKey(newKey)
+ .build();
+ s3Client.copyObject(copyRequest);
+
+ // Delete object from source folder
+ DeleteObjectRequest deleteRequest = DeleteObjectRequest.builder()
+ .bucket(bucketName)
+ .key(s3Object.key())
+ .build();
+ s3Client.deleteObject(deleteRequest);
+ }
+ }
+
+}
diff --git a/aws-modules/pom.xml b/aws-modules/pom.xml
index 02473815b5..66fa4bffa1 100644
--- a/aws-modules/pom.xml
+++ b/aws-modules/pom.xml
@@ -5,6 +5,14 @@
4.0.0
aws-modules
aws-modules
+
+
+ com.amazonaws
+ aws-java-sdk-dynamodb
+ 1.12.523
+ compile
+
+
pom
@@ -15,14 +23,17 @@
aws-app-sync
+ aws-dynamodb
aws-lambda-modules
aws-miscellaneous
aws-reactive
aws-s3
+ aws-s3-update-object
1.12.331
+ 2.20.147
3.0.0
diff --git a/azure/pom.xml b/azure/pom.xml
index aae84db0c6..6a06282a71 100644
--- a/azure/pom.xml
+++ b/azure/pom.xml
@@ -122,7 +122,6 @@
${azure.containerRegistry}.azurecr.io
1.1.0
1.1.0
- 3.3.2
\ No newline at end of file
diff --git a/core-groovy-modules/pom.xml b/core-groovy-modules/pom.xml
index 6faa7f94c8..4fdaf3ee7a 100644
--- a/core-groovy-modules/pom.xml
+++ b/core-groovy-modules/pom.xml
@@ -27,6 +27,7 @@
2.7.1
2.3-groovy-3.0
2.1.0
+ 2.21.0
diff --git a/core-java-modules/Reminder Application/Reminder Application/task/src/reminderapplication/ConstraintsBuilder.java b/core-java-modules/Reminder Application/Reminder Application/task/src/reminderapplication/ConstraintsBuilder.java
deleted file mode 100644
index ce437fac6d..0000000000
--- a/core-java-modules/Reminder Application/Reminder Application/task/src/reminderapplication/ConstraintsBuilder.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package reminderapplication;
-
-import java.awt.GridBagConstraints;
-import java.awt.Insets;
-
-public class ConstraintsBuilder {
-
- static GridBagConstraints constraint(int x, int y) {
- final GridBagConstraints gridBagConstraints = new GridBagConstraints();
- gridBagConstraints.gridx = x;
- gridBagConstraints.gridy = y;
- gridBagConstraints.insets = new Insets(5, 5, 5, 5);
- return gridBagConstraints;
- }
-}
diff --git a/core-java-modules/Reminder Application/Reminder Application/task/src/reminderapplication/EditReminderFrame.java b/core-java-modules/Reminder Application/Reminder Application/task/src/reminderapplication/EditReminderFrame.java
deleted file mode 100644
index 818cea403e..0000000000
--- a/core-java-modules/Reminder Application/Reminder Application/task/src/reminderapplication/EditReminderFrame.java
+++ /dev/null
@@ -1,194 +0,0 @@
-package reminderapplication;
-
-import static reminderapplication.ConstraintsBuilder.*;
-
-import java.awt.GridBagLayout;
-import java.awt.HeadlessException;
-import java.lang.reflect.InvocationTargetException;
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.concurrent.TimeUnit;
-import javax.swing.DefaultComboBoxModel;
-import javax.swing.DefaultListModel;
-import javax.swing.JButton;
-import javax.swing.JComboBox;
-import javax.swing.JFrame;
-import javax.swing.JLabel;
-import javax.swing.JTextField;
-import javax.swing.SwingUtilities;
-
-public class EditReminderFrame extends JFrame {
-
- private static Timer TIMER = new Timer();
-
- private final TimeReminderApplication reminderApplication;
- private final JLabel reminderTextLabel;
- private final JLabel repeatPeriodLabel;
- private final JLabel setDelayLabel;
- private final JComboBox delay;
- private final JComboBox period;
- private final JButton cancelButton;
- private final JButton okButton;
- private final JTextField textField;
- private final JLabel delaysLabel;
- private final JLabel periodLabel;
-
- private final int reminderIndex;
-
- public EditReminderFrame(TimeReminderApplication reminderApp, String reminderText, int delayInSeconds, int periodInSeconds, int index) throws HeadlessException {
- this.reminderApplication = reminderApp;
- reminderIndex = index;
- textField = createTextField(reminderText);
- delay = createDelayComboBox(delayInSeconds);
- period = createPeriodComboBox(periodInSeconds);
- cancelButton = createCancelButton();
- okButton = createOkButton();
- reminderTextLabel = createReminderTextLabel();
- repeatPeriodLabel = createRepeatPeriodLabel();
- setDelayLabel = createSetDelayLabel();
- delaysLabel = createDelaysLabel();
- periodLabel = createPeriodLabel();
- configureVisualRepresentation();
- configureActions();
- }
-
- private void configureActions() {
- updateReminder();
- }
-
- private void configureVisualRepresentation() {
- configureFrame();
- setLocationRelativeTo(null);
- setLayout(new GridBagLayout());
- add(reminderTextLabel, constraint(0,0));
- add(repeatPeriodLabel, constraint(1,0));
- add(setDelayLabel, constraint(2,0));
- add(textField, constraint(0, 1));
- add(delay, constraint(1, 1));
- add(period, constraint(2, 1));
- add(delaysLabel, constraint(1,3));
- add(periodLabel, constraint(2,3));
- add(okButton, constraint(1, 4));
- add(cancelButton, constraint(2, 4));
- pack();
- setVisible(true);
- }
-
- private void configureFrame() {
- setTitle("Set Reminder");
- setName("Set Reminder");
- setDefaultCloseOperation(DISPOSE_ON_CLOSE);
- }
-
- private static JLabel createSetDelayLabel() {
- return createLabel("Set Delay", "Set Delay Label");
- }
-
- private static JLabel createRepeatPeriodLabel() {
- return createLabel("Set Period", "Set Repeat Period Label");
- }
-
- private static JLabel createReminderTextLabel() {
- return createLabel("Reminder Text", "Reminder Text Label");
- }
-
- private JLabel createPeriodLabel() {
- return createLabel("0", "Period label");
- }
-
- private JLabel createDelaysLabel() {
- return createLabel("30", "Delays Label");
- }
-
- private JComboBox createPeriodComboBox(final int periodInSeconds) {
- final JComboBox comboBox = new JComboBox<>(new DefaultComboBoxModel<>(new Integer[]{0, 5, 10, 20}));
- comboBox.setSelectedItem(periodInSeconds);
- comboBox.setName("set Period");
- comboBox.addActionListener(e -> periodLabel.setText(comboBox.getSelectedItem().toString()));
- return comboBox;
- }
-
- private JComboBox createDelayComboBox(final int delayInSeconds) {
- final JComboBox comboBox = new JComboBox<>(new DefaultComboBoxModel<>(new Integer[]{30, 25, 15, 5}));
- comboBox.setSelectedItem(delayInSeconds);
- comboBox.setName("set Delay");
- comboBox.addActionListener(e -> delaysLabel.setText(comboBox.getSelectedItem().toString()));
- return comboBox;
- }
-
- private JTextField createTextField(final String reminderText) {
- final JTextField textField = new JTextField(20);
- textField.setName("Field");
- textField.setText(reminderText);
- return textField;
- }
-
- private JButton createOkButton() {
- final JButton button = new JButton("ok");
- button.setName("OK");
- return button;
- }
-
- private void updateReminder() {
- okButton.addActionListener(e -> this.dispose());
- okButton.addActionListener(e -> {
- final int periodInSeconds = getTimeInSeconds(period);
- final int delayInSeconds = getTimeInSeconds(delay);
- final Reminder reminder = new Reminder(textField.getText(), delayInSeconds, periodInSeconds);
- ((DefaultListModel) reminderApplication.getReminders()).set(reminderIndex, reminder);
- });
- okButton.addActionListener(e -> scheduleReminder(textField, delay, period));
- }
-
- private void scheduleReminder(final JTextField textField, final JComboBox delay, final JComboBox period) {
- final int periodInSeconds = getTimeInSeconds(period);
- if (periodInSeconds == 0)
- scheduleNonRepeatedReminder(textField, delay);
- else
- scheduleRepeatedReminder(textField, delay, period);
- }
-
- private void scheduleRepeatedReminder(final JTextField textField, final JComboBox delay, final JComboBox period) {
- final int delayInSeconds = getTimeInSeconds(delay);
- final int periodInSeconds = getTimeInSeconds(period);
- final TimerTask timerTask = getTimerTask(textField.getText(), delayInSeconds, periodInSeconds);
- TIMER.schedule(timerTask, TimeUnit.SECONDS.toMillis(delayInSeconds), TimeUnit.SECONDS.toMillis(periodInSeconds));
- }
-
- private void scheduleNonRepeatedReminder(final JTextField textField, final JComboBox delay) {
- final int delayInSeconds = getTimeInSeconds(delay);
- final int periodInSeconds = 0;
- final TimerTask timerTask = getTimerTask(textField.getText(), delayInSeconds, periodInSeconds);
- TIMER.schedule(timerTask, TimeUnit.SECONDS.toMillis(delayInSeconds));
-
- }
-
- private int getTimeInSeconds(final JComboBox comboBox) {
- if (comboBox != null && comboBox.getSelectedItem() != null)
- return ((Integer) comboBox.getSelectedItem());
- else
- return 0;
- }
-
- private TimerTask getTimerTask(final String reminderText, final Integer delayInSeconds, final Integer periodInSeconds) {
- return new TimerTask() {
- @Override
- public void run() {
- new ReminderPopupFrame(reminderApplication, reminderText, delayInSeconds, periodInSeconds);
- }
- };
- }
-
- private JButton createCancelButton() {
- final JButton button = new JButton("cancel");
- button.setName("Cancel");
- button.addActionListener(e -> this.dispose());
- return button;
- }
-
- private static JLabel createLabel(final String text, final String name) {
- JLabel label = new JLabel(text);
- label.setName(name);
- return label;
- }
-}
diff --git a/core-java-modules/Reminder Application/Reminder Application/task/src/reminderapplication/Reminder.java b/core-java-modules/Reminder Application/Reminder Application/task/src/reminderapplication/Reminder.java
deleted file mode 100644
index 8f6ff336ed..0000000000
--- a/core-java-modules/Reminder Application/Reminder Application/task/src/reminderapplication/Reminder.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package reminderapplication;
-
-public class Reminder {
-
- private static String REMINDER_FORMAT = "Reminder Text: %s; Delay: %d; Period: %d;";
-
- private final String name;
- private final int delay;
- private final int period;
-
- public Reminder(final String name, final int delay, final int period) {
- this.name = name;
- this.delay = delay;
- this.period = period;
- }
-
- public String getName() {
- return name;
- }
-
- public int getDelay() {
- return delay;
- }
-
- public int getPeriod() {
- return period;
- }
-
- @Override
- public String toString() {
- return REMINDER_FORMAT.formatted(name, delay, period);
- }
-}
diff --git a/core-java-modules/Reminder Application/Reminder Application/task/src/reminderapplication/ReminderFrame.java b/core-java-modules/Reminder Application/Reminder Application/task/src/reminderapplication/ReminderFrame.java
deleted file mode 100644
index 3a1623219c..0000000000
--- a/core-java-modules/Reminder Application/Reminder Application/task/src/reminderapplication/ReminderFrame.java
+++ /dev/null
@@ -1,186 +0,0 @@
-package reminderapplication;
-
-import static reminderapplication.ConstraintsBuilder.*;
-
-import java.awt.GridBagLayout;
-import java.awt.HeadlessException;
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.concurrent.TimeUnit;
-import javax.swing.DefaultComboBoxModel;
-import javax.swing.DefaultListModel;
-import javax.swing.JButton;
-import javax.swing.JComboBox;
-import javax.swing.JFrame;
-import javax.swing.JLabel;
-import javax.swing.JTextField;
-
-public class ReminderFrame extends JFrame {
-
- private static Timer TIMER = new Timer();
- private final TimeReminderApplication reminderApplication;
- private final JLabel reminderTextLabel;
- private final JLabel repeatPeriodLabel;
- private final JLabel setDelayLabel;
- private final JComboBox delay;
- private final JComboBox period;
- private final JButton cancelButton;
- private final JButton okButton;
- private final JTextField textField;
- private final JLabel delaysLabel;
- private final JLabel periodLabel;
-
- public ReminderFrame(TimeReminderApplication reminderApp) throws HeadlessException {
- this.reminderApplication = reminderApp;
- textField = createTextField();
- delay = createDelayComboBox();
- period = createPeriodComboBox();
- cancelButton = createCancelButton();
- okButton = createOkButton();
- reminderTextLabel = createReminderTextLabel();
- repeatPeriodLabel = createRepeatPeriodLabel();
- setDelayLabel = createSetDelayLabel();
- delaysLabel = createDelaysLabel();
- periodLabel = createPeriodLabel();
- configureVisualRepresentation();
- configureActions();
- }
-
- private void configureActions() {
- createNewReminder();
- }
-
- private void configureVisualRepresentation() {
- configureFrame();
- setLocationRelativeTo(null);
- setLayout(new GridBagLayout());
- add(reminderTextLabel, constraint(0,0));
- add(repeatPeriodLabel, constraint(1,0));
- add(setDelayLabel, constraint(2,0));
- add(textField, constraint(0, 1));
- add(delay, constraint(1, 1));
- add(period, constraint(2, 1));
- add(delaysLabel, constraint(1,3));
- add(periodLabel, constraint(2,3));
- add(okButton, constraint(1, 4));
- add(cancelButton, constraint(2, 4));
- pack();
- setVisible(true);
- }
-
- private void configureFrame() {
- setTitle("Set Reminder");
- setName("Set Reminder");
- setDefaultCloseOperation(DISPOSE_ON_CLOSE);
- }
-
- private static JLabel createSetDelayLabel() {
- return createLabel("Set Delay", "Set Delay Label");
- }
-
- private static JLabel createRepeatPeriodLabel() {
- return createLabel("Set Period", "Set Repeat Period Label");
- }
-
- private static JLabel createReminderTextLabel() {
- return createLabel("Reminder Text", "Reminder Text Label");
- }
-
- private JLabel createPeriodLabel() {
- return createLabel("0", "Period label");
- }
-
- private JLabel createDelaysLabel() {
- return createLabel("30", "Delays Label");
- }
-
- private JComboBox createPeriodComboBox() {
- final JComboBox comboBox = new JComboBox<>(new DefaultComboBoxModel<>(new Integer[]{0, 5, 10, 20}));
- comboBox.setName("set Period");
- comboBox.addActionListener(e -> periodLabel.setText(comboBox.getSelectedItem().toString()));
- return comboBox;
- }
-
- private JComboBox createDelayComboBox() {
- final JComboBox comboBox = new JComboBox<>(new DefaultComboBoxModel<>(new Integer[]{30, 25, 15, 5}));
- comboBox.setName("set Delay");
- comboBox.addActionListener(e -> delaysLabel.setText(comboBox.getSelectedItem().toString()));
- return comboBox;
- }
-
- private JTextField createTextField() {
- final JTextField textField = new JTextField(20);
- textField.setName("Field");
- return textField;
- }
-
- private JButton createOkButton() {
- final JButton button = new JButton("ok");
- button.setName("OK");
- return button;
- }
-
- private void createNewReminder() {
-
- okButton.addActionListener(e -> this.dispose());
- okButton.addActionListener(e -> {
- final int periodInSeconds = getTimeInSeconds(period);
- final int delayInSeconds = getTimeInSeconds(delay);
- final Reminder reminder = new Reminder(textField.getText(), delayInSeconds, periodInSeconds);
- ((DefaultListModel) reminderApplication.getReminders()).addElement(reminder);
- });
- okButton.addActionListener(e -> scheduleReminder(textField, delay, period));
- }
-
- private void scheduleReminder(final JTextField textField, final JComboBox delay, final JComboBox period) {
- final int periodInSeconds = getTimeInSeconds(period);
- if (periodInSeconds == 0)
- scheduleNonRepeatedReminder(textField, delay);
- else
- scheduleRepeatedReminder(textField, delay, period);
- }
-
- private void scheduleRepeatedReminder(final JTextField textField, final JComboBox delay, final JComboBox period) {
- final int delayInSeconds = getTimeInSeconds(delay) + 200;
- final int periodInSeconds = getTimeInSeconds(period);
- final TimerTask timerTask = getTimerTask(textField.getText(), delayInSeconds, periodInSeconds);
- TIMER.schedule(timerTask, TimeUnit.SECONDS.toMillis(delayInSeconds), TimeUnit.SECONDS.toMillis(periodInSeconds));
- }
-
- private void scheduleNonRepeatedReminder(final JTextField textField, final JComboBox delay) {
- final int delayInSeconds = getTimeInSeconds(delay);
- final int periodInSeconds = 0;
- final TimerTask timerTask = getTimerTask(textField.getText(), delayInSeconds, periodInSeconds);
- TIMER.schedule(timerTask, TimeUnit.SECONDS.toMillis(delayInSeconds));
-
- }
-
- private int getTimeInSeconds(final JComboBox comboBox) {
- if (comboBox != null && comboBox.getSelectedItem() != null)
- return ((Integer) comboBox.getSelectedItem());
- else
- return 0;
- }
-
- private TimerTask getTimerTask(final String reminderText, final Integer delayInSeconds, final Integer periodInSeconds) {
- return new TimerTask() {
- @Override
- public void run() {
- new ReminderPopupFrame(reminderApplication, reminderText, delayInSeconds, periodInSeconds);
- }
- };
- }
-
- private JButton createCancelButton() {
- final JButton button = new JButton("cancel");
- button.setName("Cancel");
- button.addActionListener(e -> this.dispose());
- return button;
- }
-
- private static JLabel createLabel(final String text, final String name) {
- JLabel label = new JLabel(text);
- label.setName(name);
- return label;
- }
-}
diff --git a/core-java-modules/Reminder Application/Reminder Application/task/src/reminderapplication/ReminderPopupFrame.java b/core-java-modules/Reminder Application/Reminder Application/task/src/reminderapplication/ReminderPopupFrame.java
deleted file mode 100644
index d41343cb6d..0000000000
--- a/core-java-modules/Reminder Application/Reminder Application/task/src/reminderapplication/ReminderPopupFrame.java
+++ /dev/null
@@ -1,151 +0,0 @@
-package reminderapplication;
-
-import static reminderapplication.ConstraintsBuilder.*;
-
-import java.awt.GridBagLayout;
-import java.awt.HeadlessException;
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.concurrent.TimeUnit;
-import javax.swing.DefaultComboBoxModel;
-import javax.swing.DefaultListModel;
-import javax.swing.JButton;
-import javax.swing.JComboBox;
-import javax.swing.JFrame;
-import javax.swing.JLabel;
-import javax.swing.JTextField;
-
-public class ReminderPopupFrame extends JFrame {
-
- private static final Timer TIMER = new Timer();
- private final int AUTOMATIC_CLOSE_TIME_IN_SECONDS = 10;
- private final TimeReminderApplication reminderApplication;
- private final JLabel reminderTextLabel;
- private final JLabel repeatPeriodLabel;
- private final JLabel setDelayLabel;
- private final JComboBox delay;
- private final JComboBox period;
- private final JButton cancelButton;
- private final JButton okButton;
- private final JTextField textField;
- private final JLabel delaysLabel;
- private final JLabel periodLabel;
-
- public ReminderPopupFrame(TimeReminderApplication reminderApp, final String text, final Integer delayInSeconds, final Integer periodInSeconds) throws HeadlessException {
- this.reminderApplication = reminderApp;
- textField = createTextField(text);
- delay = createDelayComboBox(delayInSeconds);
- period = createPeriodComboBox(periodInSeconds);
- cancelButton = createCancelButton();
- okButton = createDisabledOkButton();
- reminderTextLabel = createReminderTextLabel();
- repeatPeriodLabel = createRepeatPeriodLabel();
- setDelayLabel = createSetDelayLabel();
- delaysLabel = createDelaysLabel();
- periodLabel = createPeriodLabel();
- configureVisualRepresentation();
- configureActions();
- }
-
- private void configureActions() {
- scheduleClosing();
- }
-
- private void scheduleClosing() {
- final TimerTask timerTask = new TimerTask() {
- @Override
- public void run() {
- ReminderPopupFrame.this.dispose();
- }
- };
- TIMER.schedule(timerTask, TimeUnit.SECONDS.toMillis(AUTOMATIC_CLOSE_TIME_IN_SECONDS));
- }
-
- private void configureVisualRepresentation() {
- configureFrame();
- setLocationRelativeTo(null);
- setLayout(new GridBagLayout());
- add(reminderTextLabel, constraint(0,0));
- add(repeatPeriodLabel, constraint(1,0));
- add(setDelayLabel, constraint(2,0));
- add(textField, constraint(0, 1));
- add(delay, constraint(1, 1));
- add(period, constraint(2, 1));
- add(delaysLabel, constraint(1,3));
- add(periodLabel, constraint(2,3));
- add(okButton, constraint(1, 4));
- add(cancelButton, constraint(2, 4));
- pack();
- setVisible(true);
- }
-
- private void configureFrame() {
- setTitle("Set Reminder");
- setName("Set Reminder");
- setDefaultCloseOperation(DISPOSE_ON_CLOSE);
- }
-
- private static JLabel createSetDelayLabel() {
- return createLabel("Set Delay", "Set Delay Label");
- }
-
- private static JLabel createRepeatPeriodLabel() {
- return createLabel("Set Period", "Set Repeat Period Label");
- }
-
- private static JLabel createReminderTextLabel() {
- return createLabel("Reminder Text", "Reminder Text Label");
- }
-
- private JLabel createPeriodLabel() {
- return createLabel("0", "Period label");
- }
-
- private JLabel createDelaysLabel() {
- return createLabel("30", "Delays Label");
- }
-
- private JComboBox createPeriodComboBox(final Integer periodInSeconds) {
- final JComboBox comboBox = new JComboBox<>(new DefaultComboBoxModel<>(new Integer[]{0, 5, 10, 20}));
- comboBox.setName("set Period");
- comboBox.setSelectedItem(periodInSeconds);
- comboBox.addActionListener(e -> periodLabel.setText(comboBox.getSelectedItem().toString()));
- return comboBox;
- }
-
- private JComboBox createDelayComboBox(Integer delay) {
- final JComboBox comboBox = new JComboBox<>(new DefaultComboBoxModel<>(new Integer[]{30, 25, 15, 5}));
- comboBox.setSelectedItem(delay);
- comboBox.setName("set Delay");
- comboBox.addActionListener(e -> delaysLabel.setText(comboBox.getSelectedItem().toString()));
- return comboBox;
- }
-
- private JTextField createTextField(final String text) {
- final JTextField textField = new JTextField(20);
- textField.setName("Field");
- textField.setText(text);
- return textField;
- }
-
- private JButton createDisabledOkButton() {
- final JButton button = new JButton("ok");
- button.setName("OK");
- button.setEnabled(false);
- return button;
- }
-
- private JButton createCancelButton() {
- final JButton button = new JButton("cancel");
- button.setName("Cancel");
- button.addActionListener(e -> this.dispose());
- return button;
- }
-
- private static JLabel createLabel(final String text, final String name) {
- JLabel label = new JLabel(text);
- label.setName(name);
- return label;
- }
-
-}
diff --git a/core-java-modules/core-java-11-2/README.md b/core-java-modules/core-java-11-2/README.md
index ab8331f41c..b9dc82bc7f 100644
--- a/core-java-modules/core-java-11-2/README.md
+++ b/core-java-modules/core-java-11-2/README.md
@@ -5,7 +5,6 @@ This module contains articles about Java 11 core features
### Relevant articles
- [Guide To Java 8 Optional](https://www.baeldung.com/java-optional)
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
-- [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors)
- [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)
diff --git a/core-java-modules/core-java-12/pom.xml b/core-java-modules/core-java-12/pom.xml
index ba6dfc62bc..8165549d8c 100644
--- a/core-java-modules/core-java-12/pom.xml
+++ b/core-java-modules/core-java-12/pom.xml
@@ -8,9 +8,9 @@
jar
- com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
@@ -21,30 +21,8 @@