Merge branch 'master' into fix-5227

This commit is contained in:
Loredana Crusoveanu 2021-12-02 11:16:06 +02:00 committed by GitHub
commit beacee34c0
282 changed files with 3796 additions and 492 deletions

View File

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

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

@ -0,0 +1,24 @@
<?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</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apache-poi</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>5.0.0</version>
</dependency>
</dependencies>
</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,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)
- [Set Background Color of a Cell with Apache POI](https://www.baeldung.com/apache-poi-background-color)
- [Add Borders to Excel Cells With Apache POI](https://www.baeldung.com/apache-poi-add-borders)
- More articles: [[next -->]](/apache-poi-2)

View File

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

View File

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

Binary file not shown.

View File

@ -10,9 +10,8 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<artifactId>aws-lambda</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>

View File

@ -11,7 +11,6 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<modules>

View File

@ -10,9 +10,8 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<artifactId>cloud-foundry-uaa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>

View File

@ -10,9 +10,8 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<artifactId>cloud-foundry-uaa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>

View File

@ -4,14 +4,14 @@
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>cloud-foundry-uaa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>cloud-foundry-uaa</name>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<modules>

View File

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

View File

@ -5,7 +5,8 @@ import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
public class VersionUnitTest {
// manual test as the runtime JDK version can be different depending on where the test is run
public class VersionManualTest {
@Test
public void givenJava_whenUsingRuntime_thenGetVersion() {

View File

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

View File

@ -16,6 +16,7 @@ import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
import org.junit.Ignore;
public class ModuleAPIUnitTest {
@ -110,6 +111,7 @@ public class ModuleAPIUnitTest {
}
@Test
@Ignore // fixing in http://team.baeldung.com/browse/JAVA-8679
public void givenModules_whenAccessingModuleDescriptorProvides_thenProvidesAreReturned() {
Set<Provides> javaBaseProvides = javaBaseModule.getDescriptor().provides();
Set<Provides> javaSqlProvides = javaSqlModule.getDescriptor().provides();

View File

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

View File

@ -44,7 +44,6 @@
<properties>
<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>
</properties>

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>
</dependencies>
<properties>
<commons-collections4.version>4.1</commons-collections4.version>
</properties>
</project>

View File

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

View File

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

View File

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

View File

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

View File

@ -28,12 +28,6 @@
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>${hamcrest-all.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

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

View File

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

View File

@ -56,7 +56,6 @@
<properties>
<guava.version>21.0</guava.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>
<avaitility.version>1.7.0</avaitility.version>
</properties>

View File

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

View File

@ -1,7 +1,7 @@
package com.baeldung.readertox;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.ByteArrayInputStream;
import java.io.File;
@ -17,6 +17,7 @@ import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.CharSequenceReader;
import org.apache.commons.io.input.ReaderInputStream;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -181,7 +182,7 @@ public class JavaReaderToXUnitTest {
}
@Test
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStream() throws IOException {
public void givenUsingCommonsIOUtils_whenConvertingReaderIntoInputStream() throws IOException {
final Reader initialReader = new StringReader("With Commons IO");
final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader));
@ -191,7 +192,7 @@ public class JavaReaderToXUnitTest {
}
@Test
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException {
public void givenUsingCommonsIOUtils_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException {
String initialString = "With Commons IO";
final Reader initialReader = new StringReader(initialString);
@ -204,6 +205,30 @@ public class JavaReaderToXUnitTest {
targetStream.close();
}
@Test
public void givenUsingCommonsIOReaderInputStream_whenConvertingReaderIntoInputStream() throws IOException {
final Reader initialReader = new StringReader("With Commons IO");
final InputStream targetStream = new ReaderInputStream(initialReader);
initialReader.close();
targetStream.close();
}
@Test
public void givenUsingCommonsIOReaderInputStream_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException {
String initialString = "With Commons IO";
final Reader initialReader = new StringReader(initialString);
final InputStream targetStream = new ReaderInputStream(initialReader);
final String finalString = IOUtils.toString(targetStream);
assertThat(finalString, equalTo(initialString));
initialReader.close();
targetStream.close();
}
// tests - Reader to InputStream with encoding
@Test
@ -233,7 +258,7 @@ public class JavaReaderToXUnitTest {
}
@Test
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStreamWithEncoding() throws IOException {
public void givenUsingCommonsIOUtils_whenConvertingReaderIntoInputStreamWithEncoding() throws IOException {
final Reader initialReader = new StringReader("With Commons IO");
final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader), Charsets.UTF_8);
@ -243,7 +268,7 @@ public class JavaReaderToXUnitTest {
}
@Test
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStreamWithEncoding_thenCorrect() throws IOException {
public void givenUsingCommonsIOUtils_whenConvertingReaderIntoInputStreamWithEncoding_thenCorrect() throws IOException {
String initialString = "With Commons IO";
final Reader initialReader = new StringReader(initialString);
final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader), Charsets.UTF_8);
@ -255,4 +280,27 @@ public class JavaReaderToXUnitTest {
targetStream.close();
}
@Test
public void givenUsingCommonsIOReaderInputStream_whenConvertingReaderIntoInputStreamWithEncoding() throws IOException {
final Reader initialReader = new StringReader("With Commons IO");
final InputStream targetStream = new ReaderInputStream(initialReader, Charsets.UTF_8);
initialReader.close();
targetStream.close();
}
@Test
public void givenUsingCommonsIOReaderInputStream_whenConvertingReaderIntoInputStreamWithEncoding_thenCorrect() throws IOException {
String initialString = "With Commons IO";
final Reader initialReader = new StringReader(initialString);
final InputStream targetStream = new ReaderInputStream(initialReader, Charsets.UTF_8);
String finalString = IOUtils.toString(targetStream, Charsets.UTF_8);
assertThat(finalString, equalTo(initialString));
initialReader.close();
targetStream.close();
}
}

View File

@ -22,4 +22,7 @@
</dependency>
</dependencies>
<properties>
<h2.version>1.4.197</h2.version> <!-- needs to be specified as it fails with parent's 1.4.200 -->
</properties>
</project>

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)
- [Find Whether an IP Address Is in the Specified Range or Not in Java](https://www.baeldung.com/java-check-ip-address-range)
- [Find the IP Address of a Client Connected to a Server](https://www.baeldung.com/java-client-get-ip-address)
- [Unix Domain Socket in Java 16](https://www.baeldung.com/java-unix-domain-socket)
- [[<-- Prev]](/core-java-modules/core-java-networking-2)

View File

@ -64,6 +64,16 @@
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>16</source>
<target>16</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>

View File

@ -0,0 +1,49 @@
package com.baeldung.socket;
import java.io.IOException;
import java.net.StandardProtocolFamily;
import java.net.UnixDomainSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
class UnixDomainSocketClient {
public static void main(String[] args) throws Exception {
new UnixDomainSocketClient().runClient();
}
void runClient() throws IOException {
Path socketPath = Path.of(System.getProperty("user.home"))
.resolve("baeldung.socket");
UnixDomainSocketAddress socketAddress = getAddress(socketPath);
SocketChannel channel = openSocketChannel(socketAddress);
String message = "Hello from Baeldung Unix domain socket article";
writeMessage(channel, message);
}
UnixDomainSocketAddress getAddress(Path socketPath) {
return UnixDomainSocketAddress.of(socketPath);
}
SocketChannel openSocketChannel(UnixDomainSocketAddress socketAddress) throws IOException {
SocketChannel channel = SocketChannel
.open(StandardProtocolFamily.UNIX);
channel.connect(socketAddress);
return channel;
}
void writeMessage(SocketChannel socketChannel, String message) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.clear();
buffer.put(message.getBytes());
buffer.flip();
while (buffer.hasRemaining()) {
socketChannel.write(buffer);
}
}
}

View File

@ -0,0 +1,57 @@
package com.baeldung.socket;
import java.io.IOException;
import java.net.StandardProtocolFamily;
import java.net.UnixDomainSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
class UnixDomainSocketServer {
public static void main(String[] args) throws IOException, InterruptedException {
new UnixDomainSocketServer().runServer();
}
void runServer() throws IOException, InterruptedException {
Path socketPath = Path.of(System.getProperty("user.home"))
.resolve("baeldung.socket");
Files.deleteIfExists(socketPath);
UnixDomainSocketAddress socketAddress = getAddress(socketPath);
ServerSocketChannel serverChannel = createServerSocketChannel(socketAddress);
SocketChannel channel = serverChannel.accept();
while (true) {
readSocketMessage(channel)
.ifPresent(message -> System.out.printf("[Client message] %s%n", message));
Thread.sleep(100);
}
}
UnixDomainSocketAddress getAddress(Path socketPath) {
return UnixDomainSocketAddress.of(socketPath);
}
ServerSocketChannel createServerSocketChannel(UnixDomainSocketAddress socketAddress) throws IOException {
ServerSocketChannel serverChannel = ServerSocketChannel.open(StandardProtocolFamily.UNIX);
serverChannel.bind(socketAddress);
return serverChannel;
}
Optional<String> readSocketMessage(SocketChannel channel) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(1024);
int bytesRead = channel.read(buffer);
if (bytesRead < 0) return Optional.empty();
byte[] bytes = new byte[bytesRead];
buffer.flip();
buffer.get(bytes);
String message = new String(bytes);
return Optional.of(message);
}
}

View File

@ -14,7 +14,8 @@ import java.net.ServerSocket;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
public class FindFreePortUnitTest {
// fixing in JAVA-8748
public class FindFreePortManualTest {
private static int FREE_PORT_NUMBER;
private static int[] FREE_PORT_RANGE;

View File

@ -0,0 +1,82 @@
package com.baeldung.socket;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
import java.io.File;
import java.io.IOException;
import java.net.StandardProtocolFamily;
import java.net.UnixDomainSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
import java.util.UUID;
import static java.nio.file.Files.deleteIfExists;
import static org.assertj.core.util.Files.newTemporaryFile;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class UnixDomainSocketClientUnitTest {
@Test
public void givenSocketPath_shouldCreateUnixDomainSocketAddress() {
// given
File tempFile = newTemporaryFile();
Path socketPath = tempFile.toPath();
// when
UnixDomainSocketAddress address = new UnixDomainSocketClient().getAddress(socketPath);
// then
assertEquals(address.getPath(), socketPath);
// cleanup
tempFile.delete();
}
@Test
public void givenUnixDomainSocketAddress_shouldOpenSocketChannel() throws IOException {
// given
File tempFile = newTemporaryFile();
Path socketPath = tempFile.toPath();
deleteIfExists(socketPath);
UnixDomainSocketAddress address = UnixDomainSocketAddress.of(socketPath);
// bind address as a unix domain socket
ServerSocketChannel serverChannel = ServerSocketChannel.open(StandardProtocolFamily.UNIX);
serverChannel.bind(address);
// when
SocketChannel socketChannel = new UnixDomainSocketClient().openSocketChannel(address);
// then
assertTrue(socketChannel.isOpen());
assertEquals(socketChannel.getRemoteAddress(), address);
// cleanup
tempFile.delete();
}
@Test
public void givenSocketChannelAndMessage_shouldWriteMessage() throws IOException {
// given
SocketChannel socketChannel = Mockito.mock(SocketChannel.class);
String message = UUID.randomUUID().toString();
Mockito.when(socketChannel.write(Mockito.any(ByteBuffer.class)))
.thenAnswer(
(Answer<Integer>) invocationOnMock -> {
((ByteBuffer) invocationOnMock.getArguments()[0]).position(message.getBytes().length);
return -1;
}
);
// when
new UnixDomainSocketClient().writeMessage(socketChannel, message);
// then
Mockito.verify(socketChannel, Mockito.times(1)).write(Mockito.any(ByteBuffer.class));
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.socket;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.UnixDomainSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.file.Path;
import static java.nio.file.Files.deleteIfExists;
import static org.assertj.core.util.Files.newTemporaryFile;
import static org.junit.Assert.assertEquals;
public class UnixDomainSocketServerUnitTest {
@Test
public void givenSocketPath_shouldCreateUnixDomainSocketAddress() {
// given
File tempFile = newTemporaryFile();
Path socketPath = tempFile.toPath();
// when
UnixDomainSocketAddress address = new UnixDomainSocketServer().getAddress(socketPath);
// then
assertEquals(address.getPath(), socketPath);
// cleanup
tempFile.delete();
}
@Test
public void givenUnixDomainSocketAddress_shouldCreateServerSocketChannel() throws IOException {
// given
File tempFile = newTemporaryFile();
Path socketPath = tempFile.toPath();
deleteIfExists(socketPath);
UnixDomainSocketAddress address = UnixDomainSocketAddress.of(socketPath);
// when
ServerSocketChannel serverSocketChannel = new UnixDomainSocketServer().createServerSocketChannel(address);
// then
assertEquals(serverSocketChannel.getLocalAddress(), address);
// cleanup
tempFile.delete();
}
}

View File

@ -45,6 +45,12 @@
<artifactId>grep4j</artifactId>
<version>${grep4j.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
@ -69,7 +75,6 @@
</build>
<properties>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<asspectj.version>1.8.9</asspectj.version>
<maven.compiler.source>1.9</maven.compiler.source>
@ -77,6 +82,7 @@
<guava.version>25.1-jre</guava.version>
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
<lombok.version>1.18.22</lombok.version>
</properties>
</project>

View File

@ -1,12 +1,23 @@
package com.baeldung.java.shell;
package com.baeldung.shell;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
public class JavaProcessUnitIntegrationTest {
private static final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().startsWith("windows");
@ -29,6 +40,18 @@ public class JavaProcessUnitIntegrationTest {
private String homeDirectory = System.getProperty("user.home");
private ExecutorService executorService;
@Before
public void setUp() {
executorService = Executors.newSingleThreadExecutor();
}
@After
public void tearDown() {
executorService.shutdown();
}
@Test
public void givenProcess_whenCreatingViaRuntime_shouldSucceed() throws Exception {
Process process;
@ -38,9 +61,13 @@ public class JavaProcessUnitIntegrationTest {
process = Runtime.getRuntime().exec(String.format("sh -c ls %s", homeDirectory));
}
StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), consumer);
Executors.newSingleThreadExecutor().submit(streamGobbler);
Future<?> future = executorService.submit(streamGobbler);
int exitCode = process.waitFor();
Assert.assertEquals(0, exitCode);
// verify the stream output from the process
assertDoesNotThrow(() -> future.get(10, TimeUnit.SECONDS));
assertEquals(0, exitCode);
}
@Test
@ -54,8 +81,12 @@ public class JavaProcessUnitIntegrationTest {
builder.directory(new File(homeDirectory));
Process process = builder.start();
StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), consumer);
Executors.newSingleThreadExecutor().submit(streamGobbler);
Future<?> future = executorService.submit(streamGobbler);
int exitCode = process.waitFor();
Assert.assertEquals(0, exitCode);
// verify the stream output from the process
assertDoesNotThrow(() -> future.get(10, TimeUnit.SECONDS));
assertEquals(0, exitCode);
}
}

View File

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

View File

@ -18,6 +18,7 @@ public class StringFirstCharacterUppercaseUnitTest {
public void givenString_whenCheckingWithRegex_thenStringCapitalized() {
String example = "Katie";
String regEx = "[A-Z]\\w*";
Assertions.assertTrue(example.matches(regEx));
}

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 BigInteger in Java](https://www.baeldung.com/java-string-to-biginteger)
- [Convert a String to Camel Case](https://www.baeldung.com/java-string-to-camel-case)
- [Convert a ByteBuffer to String]
- More articles: [[<-- prev]](/core-java-string-conversions)

View File

@ -20,12 +20,6 @@
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>${hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.ibm.icu</groupId>
<artifactId>icu4j</artifactId>

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

@ -35,12 +35,6 @@
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>${hamcrest.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@ -12,5 +12,5 @@ This module contains articles about string operations.
- [L-Trim and R-Trim Alternatives in Java](https://www.baeldung.com/java-trim-alternatives)
- [Encode a String to UTF-8 in Java](https://www.baeldung.com/java-string-encode-utf-8)
- [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding)
- [Convert Hex to ASCII in Java](https://www.baeldung.com/java-convert-hex-to-ascii) #remove additional readme file
- [Convert Hex to ASCII in Java](https://www.baeldung.com/java-convert-hex-to-ascii)
- More articles: [[<-- prev]](../core-java-string-operations)

View File

@ -45,12 +45,6 @@
<artifactId>javax.el</artifactId>
<version>${javax.el.version}</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>${hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>

View File

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

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

@ -90,7 +90,6 @@
<module>core-java-lang-syntax-2</module>
<module>core-java-networking</module>
<module>core-java-networking-2</module>
<module>core-java-networking-3</module>
<module>core-java-nio</module>
<module>core-java-nio-2</module>
<module>core-java-optional</module>

View File

@ -144,12 +144,6 @@
</exclusions>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>${hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>

View File

@ -61,10 +61,7 @@
</build>
<properties>
<!-- marshalling -->
<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>
</properties>

View File

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

View File

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

View File

@ -1,3 +0,0 @@
### Relevant Articles:
- [Kotlin vs Java](https://www.baeldung.com/kotlin/vs-java)

View File

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

View File

@ -0,0 +1,49 @@
package com.baeldung.jackson.booleanAsInt;
public class Game {
private Long id;
private String name;
private Boolean paused;
private Boolean over;
public Game() {
}
public Game(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Boolean isPaused() {
return paused;
}
public void setPaused(Boolean paused) {
this.paused = paused;
}
public Boolean isOver() {
return over;
}
public void setOver(Boolean over) {
this.over = over;
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.jackson.booleanAsInt;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonFormat.Shape;
public class GameAnnotatedByJsonFormat {
private Long id;
private String name;
@JsonFormat(shape = Shape.NUMBER)
private boolean paused;
@JsonFormat(shape = Shape.NUMBER)
private boolean over;
public GameAnnotatedByJsonFormat() {
}
public GameAnnotatedByJsonFormat(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public boolean isPaused() {
return paused;
}
public void setPaused(boolean paused) {
this.paused = paused;
}
public boolean isOver() {
return over;
}
public void setOver(boolean over) {
this.over = over;
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.jackson.booleanAsInt;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
public class GameAnnotatedByJsonSerializeDeserialize {
private Long id;
private String name;
@JsonSerialize(using = NumericBooleanSerializer.class)
@JsonDeserialize(using = NumericBooleanDeserializer.class)
private Boolean paused;
@JsonSerialize(using = NumericBooleanSerializer.class)
@JsonDeserialize(using = NumericBooleanDeserializer.class)
private Boolean over;
public GameAnnotatedByJsonSerializeDeserialize() {
}
public GameAnnotatedByJsonSerializeDeserialize(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Boolean isPaused() {
return paused;
}
public void setPaused(Boolean paused) {
this.paused = paused;
}
public Boolean isOver() {
return over;
}
public void setOver(Boolean over) {
this.over = over;
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.jackson.booleanAsInt;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
public class NumericBooleanDeserializer extends JsonDeserializer<Boolean> {
@Override
public Boolean deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException {
if ("1".equals(p.getText())) {
return Boolean.TRUE;
}
if ("0".equals(p.getText())) {
return Boolean.FALSE;
}
// for other than "1" or "0" throw exception by using Jackson internals
throw ctxt.weirdStringException(p.getText(), Boolean.class, "only \"1\" or \"0\" recognized");
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.jackson.booleanAsInt;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
public class NumericBooleanSerializer extends JsonSerializer<Boolean> {
@Override
public void serialize(Boolean value, JsonGenerator gen, SerializerProvider serializers)
throws IOException {
gen.writeString(value ? "1" : "0");
}
}

View File

@ -0,0 +1,132 @@
package com.baeldung.jackson.booleanAsInt;
import static org.assertj.core.api.Assertions.assertThat;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonFormat.Shape;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class BooleanAsIntegerUnitTest {
private ObjectMapper mapper;
@BeforeEach
public void setup() {
mapper = new ObjectMapper();
}
@Test
public void givenBoolean_serializedAsInteger() throws Exception {
GameAnnotatedByJsonFormat
game = new GameAnnotatedByJsonFormat(1L, "My Game");
game.setPaused(true);
game.setOver(false);
String json = mapper.writeValueAsString(game);
assertThat(json)
.isEqualTo("{\"id\":1,\"name\":\"My Game\",\"paused\":1,\"over\":0}");
}
@Test
public void givenInteger_deserializedAsBooleanByDefault() throws Exception {
// Integer "1" and "0" values deserialized correctly out of the box.
// No configuration or @JsonFormat annotation needed.
String json = "{\"id\":1,\"name\":\"My Game\",\"paused\":1,\"over\":0}";
Game game = mapper.readValue(json, Game.class);
assertThat(game.isPaused()).isEqualTo(true);
assertThat(game.isOver()).isEqualTo(false);
}
@Test
public void givenBoolean_serializedAsIntegerGlobally() throws Exception {
// global configuration override for the type Boolean
mapper.configOverride(Boolean.class)
.setFormat(JsonFormat.Value.forShape(Shape.NUMBER));
Game game = new Game(1L, "My Game");
game.setPaused(true);
game.setOver(false);
String json = mapper.writeValueAsString(game);
assertThat(json)
.isEqualTo("{\"id\":1,\"name\":\"My Game\",\"paused\":1,\"over\":0}");
}
@Test
public void givenBooleanWithCustomSerializer_serializedAsNumericString() throws Exception {
GameAnnotatedByJsonSerializeDeserialize
game = new GameAnnotatedByJsonSerializeDeserialize(1L, "My Game");
game.setPaused(true);
game.setOver(false);
String json = mapper.writeValueAsString(game);
assertThat(json)
.isEqualTo("{\"id\":1,\"name\":\"My Game\",\"paused\":\"1\",\"over\":\"0\"}");
}
@Test
public void givenNumericStringWithCustomDeserializer_deserializedAsBoolean() throws Exception {
String json = "{\"id\":1,\"name\":\"My Game\",\"paused\":\"1\",\"over\":\"0\"}";
GameAnnotatedByJsonSerializeDeserialize
game = mapper.readValue(json, GameAnnotatedByJsonSerializeDeserialize.class);
assertThat(game.isPaused()).isEqualTo(true);
assertThat(game.isOver()).isEqualTo(false);
}
@Test
public void givenBooleanWithCustomSerializer_serializedAsNumericStringGlobally() throws Exception {
// setting serializers globally
SimpleModule module = new SimpleModule();
module.addSerializer(Boolean.class, new NumericBooleanSerializer());
mapper.registerModule(module);
Game game = new Game(1L, "My Game");
game.setPaused(true);
game.setOver(false);
String json = mapper.writeValueAsString(game);
assertThat(json)
.isEqualTo("{\"id\":1,\"name\":\"My Game\",\"paused\":\"1\",\"over\":\"0\"}");
}
@Test
public void givenNumericStringWithCustomDeserializer_deserializedAsBooleanGlobally() throws Exception {
// setting deserializers globally
SimpleModule module = new SimpleModule();
module.addDeserializer(Boolean.class, new NumericBooleanDeserializer());
mapper.registerModule(module);
String json = "{\"id\":1,\"name\":\"My Game\",\"paused\":\"1\",\"over\":\"0\"}";
Game game = mapper.readValue(json, Game.class);
assertThat(game.isPaused()).isEqualTo(true);
assertThat(game.isOver()).isEqualTo(false);
}
@Test
public void givenInvalidStringWithCustomDeserializer_throwsInvalidFormatException() {
// another number other than "1" or "0"
String json = "{\"id\":1,\"name\":\"My Game\",\"paused\":\"5\"}";
InvalidFormatException e = Assertions.assertThrows(
InvalidFormatException.class, () -> mapper.readValue(json, GameAnnotatedByJsonSerializeDeserialize.class)
);
assertThat(e.getValue()).isEqualTo("5");
// non-numeric string
String json2 = "{\"id\":1,\"name\":\"My Game\",\"paused\":\"xxx\"}";
InvalidFormatException e2 = Assertions.assertThrows(
InvalidFormatException.class, () -> mapper.readValue(json2, GameAnnotatedByJsonSerializeDeserialize.class)
);
assertThat(e2.getValue()).isEqualTo("xxx");
}
}

View File

@ -26,12 +26,6 @@
<artifactId>modelmapper</artifactId>
<version>${modelmapper.version}</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>${hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>

View File

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

View File

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

View File

@ -74,7 +74,6 @@
<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>
<commons-collections4.version>4.1</commons-collections4.version>
<yasson.version>1.0.1</yasson.version>
<json.version>20171018</json.version>
<gson.version>2.8.5</gson.version>

View File

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

View File

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

View File

@ -63,7 +63,6 @@
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
<!-- Hikari CP -->
<dependency>

View File

@ -118,7 +118,6 @@
<version>${spring-mock-mvc.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hamcrest/java-hamcrest -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>java-hamcrest</artifactId>
@ -196,7 +195,6 @@
<spring.version>4.3.8.RELEASE</spring.version>
<spring-mock-mvc.version>4.1.1</spring-mock-mvc.version>
<java-hamcrest.version>2.0.0.0</java-hamcrest.version>
<h2.version>1.4.200</h2.version>
<dbunit.version>2.7.0</dbunit.version>
<assertj-core.version>3.14.0</assertj-core.version>
<maven-compiler-plugin.target>1.8</maven-compiler-plugin.target>

View File

@ -167,12 +167,6 @@
<artifactId>google-oauth-client-jetty</artifactId>
<version>${google-api.version}</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>${hamcrest-all.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
@ -279,7 +273,6 @@
<protonpack.version>1.15</protonpack.version>
<google-api.version>1.23.0</google-api.version>
<jets3t-version>0.9.4.0006L</jets3t-version>
<hamcrest-all.version>1.3</hamcrest-all.version>
<javax.jdo.version>3.2.0-m7</javax.jdo.version>
<datanucleus.version>5.1.1</datanucleus.version>
<datanucleus-maven-plugin.version>5.0.2</datanucleus-maven-plugin.version>

View File

@ -1,4 +1,3 @@
### Relevant Articles:
- [Linux Commands Remove All Text After X](https://www.baeldung.com/linux/remove-text-after-x-in-file)
- [Linux Commands for Appending Multiple Lines to a File](https://www.baeldung.com/linux/appending-multiple-lines-to-file2)

View File

@ -74,4 +74,40 @@
<javax.activation.version>1.1.1</javax.activation.version>
</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>

View File

@ -43,7 +43,6 @@
<properties>
<guava.version>31.0.1-jre</guava.version>
<modelmapper.version>2.3.7</modelmapper.version>
<hamcrest.version>2.2</hamcrest.version>
</properties>
</project>

View File

@ -44,7 +44,6 @@
</dependencies>
<properties>
<h2.version>1.4.200</h2.version>
<mssql.driver.version>8.4.1.jre11</mssql.driver.version>
<oracle.driver.version>10.2.0.4.0</oracle.driver.version>
<mysql.driver.version>8.0.22</mysql.driver.version>

View File

@ -55,7 +55,6 @@
</dependencies>
<properties>
<h2.version>1.4.200</h2.version>
<commons-dbcp2.version>2.4.0</commons-dbcp2.version>
<HikariCP.version>3.2.0</HikariCP.version>
<c3p0.version>0.9.5.2</c3p0.version>

View File

@ -45,7 +45,6 @@
<properties>
<hibernate-core.version>5.4.7.Final</hibernate-core.version>
<h2.version>1.4.200</h2.version>
<maven.deploy.skip>true</maven.deploy.skip>
<spring-boot.version>2.1.7.RELEASE</spring-boot.version>
<hibernate.core.version>5.4.7.Final</hibernate.core.version>

View File

@ -1,5 +1,5 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:mydb3;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=100;MVCC=FALSE
hibernate.connection.url=jdbc:h2:mem:mydb3;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=100
hibernate.connection.username=sa
hibernate.connection.autocommit=true
hibernate.dialect=org.hibernate.dialect.H2Dialect

View File

@ -69,6 +69,7 @@
</dependencies>
<properties>
<h2.version>1.4.197</h2.version> <!-- needs to be specified as it fails with parent's 1.4.200 -->
<hibernate.version>5.4.12.Final</hibernate.version>
<hibernate-types.version>2.10.4</hibernate-types.version>
<hibernate-validator.version>6.0.16.Final</hibernate-validator.version>

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)
- [How to Return Multiple Entities In JPA Query](https://www.baeldung.com/jpa-return-multiple-entities)
- [Defining Unique Constraints in JPA](https://www.baeldung.com/jpa-unique-constraints)
- [How to Check Field Existence in MongoDB?](https://www.baeldung.com/mongodb-check-field-exists)
- [Connecting to a Specific Schema in JDBC](https://www.baeldung.com/jdbc-connect-to-schema)

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)
- [MongoDB Aggregations Using Java](https://www.baeldung.com/java-mongodb-aggregations)
- [BSON to JSON Document Conversion in Java](https://www.baeldung.com/java-convert-bson-to-json)
- [How to Check Field Existence in MongoDB?](https://www.baeldung.com/mongodb-check-field-exists)

View File

@ -45,7 +45,6 @@
<properties>
<jooq.version>3.13.4</jooq.version>
<h2.version>1.4.200</h2.version>
</properties>
</project>

View File

@ -63,7 +63,6 @@
<properties>
<r2dbc-h2.version>0.8.1.RELEASE</r2dbc-h2.version>
<h2.version>1.4.200</h2.version>
</properties>
</project>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -1,10 +1,7 @@
package com.baeldung.h2db.lazy_load_no_trans.config;
import net.ttddyy.dsproxy.listener.DataSourceQueryCountListener;
import net.ttddyy.dsproxy.listener.logging.CommonsQueryLoggingListener;
import net.ttddyy.dsproxy.listener.logging.DefaultQueryLogEntryCreator;
import net.ttddyy.dsproxy.listener.logging.SLF4JLogLevel;
import net.ttddyy.dsproxy.listener.logging.SLF4JQueryLoggingListener;
import net.ttddyy.dsproxy.support.ProxyDataSource;
import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder;
import org.aopalliance.intercept.MethodInterceptor;
@ -49,7 +46,7 @@ public class DatasourceProxyBeanPostProcessor implements BeanPostProcessor {
this.dataSource = ProxyDataSourceBuilder.create(dataSource)
.name("MyDS")
.multiline()
.logQueryBySlf4j(SLF4JLogLevel.INFO)
.logQueryBySlf4j(SLF4JLogLevel.DEBUG)
.listener(new DataSourceQueryCountListener())
.build();
}

View File

@ -4,7 +4,7 @@ spring.datasource.username=sa
spring.datasource.password=
spring.jpa.defer-datasource-initialization=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.validator.apply_to_ddl=false
#spring.jpa.properties.hibernate.check_nullability=true

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

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