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
-1
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>
@@ -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() {
-5
View File
@@ -43,9 +43,4 @@
</resources>
</build>
<properties>
<!-- util -->
<commons-collections4.version>4.1</commons-collections4.version>
</properties>
</project>
@@ -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();
-1
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>
@@ -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>
@@ -0,0 +1,5 @@
package com.baeldung.collections.mulipletypesinmap;
public interface DynamicTypeValue {
String valueDescription();
}
@@ -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));
}
}
@@ -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));
}
}
@@ -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);
}
}
@@ -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}");
}
}
@@ -22,8 +22,4 @@
</dependency>
</dependencies>
<properties>
<commons-collections4.version>4.1</commons-collections4.version>
</properties>
</project>
@@ -28,8 +28,4 @@
</dependency>
</dependencies>
<properties>
<commons-collections4.version>4.1</commons-collections4.version>
</properties>
</project>
@@ -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>
@@ -27,8 +27,4 @@
</dependency>
</dependencies>
<properties>
<commons-collections4.version>4.1</commons-collections4.version>
</properties>
</project>
@@ -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>
@@ -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>
@@ -22,8 +22,4 @@
</dependency>
</dependencies>
<properties>
<commons-collections4.version>4.1</commons-collections4.version>
</properties>
</project>
@@ -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>
@@ -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>
@@ -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());
}
@@ -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();
}
}
@@ -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>
@@ -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)
@@ -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>
@@ -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);
}
}
}
@@ -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);
}
}
@@ -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;
@@ -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));
}
}
@@ -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();
}
}

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