Merge branch 'master' into fix-5227

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

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>