Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
3aec90131c
@ -9,4 +9,6 @@ This module contains articles about Apache POI.
|
|||||||
- [Numeric Format Using POI](https://www.baeldung.com/apache-poi-numeric-format)
|
- [Numeric Format Using POI](https://www.baeldung.com/apache-poi-numeric-format)
|
||||||
- [Microsoft Word Processing in Java with Apache POI](https://www.baeldung.com/java-microsoft-word-with-apache-poi)
|
- [Microsoft Word Processing in Java with Apache POI](https://www.baeldung.com/java-microsoft-word-with-apache-poi)
|
||||||
- [Creating a MS PowerPoint Presentation in Java](https://www.baeldung.com/apache-poi-slideshow)
|
- [Creating a MS PowerPoint Presentation in Java](https://www.baeldung.com/apache-poi-slideshow)
|
||||||
|
- [Finding the Last Row in an Excel Spreadsheet From Java](https://www.baeldung.com/java-excel-find-last-row)
|
||||||
|
- [Setting Formulas in Excel with Apache POI](https://www.baeldung.com/java-apache-poi-set-formulas)
|
||||||
- More articles: [[<-- prev]](../apache-poi)
|
- More articles: [[<-- prev]](../apache-poi)
|
||||||
|
@ -22,7 +22,7 @@
|
|||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<poi.version>5.0.0</poi.version>
|
<poi.version>5.2.0</poi.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -5,7 +5,6 @@ import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
|
|||||||
import org.apache.poi.xssf.usermodel.XSSFSheet;
|
import org.apache.poi.xssf.usermodel.XSSFSheet;
|
||||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
|
|
||||||
import java.io.File;
|
|
||||||
import java.io.FileOutputStream;
|
import java.io.FileOutputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
@ -17,7 +16,7 @@ public class ExcelFormula {
|
|||||||
formulaCell.setCellFormula(formula);
|
formulaCell.setCellFormula(formula);
|
||||||
XSSFFormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
|
XSSFFormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
|
||||||
formulaEvaluator.evaluateFormulaCell(formulaCell);
|
formulaEvaluator.evaluateFormulaCell(formulaCell);
|
||||||
FileOutputStream fileOut = new FileOutputStream(new File(fileLocation));
|
FileOutputStream fileOut = new FileOutputStream(fileLocation);
|
||||||
wb.write(fileOut);
|
wb.write(fileOut);
|
||||||
wb.close();
|
wb.close();
|
||||||
fileOut.close();
|
fileOut.close();
|
@ -0,0 +1,67 @@
|
|||||||
|
package com.baeldung.poi.excel.lastrow;
|
||||||
|
|
||||||
|
import org.apache.poi.ss.usermodel.Row;
|
||||||
|
import org.apache.poi.ss.usermodel.Sheet;
|
||||||
|
import org.apache.poi.ss.usermodel.Workbook;
|
||||||
|
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URISyntaxException;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
public class LastRowUnitTest {
|
||||||
|
private static final String FILE_NAME = "lastRowTest.xlsx";
|
||||||
|
private String fileLocation;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setup() throws URISyntaxException {
|
||||||
|
fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME).toURI()).toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenExampleGrid_whenGetRow_thenReturnRowObjectIfModified() throws IOException {
|
||||||
|
Workbook workbook = new XSSFWorkbook(fileLocation);
|
||||||
|
Sheet sheet = workbook.getSheetAt(0);
|
||||||
|
|
||||||
|
assertEquals(7, sheet.getLastRowNum());
|
||||||
|
assertEquals(6, sheet.getPhysicalNumberOfRows());
|
||||||
|
|
||||||
|
assertNotNull(sheet.getRow(0));
|
||||||
|
assertNotNull(sheet.getRow(1));
|
||||||
|
assertNotNull(sheet.getRow(2));
|
||||||
|
assertNotNull(sheet.getRow(3));
|
||||||
|
assertNull(sheet.getRow(4));
|
||||||
|
assertNull(sheet.getRow(5));
|
||||||
|
assertNotNull(sheet.getRow(6));
|
||||||
|
assertNotNull(sheet.getRow(7));
|
||||||
|
assertNull(sheet.getRow(8));
|
||||||
|
|
||||||
|
assertSame(sheet.getRow(7), getLastRowFromSheet(sheet));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEmptySheet_whenGetRow_thenReturnNull() throws IOException {
|
||||||
|
Workbook workbook = new XSSFWorkbook(fileLocation);
|
||||||
|
Sheet sheet = workbook.getSheetAt(1);
|
||||||
|
|
||||||
|
assertEquals(-1, sheet.getLastRowNum());
|
||||||
|
assertEquals(0, sheet.getPhysicalNumberOfRows());
|
||||||
|
|
||||||
|
assertNull(sheet.getRow(0));
|
||||||
|
|
||||||
|
assertSame(sheet.getRow(0), getLastRowFromSheet(sheet));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Row getLastRowFromSheet(Sheet sheet) {
|
||||||
|
Row lastRow = null;
|
||||||
|
int lastRowNum = sheet.getLastRowNum();
|
||||||
|
if (lastRowNum >= 0) {
|
||||||
|
lastRow = sheet.getRow(lastRowNum);
|
||||||
|
}
|
||||||
|
return lastRow;
|
||||||
|
}
|
||||||
|
}
|
@ -3,18 +3,19 @@ package com.baeldung.poi.excel.setformula;
|
|||||||
import org.apache.poi.ss.util.CellReference;
|
import org.apache.poi.ss.util.CellReference;
|
||||||
import org.apache.poi.xssf.usermodel.XSSFSheet;
|
import org.apache.poi.xssf.usermodel.XSSFSheet;
|
||||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
import java.io.File;
|
|
||||||
import java.io.FileInputStream;
|
import java.io.FileInputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.URISyntaxException;
|
import java.net.URISyntaxException;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
class ExcelFormulaUnitTest {
|
class ExcelFormulaUnitTest {
|
||||||
private static String FILE_NAME = "com/baeldung/poi/excel/setformula/SetFormulaTest.xlsx";
|
private static final String FILE_NAME = "com/baeldung/poi/excel/setformula/SetFormulaTest.xlsx";
|
||||||
|
|
||||||
private String fileLocation;
|
private String fileLocation;
|
||||||
private ExcelFormula excelFormula;
|
private ExcelFormula excelFormula;
|
||||||
|
|
||||||
@ -26,7 +27,7 @@ class ExcelFormulaUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenExcelData_whenSetFormula_thenSuccess() throws IOException {
|
void givenExcelData_whenSetFormula_thenSuccess() throws IOException {
|
||||||
FileInputStream inputStream = new FileInputStream(new File(fileLocation));
|
FileInputStream inputStream = new FileInputStream(fileLocation);
|
||||||
XSSFWorkbook wb = new XSSFWorkbook(inputStream);
|
XSSFWorkbook wb = new XSSFWorkbook(inputStream);
|
||||||
XSSFSheet sheet = wb.getSheetAt(0);
|
XSSFSheet sheet = wb.getSheetAt(0);
|
||||||
double resultColumnA = 0;
|
double resultColumnA = 0;
|
||||||
@ -46,6 +47,6 @@ class ExcelFormulaUnitTest {
|
|||||||
|
|
||||||
double resultValue = excelFormula.setFormula(fileLocation, wb, sumFormulaForColumnA + "-" + sumFormulaForColumnB);
|
double resultValue = excelFormula.setFormula(fileLocation, wb, sumFormulaForColumnA + "-" + sumFormulaForColumnB);
|
||||||
|
|
||||||
Assert.assertEquals(resultColumnA - resultColumnB, resultValue, 0d);
|
assertEquals(resultColumnA - resultColumnB, resultValue, 0d);
|
||||||
}
|
}
|
||||||
}
|
}
|
BIN
apache-poi-2/src/test/resources/lastRowTest.xlsx
Normal file
BIN
apache-poi-2/src/test/resources/lastRowTest.xlsx
Normal file
Binary file not shown.
@ -8,7 +8,6 @@ This module contains articles about Apache POI.
|
|||||||
- [Merge Cells in Excel Using Apache POI](https://www.baeldung.com/java-apache-poi-merge-cells)
|
- [Merge Cells in Excel Using Apache POI](https://www.baeldung.com/java-apache-poi-merge-cells)
|
||||||
- [Get String Value of Excel Cell with Apache POI](https://www.baeldung.com/java-apache-poi-cell-string-value)
|
- [Get String Value of Excel Cell with Apache POI](https://www.baeldung.com/java-apache-poi-cell-string-value)
|
||||||
- [Read Excel Cell Value Rather Than Formula With Apache POI](https://www.baeldung.com/apache-poi-read-cell-value-formula)
|
- [Read Excel Cell Value Rather Than Formula With Apache POI](https://www.baeldung.com/apache-poi-read-cell-value-formula)
|
||||||
- [Setting Formulas in Excel with Apache POI](https://www.baeldung.com/java-apache-poi-set-formulas)
|
|
||||||
- [Insert a Row in Excel Using Apache POI](https://www.baeldung.com/apache-poi-insert-excel-row)
|
- [Insert a Row in Excel Using Apache POI](https://www.baeldung.com/apache-poi-insert-excel-row)
|
||||||
- [Multiline Text in Excel Cell Using Apache POI](https://www.baeldung.com/apache-poi-write-multiline-text)
|
- [Multiline Text in Excel Cell Using Apache POI](https://www.baeldung.com/apache-poi-write-multiline-text)
|
||||||
- [Set Background Color of a Cell with Apache POI](https://www.baeldung.com/apache-poi-background-color)
|
- [Set Background Color of a Cell with Apache POI](https://www.baeldung.com/apache-poi-background-color)
|
||||||
|
@ -1,128 +0,0 @@
|
|||||||
package com.baeldung.poi.excel;
|
|
||||||
|
|
||||||
import java.io.File;
|
|
||||||
import java.io.FileInputStream;
|
|
||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
import org.apache.poi.ss.usermodel.Cell;
|
|
||||||
import org.apache.poi.ss.usermodel.CellType;
|
|
||||||
import org.apache.poi.ss.usermodel.DateUtil;
|
|
||||||
import org.apache.poi.ss.usermodel.Row;
|
|
||||||
import org.apache.poi.ss.usermodel.Sheet;
|
|
||||||
import org.apache.poi.ss.usermodel.Workbook;
|
|
||||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
|
||||||
|
|
||||||
public class ExcelUtility {
|
|
||||||
<<<<<<< HEAD
|
|
||||||
private static final String ENDLINE = System.getProperty("line.separator");
|
|
||||||
|
|
||||||
public static String readExcel(String filePath) throws IOException {
|
|
||||||
File file = new File(filePath);
|
|
||||||
FileInputStream inputStream = null;
|
|
||||||
StringBuilder toReturn = new StringBuilder();
|
|
||||||
try {
|
|
||||||
inputStream = new FileInputStream(file);
|
|
||||||
Workbook baeuldungWorkBook = new XSSFWorkbook(inputStream);
|
|
||||||
for (Sheet sheet : baeuldungWorkBook) {
|
|
||||||
toReturn.append("--------------------------------------------------------------------")
|
|
||||||
.append(ENDLINE);
|
|
||||||
toReturn.append("Worksheet :")
|
|
||||||
.append(sheet.getSheetName())
|
|
||||||
.append(ENDLINE);
|
|
||||||
toReturn.append("--------------------------------------------------------------------")
|
|
||||||
.append(ENDLINE);
|
|
||||||
int firstRow = sheet.getFirstRowNum();
|
|
||||||
int lastRow = sheet.getLastRowNum();
|
|
||||||
for (int index = firstRow + 1; index <= lastRow; index++) {
|
|
||||||
Row row = sheet.getRow(index);
|
|
||||||
toReturn.append("|| ");
|
|
||||||
for (int cellIndex = row.getFirstCellNum(); cellIndex < row.getLastCellNum(); cellIndex++) {
|
|
||||||
Cell cell = row.getCell(cellIndex, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
|
|
||||||
printCellValue(cell, toReturn);
|
|
||||||
}
|
|
||||||
toReturn.append(" ||")
|
|
||||||
.append(ENDLINE);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
inputStream.close();
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
return toReturn.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void printCellValue(Cell cell, StringBuilder toReturn) {
|
|
||||||
CellType cellType = cell.getCellType()
|
|
||||||
.equals(CellType.FORMULA) ? cell.getCachedFormulaResultType() : cell.getCellType();
|
|
||||||
if (cellType.equals(CellType.STRING)) {
|
|
||||||
toReturn.append(cell.getStringCellValue())
|
|
||||||
.append(" | ");
|
|
||||||
}
|
|
||||||
if (cellType.equals(CellType.NUMERIC)) {
|
|
||||||
if (DateUtil.isCellDateFormatted(cell)) {
|
|
||||||
toReturn.append(cell.getDateCellValue())
|
|
||||||
.append(" | ");
|
|
||||||
} else {
|
|
||||||
toReturn.append(cell.getNumericCellValue())
|
|
||||||
.append(" | ");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (cellType.equals(CellType.BOOLEAN)) {
|
|
||||||
toReturn.append(cell.getBooleanCellValue())
|
|
||||||
.append(" | ");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
=======
|
|
||||||
private static final String ENDLINE = System.getProperty("line.separator");
|
|
||||||
|
|
||||||
public static String readExcel(String filePath) throws IOException {
|
|
||||||
File file = new File(filePath);
|
|
||||||
FileInputStream inputStream = null;
|
|
||||||
StringBuilder toReturn = new StringBuilder();
|
|
||||||
try {
|
|
||||||
inputStream = new FileInputStream(file);
|
|
||||||
Workbook baeuldungWorkBook = new XSSFWorkbook(inputStream);
|
|
||||||
for (Sheet sheet : baeuldungWorkBook) {
|
|
||||||
toReturn.append("--------------------------------------------------------------------").append(ENDLINE);
|
|
||||||
toReturn.append("Worksheet :").append(sheet.getSheetName()).append(ENDLINE);
|
|
||||||
toReturn.append("--------------------------------------------------------------------").append(ENDLINE);
|
|
||||||
int firstRow = sheet.getFirstRowNum();
|
|
||||||
int lastRow = sheet.getLastRowNum();
|
|
||||||
for (int index = firstRow + 1; index <= lastRow; index++) {
|
|
||||||
Row row = sheet.getRow(index);
|
|
||||||
toReturn.append("|| ");
|
|
||||||
for (int cellIndex = row.getFirstCellNum(); cellIndex < row.getLastCellNum(); cellIndex++) {
|
|
||||||
Cell cell = row.getCell(cellIndex, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
|
|
||||||
printCellValue(cell, toReturn);
|
|
||||||
}
|
|
||||||
toReturn.append(" ||").append(ENDLINE);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
inputStream.close();
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
return toReturn.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void printCellValue(Cell cell, StringBuilder toReturn) {
|
|
||||||
CellType cellType = cell.getCellType().equals(CellType.FORMULA) ? cell.getCachedFormulaResultType()
|
|
||||||
: cell.getCellType();
|
|
||||||
if (cellType.equals(CellType.STRING)) {
|
|
||||||
toReturn.append(cell.getStringCellValue()).append(" | ");
|
|
||||||
}
|
|
||||||
if (cellType.equals(CellType.NUMERIC)) {
|
|
||||||
if (DateUtil.isCellDateFormatted(cell)) {
|
|
||||||
toReturn.append(cell.getDateCellValue()).append(" | ");
|
|
||||||
} else {
|
|
||||||
toReturn.append(cell.getNumericCellValue()).append(" | ");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (cellType.equals(CellType.BOOLEAN)) {
|
|
||||||
toReturn.append(cell.getBooleanCellValue()).append(" | ");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
>>>>>>> master
|
|
||||||
}
|
|
@ -1,112 +0,0 @@
|
|||||||
package com.baeldung.poi.excel;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.net.URISyntaxException;
|
|
||||||
import java.nio.file.Paths;
|
|
||||||
import java.text.ParseException;
|
|
||||||
import java.text.SimpleDateFormat;
|
|
||||||
|
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class ExcelUtilityUnitTest {
|
|
||||||
<<<<<<< HEAD
|
|
||||||
private static final String FILE_NAME = "baeldung.xlsx";
|
|
||||||
private String fileLocation;
|
|
||||||
private static final String ENDLINE = System.getProperty("line.separator");
|
|
||||||
private StringBuilder output;
|
|
||||||
|
|
||||||
@Before
|
|
||||||
public void setupUnitTest() throws IOException, URISyntaxException, ParseException {
|
|
||||||
output = new StringBuilder();
|
|
||||||
output.append("--------------------------------------------------------------------")
|
|
||||||
.append(ENDLINE);
|
|
||||||
output.append("Worksheet :Sheet1")
|
|
||||||
.append(ENDLINE);
|
|
||||||
output.append("--------------------------------------------------------------------")
|
|
||||||
.append(ENDLINE);
|
|
||||||
output.append("|| Name1 | Surname1 | 3.55696564113E11 | ")
|
|
||||||
.append(new SimpleDateFormat("dd/MM/yyyy").parse("4/11/2021")
|
|
||||||
.toString())
|
|
||||||
.append(" | ‡ | ||")
|
|
||||||
.append(ENDLINE);
|
|
||||||
output.append("|| Name2 | Surname2 | 5.646513512E9 | ")
|
|
||||||
.append(new SimpleDateFormat("dd/MM/yyyy").parse("4/12/2021")
|
|
||||||
.toString())
|
|
||||||
.append(" | false | ||")
|
|
||||||
.append(ENDLINE);
|
|
||||||
output.append("|| Name3 | Surname3 | 3.55696564113E11 | ")
|
|
||||||
.append(new SimpleDateFormat("dd/MM/yyyy").parse("4/11/2021")
|
|
||||||
.toString())
|
|
||||||
.append(" | 7.17039641738E11 | ||")
|
|
||||||
.append(ENDLINE);
|
|
||||||
output.append("--------------------------------------------------------------------")
|
|
||||||
.append(ENDLINE);
|
|
||||||
output.append("Worksheet :Sheet2")
|
|
||||||
.append(ENDLINE);
|
|
||||||
output.append("--------------------------------------------------------------------")
|
|
||||||
.append(ENDLINE);
|
|
||||||
output.append("|| Name4 | Surname4 | 3.55675623232E11 | 13/04/2021 | ||")
|
|
||||||
.append(ENDLINE);
|
|
||||||
|
|
||||||
fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME)
|
|
||||||
.toURI())
|
|
||||||
.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenStringPath_whenReadExcel_thenReturnStringValue() throws IOException {
|
|
||||||
assertEquals(output.toString(), ExcelUtility.readExcel(fileLocation));
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenStringPath_whenReadExcel_thenThrowException() {
|
|
||||||
assertThrows(IOException.class, () -> {
|
|
||||||
ExcelUtility.readExcel("baeldung");
|
|
||||||
});
|
|
||||||
}
|
|
||||||
=======
|
|
||||||
private static final String FILE_NAME = "baeldung.xlsx";
|
|
||||||
private String fileLocation;
|
|
||||||
private static final String ENDLINE = System.getProperty("line.separator");
|
|
||||||
private StringBuilder output;
|
|
||||||
|
|
||||||
@Before
|
|
||||||
public void setupUnitTest() throws IOException, URISyntaxException, ParseException {
|
|
||||||
output = new StringBuilder();
|
|
||||||
output.append("--------------------------------------------------------------------").append(ENDLINE);
|
|
||||||
output.append("Worksheet :Sheet1").append(ENDLINE);
|
|
||||||
output.append("--------------------------------------------------------------------").append(ENDLINE);
|
|
||||||
output.append("|| Name1 | Surname1 | 3.55696564113E11 | ").append(new SimpleDateFormat("dd/MM/yyyy").parse("4/11/2021").toString()).append(" | ‡ | ||")
|
|
||||||
.append(ENDLINE);
|
|
||||||
output.append("|| Name2 | Surname2 | 5.646513512E9 | ").append(new SimpleDateFormat("dd/MM/yyyy").parse("4/12/2021").toString()).append(" | false | ||")
|
|
||||||
.append(ENDLINE);
|
|
||||||
output.append("|| Name3 | Surname3 | 3.55696564113E11 | ").append(new SimpleDateFormat("dd/MM/yyyy").parse("4/11/2021").toString()).append(" | 7.17039641738E11 | ||")
|
|
||||||
.append(ENDLINE);
|
|
||||||
output.append("--------------------------------------------------------------------").append(ENDLINE);
|
|
||||||
output.append("Worksheet :Sheet2").append(ENDLINE);
|
|
||||||
output.append("--------------------------------------------------------------------").append(ENDLINE);
|
|
||||||
output.append("|| Name4 | Surname4 | 3.55675623232E11 | 13/04/2021 | ||").append(ENDLINE);
|
|
||||||
|
|
||||||
fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME).toURI()).toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenStringPath_whenReadExcel_thenReturnStringValue() throws IOException {
|
|
||||||
assertEquals(output.toString(), ExcelUtility.readExcel(fileLocation));
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenStringPath_whenReadExcel_thenThrowException() {
|
|
||||||
assertThrows(IOException.class, () -> {
|
|
||||||
ExcelUtility.readExcel("baeldung");
|
|
||||||
});
|
|
||||||
}
|
|
||||||
>>>>>>> master
|
|
||||||
|
|
||||||
}
|
|
@ -9,4 +9,5 @@ This module contains articles about Java 8 core features
|
|||||||
- [Guide to Java BiFunction Interface](https://www.baeldung.com/java-bifunction-interface)
|
- [Guide to Java BiFunction Interface](https://www.baeldung.com/java-bifunction-interface)
|
||||||
- [Interface With Default Methods vs Abstract Class](https://www.baeldung.com/java-interface-default-method-vs-abstract-class)
|
- [Interface With Default Methods vs Abstract Class](https://www.baeldung.com/java-interface-default-method-vs-abstract-class)
|
||||||
- [Convert Between Byte Array and UUID in Java](https://www.baeldung.com/java-byte-array-to-uuid)
|
- [Convert Between Byte Array and UUID in Java](https://www.baeldung.com/java-byte-array-to-uuid)
|
||||||
|
- [Create a Simple “Rock-Paper-Scissors” Game in Java](https://www.baeldung.com/java-rock-paper-scissors)
|
||||||
- [[<-- Prev]](/core-java-modules/core-java-8)
|
- [[<-- Prev]](/core-java-modules/core-java-8)
|
||||||
|
@ -22,6 +22,6 @@ class RandomDatesUnitTest {
|
|||||||
LocalDate end = LocalDate.now();
|
LocalDate end = LocalDate.now();
|
||||||
|
|
||||||
LocalDate random = RandomDates.between(start, end);
|
LocalDate random = RandomDates.between(start, end);
|
||||||
assertThat(random).isAfter(start).isBefore(end);
|
assertThat(random).isAfterOrEqualTo(start).isBefore(end);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,43 @@
|
|||||||
|
package com.baeldung.lockbykey;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This class shows examples of how you should use the lock
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public class ExampleUsage {
|
||||||
|
|
||||||
|
void doWithSimpleExclusiveLock(String key) {
|
||||||
|
SimpleExclusiveLockByKey simpleExclusiveLockByKey = new SimpleExclusiveLockByKey();
|
||||||
|
if (simpleExclusiveLockByKey.tryLock(key)) {
|
||||||
|
try {
|
||||||
|
// do stuff
|
||||||
|
} finally {
|
||||||
|
// it is very important to unlock in the finally block to avoid locking keys forever
|
||||||
|
simpleExclusiveLockByKey.unlock(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A concrete example can be found in the unit tests
|
||||||
|
void doWithLock(String key) {
|
||||||
|
LockByKey lockByKey = new LockByKey();
|
||||||
|
lockByKey.lock(key);
|
||||||
|
try {
|
||||||
|
// do stuff
|
||||||
|
} finally {
|
||||||
|
lockByKey.unlock(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// It works exactly the same as with locks
|
||||||
|
void doWithSemaphore(String key) {
|
||||||
|
SimultaneousEntriesLockByKey lockByKey = new SimultaneousEntriesLockByKey();
|
||||||
|
lockByKey.lock(key);
|
||||||
|
try {
|
||||||
|
// do stuff
|
||||||
|
} finally {
|
||||||
|
lockByKey.unlock(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,41 @@
|
|||||||
|
package com.baeldung.lockbykey;
|
||||||
|
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import java.util.concurrent.locks.Lock;
|
||||||
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
|
|
||||||
|
public class LockByKey {
|
||||||
|
|
||||||
|
private static class LockWrapper {
|
||||||
|
private final Lock lock = new ReentrantLock();
|
||||||
|
private final AtomicInteger numberOfThreadsInQueue = new AtomicInteger(1);
|
||||||
|
|
||||||
|
private LockWrapper addThreadInQueue() {
|
||||||
|
numberOfThreadsInQueue.incrementAndGet();
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int removeThreadFromQueue() {
|
||||||
|
return numberOfThreadsInQueue.decrementAndGet();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ConcurrentHashMap<String, LockWrapper> locks = new ConcurrentHashMap<String, LockWrapper>();
|
||||||
|
|
||||||
|
public void lock(String key) {
|
||||||
|
LockWrapper lockWrapper = locks.compute(key, (k, v) -> v == null ? new LockWrapper() : v.addThreadInQueue());
|
||||||
|
lockWrapper.lock.lock();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void unlock(String key) {
|
||||||
|
LockWrapper lockWrapper = locks.get(key);
|
||||||
|
lockWrapper.lock.unlock();
|
||||||
|
if (lockWrapper.removeThreadFromQueue() == 0) {
|
||||||
|
// NB : We pass in the specific value to remove to handle the case where another thread would queue right before the removal
|
||||||
|
locks.remove(key, lockWrapper);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,18 @@
|
|||||||
|
package com.baeldung.lockbykey;
|
||||||
|
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
public class SimpleExclusiveLockByKey {
|
||||||
|
|
||||||
|
private static Set<String> usedKeys= ConcurrentHashMap.newKeySet();
|
||||||
|
|
||||||
|
public boolean tryLock(String key) {
|
||||||
|
return usedKeys.add(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void unlock(String key) {
|
||||||
|
usedKeys.remove(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.lockbykey;
|
||||||
|
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.Semaphore;
|
||||||
|
|
||||||
|
public class SimultaneousEntriesLockByKey {
|
||||||
|
|
||||||
|
private static final int ALLOWED_THREADS = 2;
|
||||||
|
|
||||||
|
private static ConcurrentHashMap<String, Semaphore> semaphores = new ConcurrentHashMap<String, Semaphore>();
|
||||||
|
|
||||||
|
public void lock(String key) {
|
||||||
|
Semaphore semaphore = semaphores.compute(key, (k, v) -> v == null ? new Semaphore(ALLOWED_THREADS) : v);
|
||||||
|
semaphore.acquireUninterruptibly();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void unlock(String key) {
|
||||||
|
Semaphore semaphore = semaphores.get(key);
|
||||||
|
semaphore.release();
|
||||||
|
if (semaphore.availablePermits() == ALLOWED_THREADS) {
|
||||||
|
semaphores.remove(key, semaphore);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,106 @@
|
|||||||
|
package com.baeldung.lockbykey;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class LockByKeyUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenNoLockedKey_WhenLock_ThenSuccess() throws InterruptedException {
|
||||||
|
AtomicBoolean threadWasExecuted = new AtomicBoolean(false);
|
||||||
|
Thread thread = new Thread(() -> {
|
||||||
|
String key = "key";
|
||||||
|
LockByKey lockByKey = new LockByKey();
|
||||||
|
lockByKey.lock(key);
|
||||||
|
try {
|
||||||
|
threadWasExecuted.set(true);
|
||||||
|
} finally {
|
||||||
|
lockByKey.unlock(key);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
thread.start();
|
||||||
|
Thread.sleep(100);
|
||||||
|
} finally {
|
||||||
|
assertTrue(threadWasExecuted.get());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenLockedKey_WhenLock_ThenFailure() throws InterruptedException {
|
||||||
|
String key = "key";
|
||||||
|
LockByKey lockByKey = new LockByKey();
|
||||||
|
lockByKey.lock(key);
|
||||||
|
AtomicBoolean anotherThreadWasExecuted = new AtomicBoolean(false);
|
||||||
|
Thread threadLockingOnAnotherKey = new Thread(() -> {
|
||||||
|
LockByKey otherLockByKey = new LockByKey();
|
||||||
|
otherLockByKey.lock(key);
|
||||||
|
try {
|
||||||
|
anotherThreadWasExecuted.set(true);
|
||||||
|
} finally {
|
||||||
|
otherLockByKey.unlock(key);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
threadLockingOnAnotherKey.start();
|
||||||
|
Thread.sleep(100);
|
||||||
|
} finally {
|
||||||
|
assertFalse(anotherThreadWasExecuted.get());
|
||||||
|
lockByKey.unlock(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenAnotherKeyLocked_WhenLock_ThenSuccess() throws InterruptedException {
|
||||||
|
String key = "key";
|
||||||
|
LockByKey lockByKey = new LockByKey();
|
||||||
|
lockByKey.lock(key);
|
||||||
|
AtomicBoolean anotherThreadWasExecuted = new AtomicBoolean(false);
|
||||||
|
Thread threadLockingOnAnotherKey = new Thread(() -> {
|
||||||
|
String anotherKey = "anotherKey";
|
||||||
|
LockByKey otherLockByKey = new LockByKey();
|
||||||
|
otherLockByKey.lock(anotherKey);
|
||||||
|
try {
|
||||||
|
anotherThreadWasExecuted.set(true);
|
||||||
|
} finally {
|
||||||
|
otherLockByKey.unlock(anotherKey);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
threadLockingOnAnotherKey.start();
|
||||||
|
Thread.sleep(100);
|
||||||
|
} finally {
|
||||||
|
assertTrue(anotherThreadWasExecuted.get());
|
||||||
|
lockByKey.unlock(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenUnlockedKey_WhenLock_ThenSuccess() throws InterruptedException {
|
||||||
|
String key = "key";
|
||||||
|
LockByKey lockByKey = new LockByKey();
|
||||||
|
lockByKey.lock(key);
|
||||||
|
AtomicBoolean anotherThreadWasExecuted = new AtomicBoolean(false);
|
||||||
|
Thread threadLockingOnAnotherKey = new Thread(() -> {
|
||||||
|
LockByKey otherLockByKey = new LockByKey();
|
||||||
|
otherLockByKey.lock(key);
|
||||||
|
try {
|
||||||
|
anotherThreadWasExecuted.set(true);
|
||||||
|
} finally {
|
||||||
|
otherLockByKey.unlock(key);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
lockByKey.unlock(key);
|
||||||
|
threadLockingOnAnotherKey.start();
|
||||||
|
Thread.sleep(100);
|
||||||
|
} finally {
|
||||||
|
assertTrue(anotherThreadWasExecuted.get());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,51 @@
|
|||||||
|
package com.baeldung.lockbykey;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class SimpleExclusiveLockByKeyUnitTest {
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void cleanUpLocks() throws Exception {
|
||||||
|
Field field = SimpleExclusiveLockByKey.class.getDeclaredField("usedKeys");
|
||||||
|
field.setAccessible(true);
|
||||||
|
field.set(null, ConcurrentHashMap.newKeySet());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenNoLockedKey_WhenTryLock_ThenSuccess() {
|
||||||
|
SimpleExclusiveLockByKey lockByKey = new SimpleExclusiveLockByKey();
|
||||||
|
assertTrue(lockByKey.tryLock("key"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenLockedKey_WhenTryLock_ThenFailure() {
|
||||||
|
String key = "key";
|
||||||
|
SimpleExclusiveLockByKey lockByKey = new SimpleExclusiveLockByKey();
|
||||||
|
lockByKey.tryLock(key);
|
||||||
|
assertFalse(lockByKey.tryLock(key));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenAnotherKeyLocked_WhenTryLock_ThenSuccess() {
|
||||||
|
SimpleExclusiveLockByKey lockByKey = new SimpleExclusiveLockByKey();
|
||||||
|
lockByKey.tryLock("other");
|
||||||
|
assertTrue(lockByKey.tryLock("key"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenUnlockedKey_WhenTryLock_ThenSuccess() {
|
||||||
|
String key = "key";
|
||||||
|
SimpleExclusiveLockByKey lockByKey = new SimpleExclusiveLockByKey();
|
||||||
|
lockByKey.tryLock(key);
|
||||||
|
lockByKey.unlock(key);
|
||||||
|
assertTrue(lockByKey.tryLock(key));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,146 @@
|
|||||||
|
package com.baeldung.lockbykey;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class SimultaneousEntriesLockByKeyUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenNoKeyUsed_WhenLock_ThenSuccess() throws InterruptedException {
|
||||||
|
AtomicBoolean threadWasExecuted = new AtomicBoolean(false);
|
||||||
|
Thread thread = new Thread(() -> {
|
||||||
|
String key = "key";
|
||||||
|
SimultaneousEntriesLockByKey lockByKey = new SimultaneousEntriesLockByKey();
|
||||||
|
lockByKey.lock(key);
|
||||||
|
try {
|
||||||
|
threadWasExecuted.set(true);
|
||||||
|
} finally {
|
||||||
|
lockByKey.unlock(key);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
thread.start();
|
||||||
|
Thread.sleep(100);
|
||||||
|
} finally {
|
||||||
|
assertTrue(threadWasExecuted.get());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenKeyLockedWithRemainingPermits_WhenLock_ThenSuccess() throws InterruptedException {
|
||||||
|
String key = "key";
|
||||||
|
SimultaneousEntriesLockByKey lockByKey = new SimultaneousEntriesLockByKey();
|
||||||
|
lockByKey.lock(key);
|
||||||
|
AtomicBoolean anotherThreadWasExecuted = new AtomicBoolean(false);
|
||||||
|
Thread threadLockingOnAnotherKey = new Thread(() -> {
|
||||||
|
SimultaneousEntriesLockByKey otherLockByKeyWithSemaphore = new SimultaneousEntriesLockByKey();
|
||||||
|
otherLockByKeyWithSemaphore.lock(key);
|
||||||
|
try {
|
||||||
|
anotherThreadWasExecuted.set(true);
|
||||||
|
} finally {
|
||||||
|
otherLockByKeyWithSemaphore.unlock(key);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
threadLockingOnAnotherKey.start();
|
||||||
|
Thread.sleep(100);
|
||||||
|
} finally {
|
||||||
|
assertTrue(anotherThreadWasExecuted.get());
|
||||||
|
lockByKey.unlock(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenKeyLockedWithNoRemainingPermits_WhenLock_ThenFailure() throws InterruptedException {
|
||||||
|
String key = "key";
|
||||||
|
SimultaneousEntriesLockByKey lockByKey = new SimultaneousEntriesLockByKey();
|
||||||
|
lockByKey.lock(key);
|
||||||
|
AtomicBoolean anotherThreadWasExecuted = new AtomicBoolean(false);
|
||||||
|
Thread threadLockingOnAnotherKey1 = new Thread(() -> {
|
||||||
|
SimultaneousEntriesLockByKey otherLockByKeyWithSemaphore = new SimultaneousEntriesLockByKey();
|
||||||
|
otherLockByKeyWithSemaphore.lock(key);
|
||||||
|
try {
|
||||||
|
Thread.sleep(200); // make sure this thread will release the lock after the assertion
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
|
||||||
|
} finally {
|
||||||
|
otherLockByKeyWithSemaphore.unlock(key);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Thread threadLockingOnAnotherKey2 = new Thread(() -> {
|
||||||
|
SimultaneousEntriesLockByKey otherLockByKey = new SimultaneousEntriesLockByKey();
|
||||||
|
try {
|
||||||
|
Thread.sleep(50); // make sure thread1 will acquire the key first
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
}
|
||||||
|
otherLockByKey.lock(key);
|
||||||
|
try {
|
||||||
|
anotherThreadWasExecuted.set(true);
|
||||||
|
} finally {
|
||||||
|
otherLockByKey.unlock(key);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
threadLockingOnAnotherKey1.start();
|
||||||
|
threadLockingOnAnotherKey2.start();
|
||||||
|
Thread.sleep(100);
|
||||||
|
} finally {
|
||||||
|
assertFalse(anotherThreadWasExecuted.get());
|
||||||
|
lockByKey.unlock(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenAnotherKeyLocked_WhenLock_ThenSuccess() throws InterruptedException {
|
||||||
|
String key = "key";
|
||||||
|
SimultaneousEntriesLockByKey lockByKey = new SimultaneousEntriesLockByKey();
|
||||||
|
lockByKey.lock(key);
|
||||||
|
AtomicBoolean anotherThreadWasExecuted = new AtomicBoolean(false);
|
||||||
|
Thread threadLockingOnAnotherKey = new Thread(() -> {
|
||||||
|
String anotherKey = "anotherKey";
|
||||||
|
SimultaneousEntriesLockByKey otherLockByKey = new SimultaneousEntriesLockByKey();
|
||||||
|
otherLockByKey.lock(anotherKey);
|
||||||
|
try {
|
||||||
|
anotherThreadWasExecuted.set(true);
|
||||||
|
} finally {
|
||||||
|
otherLockByKey.unlock(anotherKey);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
threadLockingOnAnotherKey.start();
|
||||||
|
Thread.sleep(100);
|
||||||
|
} finally {
|
||||||
|
assertTrue(anotherThreadWasExecuted.get());
|
||||||
|
lockByKey.unlock(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenUnlockedKey_WhenLock_ThenSuccess() throws InterruptedException {
|
||||||
|
String key = "key";
|
||||||
|
SimultaneousEntriesLockByKey lockByKey = new SimultaneousEntriesLockByKey();
|
||||||
|
lockByKey.lock(key);
|
||||||
|
AtomicBoolean anotherThreadWasExecuted = new AtomicBoolean(false);
|
||||||
|
Thread threadLockingOnAnotherKey = new Thread(() -> {
|
||||||
|
SimultaneousEntriesLockByKey otherLockByKey = new SimultaneousEntriesLockByKey();
|
||||||
|
otherLockByKey.lock(key);
|
||||||
|
try {
|
||||||
|
anotherThreadWasExecuted.set(true);
|
||||||
|
} finally {
|
||||||
|
otherLockByKey.unlock(key);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
lockByKey.unlock(key);
|
||||||
|
threadLockingOnAnotherKey.start();
|
||||||
|
Thread.sleep(100);
|
||||||
|
} finally {
|
||||||
|
assertTrue(anotherThreadWasExecuted.get());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -7,7 +7,12 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
|||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
public class IllegalMonitorStateExceptionUnitTest {
|
/**
|
||||||
|
* Needs to be run manually in order to demonstrate the IllegalMonitorStateException scenarios.
|
||||||
|
*
|
||||||
|
* There are some intermittent test failures in Jenkins that require further investigation.
|
||||||
|
*/
|
||||||
|
public class IllegalMonitorStateExceptionManualTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenSyncSenderAndSyncReceiverAreUsed_thenIllegalMonitorExceptionShouldNotBeThrown() throws InterruptedException {
|
void whenSyncSenderAndSyncReceiverAreUsed_thenIllegalMonitorExceptionShouldNotBeThrown() throws InterruptedException {
|
@ -7,4 +7,5 @@ This module contains articles about core Java input and output (IO)
|
|||||||
- [Java File Separator vs File Path Separator](https://www.baeldung.com/java-file-vs-file-path-separator)
|
- [Java File Separator vs File Path Separator](https://www.baeldung.com/java-file-vs-file-path-separator)
|
||||||
- [Simulate touch Command in Java](https://www.baeldung.com/java-simulate-touch-command)
|
- [Simulate touch Command in Java](https://www.baeldung.com/java-simulate-touch-command)
|
||||||
- [SequenceInputStream Class in Java](https://www.baeldung.com/java-sequenceinputstream)
|
- [SequenceInputStream Class in Java](https://www.baeldung.com/java-sequenceinputstream)
|
||||||
|
- [Read a File Into a Map in Java](https://www.baeldung.com/java-read-file-into-map)
|
||||||
- [[<-- Prev]](/core-java-modules/core-java-io-3)
|
- [[<-- Prev]](/core-java-modules/core-java-io-3)
|
||||||
|
@ -67,12 +67,17 @@ public class EmailService {
|
|||||||
MimeBodyPart mimeBodyPart = new MimeBodyPart();
|
MimeBodyPart mimeBodyPart = new MimeBodyPart();
|
||||||
mimeBodyPart.setContent(msg, "text/html; charset=utf-8");
|
mimeBodyPart.setContent(msg, "text/html; charset=utf-8");
|
||||||
|
|
||||||
|
String msgStyled = "This is my <b style='color:red;'>bold-red email</b> using JavaMailer";
|
||||||
|
MimeBodyPart mimeBodyPartWithStyledText = new MimeBodyPart();
|
||||||
|
mimeBodyPartWithStyledText.setContent(msgStyled, "text/html; charset=utf-8");
|
||||||
|
|
||||||
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
|
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
|
||||||
|
|
||||||
attachmentBodyPart.attachFile(getFile());
|
attachmentBodyPart.attachFile(getFile());
|
||||||
|
|
||||||
Multipart multipart = new MimeMultipart();
|
Multipart multipart = new MimeMultipart();
|
||||||
multipart.addBodyPart(mimeBodyPart);
|
multipart.addBodyPart(mimeBodyPart);
|
||||||
|
multipart.addBodyPart(mimeBodyPartWithStyledText);
|
||||||
multipart.addBodyPart(attachmentBodyPart);
|
multipart.addBodyPart(attachmentBodyPart);
|
||||||
|
|
||||||
message.setContent(multipart);
|
message.setContent(multipart);
|
||||||
|
@ -36,6 +36,7 @@ public class EmailServiceLiveTest {
|
|||||||
MimeMessage receivedMessage = receivedMessages[0];
|
MimeMessage receivedMessage = receivedMessages[0];
|
||||||
assertEquals("Mail Subject", subjectFromMessage(receivedMessage));
|
assertEquals("Mail Subject", subjectFromMessage(receivedMessage));
|
||||||
assertEquals("This is my first email using JavaMailer", emailTextFrom(receivedMessage));
|
assertEquals("This is my first email using JavaMailer", emailTextFrom(receivedMessage));
|
||||||
|
assertEquals("This is my <b style='color:red;'>bold-red email</b> using JavaMailer", emailStyledTextFrom(receivedMessage));
|
||||||
assertEquals("sample attachment content", attachmentContentsFrom(receivedMessage));
|
assertEquals("sample attachment content", attachmentContentsFrom(receivedMessage));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -50,11 +51,18 @@ public class EmailServiceLiveTest {
|
|||||||
.toString();
|
.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String attachmentContentsFrom(MimeMessage receivedMessage) throws Exception {
|
private static String emailStyledTextFrom(MimeMessage receivedMessage) throws IOException, MessagingException {
|
||||||
return ((MimeMultipart) receivedMessage.getContent())
|
return ((MimeMultipart) receivedMessage.getContent())
|
||||||
.getBodyPart(1)
|
.getBodyPart(1)
|
||||||
.getContent()
|
.getContent()
|
||||||
.toString();
|
.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static String attachmentContentsFrom(MimeMessage receivedMessage) throws Exception {
|
||||||
|
return ((MimeMultipart) receivedMessage.getContent())
|
||||||
|
.getBodyPart(2)
|
||||||
|
.getContent()
|
||||||
|
.toString();
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -12,4 +12,5 @@ This module contains articles about core Java non-blocking input and output (IO)
|
|||||||
- [Java NIO DatagramChannel](https://www.baeldung.com/java-nio-datagramchannel)
|
- [Java NIO DatagramChannel](https://www.baeldung.com/java-nio-datagramchannel)
|
||||||
- [Java – Path vs File](https://www.baeldung.com/java-path-vs-file)
|
- [Java – Path vs File](https://www.baeldung.com/java-path-vs-file)
|
||||||
- [What Is the Difference Between NIO and NIO.2?](https://www.baeldung.com/java-nio-vs-nio-2)
|
- [What Is the Difference Between NIO and NIO.2?](https://www.baeldung.com/java-nio-vs-nio-2)
|
||||||
|
- [Guide to ByteBuffer](https://www.baeldung.com/java-bytebuffer)
|
||||||
- [[<-- Prev]](/core-java-modules/core-java-nio)
|
- [[<-- Prev]](/core-java-modules/core-java-nio)
|
||||||
|
@ -5,3 +5,4 @@ This module contains articles about GraphQL with Java
|
|||||||
## Relevant articles:
|
## Relevant articles:
|
||||||
|
|
||||||
- [Introduction to GraphQL](https://www.baeldung.com/graphql)
|
- [Introduction to GraphQL](https://www.baeldung.com/graphql)
|
||||||
|
- [Make a Call to a GraphQL Service from a Java Application](https://www.baeldung.com/java-call-graphql-service)
|
||||||
|
@ -11,5 +11,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
|
|||||||
- [How to Set TLS Version in Apache HttpClient](https://www.baeldung.com/apache-httpclient-tls)
|
- [How to Set TLS Version in Apache HttpClient](https://www.baeldung.com/apache-httpclient-tls)
|
||||||
- [Reading an HTTP Response Body as a String in Java](https://www.baeldung.com/java-http-response-body-as-string)
|
- [Reading an HTTP Response Body as a String in Java](https://www.baeldung.com/java-http-response-body-as-string)
|
||||||
- [How To Get Cookies From the Apache HttpClient Response](https://www.baeldung.com/java-apache-httpclient-cookies)
|
- [How To Get Cookies From the Apache HttpClient Response](https://www.baeldung.com/java-apache-httpclient-cookies)
|
||||||
- [Enabling Logging for Apache HttpClient](https://www.baeldung.com/java-httpclient-enable-logging)
|
- [Enabling Logging for Apache HttpClient](https://www.baeldung.com/apache-httpclient-enable-logging)
|
||||||
- More articles: [[<-- prev]](../httpclient)
|
- More articles: [[<-- prev]](../httpclient)
|
||||||
|
@ -11,7 +11,7 @@ This module contains articles about HTTPClient that are part of the HTTPClient E
|
|||||||
- [Custom HTTP Header with the HttpClient](https://www.baeldung.com/httpclient-custom-http-header)
|
- [Custom HTTP Header with the HttpClient](https://www.baeldung.com/httpclient-custom-http-header)
|
||||||
- [HttpClient Basic Authentication](https://www.baeldung.com/httpclient-4-basic-authentication)
|
- [HttpClient Basic Authentication](https://www.baeldung.com/httpclient-4-basic-authentication)
|
||||||
- [Posting with HttpClient](https://www.baeldung.com/httpclient-post-http-request)
|
- [Posting with HttpClient](https://www.baeldung.com/httpclient-post-http-request)
|
||||||
- [Adding Parameters to HttpClient Requests](https://www.baeldung.com/java-httpclient-parameters)
|
- [Adding Parameters to HttpClient Requests](https://www.baeldung.com/apache-httpclient-parameters)
|
||||||
|
|
||||||
|
|
||||||
### Running the Tests
|
### Running the Tests
|
||||||
|
111
jakarta-ee/pom.xml
Normal file
111
jakarta-ee/pom.xml
Normal file
@ -0,0 +1,111 @@
|
|||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>mvc-2.0</artifactId>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
<packaging>war</packaging>
|
||||||
|
|
||||||
|
<name>mvc-2.0</name>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<jakartaee-api.version>9.0.0</jakartaee-api.version>
|
||||||
|
<krazo.version>2.0.0</krazo.version>
|
||||||
|
<jakarta.mvc-api.version>2.0.0</jakarta.mvc-api.version>
|
||||||
|
<junit.jupiter.version>5.8.2</junit.jupiter.version>
|
||||||
|
<local.glassfish.home>C:/glassfish6</local.glassfish.home>
|
||||||
|
<local.glassfish.user>admin</local.glassfish.user>
|
||||||
|
<local.glassfish.domain>mvn-domain</local.glassfish.domain>
|
||||||
|
<mockito.version>1.10.19</mockito.version>
|
||||||
|
<local.glassfish.passfile>
|
||||||
|
${local.glassfish.home}\\domains\\${local.glassfish.domain}\\config\\domain-passwords
|
||||||
|
</local.glassfish.passfile>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>jakarta.platform</groupId>
|
||||||
|
<artifactId>jakarta.jakartaee-web-api</artifactId>
|
||||||
|
<version>${jakartaee-api.version}</version>
|
||||||
|
<scope>provided</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>jakarta.mvc</groupId>
|
||||||
|
<artifactId>jakarta.mvc-api</artifactId>
|
||||||
|
<version>${jakarta.mvc-api.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.eclipse.krazo</groupId>
|
||||||
|
<artifactId>krazo-jersey</artifactId>
|
||||||
|
<version>${krazo.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter-api</artifactId>
|
||||||
|
<version>${junit.jupiter.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.mockito</groupId>
|
||||||
|
<artifactId>mockito-all</artifactId>
|
||||||
|
<version>${mockito.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>mvc-2.0</finalName>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.glassfish.maven.plugin</groupId>
|
||||||
|
<artifactId>maven-glassfish-plugin</artifactId>
|
||||||
|
<version>2.1</version>
|
||||||
|
<configuration>
|
||||||
|
<glassfishDirectory>${local.glassfish.home}</glassfishDirectory>
|
||||||
|
<user>admin</user>
|
||||||
|
<!-- <passwordFile>${local.glassfish.passfile}</passwordFile>-->
|
||||||
|
<adminPassword>password</adminPassword>
|
||||||
|
|
||||||
|
<domain>
|
||||||
|
<name>${local.glassfish.domain}</name>
|
||||||
|
<httpPort>8080</httpPort>
|
||||||
|
<adminPort>4848</adminPort>
|
||||||
|
|
||||||
|
</domain>
|
||||||
|
<components>
|
||||||
|
<component>
|
||||||
|
<name>${project.artifactId}</name>
|
||||||
|
<artifact>target/${project.build.finalName}.war</artifact>
|
||||||
|
|
||||||
|
</component>
|
||||||
|
</components>
|
||||||
|
<debug>true</debug>
|
||||||
|
<terse>false</terse>
|
||||||
|
<echo>true</echo>
|
||||||
|
|
||||||
|
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.8.0</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-war-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
@ -0,0 +1,84 @@
|
|||||||
|
package com.baeldung.eclipse.krazo;
|
||||||
|
|
||||||
|
import jakarta.enterprise.context.RequestScoped;
|
||||||
|
import jakarta.inject.Named;
|
||||||
|
import jakarta.mvc.RedirectScoped;
|
||||||
|
import jakarta.mvc.binding.MvcBinding;
|
||||||
|
import jakarta.validation.constraints.Email;
|
||||||
|
import jakarta.validation.constraints.Min;
|
||||||
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
import jakarta.validation.constraints.Null;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import jakarta.ws.rs.FormParam;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
@Named("user")
|
||||||
|
@RedirectScoped
|
||||||
|
public class User implements Serializable {
|
||||||
|
@MvcBinding
|
||||||
|
@Null
|
||||||
|
private String id;
|
||||||
|
|
||||||
|
@MvcBinding
|
||||||
|
@NotNull
|
||||||
|
@Size(min = 1, message = "Name cannot be blank")
|
||||||
|
@FormParam("name")
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@MvcBinding
|
||||||
|
@Min(value = 18, message = "The minimum age of the user should be 18 years")
|
||||||
|
@FormParam("age")
|
||||||
|
private int age;
|
||||||
|
|
||||||
|
@MvcBinding
|
||||||
|
@Email(message = "The email cannot be blank and should be in a valid format")
|
||||||
|
@Size(min=3, message = "Email cannot be empty")
|
||||||
|
@FormParam("email")
|
||||||
|
private String email;
|
||||||
|
|
||||||
|
@MvcBinding
|
||||||
|
@Null
|
||||||
|
@FormParam("phone")
|
||||||
|
private String phone;
|
||||||
|
|
||||||
|
public String getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(String id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getAge() {
|
||||||
|
return age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAge(int age) {
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getEmail() {
|
||||||
|
return email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEmail(String email) {
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPhone() {
|
||||||
|
return phone;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPhone(String phone) {
|
||||||
|
this.phone = phone;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,11 @@
|
|||||||
|
package com.baeldung.eclipse.krazo;
|
||||||
|
|
||||||
|
import jakarta.ws.rs.ApplicationPath;
|
||||||
|
import jakarta.ws.rs.core.Application;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default JAX-RS application listening on /app
|
||||||
|
*/
|
||||||
|
@ApplicationPath("/app")
|
||||||
|
public class UserApplication extends Application {
|
||||||
|
}
|
@ -0,0 +1,85 @@
|
|||||||
|
package com.baeldung.eclipse.krazo;
|
||||||
|
|
||||||
|
import jakarta.inject.Inject;
|
||||||
|
import jakarta.mvc.Controller;
|
||||||
|
import jakarta.mvc.Models;
|
||||||
|
import jakarta.mvc.binding.BindingResult;
|
||||||
|
import jakarta.mvc.security.CsrfProtected;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import jakarta.ws.rs.BeanParam;
|
||||||
|
import jakarta.ws.rs.GET;
|
||||||
|
import jakarta.ws.rs.POST;
|
||||||
|
import jakarta.ws.rs.Path;
|
||||||
|
import jakarta.ws.rs.Produces;
|
||||||
|
import jakarta.ws.rs.core.MediaType;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The class contains two controllers and a REST API
|
||||||
|
*/
|
||||||
|
@Path("users")
|
||||||
|
public class UserController {
|
||||||
|
@Inject
|
||||||
|
private BindingResult bindingResult;
|
||||||
|
|
||||||
|
private static final List<User> users = new ArrayList<>();
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
private Models models;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This is a controller. It displays a initial form to the user.
|
||||||
|
* @return The view name
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
@Controller
|
||||||
|
public String showForm() {
|
||||||
|
return "user.jsp";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The method handles the form submits
|
||||||
|
* Handles HTTP POST and is CSRF protected. The client invoking this controller should provide a CSRF token.
|
||||||
|
* @param user The user details that has to be stored
|
||||||
|
* @return Returns a view name
|
||||||
|
*/
|
||||||
|
@POST
|
||||||
|
@Controller
|
||||||
|
@CsrfProtected
|
||||||
|
public String saveUser(@Valid @BeanParam User user) {
|
||||||
|
if (bindingResult.isFailed()) {
|
||||||
|
models.put("errors", bindingResult.getAllErrors());
|
||||||
|
return "user.jsp";
|
||||||
|
}
|
||||||
|
String id = UUID.randomUUID().toString();
|
||||||
|
user.setId(id);
|
||||||
|
users.add(user);
|
||||||
|
return "redirect:users/success";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles a redirect view
|
||||||
|
* @return The view name
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
@Controller
|
||||||
|
@Path("success")
|
||||||
|
public String saveUserSuccess() {
|
||||||
|
return "success.jsp";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The REST API that returns all the user details in the JSON format
|
||||||
|
* @return The list of users that are saved. The List<User> is converted into Json Array.
|
||||||
|
* If no user is present a empty array is returned
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
public List<User> getUsers() {
|
||||||
|
return users;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
6
jakarta-ee/src/main/webapp/WEB-INF/beans.xml
Normal file
6
jakarta-ee/src/main/webapp/WEB-INF/beans.xml
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<beans xmlns="https://jakarta.ee/xml/ns/jakartaee"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/beans_3_0.xsd"
|
||||||
|
bean-discovery-mode="all" version="3.0">
|
||||||
|
</beans>
|
47
jakarta-ee/src/main/webapp/WEB-INF/views/success.jsp
Normal file
47
jakarta-ee/src/main/webapp/WEB-INF/views/success.jsp
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
|
||||||
|
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>MVC 2.0</title>
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
|
||||||
|
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
|
||||||
|
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Raleway:wght@100;200;300;600&display=swap" rel="stylesheet">
|
||||||
|
<link rel="stylesheet" href="${pageContext.request.contextPath}/styles.css">
|
||||||
|
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
|
||||||
|
<div class="container-fluid">
|
||||||
|
<span class="navbar-brand" href="#"><span style="font-size: 24px;">Baeldung - Eclipse Krazo</span></span>
|
||||||
|
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse"
|
||||||
|
aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
|
||||||
|
<span class="navbar-toggler-icon"></span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
<div class="container">
|
||||||
|
<div class="row align-items-center">
|
||||||
|
<div class="col-sm-7 mx-auto">
|
||||||
|
<div class="card">
|
||||||
|
|
||||||
|
<div class="card-body">
|
||||||
|
<h3 class="card-title text-success">User created successfully!</h3>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
</body>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
|
||||||
|
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
|
||||||
|
|
||||||
|
</html>
|
89
jakarta-ee/src/main/webapp/WEB-INF/views/user.jsp
Normal file
89
jakarta-ee/src/main/webapp/WEB-INF/views/user.jsp
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
|
||||||
|
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>MVC 2.0</title>
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
|
||||||
|
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
|
||||||
|
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Raleway:wght@100;200;300;600&display=swap" rel="stylesheet">
|
||||||
|
<link rel="stylesheet" href="${pageContext.request.contextPath}/styles.css">
|
||||||
|
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
|
||||||
|
<div class="container-fluid">
|
||||||
|
<span class="navbar-brand" href="#"><span style="font-size: 24px;">Baeldung - Eclipse Krazo</span></span>
|
||||||
|
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse"
|
||||||
|
aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
|
||||||
|
<span class="navbar-toggler-icon"></span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
<div class="container">
|
||||||
|
<div class="row align-items-center">
|
||||||
|
<div class="col-sm-7 mx-auto">
|
||||||
|
<h3>
|
||||||
|
<strong>User Details</strong>
|
||||||
|
</h3>
|
||||||
|
<hr class="hr-dark"/>
|
||||||
|
<c:if test="${errors.size() > 0}">
|
||||||
|
<div class="alert alert-danger" role="alert">
|
||||||
|
<dl class="row">
|
||||||
|
<c:forEach var="error" items="${errors}">
|
||||||
|
<dt class="col-sm-2">${error.paramName}</dt>
|
||||||
|
<dd class="col-sm-10">${error.message}</dd>
|
||||||
|
</c:forEach>
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
</c:if>
|
||||||
|
<form action="${mvc.basePath}/users" method="post">
|
||||||
|
<div class="form-group row mt-3">
|
||||||
|
<label for="name" class="col-sm-3 col-form-label">Name</label>
|
||||||
|
<div class="col-sm-9">
|
||||||
|
<input name="name" type="text" class="form-control" id="name">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-group row mt-3">
|
||||||
|
<label for="age" class="col-sm-3 col-form-label">Age</label>
|
||||||
|
<div class="col-sm-9">
|
||||||
|
<input name="age" type="text" class="form-control" id="age">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-group row mt-3">
|
||||||
|
<label for="email" class="col-sm-3 col-form-label">Email</label>
|
||||||
|
<div class="col-sm-9">
|
||||||
|
<input name="email" type="email" class="form-control" id="email">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-group row mt-3">
|
||||||
|
<label for="phone" class="col-sm-3 col-form-label">Phone</label>
|
||||||
|
<div class="col-sm-9">
|
||||||
|
<input type="text" class="form-control" id="phone">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<hr class="hr-dark"/>
|
||||||
|
<div class="form-group row mt-3">
|
||||||
|
<div class="col-sm-10">
|
||||||
|
<button type="submit" class="btn btn-primary"><strong>Create</strong></button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<input type="hidden" name="${mvc.csrf.name}" value="${mvc.csrf.token}"/>
|
||||||
|
|
||||||
|
</form>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
</body>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
|
||||||
|
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
|
||||||
|
|
||||||
|
</html>
|
28
jakarta-ee/src/main/webapp/styles.css
Normal file
28
jakarta-ee/src/main/webapp/styles.css
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
body, html {
|
||||||
|
font-family: Raleway, serif;
|
||||||
|
font-weight: 300;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bg-dark {
|
||||||
|
background-color: #63b175 !important;
|
||||||
|
font-weight: 600 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
padding-top: 80px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 979px) {
|
||||||
|
body {
|
||||||
|
padding-top: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hr-dark {
|
||||||
|
border-top: 2px solid #000;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package com.baeldung.eclipse.krazo;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dummy Test
|
||||||
|
*/
|
||||||
|
public class AppTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void test() {
|
||||||
|
assertTrue(true);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,116 @@
|
|||||||
|
package com.baeldung.eclipse.krazo;
|
||||||
|
|
||||||
|
import com.baeldung.eclipse.krazo.User;
|
||||||
|
import com.baeldung.eclipse.krazo.UserController;
|
||||||
|
import jakarta.mvc.Models;
|
||||||
|
import jakarta.mvc.binding.BindingResult;
|
||||||
|
import org.eclipse.krazo.core.ModelsImpl;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.MockitoAnnotations;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.mockito.Matchers.any;
|
||||||
|
import static org.mockito.Matchers.anyString;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The class contains unit tests. We do only unit tests. Most of the classes are mocked
|
||||||
|
*/
|
||||||
|
@DisplayName("Eclipse Krazo MVC 2.0 Test Suite")
|
||||||
|
class UserControllerUnitTest {
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
UserController userController = new UserController();
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
Models models;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
BindingResult bindingResult;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
public void setUpClass() {
|
||||||
|
MockitoAnnotations.initMocks(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Test Show Form")
|
||||||
|
void whenShowForm_thenReturnViewName() {
|
||||||
|
assertNotNull(userController.showForm());
|
||||||
|
assertEquals("user.jsp", userController.showForm());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Test Save User Success")
|
||||||
|
void whenSaveUser_thenReturnSuccess() {
|
||||||
|
when(bindingResult.isFailed()).thenReturn(false);
|
||||||
|
|
||||||
|
User user = new User();
|
||||||
|
|
||||||
|
assertNotNull(userController.saveUser(user));
|
||||||
|
assertDoesNotThrow(() -> userController.saveUser(user));
|
||||||
|
assertEquals("redirect:users/success", userController.saveUser(user));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Test Save User Binding Errors")
|
||||||
|
void whenSaveUser_thenReturnError() {
|
||||||
|
when(bindingResult.isFailed()).thenReturn(true);
|
||||||
|
Models testModels = new ModelsImpl();
|
||||||
|
when(models.put(anyString(), any())).thenReturn(testModels);
|
||||||
|
User user = getUser();
|
||||||
|
assertNotNull(userController.saveUser(user));
|
||||||
|
assertDoesNotThrow(() -> userController.saveUser(user));
|
||||||
|
assertEquals("user.jsp", userController.saveUser(user));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Test Save User Success View")
|
||||||
|
void whenSaveUserSuccess_thenRedirectSuccess() {
|
||||||
|
assertNotNull(userController.saveUserSuccess());
|
||||||
|
assertDoesNotThrow(() -> userController.saveUserSuccess());
|
||||||
|
assertEquals("success.jsp", userController.saveUserSuccess());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Test Get Users API")
|
||||||
|
void whenGetUser_thenReturnUsers() {
|
||||||
|
when(bindingResult.isFailed()).thenReturn(false);
|
||||||
|
|
||||||
|
User user= getUser();
|
||||||
|
|
||||||
|
assertNotNull(user);
|
||||||
|
assertEquals(30, user.getAge());
|
||||||
|
assertEquals("john doe", user.getName());
|
||||||
|
assertEquals("anymail", user.getEmail());
|
||||||
|
assertEquals("99887766554433", user.getPhone());
|
||||||
|
assertEquals("1", user.getId());
|
||||||
|
|
||||||
|
userController.saveUser(user);
|
||||||
|
userController.saveUser(user);
|
||||||
|
userController.saveUser(user);
|
||||||
|
|
||||||
|
assertNotNull(userController.getUsers());
|
||||||
|
assertDoesNotThrow(() -> userController.getUsers());
|
||||||
|
assertEquals(3, userController.getUsers().size());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private User getUser() {
|
||||||
|
User user = new User();
|
||||||
|
user.setId("1");
|
||||||
|
user.setName("john doe");
|
||||||
|
user.setAge(30);
|
||||||
|
user.setEmail("anymail");
|
||||||
|
user.setPhone("99887766554433");
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -25,6 +25,11 @@
|
|||||||
<version>${commons-lang3.version}</version>
|
<version>${commons-lang3.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.guava</groupId>
|
||||||
|
<artifactId>guava</artifactId>
|
||||||
|
<version>${guava.version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
@ -0,0 +1,44 @@
|
|||||||
|
package com.baeldung.convertLongToInt;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.function.Function;
|
||||||
|
|
||||||
|
import com.google.common.primitives.Ints;
|
||||||
|
|
||||||
|
public class ConvertLongToInt {
|
||||||
|
|
||||||
|
static Function<Long, Integer> convert = val -> Optional.ofNullable(val)
|
||||||
|
.map(Long::intValue)
|
||||||
|
.orElse(null);
|
||||||
|
|
||||||
|
public static int longToIntCast(long number) {
|
||||||
|
return (int) number;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int longToIntJavaWithMath(long number) {
|
||||||
|
return Math.toIntExact(number);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int longToIntJavaWithLambda(long number) {
|
||||||
|
return convert.apply(number);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int longToIntBoxingValues(long number) {
|
||||||
|
return Long.valueOf(number)
|
||||||
|
.intValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int longToIntGuava(long number) {
|
||||||
|
return Ints.checkedCast(number);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int longToIntGuavaSaturated(long number) {
|
||||||
|
return Ints.saturatedCast(number);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int longToIntWithBigDecimal(long number) {
|
||||||
|
return new BigDecimal(number).intValueExact();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.convertLongToInt;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class ConvertLongToIntUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void longToInt() {
|
||||||
|
long number = 186762L;
|
||||||
|
int expected = 186762;
|
||||||
|
|
||||||
|
assertEquals(expected, ConvertLongToInt.longToIntCast(number));
|
||||||
|
assertEquals(expected, ConvertLongToInt.longToIntJavaWithMath(number));
|
||||||
|
assertEquals(expected, ConvertLongToInt.longToIntJavaWithLambda(number));
|
||||||
|
assertEquals(expected, ConvertLongToInt.longToIntBoxingValues(number));
|
||||||
|
assertEquals(expected, ConvertLongToInt.longToIntGuava(number));
|
||||||
|
assertEquals(expected, ConvertLongToInt.longToIntGuavaSaturated(number));
|
||||||
|
assertEquals(expected, ConvertLongToInt.longToIntWithBigDecimal(number));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -8,7 +8,7 @@ This module contains articles about test libraries.
|
|||||||
- [Introduction to JSONassert](https://www.baeldung.com/jsonassert)
|
- [Introduction to JSONassert](https://www.baeldung.com/jsonassert)
|
||||||
- [Serenity BDD and Screenplay](https://www.baeldung.com/serenity-screenplay)
|
- [Serenity BDD and Screenplay](https://www.baeldung.com/serenity-screenplay)
|
||||||
- [Serenity BDD with Spring and JBehave](https://www.baeldung.com/serenity-spring-jbehave)
|
- [Serenity BDD with Spring and JBehave](https://www.baeldung.com/serenity-spring-jbehave)
|
||||||
- [Introduction to Awaitility](https://www.baeldung.com/awaitlity-testing)
|
- [Introduction to Awaitility](https://www.baeldung.com/awaitility-testing)
|
||||||
- [Introduction to Hoverfly in Java](https://www.baeldung.com/hoverfly)
|
- [Introduction to Hoverfly in Java](https://www.baeldung.com/hoverfly)
|
||||||
- [Testing with Hamcrest](https://www.baeldung.com/java-junit-hamcrest-guide)
|
- [Testing with Hamcrest](https://www.baeldung.com/java-junit-hamcrest-guide)
|
||||||
- [Introduction To DBUnit](https://www.baeldung.com/java-dbunit)
|
- [Introduction To DBUnit](https://www.baeldung.com/java-dbunit)
|
||||||
|
@ -7,4 +7,5 @@ This module contains articles about Project Lombok.
|
|||||||
- [Using Lombok’s @Accessors Annotation](https://www.baeldung.com/lombok-accessors)
|
- [Using Lombok’s @Accessors Annotation](https://www.baeldung.com/lombok-accessors)
|
||||||
- [Declaring Val and Var Variables in Lombok](https://www.baeldung.com/java-lombok-val-var)
|
- [Declaring Val and Var Variables in Lombok](https://www.baeldung.com/java-lombok-val-var)
|
||||||
- [Lombok Using @With Annotations](https://www.baeldung.com/lombok-with-annotations)
|
- [Lombok Using @With Annotations](https://www.baeldung.com/lombok-with-annotations)
|
||||||
|
- [Lombok's @ToString Annotation](https://www.baeldung.com/lombok-tostring)
|
||||||
- More articles: [[<-- prev]](../lombok)
|
- More articles: [[<-- prev]](../lombok)
|
||||||
|
@ -0,0 +1,56 @@
|
|||||||
|
package com.baeldung.lombok.tostring;
|
||||||
|
|
||||||
|
import lombok.ToString;
|
||||||
|
|
||||||
|
@ToString
|
||||||
|
public class Account {
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
// render this field before any others (the highest ranked)
|
||||||
|
@ToString.Include(rank = 1)
|
||||||
|
private String id;
|
||||||
|
|
||||||
|
@ToString.Exclude
|
||||||
|
private String accountNumber;
|
||||||
|
|
||||||
|
// automatically excluded
|
||||||
|
private String $ignored;
|
||||||
|
|
||||||
|
@ToString.Include
|
||||||
|
String description() {
|
||||||
|
return "Account description";
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAccountNumber() {
|
||||||
|
return accountNumber;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAccountNumber(String accountNumber) {
|
||||||
|
this.accountNumber = accountNumber;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(String id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String get$ignored() {
|
||||||
|
return $ignored;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void set$ignored(String value) {
|
||||||
|
this.$ignored = value;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,9 @@
|
|||||||
|
package com.baeldung.lombok.tostring;
|
||||||
|
|
||||||
|
import lombok.ToString;
|
||||||
|
|
||||||
|
@ToString
|
||||||
|
public enum AccountType {
|
||||||
|
CHECKING,
|
||||||
|
SAVING
|
||||||
|
}
|
@ -0,0 +1,27 @@
|
|||||||
|
package com.baeldung.lombok.tostring;
|
||||||
|
|
||||||
|
import lombok.ToString;
|
||||||
|
|
||||||
|
@ToString
|
||||||
|
public class RewardAccount extends Account {
|
||||||
|
|
||||||
|
private String rewardAccountId;
|
||||||
|
|
||||||
|
private Object[] relatedAccounts;
|
||||||
|
|
||||||
|
public String getRewardAccountId() {
|
||||||
|
return rewardAccountId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRewardAccountId(String rewardAccountId) {
|
||||||
|
this.rewardAccountId = rewardAccountId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object[] getRelatedAccounts() {
|
||||||
|
return relatedAccounts;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRelatedAccounts(Object[] relatedAccounts) {
|
||||||
|
this.relatedAccounts = relatedAccounts;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,17 @@
|
|||||||
|
package com.baeldung.lombok.tostring;
|
||||||
|
|
||||||
|
import lombok.ToString;
|
||||||
|
|
||||||
|
@ToString(callSuper = true)
|
||||||
|
public class SavingAccount extends Account {
|
||||||
|
|
||||||
|
private String savingAccountId;
|
||||||
|
|
||||||
|
public String getSavingAccountId() {
|
||||||
|
return savingAccountId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setSavingAccountId(String savingAccountId) {
|
||||||
|
this.savingAccountId = savingAccountId;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,66 @@
|
|||||||
|
package com.baeldung.lombok.tostring;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
class ToStringUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenPrintObject_thenOutputIsCorrect() {
|
||||||
|
Account account = new Account();
|
||||||
|
account.setId("12345");
|
||||||
|
account.setName("An account");
|
||||||
|
account.setAccountNumber("11111"); // should not be present in output
|
||||||
|
account.set$ignored("ignored value"); // should not be present in output
|
||||||
|
|
||||||
|
assertThat(account.toString())
|
||||||
|
.isEqualTo("Account(id=12345, name=An account, description=Account description)");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenPrintSubclassWithSuper_thenOutputIsCorrect() {
|
||||||
|
SavingAccount savingAccount = new SavingAccount();
|
||||||
|
savingAccount.setSavingAccountId("5678");
|
||||||
|
savingAccount.setId("12345");
|
||||||
|
savingAccount.setName("An account");
|
||||||
|
|
||||||
|
assertThat(savingAccount.toString())
|
||||||
|
.isEqualTo("SavingAccount(super=Account(id=12345, name=An account, description=Account description), savingAccountId=5678)");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenPrintArrays_thenOutputIsCorrect() {
|
||||||
|
RewardAccount account = new RewardAccount();
|
||||||
|
account.setRewardAccountId("12345");
|
||||||
|
|
||||||
|
// circular ref, just for demonstration
|
||||||
|
Object[] relatedAccounts = new Object[2];
|
||||||
|
relatedAccounts[0] = "54321";
|
||||||
|
relatedAccounts[1] = relatedAccounts;
|
||||||
|
|
||||||
|
account.setRelatedAccounts(relatedAccounts);
|
||||||
|
|
||||||
|
assertThat(account.toString())
|
||||||
|
.isEqualTo("RewardAccount(rewardAccountId=12345, relatedAccounts=[54321, [...]])");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenPrintSubclassWithoutSuper_thenOutputIsCorrect() {
|
||||||
|
RewardAccount rewardAccount = new RewardAccount();
|
||||||
|
rewardAccount.setRewardAccountId("12345");
|
||||||
|
|
||||||
|
assertThat(rewardAccount.toString())
|
||||||
|
.isEqualTo("RewardAccount(rewardAccountId=12345, relatedAccounts=null)");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenPrintEnum_thenOutputIsCorrect() {
|
||||||
|
assertThat(AccountType.CHECKING.toString())
|
||||||
|
.isEqualTo("AccountType.CHECKING");
|
||||||
|
|
||||||
|
assertThat(AccountType.SAVING.toString())
|
||||||
|
.isEqualTo("AccountType.SAVING");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -5,7 +5,7 @@
|
|||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>maven-profiles</artifactId>
|
<artifactId>maven-profiles</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
<name>maven-profiles</name>
|
<name>maven-profiles</name>
|
||||||
|
|
||||||
<profiles>
|
<profiles>
|
||||||
|
@ -10,7 +10,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<artifactId>parent-project</artifactId>
|
<artifactId>parent-project</artifactId>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<version>1.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -4,14 +4,13 @@
|
|||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>parent-project</artifactId>
|
<artifactId>parent-project</artifactId>
|
||||||
<version>1.0-SNAPSHOT</version>
|
|
||||||
<name>parent-project</name>
|
<name>parent-project</name>
|
||||||
<packaging>pom</packaging>
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>maven-simple</artifactId>
|
<artifactId>maven-simple</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<modules>
|
<modules>
|
||||||
|
@ -10,7 +10,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<artifactId>parent-project</artifactId>
|
<artifactId>parent-project</artifactId>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<version>1.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -10,7 +10,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<artifactId>parent-project</artifactId>
|
<artifactId>parent-project</artifactId>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<version>1.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -9,7 +9,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<artifactId>maven-simple</artifactId>
|
<artifactId>maven-simple</artifactId>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<modules>
|
<modules>
|
||||||
@ -56,8 +56,8 @@
|
|||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<maven.compiler.plugin>3.8.1</maven.compiler.plugin>
|
<maven.compiler.plugin>3.10.0</maven.compiler.plugin>
|
||||||
<maven.bulid.helper.plugin>3.2.0</maven.bulid.helper.plugin>
|
<maven.bulid.helper.plugin>3.3.0</maven.bulid.helper.plugin>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -8,7 +8,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<artifactId>plugin-management</artifactId>
|
<artifactId>plugin-management</artifactId>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
@ -8,7 +8,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<artifactId>plugin-management</artifactId>
|
<artifactId>plugin-management</artifactId>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -5,6 +5,7 @@
|
|||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>maven-simple</artifactId>
|
<artifactId>maven-simple</artifactId>
|
||||||
<name>maven-simple</name>
|
<name>maven-simple</name>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
<packaging>pom</packaging>
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
|
@ -108,7 +108,7 @@
|
|||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.mule.tools.maven</groupId>
|
<groupId>org.mule.tools.maven</groupId>
|
||||||
<artifactId>mule-maven-plugin</artifactId>
|
<artifactId>mule-maven-plugin</artifactId>
|
||||||
<version>2.2.1</version>
|
<version>${mule-maven-plugin.version}</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<deploymentType>standalone</deploymentType>
|
<deploymentType>standalone</deploymentType>
|
||||||
<muleVersion>${mule.version}</muleVersion>
|
<muleVersion>${mule.version}</muleVersion>
|
||||||
@ -203,7 +203,7 @@
|
|||||||
<id>mulesoft-release</id>
|
<id>mulesoft-release</id>
|
||||||
<name>mulesoft release repository</name>
|
<name>mulesoft release repository</name>
|
||||||
<layout>default</layout>
|
<layout>default</layout>
|
||||||
<url>https://repository.mulesoft.org/releases/</url>
|
<url>https://repository.mulesoft.org/nexus/content/repositories/public/</url>
|
||||||
<snapshots>
|
<snapshots>
|
||||||
<enabled>false</enabled>
|
<enabled>false</enabled>
|
||||||
</snapshots>
|
</snapshots>
|
||||||
@ -212,9 +212,10 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<mule.version>3.9.0</mule.version>
|
<mule.version>3.9.0</mule.version>
|
||||||
<mule.tools.version>1.2</mule.tools.version>
|
<mule.tools.version>1.8</mule.tools.version>
|
||||||
<munit.version>1.3.6</munit.version>
|
<munit.version>1.3.6</munit.version>
|
||||||
<build-helper-maven-plugin.version>1.7</build-helper-maven-plugin.version>
|
<build-helper-maven-plugin.version>1.10</build-helper-maven-plugin.version>
|
||||||
|
<mule-maven-plugin.version>2.2.1</mule-maven-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
7
nginx-forward-proxy/forward
Normal file
7
nginx-forward-proxy/forward
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
server {
|
||||||
|
listen 8888;
|
||||||
|
location / {
|
||||||
|
resolver 8.8.8.8;
|
||||||
|
proxy_pass http://$http_host$uri$is_args$args;
|
||||||
|
}
|
||||||
|
}
|
339
nginx-forward-proxy/package-lock.json
generated
Normal file
339
nginx-forward-proxy/package-lock.json
generated
Normal file
@ -0,0 +1,339 @@
|
|||||||
|
{
|
||||||
|
"name": "nginx-forward-proxy",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"lockfileVersion": 1,
|
||||||
|
"requires": true,
|
||||||
|
"dependencies": {
|
||||||
|
"ajv": {
|
||||||
|
"version": "6.12.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
|
||||||
|
"integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
|
||||||
|
"requires": {
|
||||||
|
"fast-deep-equal": "^3.1.1",
|
||||||
|
"fast-json-stable-stringify": "^2.0.0",
|
||||||
|
"json-schema-traverse": "^0.4.1",
|
||||||
|
"uri-js": "^4.2.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"asn1": {
|
||||||
|
"version": "0.2.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz",
|
||||||
|
"integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==",
|
||||||
|
"requires": {
|
||||||
|
"safer-buffer": "~2.1.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"assert-plus": {
|
||||||
|
"version": "1.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz",
|
||||||
|
"integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU="
|
||||||
|
},
|
||||||
|
"asynckit": {
|
||||||
|
"version": "0.4.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
|
||||||
|
"integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k="
|
||||||
|
},
|
||||||
|
"aws-sign2": {
|
||||||
|
"version": "0.7.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz",
|
||||||
|
"integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg="
|
||||||
|
},
|
||||||
|
"aws4": {
|
||||||
|
"version": "1.11.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/aws4/-/aws4-1.11.0.tgz",
|
||||||
|
"integrity": "sha512-xh1Rl34h6Fi1DC2WWKfxUTVqRsNnr6LsKz2+hfwDxQJWmrx8+c7ylaqBMcHfl1U1r2dsifOvKX3LQuLNZ+XSvA=="
|
||||||
|
},
|
||||||
|
"bcrypt-pbkdf": {
|
||||||
|
"version": "1.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz",
|
||||||
|
"integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=",
|
||||||
|
"requires": {
|
||||||
|
"tweetnacl": "^0.14.3"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"caseless": {
|
||||||
|
"version": "0.12.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz",
|
||||||
|
"integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw="
|
||||||
|
},
|
||||||
|
"combined-stream": {
|
||||||
|
"version": "1.0.8",
|
||||||
|
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
|
||||||
|
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
|
||||||
|
"requires": {
|
||||||
|
"delayed-stream": "~1.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"core-util-is": {
|
||||||
|
"version": "1.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
|
||||||
|
"integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac="
|
||||||
|
},
|
||||||
|
"dashdash": {
|
||||||
|
"version": "1.14.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz",
|
||||||
|
"integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=",
|
||||||
|
"requires": {
|
||||||
|
"assert-plus": "^1.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"delayed-stream": {
|
||||||
|
"version": "1.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
|
||||||
|
"integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk="
|
||||||
|
},
|
||||||
|
"ecc-jsbn": {
|
||||||
|
"version": "0.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz",
|
||||||
|
"integrity": "sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=",
|
||||||
|
"requires": {
|
||||||
|
"jsbn": "~0.1.0",
|
||||||
|
"safer-buffer": "^2.1.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"extend": {
|
||||||
|
"version": "3.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
|
||||||
|
"integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="
|
||||||
|
},
|
||||||
|
"extsprintf": {
|
||||||
|
"version": "1.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz",
|
||||||
|
"integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU="
|
||||||
|
},
|
||||||
|
"fast-deep-equal": {
|
||||||
|
"version": "3.1.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
|
||||||
|
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="
|
||||||
|
},
|
||||||
|
"fast-json-stable-stringify": {
|
||||||
|
"version": "2.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
|
||||||
|
"integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw=="
|
||||||
|
},
|
||||||
|
"forever-agent": {
|
||||||
|
"version": "0.6.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz",
|
||||||
|
"integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE="
|
||||||
|
},
|
||||||
|
"form-data": {
|
||||||
|
"version": "2.3.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz",
|
||||||
|
"integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==",
|
||||||
|
"requires": {
|
||||||
|
"asynckit": "^0.4.0",
|
||||||
|
"combined-stream": "^1.0.6",
|
||||||
|
"mime-types": "^2.1.12"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"getpass": {
|
||||||
|
"version": "0.1.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz",
|
||||||
|
"integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=",
|
||||||
|
"requires": {
|
||||||
|
"assert-plus": "^1.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"har-schema": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz",
|
||||||
|
"integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI="
|
||||||
|
},
|
||||||
|
"har-validator": {
|
||||||
|
"version": "5.1.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.5.tgz",
|
||||||
|
"integrity": "sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w==",
|
||||||
|
"requires": {
|
||||||
|
"ajv": "^6.12.3",
|
||||||
|
"har-schema": "^2.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"http-signature": {
|
||||||
|
"version": "1.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz",
|
||||||
|
"integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=",
|
||||||
|
"requires": {
|
||||||
|
"assert-plus": "^1.0.0",
|
||||||
|
"jsprim": "^1.2.2",
|
||||||
|
"sshpk": "^1.7.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"is-typedarray": {
|
||||||
|
"version": "1.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz",
|
||||||
|
"integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo="
|
||||||
|
},
|
||||||
|
"isstream": {
|
||||||
|
"version": "0.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz",
|
||||||
|
"integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo="
|
||||||
|
},
|
||||||
|
"jsbn": {
|
||||||
|
"version": "0.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz",
|
||||||
|
"integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM="
|
||||||
|
},
|
||||||
|
"json-schema": {
|
||||||
|
"version": "0.4.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz",
|
||||||
|
"integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA=="
|
||||||
|
},
|
||||||
|
"json-schema-traverse": {
|
||||||
|
"version": "0.4.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
|
||||||
|
"integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="
|
||||||
|
},
|
||||||
|
"json-stringify-safe": {
|
||||||
|
"version": "5.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz",
|
||||||
|
"integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus="
|
||||||
|
},
|
||||||
|
"jsprim": {
|
||||||
|
"version": "1.4.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.2.tgz",
|
||||||
|
"integrity": "sha512-P2bSOMAc/ciLz6DzgjVlGJP9+BrJWu5UDGK70C2iweC5QBIeFf0ZXRvGjEj2uYgrY2MkAAhsSWHDWlFtEroZWw==",
|
||||||
|
"requires": {
|
||||||
|
"assert-plus": "1.0.0",
|
||||||
|
"extsprintf": "1.3.0",
|
||||||
|
"json-schema": "0.4.0",
|
||||||
|
"verror": "1.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"mime-db": {
|
||||||
|
"version": "1.51.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.51.0.tgz",
|
||||||
|
"integrity": "sha512-5y8A56jg7XVQx2mbv1lu49NR4dokRnhZYTtL+KGfaa27uq4pSTXkwQkFJl4pkRMyNFz/EtYDSkiiEHx3F7UN6g=="
|
||||||
|
},
|
||||||
|
"mime-types": {
|
||||||
|
"version": "2.1.34",
|
||||||
|
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.34.tgz",
|
||||||
|
"integrity": "sha512-6cP692WwGIs9XXdOO4++N+7qjqv0rqxxVvJ3VHPh/Sc9mVZcQP+ZGhkKiTvWMQRr2tbHkJP/Yn7Y0npb3ZBs4A==",
|
||||||
|
"requires": {
|
||||||
|
"mime-db": "1.51.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"oauth-sign": {
|
||||||
|
"version": "0.9.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz",
|
||||||
|
"integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ=="
|
||||||
|
},
|
||||||
|
"performance-now": {
|
||||||
|
"version": "2.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz",
|
||||||
|
"integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns="
|
||||||
|
},
|
||||||
|
"psl": {
|
||||||
|
"version": "1.8.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/psl/-/psl-1.8.0.tgz",
|
||||||
|
"integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ=="
|
||||||
|
},
|
||||||
|
"punycode": {
|
||||||
|
"version": "2.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz",
|
||||||
|
"integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A=="
|
||||||
|
},
|
||||||
|
"qs": {
|
||||||
|
"version": "6.5.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/qs/-/qs-6.5.3.tgz",
|
||||||
|
"integrity": "sha512-qxXIEh4pCGfHICj1mAJQ2/2XVZkjCDTcEgfoSQxc/fYivUZxTkk7L3bDBJSoNrEzXI17oUO5Dp07ktqE5KzczA=="
|
||||||
|
},
|
||||||
|
"request": {
|
||||||
|
"version": "2.88.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/request/-/request-2.88.2.tgz",
|
||||||
|
"integrity": "sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==",
|
||||||
|
"requires": {
|
||||||
|
"aws-sign2": "~0.7.0",
|
||||||
|
"aws4": "^1.8.0",
|
||||||
|
"caseless": "~0.12.0",
|
||||||
|
"combined-stream": "~1.0.6",
|
||||||
|
"extend": "~3.0.2",
|
||||||
|
"forever-agent": "~0.6.1",
|
||||||
|
"form-data": "~2.3.2",
|
||||||
|
"har-validator": "~5.1.3",
|
||||||
|
"http-signature": "~1.2.0",
|
||||||
|
"is-typedarray": "~1.0.0",
|
||||||
|
"isstream": "~0.1.2",
|
||||||
|
"json-stringify-safe": "~5.0.1",
|
||||||
|
"mime-types": "~2.1.19",
|
||||||
|
"oauth-sign": "~0.9.0",
|
||||||
|
"performance-now": "^2.1.0",
|
||||||
|
"qs": "~6.5.2",
|
||||||
|
"safe-buffer": "^5.1.2",
|
||||||
|
"tough-cookie": "~2.5.0",
|
||||||
|
"tunnel-agent": "^0.6.0",
|
||||||
|
"uuid": "^3.3.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"safe-buffer": {
|
||||||
|
"version": "5.2.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
|
||||||
|
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="
|
||||||
|
},
|
||||||
|
"safer-buffer": {
|
||||||
|
"version": "2.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
|
||||||
|
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
|
||||||
|
},
|
||||||
|
"sshpk": {
|
||||||
|
"version": "1.17.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.17.0.tgz",
|
||||||
|
"integrity": "sha512-/9HIEs1ZXGhSPE8X6Ccm7Nam1z8KcoCqPdI7ecm1N33EzAetWahvQWVqLZtaZQ+IDKX4IyA2o0gBzqIMkAagHQ==",
|
||||||
|
"requires": {
|
||||||
|
"asn1": "~0.2.3",
|
||||||
|
"assert-plus": "^1.0.0",
|
||||||
|
"bcrypt-pbkdf": "^1.0.0",
|
||||||
|
"dashdash": "^1.12.0",
|
||||||
|
"ecc-jsbn": "~0.1.1",
|
||||||
|
"getpass": "^0.1.1",
|
||||||
|
"jsbn": "~0.1.0",
|
||||||
|
"safer-buffer": "^2.0.2",
|
||||||
|
"tweetnacl": "~0.14.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"tough-cookie": {
|
||||||
|
"version": "2.5.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz",
|
||||||
|
"integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==",
|
||||||
|
"requires": {
|
||||||
|
"psl": "^1.1.28",
|
||||||
|
"punycode": "^2.1.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"tunnel-agent": {
|
||||||
|
"version": "0.6.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
|
||||||
|
"integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=",
|
||||||
|
"requires": {
|
||||||
|
"safe-buffer": "^5.0.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"tweetnacl": {
|
||||||
|
"version": "0.14.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz",
|
||||||
|
"integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q="
|
||||||
|
},
|
||||||
|
"uri-js": {
|
||||||
|
"version": "4.4.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
|
||||||
|
"integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",
|
||||||
|
"requires": {
|
||||||
|
"punycode": "^2.1.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"uuid": {
|
||||||
|
"version": "3.4.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz",
|
||||||
|
"integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A=="
|
||||||
|
},
|
||||||
|
"verror": {
|
||||||
|
"version": "1.10.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz",
|
||||||
|
"integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=",
|
||||||
|
"requires": {
|
||||||
|
"assert-plus": "^1.0.0",
|
||||||
|
"core-util-is": "1.0.2",
|
||||||
|
"extsprintf": "^1.2.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
14
nginx-forward-proxy/package.json
Normal file
14
nginx-forward-proxy/package.json
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"name": "nginx-forward-proxy",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "Simple Client for Connecting to a Forward Proxy",
|
||||||
|
"main": "proxytest.js",
|
||||||
|
"scripts": {
|
||||||
|
"test": "echo \"Error: no test specified\" && exit 1"
|
||||||
|
},
|
||||||
|
"author": "Olsi Seferi",
|
||||||
|
"license": "ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"request": "^2.88.2"
|
||||||
|
}
|
||||||
|
}
|
11
nginx-forward-proxy/proxytest.js
Normal file
11
nginx-forward-proxy/proxytest.js
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
var request = require('request');
|
||||||
|
|
||||||
|
request({
|
||||||
|
'url':'http://www.google.com/',
|
||||||
|
'method': "GET",
|
||||||
|
'proxy':'http://192.168.100.40:8888'
|
||||||
|
},function (error, response, body) {
|
||||||
|
if (!error && response.statusCode == 200) {
|
||||||
|
console.log(body);
|
||||||
|
}
|
||||||
|
})
|
1
persistence-modules/fauna/.gitignore
vendored
Normal file
1
persistence-modules/fauna/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
/application.properties
|
56
persistence-modules/fauna/pom.xml
Normal file
56
persistence-modules/fauna/pom.xml
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<parent>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-parent</artifactId>
|
||||||
|
<version>2.6.2</version>
|
||||||
|
<relativePath/> <!-- lookup parent from repository -->
|
||||||
|
</parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>fauna-blog</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<name>fauna-blog</name>
|
||||||
|
<description>Blogging Service built with FaunaDB</description>
|
||||||
|
<properties>
|
||||||
|
<java.version>17</java.version>
|
||||||
|
</properties>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-security</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.faunadb</groupId>
|
||||||
|
<artifactId>faunadb-java</artifactId>
|
||||||
|
<version>4.2.0</version>
|
||||||
|
<scope>compile</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.security</groupId>
|
||||||
|
<artifactId>spring-security-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
</project>
|
@ -1,14 +1,13 @@
|
|||||||
package com.baeldung.autowiring;
|
package com.baeldung.faunablog;
|
||||||
|
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
import org.springframework.context.annotation.ComponentScan;
|
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
public class App {
|
public class FaunaBlogApplication {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
SpringApplication.run(App.class, args);
|
SpringApplication.run(FaunaBlogApplication.class, args);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.faunablog;
|
||||||
|
|
||||||
|
import com.faunadb.client.FaunaClient;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
import java.net.MalformedURLException;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
class FaunaConfiguration {
|
||||||
|
@Value("https://db.${fauna.region}.fauna.com/")
|
||||||
|
private String faunaUrl;
|
||||||
|
|
||||||
|
@Value("${fauna.secret}")
|
||||||
|
private String faunaSecret;
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
FaunaClient getFaunaClient() throws MalformedURLException {
|
||||||
|
return FaunaClient.builder()
|
||||||
|
.withEndpoint(faunaUrl)
|
||||||
|
.withSecret(faunaSecret)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,35 @@
|
|||||||
|
package com.baeldung.faunablog;
|
||||||
|
|
||||||
|
import com.baeldung.faunablog.users.FaunaUserDetailsService;
|
||||||
|
import com.faunadb.client.FaunaClient;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableWebSecurity
|
||||||
|
@EnableGlobalMethodSecurity(prePostEnabled = true)
|
||||||
|
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private FaunaClient faunaClient;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
|
http.csrf().disable();
|
||||||
|
http.authorizeRequests()
|
||||||
|
.antMatchers("/**").permitAll()
|
||||||
|
.and().httpBasic();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@Override
|
||||||
|
public UserDetailsService userDetailsService() {
|
||||||
|
return new FaunaUserDetailsService(faunaClient);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,3 @@
|
|||||||
|
package com.baeldung.faunablog.posts;
|
||||||
|
|
||||||
|
public record Author(String username, String name) {}
|
@ -0,0 +1,5 @@
|
|||||||
|
package com.baeldung.faunablog.posts;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
|
||||||
|
public record Post(String id, String title, String content, Author author, Instant created, Long version) {}
|
@ -0,0 +1,50 @@
|
|||||||
|
package com.baeldung.faunablog.posts;
|
||||||
|
|
||||||
|
import com.faunadb.client.errors.NotFoundException;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/posts")
|
||||||
|
public class PostsController {
|
||||||
|
@Autowired
|
||||||
|
private PostsService postsService;
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
public List<Post> listPosts(@RequestParam(value = "author", required = false) String author) throws ExecutionException, InterruptedException {
|
||||||
|
return author == null ? postsService.getAllPosts() : postsService.getAuthorPosts("graham");
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{id}")
|
||||||
|
public Post getPost(@PathVariable("id") String id, @RequestParam(value = "before", required = false) Long before)
|
||||||
|
throws ExecutionException, InterruptedException {
|
||||||
|
return postsService.getPost(id, before);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||||
|
@PreAuthorize("isAuthenticated()")
|
||||||
|
public void createPost(@RequestBody UpdatedPost post) throws ExecutionException, InterruptedException {
|
||||||
|
String name = SecurityContextHolder.getContext().getAuthentication().getName();
|
||||||
|
postsService.createPost(name, post.title(), post.content());
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{id}")
|
||||||
|
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||||
|
@PreAuthorize("isAuthenticated()")
|
||||||
|
public void updatePost(@PathVariable("id") String id, @RequestBody UpdatedPost post)
|
||||||
|
throws ExecutionException, InterruptedException {
|
||||||
|
postsService.updatePost(id, post.title(), post.content());
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(NotFoundException.class)
|
||||||
|
@ResponseStatus(HttpStatus.NOT_FOUND)
|
||||||
|
public void postNotFound() {}
|
||||||
|
}
|
@ -0,0 +1,124 @@
|
|||||||
|
package com.baeldung.faunablog.posts;
|
||||||
|
|
||||||
|
import com.faunadb.client.FaunaClient;
|
||||||
|
import com.faunadb.client.types.Value;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import static com.faunadb.client.query.Language.*;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class PostsService {
|
||||||
|
@Autowired
|
||||||
|
private FaunaClient faunaClient;
|
||||||
|
|
||||||
|
Post getPost(String id, Long before) throws ExecutionException, InterruptedException {
|
||||||
|
var query = Get(Ref(Collection("posts"), id));
|
||||||
|
if (before != null) {
|
||||||
|
query = At(Value(before - 1), query);
|
||||||
|
}
|
||||||
|
|
||||||
|
var postResult= faunaClient.query(
|
||||||
|
Let(
|
||||||
|
"post", query
|
||||||
|
).in(
|
||||||
|
Obj(
|
||||||
|
"post", Var("post"),
|
||||||
|
"author", Get(Select(Arr(Value("data"), Value("authorRef")), Var("post")))
|
||||||
|
)
|
||||||
|
)).get();
|
||||||
|
|
||||||
|
return parsePost(postResult);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Post> getAllPosts() throws ExecutionException, InterruptedException {
|
||||||
|
var postsResult = faunaClient.query(Map(
|
||||||
|
Paginate(
|
||||||
|
Join(
|
||||||
|
Documents(Collection("posts")),
|
||||||
|
Index("posts_sort_by_created_desc")
|
||||||
|
)
|
||||||
|
),
|
||||||
|
Lambda(
|
||||||
|
Arr(Value("extra"), Value("ref")),
|
||||||
|
Obj(
|
||||||
|
"post", Get(Var("ref")),
|
||||||
|
"author", Get(Select(Arr(Value("data"), Value("authorRef")), Get(Var("ref"))))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)).get();
|
||||||
|
|
||||||
|
var posts = postsResult.at("data").asCollectionOf(Value.class).get();
|
||||||
|
return posts.stream().map(this::parsePost).collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Post> getAuthorPosts(String author) throws ExecutionException, InterruptedException {
|
||||||
|
var postsResult = faunaClient.query(Map(
|
||||||
|
Paginate(
|
||||||
|
Join(
|
||||||
|
Match(Index("posts_by_author"), Select(Value("ref"), Get(Match(Index("users_by_username"), Value(author))))),
|
||||||
|
Index("posts_sort_by_created_desc")
|
||||||
|
)
|
||||||
|
),
|
||||||
|
Lambda(
|
||||||
|
Arr(Value("extra"), Value("ref")),
|
||||||
|
Obj(
|
||||||
|
"post", Get(Var("ref")),
|
||||||
|
"author", Get(Select(Arr(Value("data"), Value("authorRef")), Get(Var("ref"))))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)).get();
|
||||||
|
|
||||||
|
var posts = postsResult.at("data").asCollectionOf(Value.class).get();
|
||||||
|
return posts.stream().map(this::parsePost).collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void createPost(String author, String title, String contents) throws ExecutionException, InterruptedException {
|
||||||
|
faunaClient.query(
|
||||||
|
Create(Collection("posts"),
|
||||||
|
Obj(
|
||||||
|
"data", Obj(
|
||||||
|
"title", Value(title),
|
||||||
|
"contents", Value(contents),
|
||||||
|
"created", Now(),
|
||||||
|
"authorRef", Select(Value("ref"), Get(Match(Index("users_by_username"), Value(author)))))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
).get();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void updatePost(String id, String title, String contents) throws ExecutionException, InterruptedException {
|
||||||
|
faunaClient.query(
|
||||||
|
Update(Ref(Collection("posts"), id),
|
||||||
|
Obj(
|
||||||
|
"data", Obj(
|
||||||
|
"title", Value(title),
|
||||||
|
"contents", Value(contents))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
).get();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Post parsePost(Value entry) {
|
||||||
|
var author = entry.at("author");
|
||||||
|
var post = entry.at("post");
|
||||||
|
|
||||||
|
return new Post(
|
||||||
|
post.at("ref").to(Value.RefV.class).get().getId(),
|
||||||
|
post.at("data", "title").to(String.class).get(),
|
||||||
|
post.at("data", "contents").to(String.class).get(),
|
||||||
|
new Author(
|
||||||
|
author.at("data", "username").to(String.class).get(),
|
||||||
|
author.at("data", "name").to(String.class).get()
|
||||||
|
),
|
||||||
|
post.at("data", "created").to(Instant.class).get(),
|
||||||
|
post.at("ts").to(Long.class).get()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,3 @@
|
|||||||
|
package com.baeldung.faunablog.posts;
|
||||||
|
|
||||||
|
public record UpdatedPost(String title, String content) {}
|
@ -0,0 +1,44 @@
|
|||||||
|
package com.baeldung.faunablog.users;
|
||||||
|
|
||||||
|
import com.faunadb.client.FaunaClient;
|
||||||
|
import com.faunadb.client.types.Value;
|
||||||
|
import org.springframework.security.core.userdetails.User;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||||
|
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||||
|
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
|
||||||
|
import static com.faunadb.client.query.Language.*;
|
||||||
|
|
||||||
|
public class FaunaUserDetailsService implements UserDetailsService {
|
||||||
|
private FaunaClient faunaClient;
|
||||||
|
|
||||||
|
public FaunaUserDetailsService(FaunaClient faunaClient) {
|
||||||
|
this.faunaClient = faunaClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||||
|
try {
|
||||||
|
Value user = faunaClient.query(Map(
|
||||||
|
Paginate(Match(Index("users_by_username"), Value(username))),
|
||||||
|
Lambda(Value("user"), Get(Var("user")))))
|
||||||
|
.get();
|
||||||
|
|
||||||
|
Value userData = user.at("data").at(0).orNull();
|
||||||
|
if (userData == null) {
|
||||||
|
throw new UsernameNotFoundException("User not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
return User.withDefaultPasswordEncoder()
|
||||||
|
.username(userData.at("data", "username").to(String.class).orNull())
|
||||||
|
.password(userData.at("data", "password").to(String.class).orNull())
|
||||||
|
.roles("USER")
|
||||||
|
.build();
|
||||||
|
} catch (ExecutionException | InterruptedException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -52,9 +52,11 @@ public class HibernateManyToManyAnnotationMainIntegrationTest {
|
|||||||
|
|
||||||
for(Employee employee : employeeList) {
|
for(Employee employee : employeeList) {
|
||||||
assertNotNull(employee.getProjects());
|
assertNotNull(employee.getProjects());
|
||||||
|
assertEquals(2, employee.getProjects().size());
|
||||||
}
|
}
|
||||||
for(Project project : projectList) {
|
for(Project project : projectList) {
|
||||||
assertNotNull(project.getEmployees());
|
assertNotNull(project.getEmployees());
|
||||||
|
assertEquals(2, project.getEmployees().size());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -70,6 +72,11 @@ public class HibernateManyToManyAnnotationMainIntegrationTest {
|
|||||||
for (String emp : employeeData) {
|
for (String emp : employeeData) {
|
||||||
Employee employee = new Employee(emp.split(" ")[0], emp.split(" ")[1]);
|
Employee employee = new Employee(emp.split(" ")[0], emp.split(" ")[1]);
|
||||||
employee.setProjects(projects);
|
employee.setProjects(projects);
|
||||||
|
|
||||||
|
for (Project proj : projects) {
|
||||||
|
proj.getEmployees().add(employee);
|
||||||
|
}
|
||||||
|
|
||||||
session.persist(employee);
|
session.persist(employee);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -50,6 +50,25 @@
|
|||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
<profiles>
|
||||||
|
<profile>
|
||||||
|
<id>integration-lite-first</id>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<forkCount>1</forkCount>
|
||||||
|
<reuseForks>true</reuseForks>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</profile>
|
||||||
|
</profiles>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<!-- Cassandra -->
|
<!-- Cassandra -->
|
||||||
<cassandra-driver-core.version>3.1.2</cassandra-driver-core.version>
|
<cassandra-driver-core.version>3.1.2</cassandra-driver-core.version>
|
||||||
|
@ -13,3 +13,4 @@ This module contains articles about MongoDB in Java.
|
|||||||
- [BSON to JSON Document Conversion in Java](https://www.baeldung.com/java-convert-bson-to-json)
|
- [BSON to JSON Document Conversion in Java](https://www.baeldung.com/java-convert-bson-to-json)
|
||||||
- [How to Check Field Existence in MongoDB?](https://www.baeldung.com/mongodb-check-field-exists)
|
- [How to Check Field Existence in MongoDB?](https://www.baeldung.com/mongodb-check-field-exists)
|
||||||
- [Get Last Inserted Document ID in MongoDB With Java Driver](https://www.baeldung.com/java-mongodb-last-inserted-id)
|
- [Get Last Inserted Document ID in MongoDB With Java Driver](https://www.baeldung.com/java-mongodb-last-inserted-id)
|
||||||
|
- [Update Multiple Fields in a MongoDB Document](https://www.baeldung.com/mongodb-update-multiple-fields)
|
||||||
|
@ -0,0 +1,100 @@
|
|||||||
|
package com.baeldung.mongo;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
|
||||||
|
import org.bson.Document;
|
||||||
|
|
||||||
|
import com.mongodb.DB;
|
||||||
|
import com.mongodb.MongoClient;
|
||||||
|
import com.mongodb.client.MongoCollection;
|
||||||
|
import com.mongodb.client.MongoDatabase;
|
||||||
|
|
||||||
|
public class CollectionExistence {
|
||||||
|
|
||||||
|
private static MongoClient mongoClient;
|
||||||
|
|
||||||
|
private static String testCollectionName;
|
||||||
|
private static String databaseName;
|
||||||
|
|
||||||
|
public static void setUp() {
|
||||||
|
if (mongoClient == null) {
|
||||||
|
mongoClient = new MongoClient("localhost", 27017);
|
||||||
|
}
|
||||||
|
databaseName = "baeldung";
|
||||||
|
testCollectionName = "student";
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void collectionExistsSolution() {
|
||||||
|
|
||||||
|
DB db = mongoClient.getDB(databaseName);
|
||||||
|
|
||||||
|
System.out.println("collectionName " + testCollectionName + db.collectionExists(testCollectionName));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void createCollectionSolution() {
|
||||||
|
|
||||||
|
MongoDatabase database = mongoClient.getDatabase(databaseName);
|
||||||
|
|
||||||
|
try {
|
||||||
|
database.createCollection(testCollectionName);
|
||||||
|
|
||||||
|
} catch (Exception exception) {
|
||||||
|
System.err.println("Collection already Exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void listCollectionNamesSolution() {
|
||||||
|
|
||||||
|
MongoDatabase database = mongoClient.getDatabase(databaseName);
|
||||||
|
boolean collectionExists = database.listCollectionNames()
|
||||||
|
.into(new ArrayList<String>())
|
||||||
|
.contains(testCollectionName);
|
||||||
|
|
||||||
|
System.out.println("collectionExists:- " + collectionExists);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void countSolution() {
|
||||||
|
|
||||||
|
MongoDatabase database = mongoClient.getDatabase(databaseName);
|
||||||
|
|
||||||
|
MongoCollection<Document> collection = database.getCollection(testCollectionName);
|
||||||
|
|
||||||
|
System.out.println(collection.count());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String args[]) {
|
||||||
|
|
||||||
|
//
|
||||||
|
// Connect to cluster (default is localhost:27017)
|
||||||
|
//
|
||||||
|
setUp();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Check the db existence using DB class's method
|
||||||
|
//
|
||||||
|
collectionExistsSolution();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Check the db existence using the createCollection method of MongoDatabase class
|
||||||
|
//
|
||||||
|
createCollectionSolution();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Check the db existence using the listCollectionNames method of MongoDatabase class
|
||||||
|
//
|
||||||
|
listCollectionNamesSolution();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Check the db existence using the count method of MongoDatabase class
|
||||||
|
//
|
||||||
|
countSolution();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
@ -0,0 +1,99 @@
|
|||||||
|
package com.baeldung.mongo;
|
||||||
|
|
||||||
|
import java.io.FileNotFoundException;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import org.bson.Document;
|
||||||
|
|
||||||
|
import com.mongodb.BasicDBObject;
|
||||||
|
import com.mongodb.DBObject;
|
||||||
|
import com.mongodb.MongoClient;
|
||||||
|
import com.mongodb.client.MongoCollection;
|
||||||
|
import com.mongodb.client.MongoDatabase;
|
||||||
|
import com.mongodb.client.model.Filters;
|
||||||
|
import com.mongodb.client.model.Updates;
|
||||||
|
import com.mongodb.client.result.UpdateResult;
|
||||||
|
|
||||||
|
public class PushOperations {
|
||||||
|
|
||||||
|
private static MongoClient mongoClient;
|
||||||
|
private static String testCollectionName;
|
||||||
|
private static String databaseName;
|
||||||
|
|
||||||
|
public static void setUp() {
|
||||||
|
if (mongoClient == null) {
|
||||||
|
mongoClient = new MongoClient("localhost", 27017);
|
||||||
|
}
|
||||||
|
|
||||||
|
databaseName = "baeldung";
|
||||||
|
testCollectionName = "orders";
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void pushOperationUsingDBObject() {
|
||||||
|
|
||||||
|
MongoDatabase database = mongoClient.getDatabase(databaseName);
|
||||||
|
MongoCollection<Document> collection = database.getCollection(testCollectionName);
|
||||||
|
DBObject listItem = new BasicDBObject("items", new BasicDBObject("itemName", "PIZZA MANIA").append("quantity", 1)
|
||||||
|
.append("price", 800));
|
||||||
|
BasicDBObject searchFilter = new BasicDBObject("customerId", 1023);
|
||||||
|
BasicDBObject updateQuery = new BasicDBObject();
|
||||||
|
updateQuery.append("$push", listItem);
|
||||||
|
UpdateResult updateResult = collection.updateOne(searchFilter, updateQuery);
|
||||||
|
|
||||||
|
System.out.println("updateResult:- " + updateResult);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void pushOperationUsingDocument() {
|
||||||
|
|
||||||
|
MongoDatabase database = mongoClient.getDatabase(databaseName);
|
||||||
|
MongoCollection<Document> collection = database.getCollection(testCollectionName);
|
||||||
|
|
||||||
|
Document item = new Document().append("itemName", "PIZZA MANIA")
|
||||||
|
.append("quantity", 1)
|
||||||
|
.append("price", 800);
|
||||||
|
UpdateResult updateResult = collection.updateOne(Filters.eq("customerId", 1023), Updates.push("items", item));
|
||||||
|
|
||||||
|
System.out.println("updateResult:- " + updateResult);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void addToSetOperation() {
|
||||||
|
|
||||||
|
MongoDatabase database = mongoClient.getDatabase(databaseName);
|
||||||
|
MongoCollection<Document> collection = database.getCollection(testCollectionName);
|
||||||
|
|
||||||
|
Document item = new Document().append("itemName", "PIZZA MANIA")
|
||||||
|
.append("quantity", 1)
|
||||||
|
.append("price", 800);
|
||||||
|
UpdateResult updateResult = collection.updateOne(Filters.eq("customerId", 1023), Updates.addToSet("items", item));
|
||||||
|
System.out.println("updateResult:- " + updateResult);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String args[]) {
|
||||||
|
|
||||||
|
//
|
||||||
|
// Connect to cluster (default is localhost:27017)
|
||||||
|
//
|
||||||
|
setUp();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Push document into the array using DBObject
|
||||||
|
//
|
||||||
|
|
||||||
|
pushOperationUsingDBObject();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Push document into the array using Document.
|
||||||
|
//
|
||||||
|
|
||||||
|
pushOperationUsingDocument();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Push document into the array using addToSet operator.
|
||||||
|
//
|
||||||
|
addToSetOperation();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,128 @@
|
|||||||
|
package com.baeldung.mongo.update;
|
||||||
|
|
||||||
|
import org.bson.Document;
|
||||||
|
|
||||||
|
import com.mongodb.MongoClient;
|
||||||
|
import com.mongodb.client.MongoCollection;
|
||||||
|
import com.mongodb.client.MongoDatabase;
|
||||||
|
import com.mongodb.client.model.Filters;
|
||||||
|
import com.mongodb.client.model.FindOneAndReplaceOptions;
|
||||||
|
import com.mongodb.client.model.FindOneAndUpdateOptions;
|
||||||
|
import com.mongodb.client.model.ReturnDocument;
|
||||||
|
import com.mongodb.client.model.Updates;
|
||||||
|
import com.mongodb.client.result.UpdateResult;
|
||||||
|
|
||||||
|
public class UpdateFields {
|
||||||
|
|
||||||
|
private static MongoClient mongoClient;
|
||||||
|
private static MongoDatabase database;
|
||||||
|
private static MongoCollection<Document> collection;
|
||||||
|
|
||||||
|
public static void updateOne() {
|
||||||
|
|
||||||
|
UpdateResult updateResult = collection.updateOne(Filters.eq("student_name", "Paul Starc"), Updates.set("address", "Hostel 2"));
|
||||||
|
|
||||||
|
System.out.println("updateResult:- " + updateResult);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void updateMany() {
|
||||||
|
|
||||||
|
UpdateResult updateResult = collection.updateMany(Filters.lt("age", 20), Updates.set("Review", true));
|
||||||
|
|
||||||
|
System.out.println("updateResult:- " + updateResult);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void replaceOne() {
|
||||||
|
|
||||||
|
Document replaceDocument = new Document();
|
||||||
|
replaceDocument.append("student_id", 8764)
|
||||||
|
.append("student_name", "Paul Starc")
|
||||||
|
.append("address", "Hostel 3")
|
||||||
|
.append("age", 18)
|
||||||
|
.append("roll_no", 199406);
|
||||||
|
|
||||||
|
UpdateResult updateResult = collection.replaceOne(Filters.eq("student_id", 8764), replaceDocument);
|
||||||
|
|
||||||
|
System.out.println("updateResult:- " + updateResult);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void findOneAndReplace() {
|
||||||
|
|
||||||
|
Document replaceDocument = new Document();
|
||||||
|
replaceDocument.append("student_id", 8764)
|
||||||
|
.append("student_name", "Paul Starc")
|
||||||
|
.append("address", "Hostel 4")
|
||||||
|
.append("age", 18)
|
||||||
|
.append("roll_no", 199406);
|
||||||
|
Document sort = new Document("roll_no", 1);
|
||||||
|
Document projection = new Document("_id", 0).append("student_id", 1)
|
||||||
|
.append("address", 1);
|
||||||
|
Document resultDocument = collection.findOneAndReplace(Filters.eq("student_id", 8764), replaceDocument, new FindOneAndReplaceOptions().upsert(true)
|
||||||
|
.sort(sort)
|
||||||
|
.projection(projection)
|
||||||
|
.returnDocument(ReturnDocument.AFTER));
|
||||||
|
|
||||||
|
System.out.println("resultDocument:- " + resultDocument);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void findOneAndUpdate() {
|
||||||
|
|
||||||
|
Document sort = new Document("roll_no", 1);
|
||||||
|
Document projection = new Document("_id", 0).append("student_id", 1)
|
||||||
|
.append("address", 1);
|
||||||
|
Document resultDocument = collection.findOneAndUpdate(Filters.eq("student_id", 8764), Updates.inc("roll_no", 5), new FindOneAndUpdateOptions().upsert(true)
|
||||||
|
.sort(sort)
|
||||||
|
.projection(projection)
|
||||||
|
.returnDocument(ReturnDocument.AFTER));
|
||||||
|
|
||||||
|
System.out.println("resultDocument:- " + resultDocument);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void setup() {
|
||||||
|
if (mongoClient == null) {
|
||||||
|
mongoClient = new MongoClient("localhost", 27017);
|
||||||
|
database = mongoClient.getDatabase("baeldung");
|
||||||
|
collection = database.getCollection("student");
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
//
|
||||||
|
// Connect to cluster (default is localhost:27017)
|
||||||
|
//
|
||||||
|
setup();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Update a document using updateOne method
|
||||||
|
//
|
||||||
|
updateOne();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Update documents using updateMany method
|
||||||
|
//
|
||||||
|
updateMany();
|
||||||
|
|
||||||
|
//
|
||||||
|
// replace a document using replaceOne method
|
||||||
|
//
|
||||||
|
replaceOne();
|
||||||
|
|
||||||
|
//
|
||||||
|
// replace a document using findOneAndReplace method
|
||||||
|
//
|
||||||
|
findOneAndReplace();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Update a document using findOneAndUpdate method
|
||||||
|
//
|
||||||
|
findOneAndUpdate();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -25,8 +25,7 @@ public class UpdateMultipleFields {
|
|||||||
// Update query
|
// Update query
|
||||||
//
|
//
|
||||||
|
|
||||||
UpdateResult updateResult = collection.updateMany(Filters.eq("employee_id", 794875),
|
UpdateResult updateResult = collection.updateMany(Filters.eq("employee_id", 794875), Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager")));
|
||||||
Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager")));
|
|
||||||
|
|
||||||
System.out.println("updateResult:- " + updateResult);
|
System.out.println("updateResult:- " + updateResult);
|
||||||
System.out.println("updateResult:- " + updateResult.getModifiedCount());
|
System.out.println("updateResult:- " + updateResult.getModifiedCount());
|
||||||
|
@ -0,0 +1,98 @@
|
|||||||
|
package com.baeldung.mongo;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
|
||||||
|
import org.bson.Document;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.mongodb.DB;
|
||||||
|
import com.mongodb.MongoClient;
|
||||||
|
import com.mongodb.client.MongoCollection;
|
||||||
|
import com.mongodb.client.MongoDatabase;
|
||||||
|
|
||||||
|
public class CollectionExistenceLiveTest {
|
||||||
|
|
||||||
|
private MongoClient mongoClient;
|
||||||
|
private String testCollectionName;
|
||||||
|
private String databaseName;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setup() {
|
||||||
|
if (mongoClient == null) {
|
||||||
|
mongoClient = new MongoClient("localhost", 27017);
|
||||||
|
databaseName = "baeldung";
|
||||||
|
testCollectionName = "student";
|
||||||
|
|
||||||
|
// Create a new collection if it doesn't exists.
|
||||||
|
try {
|
||||||
|
MongoDatabase database = mongoClient.getDatabase(databaseName);
|
||||||
|
database.createCollection(testCollectionName);
|
||||||
|
|
||||||
|
} catch (Exception exception) {
|
||||||
|
|
||||||
|
System.out.println("Collection already Exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCreateCollection_whenCollectionAlreadyExists_thenCheckingForCollectionExistence() {
|
||||||
|
|
||||||
|
MongoDatabase database = mongoClient.getDatabase(databaseName);
|
||||||
|
Boolean collectionStatus = false;
|
||||||
|
Boolean expectedStatus = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
database.createCollection(testCollectionName);
|
||||||
|
|
||||||
|
} catch (Exception exception) {
|
||||||
|
collectionStatus = true;
|
||||||
|
System.err.println("Collection already Exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(expectedStatus, collectionStatus);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCollectionExists_whenCollectionAlreadyExists_thenCheckingForCollectionExistence() {
|
||||||
|
|
||||||
|
DB db = mongoClient.getDB(databaseName);
|
||||||
|
Boolean collectionStatus = db.collectionExists(testCollectionName);
|
||||||
|
|
||||||
|
Boolean expectedStatus = true;
|
||||||
|
assertEquals(expectedStatus, collectionStatus);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenListCollectionNames_whenCollectionAlreadyExists_thenCheckingForCollectionExistence() {
|
||||||
|
|
||||||
|
MongoDatabase database = mongoClient.getDatabase(databaseName);
|
||||||
|
boolean collectionExists = database.listCollectionNames()
|
||||||
|
.into(new ArrayList<String>())
|
||||||
|
.contains(testCollectionName);
|
||||||
|
|
||||||
|
Boolean expectedStatus = true;
|
||||||
|
assertEquals(expectedStatus, collectionExists);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCount_whenCollectionAlreadyExists_thenCheckingForCollectionExistence() {
|
||||||
|
|
||||||
|
MongoDatabase database = mongoClient.getDatabase(databaseName);
|
||||||
|
|
||||||
|
MongoCollection<Document> collection = database.getCollection(testCollectionName);
|
||||||
|
Boolean collectionExists = collection.count() > 0 ? true : false;
|
||||||
|
|
||||||
|
Boolean expectedStatus = false;
|
||||||
|
assertEquals(expectedStatus, collectionExists);
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,92 @@
|
|||||||
|
package com.baeldung.mongo;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
|
||||||
|
import org.bson.Document;
|
||||||
|
import org.junit.AfterClass;
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.mongodb.BasicDBObject;
|
||||||
|
import com.mongodb.DBObject;
|
||||||
|
import com.mongodb.MongoClient;
|
||||||
|
import com.mongodb.client.MongoCollection;
|
||||||
|
import com.mongodb.client.MongoDatabase;
|
||||||
|
import com.mongodb.client.model.Filters;
|
||||||
|
import com.mongodb.client.model.Updates;
|
||||||
|
import com.mongodb.client.result.UpdateResult;
|
||||||
|
|
||||||
|
public class PushOperationLiveTest {
|
||||||
|
|
||||||
|
private static MongoClient mongoClient;
|
||||||
|
private static MongoDatabase db;
|
||||||
|
private static MongoCollection<Document> collection;
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void setup() {
|
||||||
|
if (mongoClient == null) {
|
||||||
|
mongoClient = new MongoClient("localhost", 27017);
|
||||||
|
db = mongoClient.getDatabase("baeldung");
|
||||||
|
collection = db.getCollection("orders");
|
||||||
|
|
||||||
|
collection.insertOne(
|
||||||
|
Document.parse("{\n" + " \"customerId\": 1023,\n" + " \"orderTimestamp\": NumberLong(\"1646460073000\"),\n" + " \"shippingDestination\": \"336, Street No.1 Pawai Mumbai\",\n" + " \"purchaseOrder\": 1000,\n"
|
||||||
|
+ " \"contactNumber\":\"9898987676\",\n" + " \"items\": [ \n" + " {\n" + " \"itemName\": \"BERGER\",\n" + " \"quantity\": 1,\n" + " \"price\": 500\n" + " },\n"
|
||||||
|
+ " {\n" + " \"itemName\": \"VEG PIZZA\",\n" + " \"quantity\": 1,\n" + " \"price\": 800\n" + " } \n" + " ]\n" + " }"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenOrderCollection_whenPushOperationUsingDBObject_thenCheckingForDocument() {
|
||||||
|
|
||||||
|
DBObject listItem = new BasicDBObject("items", new BasicDBObject("itemName", "PIZZA MANIA").append("quantity", 1)
|
||||||
|
.append("price", 800));
|
||||||
|
BasicDBObject searchFilter = new BasicDBObject("customerId", 1023);
|
||||||
|
BasicDBObject updateQuery = new BasicDBObject();
|
||||||
|
updateQuery.append("$push", listItem);
|
||||||
|
UpdateResult updateResult = collection.updateOne(searchFilter, updateQuery);
|
||||||
|
|
||||||
|
Document orderDetail = collection.find(Filters.eq("customerId", 1023))
|
||||||
|
.first();
|
||||||
|
assertNotNull(orderDetail);
|
||||||
|
assertFalse(orderDetail.isEmpty());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenOrderCollection_whenPushOperationUsingDocument_thenCheckingForDocument() {
|
||||||
|
|
||||||
|
Document item = new Document().append("itemName", "PIZZA MANIA")
|
||||||
|
.append("quantity", 1)
|
||||||
|
.append("price", 800);
|
||||||
|
UpdateResult updateResult = collection.updateOne(Filters.eq("customerId", 1023), Updates.push("items", item));
|
||||||
|
|
||||||
|
Document orderDetail = collection.find(Filters.eq("customerId", 1023))
|
||||||
|
.first();
|
||||||
|
assertNotNull(orderDetail);
|
||||||
|
assertFalse(orderDetail.isEmpty());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenOrderCollection_whenAddToSetOperation_thenCheckingForDocument() {
|
||||||
|
|
||||||
|
Document item = new Document().append("itemName", "PIZZA MANIA")
|
||||||
|
.append("quantity", 1)
|
||||||
|
.append("price", 800);
|
||||||
|
UpdateResult updateResult = collection.updateOne(Filters.eq("customerId", 1023), Updates.addToSet("items", item));
|
||||||
|
|
||||||
|
Document orderDetail = collection.find(Filters.eq("customerId", 1023))
|
||||||
|
.first();
|
||||||
|
assertNotNull(orderDetail);
|
||||||
|
assertFalse(orderDetail.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterClass
|
||||||
|
public static void cleanUp() {
|
||||||
|
mongoClient.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,143 @@
|
|||||||
|
package com.baeldung.update;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
|
||||||
|
import org.bson.Document;
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.mongodb.MongoClient;
|
||||||
|
import com.mongodb.client.MongoCollection;
|
||||||
|
import com.mongodb.client.MongoDatabase;
|
||||||
|
import com.mongodb.client.model.Filters;
|
||||||
|
import com.mongodb.client.model.FindOneAndReplaceOptions;
|
||||||
|
import com.mongodb.client.model.FindOneAndUpdateOptions;
|
||||||
|
import com.mongodb.client.model.ReturnDocument;
|
||||||
|
import com.mongodb.client.model.Updates;
|
||||||
|
import com.mongodb.client.result.UpdateResult;
|
||||||
|
|
||||||
|
public class UpdateFieldLiveTest {
|
||||||
|
|
||||||
|
private static MongoClient mongoClient;
|
||||||
|
private static MongoDatabase db;
|
||||||
|
private static MongoCollection<Document> collection;
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void setup() {
|
||||||
|
if (mongoClient == null) {
|
||||||
|
mongoClient = new MongoClient("localhost", 27017);
|
||||||
|
db = mongoClient.getDatabase("baeldung");
|
||||||
|
collection = db.getCollection("student");
|
||||||
|
|
||||||
|
collection.insertOne(Document.parse("{ \"student_id\": 8764,\"student_name\": \"Paul Starc\",\"address\": \"Hostel 1\",\"age\": 16,\"roll_no\":199406}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void updateOne() {
|
||||||
|
|
||||||
|
UpdateResult updateResult = collection.updateOne(Filters.eq("student_name", "Paul Starc"), Updates.set("address", "Hostel 2"));
|
||||||
|
|
||||||
|
Document studentDetail = collection.find(Filters.eq("student_name", "Paul Starc"))
|
||||||
|
.first();
|
||||||
|
assertNotNull(studentDetail);
|
||||||
|
assertFalse(studentDetail.isEmpty());
|
||||||
|
|
||||||
|
String address = studentDetail.getString("address");
|
||||||
|
String expectedAdderess = "Hostel 2";
|
||||||
|
|
||||||
|
assertEquals(expectedAdderess, address);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void updateMany() {
|
||||||
|
|
||||||
|
UpdateResult updateResult = collection.updateMany(Filters.lt("age", 20), Updates.set("Review", true));
|
||||||
|
|
||||||
|
Document studentDetail = collection.find(Filters.eq("student_name", "Paul Starc"))
|
||||||
|
.first();
|
||||||
|
assertNotNull(studentDetail);
|
||||||
|
assertFalse(studentDetail.isEmpty());
|
||||||
|
|
||||||
|
Boolean review = studentDetail.getBoolean("Review");
|
||||||
|
Boolean expectedAdderess = true;
|
||||||
|
|
||||||
|
assertEquals(expectedAdderess, review);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void replaceOne() {
|
||||||
|
|
||||||
|
Document replaceDocument = new Document();
|
||||||
|
replaceDocument.append("student_id", 8764)
|
||||||
|
.append("student_name", "Paul Starc")
|
||||||
|
.append("address", "Hostel 3")
|
||||||
|
.append("age", 18)
|
||||||
|
.append("roll_no", 199406);
|
||||||
|
|
||||||
|
UpdateResult updateResult = collection.replaceOne(Filters.eq("student_id", 8764), replaceDocument);
|
||||||
|
|
||||||
|
Document studentDetail = collection.find(Filters.eq("student_name", "Paul Starc"))
|
||||||
|
.first();
|
||||||
|
assertNotNull(studentDetail);
|
||||||
|
assertFalse(studentDetail.isEmpty());
|
||||||
|
|
||||||
|
Integer age = studentDetail.getInteger("age");
|
||||||
|
Integer expectedAge = 18;
|
||||||
|
|
||||||
|
assertEquals(expectedAge, age);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void findOneAndReplace() {
|
||||||
|
|
||||||
|
Document replaceDocument = new Document();
|
||||||
|
replaceDocument.append("student_id", 8764)
|
||||||
|
.append("student_name", "Paul Starc")
|
||||||
|
.append("address", "Hostel 4")
|
||||||
|
.append("age", 18)
|
||||||
|
.append("roll_no", 199406);
|
||||||
|
Document sort = new Document("roll_no", 1);
|
||||||
|
Document projection = new Document("_id", 0).append("student_id", 1)
|
||||||
|
.append("address", 1);
|
||||||
|
Document resultDocument = collection.findOneAndReplace(Filters.eq("student_id", 8764), replaceDocument, new FindOneAndReplaceOptions().upsert(true)
|
||||||
|
.sort(sort)
|
||||||
|
.projection(projection)
|
||||||
|
.returnDocument(ReturnDocument.AFTER));
|
||||||
|
|
||||||
|
Document studentDetail = collection.find(Filters.eq("student_name", "Paul Starc"))
|
||||||
|
.first();
|
||||||
|
assertNotNull(studentDetail);
|
||||||
|
assertFalse(studentDetail.isEmpty());
|
||||||
|
|
||||||
|
Integer age = studentDetail.getInteger("age");
|
||||||
|
Integer expectedAge = 18;
|
||||||
|
|
||||||
|
assertEquals(expectedAge, age);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void findOneAndUpdate() {
|
||||||
|
|
||||||
|
Document sort = new Document("roll_no", 1);
|
||||||
|
Document projection = new Document("_id", 0).append("student_id", 1)
|
||||||
|
.append("address", 1);
|
||||||
|
Document resultDocument = collection.findOneAndUpdate(Filters.eq("student_id", 8764), Updates.inc("roll_no", 5), new FindOneAndUpdateOptions().upsert(true)
|
||||||
|
.sort(sort)
|
||||||
|
.projection(projection)
|
||||||
|
.returnDocument(ReturnDocument.AFTER));
|
||||||
|
|
||||||
|
Document studentDetail = collection.find(Filters.eq("student_name", "Paul Starc"))
|
||||||
|
.first();
|
||||||
|
assertNotNull(studentDetail);
|
||||||
|
assertFalse(studentDetail.isEmpty());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -2,8 +2,6 @@ package com.baeldung.update;
|
|||||||
|
|
||||||
import static org.junit.Assert.assertFalse;
|
import static org.junit.Assert.assertFalse;
|
||||||
import static org.junit.Assert.assertNotNull;
|
import static org.junit.Assert.assertNotNull;
|
||||||
import static org.junit.Assert.assertNull;
|
|
||||||
import static org.junit.Assert.assertSame;
|
|
||||||
|
|
||||||
import org.bson.Document;
|
import org.bson.Document;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
@ -15,7 +13,6 @@ import com.mongodb.client.MongoCollection;
|
|||||||
import com.mongodb.client.MongoDatabase;
|
import com.mongodb.client.MongoDatabase;
|
||||||
import com.mongodb.client.model.Filters;
|
import com.mongodb.client.model.Filters;
|
||||||
import com.mongodb.client.model.Updates;
|
import com.mongodb.client.model.Updates;
|
||||||
import com.mongodb.client.result.UpdateResult;
|
|
||||||
|
|
||||||
public class UpdateMultipleFieldsLiveTest {
|
public class UpdateMultipleFieldsLiveTest {
|
||||||
|
|
||||||
@ -30,8 +27,7 @@ public class UpdateMultipleFieldsLiveTest {
|
|||||||
db = mongoClient.getDatabase("baeldung");
|
db = mongoClient.getDatabase("baeldung");
|
||||||
collection = db.getCollection("employee");
|
collection = db.getCollection("employee");
|
||||||
|
|
||||||
collection.insertOne(Document.parse(
|
collection.insertOne(Document.parse("{'employee_id':794875,'employee_name': 'David Smith','job': 'Sales Representative','department_id': 2,'salary': 20000,'hire_date': NumberLong(\"1643969311817\")}"));
|
||||||
"{'employee_id':794875,'employee_name': 'David smith','job': 'Sales Representative','department_id': 2,'salary': 20000,'hire_date': NumberLong(\"1643969311817\")}"));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -47,7 +43,8 @@ public class UpdateMultipleFieldsLiveTest {
|
|||||||
|
|
||||||
collection.updateMany(searchQuery, setQuery);
|
collection.updateMany(searchQuery, setQuery);
|
||||||
|
|
||||||
Document nameDoc = collection.find(Filters.eq("employee_id", 794875)).first();
|
Document nameDoc = collection.find(Filters.eq("employee_id", 794875))
|
||||||
|
.first();
|
||||||
assertNotNull(nameDoc);
|
assertNotNull(nameDoc);
|
||||||
assertFalse(nameDoc.isEmpty());
|
assertFalse(nameDoc.isEmpty());
|
||||||
|
|
||||||
@ -62,10 +59,10 @@ public class UpdateMultipleFieldsLiveTest {
|
|||||||
@Test
|
@Test
|
||||||
public void updateMultipleFieldsUsingDocument() {
|
public void updateMultipleFieldsUsingDocument() {
|
||||||
|
|
||||||
collection.updateMany(Filters.eq("employee_id", 794875),
|
collection.updateMany(Filters.eq("employee_id", 794875), Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager")));
|
||||||
Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager")));
|
|
||||||
|
|
||||||
Document nameDoc = collection.find(Filters.eq("employee_id", 794875)).first();
|
Document nameDoc = collection.find(Filters.eq("employee_id", 794875))
|
||||||
|
.first();
|
||||||
assertNotNull(nameDoc);
|
assertNotNull(nameDoc);
|
||||||
assertFalse(nameDoc.isEmpty());
|
assertFalse(nameDoc.isEmpty());
|
||||||
|
|
||||||
@ -78,3 +75,4 @@ public class UpdateMultipleFieldsLiveTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
8
pom.xml
8
pom.xml
@ -462,6 +462,7 @@
|
|||||||
<module>jaxb</module>
|
<module>jaxb</module>
|
||||||
<module>jee-7</module>
|
<module>jee-7</module>
|
||||||
<module>jee-7-security</module>
|
<module>jee-7-security</module>
|
||||||
|
<module>jakarta-ee</module>
|
||||||
<module>jersey</module>
|
<module>jersey</module>
|
||||||
<module>jgit</module>
|
<module>jgit</module>
|
||||||
<module>jgroups</module>
|
<module>jgroups</module>
|
||||||
@ -518,7 +519,7 @@
|
|||||||
<module>micronaut</module>
|
<module>micronaut</module>
|
||||||
<module>microprofile</module>
|
<module>microprofile</module>
|
||||||
<module>msf4j</module>
|
<module>msf4j</module>
|
||||||
<!-- <module>muleesb</module> --> <!-- Module broken, fixing in https://team.baeldung.com/browse/JAVA-10335 -->
|
<module>muleesb</module>
|
||||||
<module>mustache</module>
|
<module>mustache</module>
|
||||||
<module>mybatis</module>
|
<module>mybatis</module>
|
||||||
|
|
||||||
@ -945,6 +946,7 @@
|
|||||||
<module>jaxb</module>
|
<module>jaxb</module>
|
||||||
<module>jee-7</module>
|
<module>jee-7</module>
|
||||||
<module>jee-7-security</module>
|
<module>jee-7-security</module>
|
||||||
|
<module>jakarta-ee</module>
|
||||||
<module>jersey</module>
|
<module>jersey</module>
|
||||||
<module>jgit</module>
|
<module>jgit</module>
|
||||||
<module>jgroups</module>
|
<module>jgroups</module>
|
||||||
@ -1001,7 +1003,7 @@
|
|||||||
<module>micronaut</module>
|
<module>micronaut</module>
|
||||||
<module>microprofile</module>
|
<module>microprofile</module>
|
||||||
<module>msf4j</module>
|
<module>msf4j</module>
|
||||||
<!-- <module>muleesb</module> --> <!-- Module broken, fixing in https://team.baeldung.com/browse/JAVA-10335 -->
|
<module>muleesb</module>
|
||||||
<module>mustache</module>
|
<module>mustache</module>
|
||||||
<module>mybatis</module>
|
<module>mybatis</module>
|
||||||
|
|
||||||
@ -1347,6 +1349,7 @@
|
|||||||
<module>spring-boot-modules/spring-boot-cassandre</module>
|
<module>spring-boot-modules/spring-boot-cassandre</module>
|
||||||
<module>spring-boot-modules/spring-boot-camel</module>
|
<module>spring-boot-modules/spring-boot-camel</module>
|
||||||
<module>testing-modules/testing-assertions</module>
|
<module>testing-modules/testing-assertions</module>
|
||||||
|
<module>persistence-modules/fauna</module>
|
||||||
</modules>
|
</modules>
|
||||||
</profile>
|
</profile>
|
||||||
|
|
||||||
@ -1409,6 +1412,7 @@
|
|||||||
<module>spring-boot-modules/spring-boot-cassandre</module>
|
<module>spring-boot-modules/spring-boot-cassandre</module>
|
||||||
<module>spring-boot-modules/spring-boot-camel</module>
|
<module>spring-boot-modules/spring-boot-camel</module>
|
||||||
<module>testing-modules/testing-assertions</module>
|
<module>testing-modules/testing-assertions</module>
|
||||||
|
<module>persistence-modules/fauna</module>
|
||||||
</modules>
|
</modules>
|
||||||
</profile>
|
</profile>
|
||||||
</profiles>
|
</profiles>
|
||||||
|
@ -1,3 +0,0 @@
|
|||||||
### Relevant Articles:
|
|
||||||
|
|
||||||
- [Spring @Autowired Field Null – Common Causes and Solutions](https://www.baeldung.com/spring-autowired-field-null)
|
|
@ -1,24 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<artifactId>spring-5-autowiring-beans</artifactId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<name>spring-5-autowiring-beans</name>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>parent-boot-2</artifactId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<relativePath>../parent-boot-2</relativePath>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
</project>
|
|
@ -1,18 +0,0 @@
|
|||||||
package com.baeldung.autowiring.controller;
|
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.stereotype.Controller;
|
|
||||||
|
|
||||||
import com.baeldung.autowiring.service.MyService;
|
|
||||||
|
|
||||||
@Controller
|
|
||||||
public class CorrectController {
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
MyService myService;
|
|
||||||
|
|
||||||
public String control() {
|
|
||||||
return myService.serve();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,15 +0,0 @@
|
|||||||
package com.baeldung.autowiring.controller;
|
|
||||||
|
|
||||||
import org.springframework.stereotype.Controller;
|
|
||||||
|
|
||||||
import com.baeldung.autowiring.service.MyService;
|
|
||||||
|
|
||||||
@Controller
|
|
||||||
public class FlawedController {
|
|
||||||
|
|
||||||
public String control() {
|
|
||||||
MyService userService = new MyService();
|
|
||||||
return userService.serve();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,10 +0,0 @@
|
|||||||
package com.baeldung.autowiring.service;
|
|
||||||
|
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
|
|
||||||
@Component
|
|
||||||
public class MyComponent {
|
|
||||||
|
|
||||||
public void doWork() {}
|
|
||||||
|
|
||||||
}
|
|
@ -1,19 +0,0 @@
|
|||||||
package com.baeldung.autowiring.service;
|
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The bean corresponding to this class is defined in MyServiceConfiguration
|
|
||||||
* Alternatively, you could choose to decorate this class with @Component or @Service
|
|
||||||
*/
|
|
||||||
public class MyService {
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
MyComponent myComponent;
|
|
||||||
|
|
||||||
public String serve() {
|
|
||||||
myComponent.doWork();
|
|
||||||
return "success";
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,14 +0,0 @@
|
|||||||
package com.baeldung.autowiring.service;
|
|
||||||
|
|
||||||
import org.springframework.context.annotation.Bean;
|
|
||||||
import org.springframework.context.annotation.Configuration;
|
|
||||||
|
|
||||||
@Configuration
|
|
||||||
public class MyServiceConfiguration {
|
|
||||||
|
|
||||||
@Bean
|
|
||||||
MyService myService() {
|
|
||||||
return new MyService();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,23 +0,0 @@
|
|||||||
package com.baeldung.autowiring.controller;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
|
||||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
|
||||||
|
|
||||||
@ExtendWith(SpringExtension.class)
|
|
||||||
@SpringBootTest
|
|
||||||
public class CorrectControllerIntegrationTest {
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
CorrectController controller;
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void whenControl_ThenRunSuccessfully() {
|
|
||||||
assertDoesNotThrow(() -> controller.control());
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,28 +0,0 @@
|
|||||||
package com.baeldung.autowiring.controller;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
|
||||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
|
||||||
|
|
||||||
@ExtendWith(SpringExtension.class)
|
|
||||||
@SpringBootTest
|
|
||||||
public class FlawedControllerIntegrationTest {
|
|
||||||
|
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(FlawedControllerIntegrationTest.class);
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
FlawedController myController;
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void whenControl_ThenThrowNullPointerException() {
|
|
||||||
NullPointerException npe = assertThrows(NullPointerException.class, () -> myController.control());
|
|
||||||
LOGGER.error("Got a NullPointerException", npe);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.keycloak;
|
||||||
|
|
||||||
|
import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class KeycloakConfig {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
|
||||||
|
return new KeycloakSpringBootConfigResolver();
|
||||||
|
}
|
||||||
|
}
|
@ -23,11 +23,6 @@ class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
|
|||||||
auth.authenticationProvider(keycloakAuthenticationProvider);
|
auth.authenticationProvider(keycloakAuthenticationProvider);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
|
||||||
public KeycloakSpringBootConfigResolver KeycloakConfigResolver() {
|
|
||||||
return new KeycloakSpringBootConfigResolver();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Specifies the session authentication strategy
|
// Specifies the session authentication strategy
|
||||||
@Bean
|
@Bean
|
||||||
@Override
|
@Override
|
||||||
|
@ -0,0 +1,55 @@
|
|||||||
|
package com.baeldung.cloud.openfeign.fileupload.config;
|
||||||
|
|
||||||
|
public class ExceptionMessage {
|
||||||
|
private String timestamp;
|
||||||
|
private int status;
|
||||||
|
private String error;
|
||||||
|
private String message;
|
||||||
|
private String path;
|
||||||
|
|
||||||
|
public String getTimestamp() {
|
||||||
|
return timestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTimestamp(String timestamp) {
|
||||||
|
this.timestamp = timestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getStatus() {
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setStatus(int status) {
|
||||||
|
this.status = status;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getError() {
|
||||||
|
return error;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setError(String error) {
|
||||||
|
this.error = error;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getMessage() {
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMessage(String message) {
|
||||||
|
this.message = message;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPath() {
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPath(String path) {
|
||||||
|
this.path = path;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "ExceptionMessage [timestamp=" + timestamp + ", status=" + status + ", error=" + error + ", message=" + message + ", path=" + path + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -7,6 +7,7 @@ import org.springframework.context.annotation.Bean;
|
|||||||
import org.springframework.web.client.RestTemplate;
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
import feign.codec.Encoder;
|
import feign.codec.Encoder;
|
||||||
|
import feign.codec.ErrorDecoder;
|
||||||
import feign.form.spring.SpringFormEncoder;
|
import feign.form.spring.SpringFormEncoder;
|
||||||
|
|
||||||
public class FeignSupportConfig {
|
public class FeignSupportConfig {
|
||||||
@ -19,4 +20,9 @@ public class FeignSupportConfig {
|
|||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public ErrorDecoder errorDecoder() {
|
||||||
|
return new RetreiveMessageErrorDecoder();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,35 @@
|
|||||||
|
package com.baeldung.cloud.openfeign.fileupload.config;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
|
||||||
|
import com.baeldung.cloud.openfeign.exception.BadRequestException;
|
||||||
|
import com.baeldung.cloud.openfeign.exception.NotFoundException;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
import feign.Response;
|
||||||
|
import feign.codec.ErrorDecoder;
|
||||||
|
|
||||||
|
public class RetreiveMessageErrorDecoder implements ErrorDecoder {
|
||||||
|
private final ErrorDecoder errorDecoder = new Default();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Exception decode(String methodKey, Response response) {
|
||||||
|
ExceptionMessage message = null;
|
||||||
|
try (InputStream bodyIs = response.body()
|
||||||
|
.asInputStream()) {
|
||||||
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
|
message = mapper.readValue(bodyIs, ExceptionMessage.class);
|
||||||
|
} catch (IOException e) {
|
||||||
|
return new Exception(e.getMessage());
|
||||||
|
}
|
||||||
|
switch (response.status()) {
|
||||||
|
case 400:
|
||||||
|
return new BadRequestException(message.getMessage() != null ? message.getMessage() : "Bad Request");
|
||||||
|
case 404:
|
||||||
|
return new NotFoundException(message.getMessage() != null ? message.getMessage() : "Not found");
|
||||||
|
default:
|
||||||
|
return errorDecoder.decode(methodKey, response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user