Merge branch 'eugenp:master' into master

This commit is contained in:
Mladen Savic 2021-12-07 16:14:17 +01:00 committed by GitHub
commit e8abe028d3
154 changed files with 2107 additions and 289 deletions

View File

@ -37,7 +37,7 @@
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>
<version>${commons.lang3.version}</version> <version>${commons-lang3.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>pl.pragmatists</groupId> <groupId>pl.pragmatists</groupId>
@ -63,10 +63,8 @@
</dependencies> </dependencies>
<properties> <properties>
<commons-collections4.version>4.3</commons-collections4.version>
<guava.version>28.0-jre</guava.version> <guava.version>28.0-jre</guava.version>
<retrofit.version>2.6.0</retrofit.version> <retrofit.version>2.6.0</retrofit.version>
<commons.lang3.version>3.8.1</commons.lang3.version>
<JUnitParams.version>1.1.0</JUnitParams.version> <JUnitParams.version>1.1.0</JUnitParams.version>
</properties> </properties>

3
apache-poi-2/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
*.docx
temp.xls
temp.xlsx

8
apache-poi-2/README.md Normal file
View File

@ -0,0 +1,8 @@
## Apache POI
This module contains articles about Apache POI
### Relevant Articles:
- [Adding a Column to an Excel Sheet Using Apache POI](https://www.baeldung.com/java-excel-add-column)
- More articles: [[<-- prev]](/apache-poi)

29
apache-poi-2/pom.xml Normal file
View File

@ -0,0 +1,29 @@
<?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>apache-poi-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apache-poi-2</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
</dependencies>
<properties>
<poi.version>5.0.0</poi.version>
</properties>
</project>

View File

@ -0,0 +1,16 @@
package com.baeldung.poi.excel.newcolumn;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelColumn {
public void addColumn(Sheet sheet, CellType cellType) {
for (Row currentRow : sheet) {
currentRow.createCell(currentRow.getLastCellNum(), cellType);
}
}
}

View File

@ -0,0 +1,76 @@
package com.baeldung.poi.excel.write.addimageincell;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
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.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* This Helper class Add an Image to a Cell of an Excel File With apache-poi api.
*
*/
public class ExcelCellImageHelper {
public static void main(String[] args) throws IOException, InvalidFormatException {
try (final Workbook workbook = new XSSFWorkbook();
FileOutputStream saveExcel = new FileOutputStream("target/baeldung-apachepoi.xlsx");) {
Sheet sheet = workbook.createSheet("Avengers");
XSSFDrawing drawing = (XSSFDrawing) sheet.createDrawingPatriarch();
XSSFClientAnchor ironManAnchor = new XSSFClientAnchor();
XSSFClientAnchor spiderManAnchor = new XSSFClientAnchor();
// Fill row1 data
Row row1 = sheet.createRow(0);
row1.setHeight((short) 1000);
row1.createCell(0)
.setCellValue("IRON-MAN");
updateCellWithImage(workbook, 1, drawing, ironManAnchor, "ironman.png");
// Fill row2 data
Row row2 = sheet.createRow(1);
row2.setHeight((short) 1000);
row2.createCell(0)
.setCellValue("SPIDER-MAN");
updateCellWithImage(workbook, 2, drawing, spiderManAnchor, "spiderman.png");
// Resize all columns to fit the content size
for (int i = 0; i < 2; i++) {
sheet.autoSizeColumn(i);
}
workbook.write(saveExcel);
}
}
/**
* This method position the anchor for a given rowNum and add the image correctly.
* @param workbook
* @param rowNum
* @param drawing
* @param inputImageAnchor
* @throws IOException
*/
private static void updateCellWithImage(Workbook workbook, int rowNum, XSSFDrawing drawing, XSSFClientAnchor inputImageAnchor, String inputImageName) throws IOException {
InputStream inputImageStream = ExcelCellImageHelper.class.getClassLoader()
.getResourceAsStream(inputImageName);
byte[] inputImageBytes = IOUtils.toByteArray(inputImageStream);
int inputImagePictureID = workbook.addPicture(inputImageBytes, Workbook.PICTURE_TYPE_PNG);
inputImageStream.close();
inputImageAnchor.setCol1(1);
inputImageAnchor.setRow1(rowNum - 1);
inputImageAnchor.setCol2(2);
inputImageAnchor.setRow2(rowNum);
drawing.createPicture(inputImageAnchor, inputImagePictureID);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

View File

@ -0,0 +1,40 @@
package com.baeldung.poi.excel.newcolumn;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import static org.junit.Assert.assertEquals;
public class ExcelColumnUnitTest {
private static final String FILE_NAME = "newColumnTest.xlsx";
private String fileLocation;
@Before
public void setup() throws URISyntaxException {
fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME).toURI()).toString();
}
@Test
public void givenExistingRows_whenAddNewColumn_thenRowColumnNumberIncreased() throws IOException {
Workbook workbook = new XSSFWorkbook(fileLocation);
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(0);
assertEquals(5, row.getLastCellNum());
ExcelColumn excelColumn = new ExcelColumn();
excelColumn.addColumn(sheet, CellType.STRING);
assertEquals(6, row.getLastCellNum());
workbook.close();
}
}

Binary file not shown.

View File

@ -15,3 +15,4 @@ This module contains articles about Apache POI
- [Multiline Text in Excel Cell Using Apache POI](https://www.baeldung.com/apache-poi-write-multiline-text) - [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)
- [Add Borders to Excel Cells With Apache POI](https://www.baeldung.com/apache-poi-add-borders) - [Add Borders to Excel Cells With Apache POI](https://www.baeldung.com/apache-poi-add-borders)
- More articles: [[next -->]](/apache-poi-2)

View File

@ -0,0 +1,75 @@
package com.baeldung.poi.excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelUtility {
private static final String ENDLINE = System.getProperty("line.separator");
public static String readExcel(String filePath) throws IOException {
File file = new File(filePath);
FileInputStream inputStream = null;
StringBuilder toReturn = new StringBuilder();
try {
inputStream = new FileInputStream(file);
Workbook baeuldungWorkBook = new XSSFWorkbook(inputStream);
for (Sheet sheet : baeuldungWorkBook) {
toReturn.append("--------------------------------------------------------------------")
.append(ENDLINE);
toReturn.append("Worksheet :")
.append(sheet.getSheetName())
.append(ENDLINE);
toReturn.append("--------------------------------------------------------------------")
.append(ENDLINE);
int firstRow = sheet.getFirstRowNum();
int lastRow = sheet.getLastRowNum();
for (int index = firstRow + 1; index <= lastRow; index++) {
Row row = sheet.getRow(index);
toReturn.append("|| ");
for (int cellIndex = row.getFirstCellNum(); cellIndex < row.getLastCellNum(); cellIndex++) {
Cell cell = row.getCell(cellIndex, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
printCellValue(cell, toReturn);
}
toReturn.append(" ||")
.append(ENDLINE);
}
}
inputStream.close();
} catch (IOException e) {
throw e;
}
return toReturn.toString();
}
public static void printCellValue(Cell cell, StringBuilder toReturn) {
CellType cellType = cell.getCellType()
.equals(CellType.FORMULA) ? cell.getCachedFormulaResultType() : cell.getCellType();
if (cellType.equals(CellType.STRING)) {
toReturn.append(cell.getStringCellValue())
.append(" | ");
}
if (cellType.equals(CellType.NUMERIC)) {
if (DateUtil.isCellDateFormatted(cell)) {
toReturn.append(cell.getDateCellValue())
.append(" | ");
} else {
toReturn.append(cell.getNumericCellValue())
.append(" | ");
}
}
if (cellType.equals(CellType.BOOLEAN)) {
toReturn.append(cell.getBooleanCellValue())
.append(" | ");
}
}
}

View File

@ -0,0 +1,128 @@
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
}

View File

@ -0,0 +1,72 @@
package com.baeldung.poi.excel;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.junit.Before;
import org.junit.Test;
public class ExcelUtilityUnitTest {
private static final String FILE_NAME = "baeldung.xlsx";
private String fileLocation;
private static final String ENDLINE = System.getProperty("line.separator");
private StringBuilder output;
@Before
public void setupUnitTest() throws IOException, URISyntaxException, ParseException {
output = new StringBuilder();
output.append("--------------------------------------------------------------------")
.append(ENDLINE);
output.append("Worksheet :Sheet1")
.append(ENDLINE);
output.append("--------------------------------------------------------------------")
.append(ENDLINE);
output.append("|| Name1 | Surname1 | 3.55696564113E11 | ")
.append(new SimpleDateFormat("dd/MM/yyyy").parse("4/11/2021")
.toString())
.append(" | ‡ | ||")
.append(ENDLINE);
output.append("|| Name2 | Surname2 | 5.646513512E9 | ")
.append(new SimpleDateFormat("dd/MM/yyyy").parse("4/12/2021")
.toString())
.append(" | false | ||")
.append(ENDLINE);
output.append("|| Name3 | Surname3 | 3.55696564113E11 | ")
.append(new SimpleDateFormat("dd/MM/yyyy").parse("4/11/2021")
.toString())
.append(" | 7.17039641738E11 | ||")
.append(ENDLINE);
output.append("--------------------------------------------------------------------")
.append(ENDLINE);
output.append("Worksheet :Sheet2")
.append(ENDLINE);
output.append("--------------------------------------------------------------------")
.append(ENDLINE);
output.append("|| Name4 | Surname4 | 3.55675623232E11 | 13/04/2021 | ||")
.append(ENDLINE);
fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME)
.toURI())
.toString();
}
@Test
public void givenStringPath_whenReadExcel_thenReturnStringValue() throws IOException {
assertEquals(output.toString(), ExcelUtility.readExcel(fileLocation));
}
@Test
public void givenStringPath_whenReadExcel_thenThrowException() {
assertThrows(IOException.class, () -> {
ExcelUtility.readExcel("baeldung");
});
}
}

View File

@ -0,0 +1,112 @@
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
}

Binary file not shown.

View File

@ -39,7 +39,6 @@
<properties> <properties>
<maven.compiler.source.version>10</maven.compiler.source.version> <maven.compiler.source.version>10</maven.compiler.source.version>
<maven.compiler.target.version>10</maven.compiler.target.version> <maven.compiler.target.version>10</maven.compiler.target.version>
<commons-collections4.version>4.1</commons-collections4.version>
</properties> </properties>
</project> </project>

View File

@ -12,6 +12,7 @@
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId> <artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent> </parent>
<dependencies> <dependencies>
@ -35,18 +36,6 @@
<artifactId>jakarta.xml.ws-api</artifactId> <artifactId>jakarta.xml.ws-api</artifactId>
<version>${jakarta.ws-api.version}</version> <version>${jakarta.ws-api.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-rt</artifactId>
<version>${jaxws-rt.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-ri</artifactId>
<version>${jaxws-ri.version}</version>
<type>pom</type>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -82,10 +71,8 @@
<maven.compiler.target.version>11</maven.compiler.target.version> <maven.compiler.target.version>11</maven.compiler.target.version>
<guava.version>29.0-jre</guava.version> <guava.version>29.0-jre</guava.version>
<mockserver.version>5.11.1</mockserver.version> <mockserver.version>5.11.1</mockserver.version>
<jakarta.ws-api.version>3.0.0</jakarta.ws-api.version> <jakarta.ws-api.version>3.0.1</jakarta.ws-api.version>
<jaxws-rt.version>3.0.0</jaxws-rt.version> <jaxws-maven-plugin.version>3.0.2</jaxws-maven-plugin.version>
<jaxws-ri.version>2.3.1</jaxws-ri.version>
<jaxws-maven-plugin.version>2.3.2</jaxws-maven-plugin.version>
</properties> </properties>
</project> </project>

View File

@ -1,10 +1,10 @@
package com.baeldung.soap.ws.client.generated; package com.baeldung.soap.ws.client.generated;
import javax.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType; import jakarta.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType; import jakarta.xml.bind.annotation.XmlType;
/** /**

View File

@ -1,19 +1,19 @@
package com.baeldung.soap.ws.client.generated; package com.baeldung.soap.ws.client.generated;
import javax.jws.WebMethod; import jakarta.jws.WebMethod;
import javax.jws.WebParam; import jakarta.jws.WebParam;
import javax.jws.WebResult; import jakarta.jws.WebResult;
import javax.jws.WebService; import jakarta.jws.WebService;
import javax.jws.soap.SOAPBinding; import jakarta.jws.soap.SOAPBinding;
import javax.xml.bind.annotation.XmlSeeAlso; import jakarta.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.Action; import jakarta.xml.ws.Action;
/** /**
* This class was generated by the JAX-WS RI. * This class was generated by the JAX-WS RI.
* JAX-WS RI 2.3.2 * JAX-WS RI 3.0.2
* Generated source version: 2.2 * Generated source version: 3.0
* *
*/ */
@WebService(name = "CountryService", targetNamespace = "http://server.ws.soap.baeldung.com/") @WebService(name = "CountryService", targetNamespace = "http://server.ws.soap.baeldung.com/")

View File

@ -4,17 +4,17 @@ package com.baeldung.soap.ws.client.generated;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import javax.xml.namespace.QName; import javax.xml.namespace.QName;
import javax.xml.ws.Service; import jakarta.xml.ws.Service;
import javax.xml.ws.WebEndpoint; import jakarta.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient; import jakarta.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceException; import jakarta.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature; import jakarta.xml.ws.WebServiceFeature;
/** /**
* This class was generated by the JAX-WS RI. * This class was generated by the JAX-WS RI.
* JAX-WS RI 2.3.2 * JAX-WS RI 3.0.2
* Generated source version: 2.2 * Generated source version: 3.0
* *
*/ */
@WebServiceClient(name = "CountryServiceImplService", targetNamespace = "http://server.ws.soap.baeldung.com/", wsdlLocation = "http://localhost:8888/ws/country?wsdl") @WebServiceClient(name = "CountryServiceImplService", targetNamespace = "http://server.ws.soap.baeldung.com/", wsdlLocation = "http://localhost:8888/ws/country?wsdl")
@ -75,7 +75,7 @@ public class CountryServiceImplService
/** /**
* *
* @param features * @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. * A list of {@link jakarta.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return * @return
* returns CountryService * returns CountryService
*/ */

View File

@ -1,15 +1,14 @@
package com.baeldung.soap.ws.client.generated; package com.baeldung.soap.ws.client.generated;
import javax.xml.bind.annotation.XmlEnum; import jakarta.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType; import jakarta.xml.bind.annotation.XmlType;
/** /**
* <p>Java class for currency. * <p>Java class for currency.
* *
* <p>The following schema fragment specifies the expected content contained within this class. * <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre> * <pre>
* &lt;simpleType name="currency"&gt; * &lt;simpleType name="currency"&gt;
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt;

View File

@ -1,7 +1,7 @@
package com.baeldung.soap.ws.client.generated; package com.baeldung.soap.ws.client.generated;
import javax.xml.bind.annotation.XmlRegistry; import jakarta.xml.bind.annotation.XmlRegistry;
/** /**

View File

@ -1,2 +1,2 @@
@javax.xml.bind.annotation.XmlSchema(namespace = "http://server.ws.soap.baeldung.com/") @jakarta.xml.bind.annotation.XmlSchema(namespace = "http://server.ws.soap.baeldung.com/")
package com.baeldung.soap.ws.client.generated; package com.baeldung.soap.ws.client.generated;

View File

@ -13,6 +13,8 @@
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId> <artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent> </parent>
<dependencies> <dependencies>

View File

@ -43,9 +43,4 @@
</resources> </resources>
</build> </build>
<properties>
<!-- util -->
<commons-collections4.version>4.1</commons-collections4.version>
</properties>
</project> </project>

View File

@ -76,7 +76,6 @@
<maven.compiler.source>1.9</maven.compiler.source> <maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target> <maven.compiler.target>1.9</maven.compiler.target>
<guava.version>25.1-jre</guava.version> <guava.version>25.1-jre</guava.version>
<commons-collections4.version>4.1</commons-collections4.version>
</properties> </properties>
</project> </project>

View File

@ -44,7 +44,6 @@
<properties> <properties>
<eclipse.collections.version>7.1.0</eclipse.collections.version> <eclipse.collections.version>7.1.0</eclipse.collections.version>
<commons-collections4.version>4.1</commons-collections4.version>
<commons-exec.version>1.3</commons-exec.version> <commons-exec.version>1.3</commons-exec.version>
</properties> </properties>

View File

@ -11,7 +11,7 @@
- [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance) - [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance)
- [Fail-Safe Iterator vs Fail-Fast Iterator](https://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator) - [Fail-Safe Iterator vs Fail-Fast Iterator](https://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
- [Quick Guide to the Java Stack](https://www.baeldung.com/java-stack) - [Quick Guide to the Java Stack](https://www.baeldung.com/java-stack)
- [Convert an Array of Primitives to a List](https://www.baeldung.com/java-primitive-array-to-list)
- [A Guide to BitSet in Java](https://www.baeldung.com/java-bitset) - [A Guide to BitSet in Java](https://www.baeldung.com/java-bitset)
- [Get the First Key and Value From a HashMap](https://www.baeldung.com/java-hashmap-get-first-entry) - [Get the First Key and Value From a HashMap](https://www.baeldung.com/java-hashmap-get-first-entry)
- [Performance of removeAll() in a HashSet](https://www.baeldung.com/java-hashset-removeall-performance) - [Performance of removeAll() in a HashSet](https://www.baeldung.com/java-hashset-removeall-performance)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-2) [[next -->]](/core-java-modules/core-java-collections-4)

View File

@ -1,4 +1,4 @@
package com.baeldung.stack; package com.baeldung.collections.stack;
import org.junit.Test; import org.junit.Test;

View File

@ -0,0 +1,5 @@
package com.baeldung.collections.mulipletypesinmap;
public interface DynamicTypeValue {
String valueDescription();
}

View File

@ -0,0 +1,24 @@
package com.baeldung.collections.mulipletypesinmap;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
public class InstantTypeValue implements DynamicTypeValue {
private static DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
.withZone(ZoneId.systemDefault());
private Instant value;
public InstantTypeValue(Instant value) {
this.value = value;
}
@Override
public String valueDescription() {
if (value == null) {
return "The value is null.";
}
return String.format("The value is an instant: %s", FORMATTER.format(value));
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.collections.mulipletypesinmap;
import java.util.Arrays;
public class IntArrayTypeValue implements DynamicTypeValue {
private int[] value;
public IntArrayTypeValue(int[] value) {
this.value = value;
}
@Override
public String valueDescription() {
if (value == null) {
return "The value is null.";
}
return String.format("The value is an array of %d integers: %s", value.length, Arrays.toString(value));
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.collections.mulipletypesinmap;
public class IntegerTypeValue implements DynamicTypeValue {
private Integer value;
public IntegerTypeValue(Integer value) {
this.value = value;
}
@Override
public String valueDescription() {
if(value == null){
return "The value is null.";
}
return String.format("The value is a %s integer: %d", value > 0 ? "positive" : "negative", value);
}
}

View File

@ -0,0 +1,75 @@
package com.baeldung.multipletypesinmap;
import com.baeldung.collections.mulipletypesinmap.DynamicTypeValue;
import com.baeldung.collections.mulipletypesinmap.InstantTypeValue;
import com.baeldung.collections.mulipletypesinmap.IntArrayTypeValue;
import com.baeldung.collections.mulipletypesinmap.IntegerTypeValue;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
class MultipleTypesInMapUnitTest {
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
.withZone(ZoneId.systemDefault());
private static final Integer intValue = 777;
private static final int[] intArray = new int[]{2, 3, 5, 7, 11, 13};
private static final Instant instant = Instant.now();
private static final String KEY_INT = "E1 (Integer)";
private static final String KEY_INT_ARRAY = "E2 (IntArray)";
private static final String KEY_INSTANT = "E3 (Instant)";
@Test
void givenThreeTypes_whenUsingRawMap_thenPrintDescription() {
Map<String, Object> rawMap = new HashMap<>();
rawMap.put(KEY_INT, intValue);
rawMap.put(KEY_INT_ARRAY, intArray);
rawMap.put(KEY_INSTANT, instant);
rawMap.forEach((k, v) -> {
if (v instanceof Integer) {
Integer theV = (Integer) v;
String desc = String.format("The value is a %s integer: %d", theV > 0 ? "positive" : "negative", theV);
System.out.println(k + " -> " + desc);
assertThat(k).isEqualTo(KEY_INT);
assertThat(desc).isEqualTo("The value is a positive integer: 777");
} else if (v instanceof int[]) {
int[] theV = (int[]) v;
String desc = String.format("The value is an array of %d integers: %s", theV.length, Arrays.toString(theV));
System.out.println(k + " -> " + desc);
assertThat(k).isEqualTo(KEY_INT_ARRAY);
assertThat(desc).isEqualTo("The value is an array of 6 integers: [2, 3, 5, 7, 11, 13]");
} else if (v instanceof Instant) {
Instant theV = (Instant) v;
String desc = String.format("The value is an instant: %s", FORMATTER.format(theV));
System.out.println(k + " -> " + desc);
assertThat(k).isEqualTo(KEY_INSTANT);
assertThat(desc).matches("^The value is an instant: \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}");
} else {
throw new IllegalStateException("Unknown Type found.");
}
});
}
@Test
void givenThreeTypes_whenUsingAnInterface_thenPrintDescription() {
Map<String, DynamicTypeValue> theMap = new HashMap<>();
theMap.put(KEY_INT, new IntegerTypeValue(intValue));
theMap.put(KEY_INT_ARRAY, new IntArrayTypeValue(intArray));
theMap.put(KEY_INSTANT, new InstantTypeValue(instant));
theMap.forEach((k, v) -> System.out.println(k + " -> " + v.valueDescription()));
assertThat(theMap.get(KEY_INT).valueDescription()).isEqualTo("The value is a positive integer: 777");
assertThat(theMap.get(KEY_INT_ARRAY).valueDescription()).isEqualTo("The value is an array of 6 integers: [2, 3, 5, 7, 11, 13]");
assertThat(theMap.get(KEY_INSTANT).valueDescription()).matches("^The value is an instant: \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}");
}
}

View File

@ -22,8 +22,4 @@
</dependency> </dependency>
</dependencies> </dependencies>
<properties>
<commons-collections4.version>4.1</commons-collections4.version>
</properties>
</project> </project>

View File

@ -28,8 +28,4 @@
</dependency> </dependency>
</dependencies> </dependencies>
<properties>
<commons-collections4.version>4.1</commons-collections4.version>
</properties>
</project> </project>

View File

@ -54,7 +54,6 @@
</dependencies> </dependencies>
<properties> <properties>
<commons-collections4.version>4.1</commons-collections4.version>
<trove4j.version>3.0.2</trove4j.version> <trove4j.version>3.0.2</trove4j.version>
<fastutil.version>8.1.0</fastutil.version> <fastutil.version>8.1.0</fastutil.version>
<colt.version>1.2.0</colt.version> <colt.version>1.2.0</colt.version>

View File

@ -27,8 +27,4 @@
</dependency> </dependency>
</dependencies> </dependencies>
<properties>
<commons-collections4.version>4.1</commons-collections4.version>
</properties>
</project> </project>

View File

@ -55,7 +55,6 @@
<properties> <properties>
<streamex.version>0.6.5</streamex.version> <streamex.version>0.6.5</streamex.version>
<commons-collections4.version>4.1</commons-collections4.version>
<avaitility.version>1.7.0</avaitility.version> <avaitility.version>1.7.0</avaitility.version>
<eclipse-collections.version>8.2.0</eclipse-collections.version> <eclipse-collections.version>8.2.0</eclipse-collections.version>
<hppc.version>0.7.2</hppc.version> <hppc.version>0.7.2</hppc.version>

View File

@ -22,8 +22,4 @@
</dependency> </dependency>
</dependencies> </dependencies>
<properties>
<commons-collections4.version>4.1</commons-collections4.version>
</properties>
</project> </project>

View File

@ -49,7 +49,6 @@
<properties> <properties>
<maven.compiler.source>11</maven.compiler.source> <maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target> <maven.compiler.target>11</maven.compiler.target>
<commons-collections4.version>4.3</commons-collections4.version>
<gson.version>2.8.5</gson.version> <gson.version>2.8.5</gson.version>
</properties> </properties>

View File

@ -12,4 +12,5 @@ This module contains articles about Java collections
- [Defining a Char Stack in Java](https://www.baeldung.com/java-char-stack) - [Defining a Char Stack in Java](https://www.baeldung.com/java-char-stack)
- [Guide to the Java Queue Interface](https://www.baeldung.com/java-queue) - [Guide to the Java Queue Interface](https://www.baeldung.com/java-queue)
- [An Introduction to Synchronized Java Collections](https://www.baeldung.com/java-synchronized-collections) - [An Introduction to Synchronized Java Collections](https://www.baeldung.com/java-synchronized-collections)
- [[More -->]](/core-java-modules/core-java-collections-2) - [Convert an Array of Primitives to a List](https://www.baeldung.com/java-primitive-array-to-list)
- More articles: [[next -->]](/core-java-modules/core-java-collections-2)

View File

@ -25,6 +25,11 @@
<artifactId>jmh-generator-annprocess</artifactId> <artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator.version}</version> <version>${jmh-generator.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -1,13 +1,15 @@
package com.baeldung.collections.iterators; package com.baeldung.collections.convertarrayprimitives;
import java.util.List;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.IntStream; import java.util.stream.IntStream;
import com.google.common.primitives.Ints;
import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.ArrayUtils;
import com.google.common.primitives.Ints;
public class ConvertPrimitivesArrayToList { public class ConvertPrimitivesArrayToList {
public static void failConvert() { public static void failConvert() {

View File

@ -1,14 +1,11 @@
package com.baeldung.collections.iterators; package com.baeldung.collections.convertarrayprimitives;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
import com.google.common.primitives.Ints;
import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import org.junit.Test;
public class ConvertPrimitivesArrayToListUnitTest { public class ConvertPrimitivesArrayToListUnitTest {
@Test @Test

View File

@ -56,7 +56,6 @@
<properties> <properties>
<guava.version>21.0</guava.version> <guava.version>21.0</guava.version>
<commons-math3.version>3.6.1</commons-math3.version> <commons-math3.version>3.6.1</commons-math3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version> <collections-generic.version>4.01</collections-generic.version>
<avaitility.version>1.7.0</avaitility.version> <avaitility.version>1.7.0</avaitility.version>
</properties> </properties>

View File

@ -1,11 +1,12 @@
package com.baeldung.exceptions.illegalmonitorstate; package com.baeldung.exceptions.illegalmonitorstate;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.*;
public class IllegalMonitorStateExceptionUnitTest { public class IllegalMonitorStateExceptionUnitTest {
@Test @Test
@ -20,11 +21,11 @@ public class IllegalMonitorStateExceptionUnitTest {
Thread senderThread = new Thread(sender, "sender-thread"); Thread senderThread = new Thread(sender, "sender-thread");
senderThread.start(); senderThread.start();
senderThread.join(1000); // we need to wait for the sender and receiver threads to finish
receiverThread.join(1000); senderThread.join(10_000);
receiverThread.join(10_000);
// we need to wait for enough time so that sender has had a chance to send the data assertEquals("test", receiver.getMessage());
assertTimeout(Duration.ofSeconds(10), () -> assertEquals("test", receiver.getMessage()));
assertFalse(sender.hasIllegalMonitorStateExceptionOccurred()); assertFalse(sender.hasIllegalMonitorStateExceptionOccurred());
assertFalse(receiver.hasIllegalMonitorStateExceptionOccurred()); assertFalse(receiver.hasIllegalMonitorStateExceptionOccurred());
} }

View File

@ -2,6 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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"> 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> <modelVersion>4.0.0</modelVersion>
<artifactId>core-java-lang-oop-methods</artifactId> <artifactId>core-java-lang-oop-methods</artifactId>
<name>core-java-lang-oop-methods</name> <name>core-java-lang-oop-methods</name>
@ -33,7 +34,9 @@
</dependencies> </dependencies>
<properties> <properties>
<lombok.version>1.18.12</lombok.version> <lombok.version>1.18.22</lombok.version>
<commons-lang.version>2.6</commons-lang.version>
<assertj-core.version>3.10.0</assertj-core.version>
<equalsverifier.version>3.0.3</equalsverifier.version> <equalsverifier.version>3.0.3</equalsverifier.version>
</properties> </properties>

View File

@ -0,0 +1,17 @@
package com.baeldung.utilities;
public final class StringUtils {
private StringUtils() {
throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
}
public static boolean isEmpty(String source) {
return source == null || source.length() == 0;
}
public static String wrap(String source, String wrapWith) {
return isEmpty(source) ? source : wrapWith + source + wrapWith;
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.utilities.alternatives;
public enum StringUtilsEnum {;
public static boolean isEmpty(String source) {
return source == null || source.length() == 0;
}
public static String wrap(String source, String wrapWith) {
return isEmpty(source) ? source : wrapWith + source + wrapWith;
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.utilities.alternatives;
public interface StringUtilsInterface {
static boolean isEmpty(String source) {
return source == null || source.length() == 0;
}
static String wrap(String source, String wrapWith) {
return isEmpty(source) ? source : wrapWith + source + wrapWith;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.utilities.lombok;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@NoArgsConstructor(access= AccessLevel.PRIVATE)
public final class StringUtilsWithNoArgsConstructor {
public static boolean isEmpty(String source) {
return source == null || source.length() == 0;
}
public static String wrap(String source, String wrapWith) {
return isEmpty(source) ? source : wrapWith + source + wrapWith;
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.utilities.lombok;
import lombok.experimental.UtilityClass;
@UtilityClass
public class StringUtilsWithUtilityClass {
public static boolean isEmpty(String source) {
return source == null || source.length() == 0;
}
public static String wrap(String source, String wrapWith) {
return isEmpty(source) ? source : wrapWith + source + wrapWith;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.utilities.warning;
@SuppressWarnings("java:S1118")
public final class StringUtilsSuppressWarning {
public static boolean isEmpty(String source) {
return source == null || source.length() == 0;
}
public static String wrap(String source, String wrapWith) {
return isEmpty(source) ? source : wrapWith + source + wrapWith;
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.utilities;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.*;
class StringUtilsUnitTest {
@Test
void givenAnEmptyString_whenCallingIsEmpty_thenResultIsTrue() {
assertThat(StringUtils.isEmpty("")).isTrue();
}
@Test
void givenNonEmptyString_whenCallingIsEmpty_thenResultIsFalse() {
assertThat(StringUtils.isEmpty("asd")).isFalse();
}
@Test
void givenAnEmptyString_whenCallingWrap_thenResultIsAnEmptyString() {
assertThat(StringUtils.wrap("", "wrapper")).isEmpty();
}
@Test
void givenNonEmptyString_whenCallingWrap_thenResultIsWrappedString() {
assertThat(StringUtils.wrap("asd", "wrapper")).isEqualTo("wrapperasdwrapper");
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.utilities.alternatives;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class StringUtilsEnumUnitTest {
@Test
void givenAnEmptyString_whenCallingIsEmpty_thenResultIsTrue() {
assertThat(StringUtilsEnum.isEmpty("")).isTrue();
}
@Test
void givenNonEmptyString_whenCallingIsEmpty_thenResultIsFalse() {
assertThat(StringUtilsEnum.isEmpty("asd")).isFalse();
}
@Test
void givenAnEmptyString_whenCallingWrap_thenResultIsAnEmptyString() {
assertThat(StringUtilsEnum.wrap("", "wrapper")).isEmpty();
}
@Test
void givenNonEmptyString_whenCallingWrap_thenResultIsWrappedString() {
assertThat(StringUtilsEnum.wrap("asd", "wrapper")).isEqualTo("wrapperasdwrapper");
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.utilities.alternatives;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class StringUtilsInterfaceUnitTest {
@Test
void givenAnEmptyString_whenCallingIsEmpty_thenResultIsTrue() {
assertThat(StringUtilsInterface.isEmpty("")).isTrue();
}
@Test
void givenNonEmptyString_whenCallingIsEmpty_thenResultIsFalse() {
assertThat(StringUtilsInterface.isEmpty("asd")).isFalse();
}
@Test
void givenAnEmptyString_whenCallingWrap_thenResultIsAnEmptyString() {
assertThat(StringUtilsInterface.wrap("", "wrapper")).isEmpty();
}
@Test
void givenNonEmptyString_whenCallingWrap_thenResultIsWrappedString() {
assertThat(StringUtilsInterface.wrap("asd", "wrapper")).isEqualTo("wrapperasdwrapper");
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.utilities.lombok;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class StringUtilsWithNoArgsConstructorUnitTest {
@Test
void givenAnEmptyString_whenCallingIsEmpty_thenResultIsTrue() {
assertThat(StringUtilsWithNoArgsConstructor.isEmpty("")).isTrue();
}
@Test
void givenNonEmptyString_whenCallingIsEmpty_thenResultIsFalse() {
assertThat(StringUtilsWithNoArgsConstructor.isEmpty("asd")).isFalse();
}
@Test
void givenAnEmptyString_whenCallingWrap_thenResultIsAnEmptyString() {
assertThat(StringUtilsWithNoArgsConstructor.wrap("", "wrapper")).isEmpty();
}
@Test
void givenNonEmptyString_whenCallingWrap_thenResultIsWrappedString() {
assertThat(StringUtilsWithNoArgsConstructor.wrap("asd", "wrapper")).isEqualTo("wrapperasdwrapper");
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.utilities.lombok;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class StringUtilsWithUtilityClassUnitTest {
@Test
void givenAnEmptyString_whenCallingIsEmpty_thenResultIsTrue() {
assertThat(StringUtilsWithUtilityClass.isEmpty("")).isTrue();
}
@Test
void givenNonEmptyString_whenCallingIsEmpty_thenResultIsFalse() {
assertThat(StringUtilsWithUtilityClass.isEmpty("asd")).isFalse();
}
@Test
void givenAnEmptyString_whenCallingWrap_thenResultIsAnEmptyString() {
assertThat(StringUtilsWithUtilityClass.wrap("", "wrapper")).isEmpty();
}
@Test
void givenNonEmptyString_whenCallingWrap_thenResultIsWrappedString() {
assertThat(StringUtilsWithUtilityClass.wrap("asd", "wrapper")).isEqualTo("wrapperasdwrapper");
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.utilities.warning;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class StringUtilsStringUtilsSuppressWarningUnitTest {
@Test
void givenAnEmptyString_whenCallingIsEmpty_thenResultIsTrue() {
assertThat(StringUtilsSuppressWarning.isEmpty("")).isTrue();
}
@Test
void givenNonEmptyString_whenCallingIsEmpty_thenResultIsFalse() {
assertThat(StringUtilsSuppressWarning.isEmpty("asd")).isFalse();
}
@Test
void givenAnEmptyString_whenCallingWrap_thenResultIsAnEmptyString() {
assertThat(StringUtilsSuppressWarning.wrap("", "wrapper")).isEmpty();
}
@Test
void givenNonEmptyString_whenCallingWrap_thenResultIsWrappedString() {
assertThat(StringUtilsSuppressWarning.wrap("asd", "wrapper")).isEqualTo("wrapperasdwrapper");
}
}

View File

@ -9,4 +9,5 @@ This module contains articles about networking in Java
- [Connection Timeout vs. Read Timeout for Java Sockets](https://www.baeldung.com/java-socket-connection-read-timeout) - [Connection Timeout vs. Read Timeout for Java Sockets](https://www.baeldung.com/java-socket-connection-read-timeout)
- [Find Whether an IP Address Is in the Specified Range or Not in Java](https://www.baeldung.com/java-check-ip-address-range) - [Find Whether an IP Address Is in the Specified Range or Not in Java](https://www.baeldung.com/java-check-ip-address-range)
- [Find the IP Address of a Client Connected to a Server](https://www.baeldung.com/java-client-get-ip-address) - [Find the IP Address of a Client Connected to a Server](https://www.baeldung.com/java-client-get-ip-address)
- [Unix Domain Socket in Java 16](https://www.baeldung.com/java-unix-domain-socket)
- [[<-- Prev]](/core-java-modules/core-java-networking-2) - [[<-- Prev]](/core-java-modules/core-java-networking-2)

View File

@ -4,36 +4,26 @@ import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.Tomcat;
import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.ServerConnector;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.util.SocketUtils; import org.springframework.util.SocketUtils;
import java.io.IOException; import java.io.IOException;
import java.net.ServerSocket; import java.net.ServerSocket;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
public class FindFreePortUnitTest { public class FindFreePortUnitTest {
private static int FREE_PORT_NUMBER; private static final int DEFAULT_RANDOM_PORT = 34307;
private static int[] FREE_PORT_RANGE;
@BeforeAll
public static void getExplicitFreePortNumberAndRange() {
try (ServerSocket serverSocket = new ServerSocket(0)) {
FREE_PORT_NUMBER = serverSocket.getLocalPort();
FREE_PORT_RANGE = new int[] {FREE_PORT_NUMBER, FREE_PORT_NUMBER + 1, FREE_PORT_NUMBER + 2};
} catch (IOException e) {
fail("No free port is available");
}
}
@Test @Test
public void givenExplicitFreePort_whenCreatingServerSocket_thenThatPortIsAssigned() { public void givenExplicitFreePort_whenCreatingServerSocket_thenThatPortIsAssigned() {
try (ServerSocket serverSocket = new ServerSocket(FREE_PORT_NUMBER)) { int freePort = getFreePort();
try (ServerSocket serverSocket = new ServerSocket(freePort)) {
assertThat(serverSocket).isNotNull(); assertThat(serverSocket).isNotNull();
assertThat(serverSocket.getLocalPort()).isEqualTo(FREE_PORT_NUMBER); assertThat(serverSocket.getLocalPort()).isEqualTo(freePort);
} catch (IOException e) { } catch (IOException e) {
fail("Port is not available"); fail("Port is not available");
} }
@ -41,8 +31,10 @@ public class FindFreePortUnitTest {
@Test @Test
public void givenExplicitOccupiedPort_whenCreatingServerSocket_thenExceptionIsThrown() { public void givenExplicitOccupiedPort_whenCreatingServerSocket_thenExceptionIsThrown() {
try (ServerSocket serverSocket = new ServerSocket(FREE_PORT_NUMBER)) { int freePort = getFreePort();
new ServerSocket(FREE_PORT_NUMBER);
try (ServerSocket serverSocket = new ServerSocket(freePort)) {
new ServerSocket(freePort);
fail("Same port cannot be used twice"); fail("Same port cannot be used twice");
} catch (IOException e) { } catch (IOException e) {
assertThat(e).hasMessageContaining("Address already in use"); assertThat(e).hasMessageContaining("Address already in use");
@ -51,7 +43,7 @@ public class FindFreePortUnitTest {
@Test @Test
public void givenExplicitPortRange_whenCreatingServerSocket_thenOnePortIsAssigned() { public void givenExplicitPortRange_whenCreatingServerSocket_thenOnePortIsAssigned() {
for (int port : FREE_PORT_RANGE) { for (int port : getFreePorts()) {
try (ServerSocket serverSocket = new ServerSocket(port)) { try (ServerSocket serverSocket = new ServerSocket(port)) {
assertThat(serverSocket).isNotNull(); assertThat(serverSocket).isNotNull();
assertThat(serverSocket.getLocalPort()).isEqualTo(port); assertThat(serverSocket.getLocalPort()).isEqualTo(port);
@ -104,11 +96,12 @@ public class FindFreePortUnitTest {
public void givenExplicitFreePort_whenCreatingJettyServer_thenThatPortIsAssigned() throws Exception { public void givenExplicitFreePort_whenCreatingJettyServer_thenThatPortIsAssigned() throws Exception {
Server jettyServer = new Server(); Server jettyServer = new Server();
ServerConnector serverConnector = new ServerConnector(jettyServer); ServerConnector serverConnector = new ServerConnector(jettyServer);
serverConnector.setPort(FREE_PORT_NUMBER); int freePort = getFreePort();
serverConnector.setPort(freePort);
jettyServer.addConnector(serverConnector); jettyServer.addConnector(serverConnector);
try { try {
jettyServer.start(); jettyServer.start();
assertThat(serverConnector.getLocalPort()).isEqualTo(FREE_PORT_NUMBER); assertThat(serverConnector.getLocalPort()).isEqualTo(freePort);
} catch (Exception e) { } catch (Exception e) {
fail("Failed to start Jetty server"); fail("Failed to start Jetty server");
} finally { } finally {
@ -135,10 +128,11 @@ public class FindFreePortUnitTest {
@Test @Test
public void givenExplicitFreePort_whenCreatingTomcatServer_thenThatPortIsAssigned() throws Exception { public void givenExplicitFreePort_whenCreatingTomcatServer_thenThatPortIsAssigned() throws Exception {
Tomcat tomcatServer = new Tomcat(); Tomcat tomcatServer = new Tomcat();
tomcatServer.setPort(FREE_PORT_NUMBER); int freePort = getFreePort();
tomcatServer.setPort(freePort);
try { try {
tomcatServer.start(); tomcatServer.start();
assertThat(tomcatServer.getConnector().getLocalPort()).isEqualTo(FREE_PORT_NUMBER); assertThat(tomcatServer.getConnector().getLocalPort()).isEqualTo(freePort);
} catch (LifecycleException e) { } catch (LifecycleException e) {
fail("Failed to start Tomcat server"); fail("Failed to start Tomcat server");
} finally { } finally {
@ -147,4 +141,16 @@ public class FindFreePortUnitTest {
} }
} }
private int[] getFreePorts() {
int freePort = getFreePort();
return new int[]{freePort - 1, freePort, freePort + 1};
}
private int getFreePort() {
try(ServerSocket serverSocket = new ServerSocket(0)){
return serverSocket.getLocalPort();
} catch (IOException ex){
return DEFAULT_RANDOM_PORT;
}
}
} }

View File

@ -75,7 +75,6 @@
</build> </build>
<properties> <properties>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version> <collections-generic.version>4.01</collections-generic.version>
<asspectj.version>1.8.9</asspectj.version> <asspectj.version>1.8.9</asspectj.version>
<maven.compiler.source>1.9</maven.compiler.source> <maven.compiler.source>1.9</maven.compiler.source>

View File

@ -0,0 +1,10 @@
package com.baeldung.jmx;
public class JMXConfiguration {
public static void main(String[] args) {
while (true) {
// to ensure application does not terminate
}
}
}

View File

@ -11,6 +11,9 @@ import org.junit.jupiter.api.Test;
public class MatcherUnitTest { public class MatcherUnitTest {
private static final String STRING_INPUT = "test+";
private static final String REGEX = "\\+";
@Test @Test
public void whenFindFourDigitWorks_thenCorrect() { public void whenFindFourDigitWorks_thenCorrect() {
Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d"); Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d");
@ -60,4 +63,16 @@ public class MatcherUnitTest {
assertTrue(m.matches());// matches will always return the same return assertTrue(m.matches());// matches will always return the same return
} }
@Test
public void whenUsingMatcher_thenReturnTrue() {
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(STRING_INPUT);
assertTrue(matcher.find());
}
@Test
public void whenUsingMatches_thenReturnFalse() {
assertFalse(Pattern.matches(REGEX, STRING_INPUT));
}
} }

View File

@ -13,5 +13,4 @@ This module contains articles about string-related algorithms.
- [Remove Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters) - [Remove Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters)
- [Counting Words in a String with Java](https://www.baeldung.com/java-word-counting) - [Counting Words in a String with Java](https://www.baeldung.com/java-word-counting)
- [Finding the Difference Between Two Strings in Java](https://www.baeldung.com/java-difference-between-two-strings) - [Finding the Difference Between Two Strings in Java](https://www.baeldung.com/java-difference-between-two-strings)
- [Check if the First Letter of a String is Uppercase](https://www.baeldung.com/java-check-first-letter-uppercase)
- More articles: [[<-- prev]](../core-java-string-algorithms) - More articles: [[<-- prev]](../core-java-string-algorithms)

View File

@ -6,3 +6,4 @@ This module contains articles about string-related algorithms.
- [Check if Two Strings are Anagrams in Java](https://www.baeldung.com/java-strings-anagrams) - [Check if Two Strings are Anagrams in Java](https://www.baeldung.com/java-strings-anagrams)
- [Email Validation in Java](https://www.baeldung.com/java-email-validation-regex) - [Email Validation in Java](https://www.baeldung.com/java-email-validation-regex)
- [Check if the First Letter of a String is Uppercase](https://www.baeldung.com/java-check-first-letter-uppercase)

View File

@ -49,8 +49,8 @@
</build> </build>
<properties> <properties>
<guava.version>28.1-jre</guava.version> <guava.version>31.0.1-jre</guava.version>
<validator.version>1.7</validator.version> <validator.version>1.7</validator.version>
</properties> </properties>
</project> </project>

View File

@ -1,15 +1,12 @@
package com.baeldung.isuppercase; package com.baeldung.isuppercase;
import com.google.common.base.Ascii;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance;
import com.google.common.base.Ascii;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.matchesPattern;
@TestInstance(TestInstance.Lifecycle.PER_CLASS) @TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class StringFirstCharacterUppercase { public class StringFirstCharacterUppercaseUnitTest {
@Test @Test
public void givenString_whenCheckingWithCharacterIsUpperCase_thenStringCapitalized() { public void givenString_whenCheckingWithCharacterIsUpperCase_thenStringCapitalized() {
@ -21,7 +18,8 @@ public class StringFirstCharacterUppercase {
public void givenString_whenCheckingWithRegex_thenStringCapitalized() { public void givenString_whenCheckingWithRegex_thenStringCapitalized() {
String example = "Katie"; String example = "Katie";
String regEx = "[A-Z]\\w*"; String regEx = "[A-Z]\\w*";
assertThat(example, matchesPattern(regEx));
Assertions.assertTrue(example.matches(regEx));
} }
@Test @Test

View File

@ -9,4 +9,5 @@ This module contains articles about string conversions from/to another type.
- [Converting String to BigDecimal in Java](https://www.baeldung.com/java-string-to-bigdecimal) - [Converting String to BigDecimal in Java](https://www.baeldung.com/java-string-to-bigdecimal)
- [Converting String to BigInteger in Java](https://www.baeldung.com/java-string-to-biginteger) - [Converting String to BigInteger in Java](https://www.baeldung.com/java-string-to-biginteger)
- [Convert a String to Camel Case](https://www.baeldung.com/java-string-to-camel-case) - [Convert a String to Camel Case](https://www.baeldung.com/java-string-to-camel-case)
- [Convert a ByteBuffer to String]
- More articles: [[<-- prev]](/core-java-string-conversions) - More articles: [[<-- prev]](/core-java-string-conversions)

View File

@ -0,0 +1,44 @@
package com.baeldung.bytebuffertostring;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.junit.Test;
public class ByteArrayToStringUnitTest {
private static Charset charset = StandardCharsets.UTF_8;
private static final String content = "baeldung";
@Test
public void convertUsingNewStringFromBufferArray_thenOK() {
// Allocate a ByteBuffer
ByteBuffer byteBuffer = ByteBuffer.wrap(content.getBytes());
if (byteBuffer.hasArray()) {
String newContent = new String(byteBuffer.array(), charset);
assertEquals(content, newContent);
}
}
@Test
public void convertUsingNewStringFromByteBufferGetBytes_thenOK() {
// Allocate a ByteBuffer
ByteBuffer byteBuffer = ByteBuffer.wrap(content.getBytes());
byte[] bytes = new byte[byteBuffer.remaining()];
byteBuffer.get(bytes);
String newContent = new String(bytes, charset);
assertEquals(content, newContent);
}
@Test
public void convertUsingCharsetDecode_thenOK() {
// Allocate a ByteBuffer
ByteBuffer byteBuffer = ByteBuffer.wrap(content.getBytes());
String newContent = charset.decode(byteBuffer)
.toString();
assertEquals(content, newContent);
}
}

View File

@ -1,2 +0,0 @@
### Relevant Articles:
- [Convert Hex to ASCII in Java](http://www.baeldung.com/java-convert-hex-to-ascii)

View File

@ -2,4 +2,5 @@
- [Ignoring Commas in Quotes When Splitting a Comma-separated String](https://www.baeldung.com/java-split-string-commas) - [Ignoring Commas in Quotes When Splitting a Comma-separated String](https://www.baeldung.com/java-split-string-commas)
- [Compare Strings While Ignoring Whitespace in Java](https://www.baeldung.com/java-compare-string-whitespace) - [Compare Strings While Ignoring Whitespace in Java](https://www.baeldung.com/java-compare-string-whitespace)
- [Concatenating Null Strings in Java](https://www.baeldung.com/java-concat-null-string)

View File

@ -0,0 +1,86 @@
package com.baeldung.concatenation;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ConcatenatingNull {
public static void main(String[] args) {
String[] values = { "Java ", null, "", "is ", "great!" };
concatenateUsingPlusOperator(values);
concatenateUsingHelperMethod(values);
concatenateUsingStringBuilder(values);
concatenateUsingJoin(values);
concatenateUsingStringJoiner(values);
concatenateUsingCollectorsJoining(values);
concatenateUsingStringConcat(values);
}
public static String concatenateUsingStringConcat(String[] values) {
String result = "";
for (String value : values) {
result = result.concat(getNonNullString(value));
}
return result;
}
public static String concatenateUsingCollectorsJoining(String[] values) {
String result = Stream.of(values).filter(value -> null != value).collect(Collectors.joining(""));
return result;
}
public static String concatenateUsingStringJoiner(String[] values) {
StringJoiner result = new StringJoiner("");
for (String value : values) {
result = result.add(getNonNullString(value));
}
return result.toString();
}
public static String concatenateUsingJoin(String[] values) {
String result = String.join("", values);
return result;
}
public static String concatenateUsingStringBuilder(String[] values) {
StringBuilder result = new StringBuilder();
for (String value : values) {
result = result.append(getNonNullString(value));
}
return result.toString();
}
public static String concatenateUsingHelperMethod(String[] values) {
String result = "";
for (String value : values) {
result = result + getNonNullString(value);
}
return result;
}
public static String concatenateUsingPlusOperator(String[] values) {
String result = "";
for (String value : values) {
result = result + (value == null ? "" : value);
}
return result;
}
private static String getNonNullString(String value) {
return value == null ? "" : value;
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.concatenation;
import static com.baeldung.concatenation.ConcatenatingNull.concatenateUsingCollectorsJoining;
import static com.baeldung.concatenation.ConcatenatingNull.concatenateUsingHelperMethod;
import static com.baeldung.concatenation.ConcatenatingNull.concatenateUsingJoin;
import static com.baeldung.concatenation.ConcatenatingNull.concatenateUsingPlusOperator;
import static com.baeldung.concatenation.ConcatenatingNull.concatenateUsingStringBuilder;
import static com.baeldung.concatenation.ConcatenatingNull.concatenateUsingStringConcat;
import static com.baeldung.concatenation.ConcatenatingNull.concatenateUsingStringJoiner;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class ConcatenatingNullUnitTest {
String[] values = { "Java ", null, "", "is ", "great!" };
@Test
public void givenStringElementsWithNull_whenConcatenatedUsingPlus_thenNullIsIgnored() {
String result = concatenateUsingPlusOperator(values);
assertEquals("Java is great!", result);
}
@Test
public void givenStringElementsWithNull_whenConcatenatedUsingHelperMethod_thenNullIsIgnored() {
String result = concatenateUsingHelperMethod(values);
assertEquals("Java is great!", result);
}
@Test
public void givenStringElementsWithNull_whenConcatenatedUsingStringBuilder_thenNullIsIgnored() {
String result = concatenateUsingStringBuilder(values);
assertEquals("Java is great!", result);
}
@Test
public void givenStringElementsWithNull_whenConcatenatedUsingJoin_thenNullIsNotIgnored() {
String result = concatenateUsingJoin(values);
assertEquals("Java nullis great!", result);
}
@Test
public void givenStringElementsWithNull_whenConcatenatedUsingStringJoiner_thenNullIsIgnored() {
String result = concatenateUsingStringJoiner(values);
assertEquals("Java is great!", result);
}
@Test
public void givenStringElementsWithNull_whenConcatenatedUsingCollectorsJoining_thenNullIsIgnored() {
String result = concatenateUsingCollectorsJoining(values);
assertEquals("Java is great!", result);
}
@Test
public void givenStringElementsWithNull_whenConcatenatedUsingStringConcat_thenNullIsIgnored() {
String result = concatenateUsingStringConcat(values);
assertEquals("Java is great!", result);
}
}

View File

@ -38,15 +38,15 @@
<version>${asspectj.version}</version> <version>${asspectj.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.powermock</groupId> <groupId>org.mockito</groupId>
<artifactId>powermock-module-junit4</artifactId> <artifactId>mockito-inline</artifactId>
<version>${powermock.version}</version> <version>${mockito-inline.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.powermock</groupId> <groupId>org.mockito</groupId>
<artifactId>powermock-api-mockito2</artifactId> <artifactId>mockito-core</artifactId>
<version>${powermock.version}</version> <version>${mockito-inline.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
@ -82,10 +82,10 @@
<properties> <properties>
<commons-math3.version>3.6.1</commons-math3.version> <commons-math3.version>3.6.1</commons-math3.version>
<joda.version>2.10</joda.version> <joda.version>2.10</joda.version>
<lombok.version>1.18.12</lombok.version> <lombok.version>1.18.22</lombok.version>
<asspectj.version>1.8.9</asspectj.version> <asspectj.version>1.8.9</asspectj.version>
<powermock.version>2.0.7</powermock.version>
<jmockit.version>1.44</jmockit.version> <jmockit.version>1.44</jmockit.version>
<mockito-inline.version>4.0.0</mockito-inline.version>
</properties> </properties>
</project> </project>

View File

@ -1,20 +1,15 @@
package com.baeldung.time; package com.baeldung.time;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.mockito.MockedStatic;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.time.Clock; import java.time.Clock;
import java.time.Instant; import java.time.Instant;
import java.time.ZoneId; import java.time.ZoneId;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.mockito.Mockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Instant.class })
public class InstantUnitTest { public class InstantUnitTest {
@Test @Test
@ -22,12 +17,12 @@ public class InstantUnitTest {
String instantExpected = "2014-12-22T10:15:30Z"; String instantExpected = "2014-12-22T10:15:30Z";
Clock clock = Clock.fixed(Instant.parse(instantExpected), ZoneId.of("UTC")); Clock clock = Clock.fixed(Instant.parse(instantExpected), ZoneId.of("UTC"));
Instant instant = Instant.now(clock); Instant instant = Instant.now(clock);
mockStatic(Instant.class);
when(Instant.now()).thenReturn(instant);
Instant now = Instant.now(); try (MockedStatic<Instant> mockedStatic = mockStatic(Instant.class)) {
mockedStatic.when(Instant::now).thenReturn(instant);
assertThat(now.toString()).isEqualTo(instantExpected); Instant now = Instant.now();
assertThat(now.toString()).isEqualTo(instantExpected);
}
} }
@Test @Test

View File

@ -1,9 +1,6 @@
package com.baeldung.time; package com.baeldung.time;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.time.Clock; import java.time.Clock;
import java.time.Instant; import java.time.Instant;
@ -11,11 +8,7 @@ import java.time.LocalDateTime;
import java.time.ZoneId; import java.time.ZoneId;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ LocalDateTime.class })
public class LocalDateTimeUnitTest { public class LocalDateTimeUnitTest {
@Test @Test

View File

@ -61,10 +61,7 @@
</build> </build>
<properties> <properties>
<!-- marshalling -->
<gson.version>2.8.0</gson.version> <gson.version>2.8.0</gson.version>
<!-- util -->
<commons-collections4.version>4.1</commons-collections4.version>
<joda-time.version>2.9.6</joda-time.version> <joda-time.version>2.9.6</joda-time.version>
</properties> </properties>

View File

@ -45,9 +45,6 @@
</build> </build>
<properties> <properties>
<!-- util -->
<commons-collections4.version>4.1</commons-collections4.version>
<!-- testing -->
<java-hamcrest.version>2.0.0.0</java-hamcrest.version> <java-hamcrest.version>2.0.0.0</java-hamcrest.version>
</properties> </properties>

View File

@ -50,10 +50,7 @@
</build> </build>
<properties> <properties>
<!-- util -->
<commons-collections4.version>4.1</commons-collections4.version>
<jool.version>0.9.12</jool.version> <jool.version>0.9.12</jool.version>
<!-- testing -->
<java-hamcrest.version>2.0.0.0</java-hamcrest.version> <java-hamcrest.version>2.0.0.0</java-hamcrest.version>
</properties> </properties>

View File

@ -11,4 +11,5 @@ This module contains articles about Jackson conversions.
- [Jackson Streaming API](https://www.baeldung.com/jackson-streaming-api) - [Jackson Streaming API](https://www.baeldung.com/jackson-streaming-api)
- [Jackson: java.util.LinkedHashMap cannot be cast to X](https://www.baeldung.com/jackson-linkedhashmap-cannot-be-cast) - [Jackson: java.util.LinkedHashMap cannot be cast to X](https://www.baeldung.com/jackson-linkedhashmap-cannot-be-cast)
- [Deserialize Snake Case to Camel Case With Jackson](https://www.baeldung.com/jackson-deserialize-snake-to-camel-case) - [Deserialize Snake Case to Camel Case With Jackson](https://www.baeldung.com/jackson-deserialize-snake-to-camel-case)
- [Serialize and Deserialize Booleans as Integers With Jackson](https://www.baeldung.com/jackson-booleans-as-integers)
- More articles: [[<-- prev]](../jackson-conversions) - More articles: [[<-- prev]](../jackson-conversions)

View File

@ -38,8 +38,4 @@
</resources> </resources>
</build> </build>
<properties>
<commons-collections4.version>4.4</commons-collections4.version>
</properties>
</project> </project>

View File

@ -30,7 +30,6 @@
</dependencies> </dependencies>
<properties> <properties>
<commons-collections4.version>4.1</commons-collections4.version>
<spring.version>5.2.5.RELEASE</spring.version> <spring.version>5.2.5.RELEASE</spring.version>
</properties> </properties>

View File

@ -8,3 +8,5 @@ This module contains articles about JSON.
- [Introduction to Moshi Json](https://www.baeldung.com/java-json-moshi) - [Introduction to Moshi Json](https://www.baeldung.com/java-json-moshi)
- [Hypermedia Serialization With JSON-LD](https://www.baeldung.com/json-linked-data) - [Hypermedia Serialization With JSON-LD](https://www.baeldung.com/json-linked-data)
- [Generate a Java Class From JSON](https://www.baeldung.com/java-generate-class-from-json) - [Generate a Java Class From JSON](https://www.baeldung.com/java-generate-class-from-json)
- [A Guide to FastJson](https://www.baeldung.com/fastjson)
- More Articles: [[<-- prev]](/json)

View File

@ -14,6 +14,11 @@
</parent> </parent>
<dependencies> <dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.jsonschema2pojo</groupId> <groupId>org.jsonschema2pojo</groupId>
<artifactId>jsonschema2pojo-core</artifactId> <artifactId>jsonschema2pojo-core</artifactId>
@ -142,6 +147,7 @@
<properties> <properties>
<jsoniter.version>0.9.23</jsoniter.version> <jsoniter.version>0.9.23</jsoniter.version>
<moshi.version>1.9.2</moshi.version> <moshi.version>1.9.2</moshi.version>
<fastjson.version>1.2.21</fastjson.version>
</properties> </properties>
</project> </project>

View File

@ -1,4 +1,4 @@
package fast_json; package com.baeldung.fastjson;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;

View File

@ -1,4 +1,4 @@
package fast_json; package com.baeldung.fastjson;
import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONField;

View File

@ -4,7 +4,6 @@ This module contains articles about JSON.
### Relevant Articles: ### Relevant Articles:
- [Introduction to JSON Schema in Java](https://www.baeldung.com/introduction-to-json-schema-in-java) - [Introduction to JSON Schema in Java](https://www.baeldung.com/introduction-to-json-schema-in-java)
- [A Guide to FastJson](https://www.baeldung.com/fastjson)
- [Introduction to JSONForms](https://www.baeldung.com/introduction-to-jsonforms) - [Introduction to JSONForms](https://www.baeldung.com/introduction-to-jsonforms)
- [Introduction to JsonPath](https://www.baeldung.com/guide-to-jayway-jsonpath) - [Introduction to JsonPath](https://www.baeldung.com/guide-to-jayway-jsonpath)
- [Introduction to JSON-Java (org.json)](https://www.baeldung.com/java-org-json) - [Introduction to JSON-Java (org.json)](https://www.baeldung.com/java-org-json)
@ -14,3 +13,4 @@ This module contains articles about JSON.
- [Iterating Over an Instance of org.json.JSONObject](https://www.baeldung.com/jsonobject-iteration) - [Iterating Over an Instance of org.json.JSONObject](https://www.baeldung.com/jsonobject-iteration)
- [Escape JSON String in Java](https://www.baeldung.com/java-json-escaping) - [Escape JSON String in Java](https://www.baeldung.com/java-json-escaping)
- [Reducing JSON Data Size](https://www.baeldung.com/json-reduce-data-size) - [Reducing JSON Data Size](https://www.baeldung.com/json-reduce-data-size)
- More Articles: [[next -->]](/json-2)

View File

@ -26,11 +26,6 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.json</groupId> <groupId>org.json</groupId>
<artifactId>json</artifactId> <artifactId>json</artifactId>
@ -72,9 +67,7 @@
<properties> <properties>
<everit.json.schema.version>1.4.1</everit.json.schema.version> <everit.json.schema.version>1.4.1</everit.json.schema.version>
<fastjson.version>1.2.21</fastjson.version>
<jsonb-api.version>1.0</jsonb-api.version> <jsonb-api.version>1.0</jsonb-api.version>
<commons-collections4.version>4.1</commons-collections4.version>
<yasson.version>1.0.1</yasson.version> <yasson.version>1.0.1</yasson.version>
<json.version>20171018</json.version> <json.version>20171018</json.version>
<gson.version>2.8.5</gson.version> <gson.version>2.8.5</gson.version>

View File

@ -146,7 +146,6 @@
<renjin.version>3.5-beta72</renjin.version> <renjin.version>3.5-beta72</renjin.version>
<rcaller.version>3.0</rcaller.version> <rcaller.version>3.0</rcaller.version>
<rserve.version>1.8.1</rserve.version> <rserve.version>1.8.1</rserve.version>
<commons-collections4.version>4.4</commons-collections4.version>
<libphonenumber.version>8.12.9</libphonenumber.version> <libphonenumber.version>8.12.9</libphonenumber.version>
<org.modelmapper.version>2.4.4</org.modelmapper.version> <org.modelmapper.version>2.4.4</org.modelmapper.version>
</properties> </properties>

View File

@ -16,7 +16,7 @@
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId> <artifactId>commons-collections4</artifactId>
<version>${commons.collections.version}</version> <version>${commons-collections4.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.hamcrest</groupId> <groupId>org.hamcrest</groupId>
@ -27,7 +27,6 @@
</dependencies> </dependencies>
<properties> <properties>
<commons.collections.version>4.1</commons.collections.version>
<org.hamcrest.java-hamcrest.version>2.0.0.0</org.hamcrest.java-hamcrest.version> <org.hamcrest.java-hamcrest.version>2.0.0.0</org.hamcrest.java-hamcrest.version>
</properties> </properties>

View File

@ -74,4 +74,40 @@
<javax.activation.version>1.1.1</javax.activation.version> <javax.activation.version>1.1.1</javax.activation.version>
</properties> </properties>
<profiles>
<profile>
<id>integration-lite-first</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<logback.configurationFile>${project.basedir}/src/test/resources/logback-test.xml</logback.configurationFile>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>integration-lite-second</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<logback.configurationFile>${project.basedir}/src/test/resources/logback-test.xml</logback.configurationFile>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project> </project>

View File

@ -13,5 +13,4 @@ This module contains articles about the Java Persistence API (JPA) in Java.
- [Returning an Auto-Generated Id with JPA](https://www.baeldung.com/jpa-get-auto-generated-id) - [Returning an Auto-Generated Id with JPA](https://www.baeldung.com/jpa-get-auto-generated-id)
- [How to Return Multiple Entities In JPA Query](https://www.baeldung.com/jpa-return-multiple-entities) - [How to Return Multiple Entities In JPA Query](https://www.baeldung.com/jpa-return-multiple-entities)
- [Defining Unique Constraints in JPA](https://www.baeldung.com/jpa-unique-constraints) - [Defining Unique Constraints in JPA](https://www.baeldung.com/jpa-unique-constraints)
- [How to Check Field Existence in MongoDB?](https://www.baeldung.com/mongodb-check-field-exists)
- [Connecting to a Specific Schema in JDBC](https://www.baeldung.com/jdbc-connect-to-schema) - [Connecting to a Specific Schema in JDBC](https://www.baeldung.com/jdbc-connect-to-schema)

View File

@ -11,3 +11,4 @@ This module contains articles about MongoDB in Java.
- [Introduction to Morphia Java ODM for MongoDB](https://www.baeldung.com/mongodb-morphia) - [Introduction to Morphia Java ODM for MongoDB](https://www.baeldung.com/mongodb-morphia)
- [MongoDB Aggregations Using Java](https://www.baeldung.com/java-mongodb-aggregations) - [MongoDB Aggregations Using Java](https://www.baeldung.com/java-mongodb-aggregations)
- [BSON to JSON Document Conversion in Java](https://www.baeldung.com/java-convert-bson-to-json) - [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)

View File

@ -7,5 +7,4 @@
- [Resolving “Failed to Configure a DataSource” Error](https://www.baeldung.com/spring-boot-failed-to-configure-data-source) - [Resolving “Failed to Configure a DataSource” Error](https://www.baeldung.com/spring-boot-failed-to-configure-data-source)
- [Hibernate Field Naming with Spring Boot](https://www.baeldung.com/hibernate-field-naming-spring-boot) - [Hibernate Field Naming with Spring Boot](https://www.baeldung.com/hibernate-field-naming-spring-boot)
- [Spring Boot with Hibernate](https://www.baeldung.com/spring-boot-hibernate) - [Spring Boot with Hibernate](https://www.baeldung.com/spring-boot-hibernate)
- [A Guide to Spring AbstractRoutingDatasource](https://www.baeldung.com/spring-abstract-routing-data-source) - More articles: [[more -->]](../spring-boot-persistence-2)
- More articles: [[more -->]](../spring-boot-persistence-2)

View File

@ -5,7 +5,6 @@
- [JPA Pagination](https://www.baeldung.com/jpa-pagination) - [JPA Pagination](https://www.baeldung.com/jpa-pagination)
- [Sorting with JPA](https://www.baeldung.com/jpa-sort) - [Sorting with JPA](https://www.baeldung.com/jpa-sort)
- [Self-Contained Testing Using an In-Memory Database](https://www.baeldung.com/spring-jpa-test-in-memory-database) - [Self-Contained Testing Using an In-Memory Database](https://www.baeldung.com/spring-jpa-test-in-memory-database)
- [Obtaining Auto-generated Keys in Spring JDBC](https://www.baeldung.com/spring-jdbc-autogenerated-keys)
- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations) - [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations)
- [A Guide to Spring AbstractRoutingDatasource](https://www.baeldung.com/spring-abstract-routing-data-source) - [A Guide to Spring AbstractRoutingDatasource](https://www.baeldung.com/spring-abstract-routing-data-source)
- More articles: [[next -->]](/spring-jpa-2) - More articles: [[next -->]](/spring-jpa-2)

View File

@ -1433,6 +1433,7 @@
<jmh-core.version>1.33</jmh-core.version> <jmh-core.version>1.33</jmh-core.version>
<jmh-generator.version>1.33</jmh-generator.version> <jmh-generator.version>1.33</jmh-generator.version>
<maven-failsafe-plugin.version>2.21.0</maven-failsafe-plugin.version> <maven-failsafe-plugin.version>2.21.0</maven-failsafe-plugin.version>
<commons-collections4.version>4.4</commons-collections4.version>
<commons-io.version>2.11.0</commons-io.version> <commons-io.version>2.11.0</commons-io.version>
<commons-lang.version>2.6</commons-lang.version> <commons-lang.version>2.6</commons-lang.version>
<commons-lang3.version>3.12.0</commons-lang3.version> <commons-lang3.version>3.12.0</commons-lang3.version>

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