Merge branch 'eugenp:master' into PR-6910

This commit is contained in:
parthiv39731 2023-10-17 20:04:47 +05:30 committed by GitHub
commit 091db2e590
220 changed files with 1131 additions and 557 deletions

View File

@ -8,9 +8,9 @@
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
@ -21,30 +21,8 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
<compilerArgs>--enable-preview</compilerArgs>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source.version>12</maven.compiler.source.version>
<maven.compiler.target.version>12</maven.compiler.target.version>
<java.version>17</java.version>
</properties>
</project>

View File

@ -19,19 +19,6 @@ public class SwitchUnitTest {
Assert.assertEquals(value, 2);
}
@Test
public void switchLocalVariable(){
var month = Month.AUG;
int i = switch (month){
case JAN,JUN, JUL -> 3;
case FEB,SEP, OCT, NOV, DEC -> 1;
case MAR,MAY, APR, AUG -> {
int j = month.toString().length() * 4;
break j;
}
};
Assert.assertEquals(12, i);
}
enum Month {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}
}

View File

@ -8,39 +8,13 @@
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
<release>13</release>
<compilerArgs>--enable-preview</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.plugin.version}</version>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source.version>13</maven.compiler.source.version>
<maven.compiler.target.version>13</maven.compiler.target.version>
<surefire.plugin.version>3.0.0-M3</surefire.plugin.version>
<java.version>17</java.version>
</properties>
</project>

View File

@ -7,7 +7,6 @@ import org.junit.Test;
public class SwitchExpressionsWithYieldUnitTest {
@Test
@SuppressWarnings("preview")
public void whenSwitchingOnOperationSquareMe_thenWillReturnSquare() {
var me = 4;
var operation = "squareMe";

View File

@ -8,7 +8,6 @@ public class TextBlocksUnitTest {
private static final String JSON_STRING = "{\r\n" + "\"name\" : \"Baeldung\",\r\n" + "\"website\" : \"https://www.%s.com/\"\r\n" + "}";
@SuppressWarnings("preview")
private static final String TEXT_BLOCK_JSON = """
{
"name" : "Baeldung",
@ -25,7 +24,6 @@ public class TextBlocksUnitTest {
}
@SuppressWarnings("removal")
@Test
public void whenTextBlocks_thenFormattedWorksAsFormat() {
assertThat(TEXT_BLOCK_JSON.formatted("baeldung")

View File

@ -13,7 +13,6 @@ import org.junit.Test;
public class SwitchExpressionsUnitTest {
@Test
@SuppressWarnings ("preview")
public void whenSwitchingOverMonthJune_thenWillReturn3() {
var month = JUNE;
@ -29,7 +28,6 @@ public class SwitchExpressionsUnitTest {
}
@Test
@SuppressWarnings ("preview")
public void whenSwitchingOverMonthAugust_thenWillReturn24() {
var month = AUGUST;
@ -47,7 +45,6 @@ public class SwitchExpressionsUnitTest {
}
@Test
@SuppressWarnings ("preview")
public void whenSwitchingOverMonthJanuary_thenWillReturn3() {
Function<Month, Integer> func = (month) -> {
@ -61,7 +58,6 @@ public class SwitchExpressionsUnitTest {
}
@Test
@SuppressWarnings ("preview")
public void whenSwitchingOverMonthAugust_thenWillReturn2() {
var month = AUGUST;

View File

@ -8,10 +8,9 @@
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
@ -27,33 +26,8 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<release>${maven.compiler.release}</release>
<compilerArgs>--enable-preview</compilerArgs>
<source>14</source>
<target>14</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.plugin.version}</version>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.release>15</maven.compiler.release>
<surefire.plugin.version>3.0.0-M3</surefire.plugin.version>
<java.version>17</java.version>
</properties>
</project>

View File

@ -0,0 +1,98 @@
package com.baeldung.map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
class Magic {
public String nullFunc() {
return null;
}
public String strFunc(String input) {
return input + ": A nice string";
}
}
public class PutIfAbsentVsComputeIfAbsentUnitTest {
private static final Map<String, String> MY_MAP = new HashMap<>();
private Magic magic = new Magic();
@BeforeEach
void resetTheMap() {
MY_MAP.clear();
MY_MAP.put("Key A", "value A");
MY_MAP.put("Key B", "value B");
MY_MAP.put("Key C", "value C");
MY_MAP.put("Key Null", null);
}
@Test
void whenCallingPutIfAbsentWithAbsentKey_thenGetNull() {
String putResult = MY_MAP.putIfAbsent("new key1", magic.nullFunc());
assertNull(putResult);
putResult = MY_MAP.putIfAbsent("new key2", magic.strFunc("new key2"));
assertNull(putResult);
putResult = MY_MAP.putIfAbsent("Key Null", magic.strFunc("Key Null"));
assertNull(putResult);
}
@Test
void whenCallingComputeIfAbsentWithAbsentKey_thenGetExpectedResult() {
String computeResult = MY_MAP.computeIfAbsent("new key1", k -> magic.nullFunc());
assertNull(computeResult);
computeResult = MY_MAP.computeIfAbsent("new key2", k -> magic.strFunc(k));
assertEquals("new key2: A nice string", computeResult);
computeResult = MY_MAP.computeIfAbsent("Key Null", k -> magic.strFunc(k));
assertEquals("Key Null: A nice string", computeResult);
}
@Test
void whenCallingPutIfAbsentWithAbsentKey_thenNullIsPut() {
assertEquals(4, MY_MAP.size()); // initial: 4 entries
MY_MAP.putIfAbsent("new key", magic.nullFunc());
assertEquals(5, MY_MAP.size());
assertTrue(MY_MAP.containsKey("new key")); // new entry has been added to the map
assertNull(MY_MAP.get("new key"));
}
@Test
void whenCallingComputeIfAbsentWithAbsentKey_thenNullIsNotPut() {
assertEquals(4, MY_MAP.size()); // initial: 4 entries
MY_MAP.computeIfAbsent("new key", k -> magic.nullFunc());
assertEquals(4, MY_MAP.size());
assertFalse(MY_MAP.containsKey("new key")); // <- no new entry added
}
@Test
void whenCallingPutIfAbsent_thenFunctionIsAlwaysCalled() {
Magic spyMagic = spy(magic);
MY_MAP.putIfAbsent("Key A", spyMagic.strFunc("Key A"));
verify(spyMagic, times(1)).strFunc(anyString());
MY_MAP.putIfAbsent("new key", spyMagic.strFunc("new key"));
verify(spyMagic, times(2)).strFunc(anyString());
}
@Test
void whenCallingComputeIfAbsent_thenFunctionIsCalledOnDemand() {
Magic spyMagic = spy(magic);
MY_MAP.computeIfAbsent("Key A", k -> spyMagic.strFunc(k));
verify(spyMagic, never()).strFunc(anyString());
MY_MAP.computeIfAbsent("new key", k -> spyMagic.strFunc(k));
verify(spyMagic, times(1)).strFunc(anyString());
}
}

View File

@ -0,0 +1,62 @@
package com.baeldung.writehashmaptocsvfile;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class WriteHashmaptoCVSFileUnitTest {
@Test
public void givenEmployeeData_whenWriteToCSV_thenCSVFileIsCreated() {
Map<String, String> employeeData = new HashMap<>();
employeeData.put("Name", "John Doe");
employeeData.put("Title", "Software Engineer");
employeeData.put("Department", "Engineering");
employeeData.put("Salary", "75000");
try (FileWriter csvWriter = new FileWriter("employee_data.csv")) {
// Write header row
csvWriter.append("Name,Title,Department,Salary\n");
// Write data row
csvWriter.append(employeeData.get("Name")).append(",");
csvWriter.append(employeeData.get("Title")).append(",");
csvWriter.append(employeeData.get("Department")).append(",");
csvWriter.append(employeeData.get("Salary")).append("\n");
} catch (IOException e) {
e.printStackTrace();
}
// Ensure the CSV file exists
assertTrue(new File("employee_data.csv").exists(), "CSV file does not exist!");
}
@Test
public void givenCSVFile_whenRead_thenContentsMatchExpected() {
// Read the actual content of the CSV file
StringBuilder actualCsvContent = new StringBuilder();
try {
Files.lines(Paths.get("employee_data.csv"))
.forEach(line -> actualCsvContent.append(line).append("\n"));
// Define the expected CSV content
String expectedCsvContent = "Name,Title,Department,Salary\n" +
"John Doe,Software Engineer,Engineering,75000\n";
// Compare the actual content with the expected content
assertEquals(expectedCsvContent, actualCsvContent.toString());
System.out.println("CSV file created successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,36 @@
<?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>core-java-concurrency-advanced-5</artifactId>
<name>core-java-concurrency-advanced-5</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<build>
<finalName>core-java-concurrency-advanced-5</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
</project>

View File

@ -0,0 +1,24 @@
package com.baeldung.wait_synchronization;
public class ConditionChecker {
private volatile Boolean jobIsDone;
private final Object lock = new Object();
public void ensureCondition() {
synchronized (lock) {
while (!jobIsDone) {
try {
lock.wait();
} catch (InterruptedException e) { }
}
}
}
public void complete() {
synchronized (lock) {
jobIsDone = true;
lock.notify();
}
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.wait_synchronization;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
class ConditionCheckerUnitTest {
@Test
public void givenBothMethodsAreSynchronized_whenBothMethodsAreCalled_thenNoExceptionsOrDeadlocks() {
ConditionChecker conditionChecker = new ConditionChecker();
ExecutorService executorService = Executors.newFixedThreadPool(2);
Assertions.assertThatCode(() -> {
executorService.submit(conditionChecker::ensureCondition);
executorService.submit(conditionChecker::complete);
}).doesNotThrowAnyException();
}
}

View File

@ -65,7 +65,7 @@
<properties>
<commons-validator.version>1.6</commons-validator.version>
<joda-time.version>2.10.10</joda-time.version>
<joda-time.version>2.12.5</joda-time.version>
<hirondelle-date4j.version>RELEASE</hirondelle-date4j.version>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>

View File

@ -15,6 +15,7 @@ import java.util.Map;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.web.util.UriComponentsBuilder;
@ -23,95 +24,101 @@ import com.google.common.collect.ImmutableMap;
public class UrlUnitTest {
@Test
public void givenUrl_whenCanIdentifyProtocol_thenCorrect() throws MalformedURLException {
final URL url = new URL("http://baeldung.com");
public void givenUrl_whenCanIdentifyProtocol_thenCorrect() throws MalformedURLException, URISyntaxException {
final URL url = new URI("http://baeldung.com").toURL();
assertEquals("http", url.getProtocol());
}
@Test
public void givenUrl_whenCanGetHost_thenCorrect() throws MalformedURLException {
final URL url = new URL("http://baeldung.com");
public void givenUrl_whenCanGetHost_thenCorrect() throws MalformedURLException, URISyntaxException {
final URL url = new URI("http://baeldung.com").toURL();
assertEquals("baeldung.com", url.getHost());
}
@Test
public void givenUrl_whenCanGetFileName_thenCorrect2() throws MalformedURLException {
final URL url = new URL("http://baeldung.com/articles?topic=java&version=8");
public void givenUrl_whenCanGetFileName_thenCorrect2() throws MalformedURLException, URISyntaxException {
final URL url = new URI("http://baeldung.com/articles?topic=java&version=8").toURL();
assertEquals("/articles?topic=java&version=8", url.getFile());
}
@Test
public void givenUrl_whenCanGetFileName_thenCorrect1() throws MalformedURLException {
final URL url = new URL("http://baeldung.com/guidelines.txt");
public void givenUrl_whenCanGetFileName_thenCorrect1() throws MalformedURLException, URISyntaxException {
final URL url = new URI("http://baeldung.com/guidelines.txt").toURL();
assertEquals("/guidelines.txt", url.getFile());
}
@Test
public void givenUrl_whenCanGetPathParams_thenCorrect() throws MalformedURLException {
final URL url = new URL("http://baeldung.com/articles?topic=java&version=8");
public void givenUrl_whenCanGetPathParams_thenCorrect() throws MalformedURLException, URISyntaxException {
final URL url = new URI("http://baeldung.com/articles?topic=java&version=8").toURL();
assertEquals("/articles", url.getPath());
}
@Test
public void givenUrl_whenCanGetQueryParams_thenCorrect() throws MalformedURLException {
final URL url = new URL("http://baeldung.com/articles?topic=java");
assertEquals("topic=java", url.getQuery());
public void givenUrl_whenCanGetQueryParams_thenCorrect() throws MalformedURLException, URISyntaxException {
final URL url = new URI("http://baeldung.com/articles?topic=java&amp;version=8").toURL();
assertEquals("topic=java&amp;version=8", url.getQuery());
}
@Test
public void givenUrl_whenGetsDefaultPort_thenCorrect() throws MalformedURLException {
final URL url = new URL("http://baeldung.com");
public void givenUrl_whenGetsDefaultPort_thenCorrect() throws MalformedURLException, URISyntaxException {
final URL url = new URI("http://baeldung.com").toURL();
assertEquals(-1, url.getPort());
assertEquals(80, url.getDefaultPort());
}
@Test
public void givenUrl_whenGetsPort_thenCorrect() throws MalformedURLException {
final URL url = new URL("http://baeldung.com:8090");
public void givenUrl_whenGetsPort_thenCorrect() throws MalformedURLException, URISyntaxException {
final URL url = new URI("http://baeldung.com:8090").toURL();
assertEquals(8090, url.getPort());
assertEquals(80, url.getDefaultPort());
}
@Test
public void givenBaseUrl_whenCreatesRelativeUrl_thenCorrect() throws MalformedURLException {
final URL baseUrl = new URL("http://baeldung.com");
final URL relativeUrl = new URL(baseUrl, "a-guide-to-java-sockets");
assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString());
public void givenHomeUrlAndFullUrl_whenRelativize_thenCorrect() throws MalformedURLException, URISyntaxException {
final URI homeUri = new URI("http://baeldung.com");
final URI fullUri = new URI("http://baeldung.com" + "/a-guide-to-java-sockets");
final URI relativeUri = homeUri.relativize(fullUri);
assertEquals("a-guide-to-java-sockets", relativeUri.toString());
}
@Test
public void givenAbsoluteUrl_whenIgnoresBaseUrl_thenCorrect() throws MalformedURLException {
final URL baseUrl = new URL("http://baeldung.com");
final URL relativeUrl = new URL(baseUrl, "http://baeldung.com/a-guide-to-java-sockets");
assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString());
}
@Test
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException {
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException, URISyntaxException {
final String protocol = "http";
final String host = "baeldung.com";
final String file = "/guidelines.txt";
final URL url = new URL(protocol, host, file);
assertEquals("http://baeldung.com/guidelines.txt", url.toString());
final String fragment = "myImage";
final URL url = new URI(protocol, host, file, fragment).toURL();
assertEquals("http://baeldung.com/guidelines.txt#myImage", url.toString());
}
@Test
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect2() throws MalformedURLException {
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect2() throws MalformedURLException, URISyntaxException {
final String protocol = "http";
final String username = "admin";
final String host = "baeldung.com";
final String file = "/articles?topic=java&version=8";
final URL url = new URL(protocol, host, file);
assertEquals("http://baeldung.com/articles?topic=java&version=8", url.toString());
final String file = "/articles";
final String query = "topic=java&version=8";
final String fragment = "myImage";
final URL url = new URI(protocol, username, host, -1, file, query, fragment).toURL();
assertEquals("http://admin@baeldung.com/articles?topic=java&version=8#myImage", url.toString());
}
@Test
public void givenUrlComponentsWithPort_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException {
public void givenRelativeUrl_whenCreatesRelativeUrl_thenThrows() throws URISyntaxException, MalformedURLException {
final URI uri = new URI("/a-guide-to-java-sockets");
Assert.assertThrows(IllegalArgumentException.class, () -> uri.toURL());
}
@Test
public void givenUrlComponentsWithPort_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException, URISyntaxException {
final String protocol = "http";
final String username = "admin";
final String host = "baeldung.com";
final int port = 9000;
final String file = "/guidelines.txt";
final URL url = new URL(protocol, host, port, file);
assertEquals("http://baeldung.com:9000/guidelines.txt", url.toString());
final String fragment = "myImage";
final URL url = new URI(protocol, username, host, port, file, null, fragment).toURL();
assertEquals("http://admin@baeldung.com:9000/guidelines.txt#myImage", url.toString());
}
@Test
@ -120,7 +127,8 @@ public class UrlUnitTest {
uriBuilder.setPort(9090);
uriBuilder.addParameter("topic", "java");
uriBuilder.addParameter("version", "8");
URL url = uriBuilder.build().toURL();
URL url = uriBuilder.build()
.toURL();
assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
}
@ -130,26 +138,27 @@ public class UrlUnitTest {
URIBuilder uriBuilder = new URIBuilder("http://baeldung.com/articles");
uriBuilder.setPort(9090);
uriBuilder.addParameters(paramMap.entrySet()
.stream()
.map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
.collect(toList()));
.stream()
.map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
.collect(toList()));
URL url = uriBuilder.build().toURL();
URL url = uriBuilder.build()
.toURL();
assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
}
@Test
public void givenUrlParameters_whenBuildUrlWithSpringUriComponentsBuilder_thenSuccess() throws MalformedURLException {
URL url = UriComponentsBuilder.newInstance()
.scheme("http")
.host("baeldung.com")
.port(9090)
.path("articles")
.queryParam("topic", "java")
.queryParam("version", "8")
.build()
.toUri()
.toURL();
.scheme("http")
.host("baeldung.com")
.port(9090)
.path("articles")
.queryParam("topic", "java")
.queryParam("version", "8")
.build()
.toUri()
.toURL();
assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
}

View File

@ -0,0 +1,2 @@
### Relevant Articles:

View File

@ -0,0 +1,72 @@
<?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>core-java-string-operations-7</artifactId>
<name>core-java-string-operations-7</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${apache.commons.lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>${commons-text.version}</version>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
<version>4.9.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
<version>4.9.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<apache.commons.lang3.version>3.12.0</apache.commons.lang3.version>
<commons-text.version>1.10.0</commons-text.version>
</properties>
</project>

View File

@ -0,0 +1,47 @@
package com.baeldung.centertext;
import liquibase.repackaged.org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals;
public class CenteringTextUnitTest {
@Test
public void givenTextAndTotalWidth_whenUsingStringFormat_thenTextIsCentered() {
String text = "Centered Text";
int totalWidth = 20;
int padding = (totalWidth - text.length()) / 2;
String centeredText = String.format("%" + padding + "s%s%" + padding + "s", "", text, "");
String expectedCenteredText = " Centered Text ";
Assert.assertEquals("Centered Text", expectedCenteredText, centeredText);
}
@Test
public void givenTextAndTotalWidth_whenCenterUsingStringBuilder_thenTextIsCentered() {
String text = "Centered Text";
int width = 20;
int padding = (width - text.length()) / 2;
StringBuilder centeredText = new StringBuilder();
for (int i = 0; i < padding; i++) {
centeredText.append(" ");
}
centeredText.append(text);
for (int i = 0; i < padding; i++) {
centeredText.append(" ");
}
String centeredTextString = centeredText.toString();
String expectedCenteredText = " Centered Text ";
Assert.assertEquals("Centered Text", expectedCenteredText, centeredTextString);
}
@Test
public void givenTextAndTotalWidth_whenUsingStringUtilsCenterMethod_thenTextIsCentered() {
String text = "Centered Text";
int width = 20;
String centeredText = StringUtils.center(text, width);
String expectedCenteredText = StringUtils.center("Centered Text", width);
assertEquals("Centered Text", expectedCenteredText, centeredText);
}
}

View File

@ -34,6 +34,9 @@
<module>core-java-11</module>
<module>core-java-11-2</module>
<module>core-java-11-3</module>
<module>core-java-12</module>
<module>core-java-13</module>
<module>core-java-15</module>
<module>core-java-collections-array-list</module>
<module>core-java-collections-array-list-2</module>
<module>core-java-collections-list-4</module>
@ -178,6 +181,7 @@
<module>core-java-string-operations</module>
<module>core-java-string-operations-2</module>
<module>core-java-string-operations-6</module>
<module>core-java-string-operations-7</module>
<module>core-java-regex</module>
<module>core-java-regex-2</module>
<module>core-java-uuid</module>

View File

@ -237,7 +237,6 @@
<jsoniter.version>0.9.23</jsoniter.version>
<moshi.version>1.9.2</moshi.version>
<fastjson.version>1.2.21</fastjson.version>
<json.version>20211205</json.version>
<jsonschema2pojo-core.version>1.1.1</jsonschema2pojo-core.version>
<jackson-jsonld.version>0.1.1</jackson-jsonld.version>
<hydra-jsonld.version>0.4.2</hydra-jsonld.version>

View File

@ -38,7 +38,6 @@
<properties>
<jsonb-api.version>1.0</jsonb-api.version>
<json.version>20230227</json.version>
<gson.version>2.8.5</gson.version>
<javax.version>1.1.2</javax.version>
<json-unit-assertj.version>2.28.0</json-unit-assertj.version>

View File

@ -37,7 +37,6 @@
</dependencies>
<properties>
<json.version>20211205</json.version>
<gson.version>2.10.1</gson.version>
<guava.version>32.1.2-jre</guava.version>
</properties>

View File

@ -68,7 +68,6 @@
<networknt.json.schema.version>1.0.72</networknt.json.schema.version>
<jsonb-api.version>1.0</jsonb-api.version>
<yasson.version>1.0.1</yasson.version>
<json.version>20230227</json.version>
<gson.version>2.8.5</gson.version>
<javax.version>1.1.2</javax.version>
<json-unit-assertj.version>2.28.0</json-unit-assertj.version>

View File

@ -34,4 +34,8 @@
</pluginManagement>
</build>
<properties>
<json.version>20230618</json.version>
</properties>
</project>

View File

@ -4,9 +4,9 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>api-service</artifactId>
<artifactId>lightrun-api-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>api-service</name>
<name>lightrun-api-service</name>
<description>Aggregator Service for LightRun Article</description>
<parent>

View File

@ -4,9 +4,9 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>tasks-service</artifactId>
<artifactId>lightrun-tasks-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>tasks-service</name>
<name>lightrun-tasks-service</name>
<description>Tasks Service for LightRun Article</description>
<parent>

View File

@ -4,9 +4,9 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>users-service</artifactId>
<artifactId>lightrun-users-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>users-service</name>
<name>lightrun-users-service</name>
<description>Users Service for LightRun Article</description>
<parent>

View File

@ -18,9 +18,9 @@
</parent>
<modules>
<module>tasks-service</module>
<module>users-service</module>
<module>api-service</module>
<module>lightrun-tasks-service</module>
<module>lightrun-users-service</module>
<module>lightrun-api-service</module>
</modules>
</project>

View File

@ -16,6 +16,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
public class JSONLayoutIntegrationTest {
private static Logger logger;
private static Logger jsonlogger;
private ByteArrayOutputStream consoleOutput = new ByteArrayOutputStream();
private PrintStream ps = new PrintStream(consoleOutput);
@ -23,16 +24,24 @@ public class JSONLayoutIntegrationTest {
public void setUp() {
// Redirect console output to our stream
System.setOut(ps);
logger = LoggerFactory.getLogger("jsonLogger");
}
@Test
public void whenLogLayoutInJSON_thenOutputIsCorrectJSON() {
public void givenJsonLayout_whenLogInJSON_thenOutputIsCorrectJSON() {
logger = LoggerFactory.getLogger("jsonLogger");
logger.debug("Debug message");
String currentLog = consoleOutput.toString();
assertTrue(!currentLog.isEmpty() && isValidJSON(currentLog));
}
@Test
public void givenJsonEncoder_whenLogInJSON_thenOutputIsCorrectJSON() {
jsonlogger = LoggerFactory.getLogger("jsonEncoderLogger");
jsonlogger.debug("Debug message");
String currentLog = consoleOutput.toString();
assertTrue(!currentLog.isEmpty() && isValidJSON(currentLog));
}
public static boolean isValidJSON(String jsonInString) {
try {
final ObjectMapper mapper = new ObjectMapper();

View File

@ -19,10 +19,18 @@
</layout>
</appender>
<appender name="jsonEncoder" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.JsonEncoder"/>
</appender>
<logger name="jsonLogger" level="TRACE">
<appender-ref ref="json" />
</logger>
<logger name="jsonEncoderLogger" level="TRACE">
<appender-ref ref="jsonEncoder" />
</logger>
<root level="debug">
<appender-ref ref="map" />
<appender-ref ref="badMap" />

View File

@ -4,8 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.jacoco-coverage-aggregation</groupId>
<artifactId>aggregate-report</artifactId>
<name>aggregate-report</name>
<artifactId>jacoco-coverage-aggregate-report</artifactId>
<name>jacoco-coverage-aggregate-report</name>
<packaging>pom</packaging>
<parent>

View File

@ -4,8 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.jacoco-coverage-aggregation</groupId>
<artifactId>controllers</artifactId>
<name>controllers</name>
<artifactId>jacoco-coverage-controllers-example</artifactId>
<name>jacoco-coverage-controllers-example</name>
<packaging>jar</packaging>
<parent>

View File

@ -4,8 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.jacoco-coverage-aggregation</groupId>
<artifactId>services</artifactId>
<name>services</name>
<artifactId>jacoco-coverage-services-example</artifactId>
<name>jacoco-coverage-services-example</name>
<packaging>jar</packaging>
<parent>

View File

@ -17,9 +17,9 @@
</parent>
<modules>
<module>services</module>
<module>controllers</module>
<module>aggregate-report</module>
<module>jacoco-coverage-services-example</module>
<module>jacoco-coverage-controllers-example</module>
<module>jacoco-coverage-aggregate-report</module>
</modules>
<build>

View File

@ -3,12 +3,12 @@
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>module1</artifactId>
<artifactId>parent-pom-module1</artifactId>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung.maven-parent-pom-resolution</groupId>
<artifactId>aggregator</artifactId>
<artifactId>maven-parent-pom-aggregator</artifactId>
<version>1.0.0-SNAPSHOT</version>
<!-- The parent pom is resolved to project a's pom.xml -->
</parent>

View File

@ -3,12 +3,12 @@
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>module3</artifactId>
<artifactId>parent-pom-module3</artifactId>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung.maven-parent-pom-resolution</groupId>
<artifactId>aggregator</artifactId>
<artifactId>maven-parent-pom-aggregator</artifactId>
<version>1.0.0-SNAPSHOT</version>
<!-- removing relativePath won't work even if project-a is the aggregator project -->
<!-- it only works in IntelliJ IDEA when project-a is registered as a Maven Project -->

View File

@ -3,19 +3,19 @@
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>module2</artifactId>
<artifactId>parent-pom-module2</artifactId>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung.maven-parent-pom-resolution</groupId>
<artifactId>module1</artifactId>
<artifactId>parent-pom-module1</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../module1/pom.xml</relativePath>
<relativePath>../parent-pom-module1/pom.xml</relativePath>
<!-- The parent pom is resolved to project a's pom.xml -->
</parent>
<modules>
<module>module3</module>
<module>parent-pom-module3</module>
</modules>
</project>

View File

@ -4,19 +4,18 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.maven-parent-pom-resolution</groupId>
<artifactId>aggregator</artifactId>
<artifactId>maven-parent-pom-aggregator</artifactId>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>maven-parent-pom-resolution</artifactId>
<version>1.0.0-SNAPSHOT</version>
<!-- The parent pom is resolved to ../pom.xml -->
</parent>
<modules>
<module>module1</module>
<module>module2</module>
<module>parent-pom-module1</module>
<module>parent-pom-module2</module>
</modules>
</project>

View File

@ -9,7 +9,7 @@
<packaging>pom</packaging>
<modules>
<module>aggregator</module>
<module>maven-parent-pom-aggregator</module>
<module>disable-plugin-examples</module>
</modules>

View File

@ -1,14 +1,16 @@
package com.baeldung.bridge;
import static com.baeldung.util.LoggerUtil.LOG;
public class BridgePatternDriver {
public static void main(String[] args) {
//a square with red color
Shape square = new Square(new Red());
System.out.println(square.draw());
LOG.info(square.draw());
//a triangle with blue color
Shape triangle = new Triangle(new Blue());
System.out.println(triangle.draw());
LOG.info(triangle.draw());
}
}

View File

@ -1,5 +1,7 @@
package com.baeldung.composite;
import static com.baeldung.util.LoggerUtil.LOG;
/**
* Created by Gebruiker on 5/1/2018.
*/
@ -14,7 +16,7 @@ public class FinancialDepartment implements Department {
}
public void printDepartmentName() {
System.out.println(getClass().getSimpleName());
LOG.info(getClass().getSimpleName());
}
public Integer getId() {

View File

@ -1,5 +1,7 @@
package com.baeldung.composite;
import static com.baeldung.util.LoggerUtil.LOG;
/**
* Created by Gebruiker on 5/1/2018.
*/
@ -14,7 +16,7 @@ public class SalesDepartment implements Department {
}
public void printDepartmentName() {
System.out.println(getClass().getSimpleName());
LOG.info(getClass().getSimpleName());
}
public Integer getId() {

View File

@ -1,6 +1,6 @@
# Root logger
log4j.rootLogger=INFO, file, stdout
log4j.rootLogger=INFO, stdout
# Write to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender

12
pom.xml
View File

@ -361,7 +361,6 @@
<module>muleesb</module>
<module>web-modules/java-lite</module>
<module>web-modules/restx</module>
<module>persistence-modules/deltaspike</module> <!-- delta spike it doesn't support yet the jakarta API-->
<module>persistence-modules/hibernate-ogm</module> <!-- hibernate-ogm wasn't updated because it doesn't support jakarta API -->
<module>persistence-modules/spring-data-cassandra-reactive</module> <!--JAVA-21844-->
@ -534,7 +533,6 @@
<module>lombok-modules/lombok-custom</module>
<module>muleesb</module>
<module>web-modules/java-lite</module>
<module>web-modules/restx</module>
<module>persistence-modules/deltaspike</module> <!-- delta spike it doesn't support yet the jakarta API-->
<module>persistence-modules/hibernate-ogm</module> <!-- hibernate-ogm wasn't updated because it doesn't support jakarta API -->
<module>persistence-modules/spring-data-cassandra-reactive</module> <!--JAVA-21844-->
@ -770,10 +768,7 @@
<module>core-java-modules</module>
<!-- <module>core-java-modules/core-java-9-new-features</module> --> <!-- uses preview features, to be decided how to handle -->
<!-- <module>core-java-modules/core-java-12</module> --> <!-- uses preview features, to be decided how to handle -->
<!-- <module>core-java-modules/core-java-13</module> --> <!-- uses preview features, to be decided how to handle -->
<!-- <module>core-java-modules/core-java-14</module> --> <!-- uses preview features, to be decided how to handle -->
<!-- <module>core-java-modules/core-java-15</module> --> <!-- uses preview features, to be decided how to handle -->
<!-- <module>core-java-modules/core-java-16</module> --> <!-- uses preview features, to be decided how to handle -->
<!-- <module>core-java-modules/core-java-17</module> --> <!-- uses preview features, to be decided how to handle -->
<!-- <module>core-java-modules/core-java-19</module> --> <!-- uses preview features, to be decided how to handle -->
@ -942,6 +937,7 @@
<module>gradle-modules/gradle/maven-to-gradle</module>
<module>persistence-modules/spring-data-neo4j</module>
<module>parent-boot-3</module>
<module>spring-kafka-2</module>
<!--<module>java-panama</module> Java-19 module-->
</modules>
@ -1050,10 +1046,7 @@
<module>core-java-modules</module>
<module>gcp-firebase</module>
<!-- <module>core-java-modules/core-java-9-new-features</module> --> <!-- uses preview features, to be decided how to handle -->
<!-- <module>core-java-modules/core-java-12</module> --> <!-- uses preview features, to be decided how to handle -->
<!-- <module>core-java-modules/core-java-13</module> --> <!-- uses preview features, to be decided how to handle -->
<!-- <module>core-java-modules/core-java-14</module> --> <!-- uses preview features, to be decided how to handle -->
<!-- <module>core-java-modules/core-java-15</module> --> <!-- uses preview features, to be decided how to handle -->
<!-- <module>core-java-modules/core-java-16</module> --> <!-- uses preview features, to be decided how to handle -->
<!-- <module>core-java-modules/core-java-17</module> --> <!-- uses preview features, to be decided how to handle -->
<!-- <module>core-java-modules/core-java-19</module> --> <!-- uses preview features, to be decided how to handle -->
@ -1225,6 +1218,9 @@
<module>gradle-modules/gradle/maven-to-gradle</module>
<module>persistence-modules/spring-data-neo4j</module>
<module>spring-actuator</module>
<module>spring-cloud-modules/spring-cloud-contract</module>
<module>spring-kafka-2</module>
<!--<module>java-panama</module> Java-19 module-->
</modules>
<properties>

View File

@ -0,0 +1,22 @@
package com.baeldung.webflux.zipwhen.model;
public class User {
private final String id;
private final String email;
public User(String id, String email) {
this.id = id;
this.email = email;
}
public String getId() {
return id;
}
public String getEmail() {
return email;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.webflux.zipwhen.service;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.baeldung.webflux.zipwhen.model.User;
import reactor.core.publisher.Mono;
public class DatabaseService {
private Map<String, User> dataStore = new ConcurrentHashMap<>();
public Mono<Boolean> saveUserData(User user) {
return Mono.create(sink -> {
try {
dataStore.put(user.getId(), user);
sink.success(true);
} catch (Exception e) {
sink.success(false);
}
});
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.webflux.zipwhen.service;
import reactor.core.publisher.Mono;
public class EmailService {
private final UserService userService;
public EmailService(UserService userService) {
this.userService = userService;
}
public Mono<Boolean> sendEmail(String userId) {
return userService.getUser(userId)
.flatMap(user -> {
System.out.println("Sending email to: " + user.getEmail());
return Mono.just(true);
})
.defaultIfEmpty(false);
}
}

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