Merge branch 'eugenp:master' into master

This commit is contained in:
sebx59
2022-11-24 10:55:33 +01:00
committed by GitHub
48 changed files with 1205 additions and 201 deletions
@@ -0,0 +1,21 @@
package com.baeldung.shell;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.function.Consumer;
public class StreamGobbler implements Runnable {
private final InputStream inputStream;
private final Consumer<String> consumer;
public StreamGobbler(InputStream inputStream, Consumer<String> consumer) {
this.inputStream = inputStream;
this.consumer = consumer;
}
@Override
public void run() {
new BufferedReader(new InputStreamReader(inputStream)).lines().forEach(consumer);
}
}
@@ -5,10 +5,7 @@ import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
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;
@@ -21,21 +18,6 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
public class JavaProcessUnitIntegrationTest {
private static final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().startsWith("windows");
private static class StreamGobbler implements Runnable {
private InputStream inputStream;
private Consumer<String> consumer;
public StreamGobbler(InputStream inputStream, Consumer<String> consumer) {
this.inputStream = inputStream;
this.consumer = consumer;
}
@Override
public void run() {
new BufferedReader(new InputStreamReader(inputStream)).lines().forEach(consumer);
}
}
private Consumer<String> consumer = Assert::assertNotNull;
private String homeDirectory = System.getProperty("user.home");
@@ -58,7 +40,7 @@ public class JavaProcessUnitIntegrationTest {
if (IS_WINDOWS) {
process = Runtime.getRuntime().exec(String.format("cmd.exe /c dir %s", homeDirectory));
} else {
process = Runtime.getRuntime().exec(String.format("sh -c ls %s", homeDirectory));
process = Runtime.getRuntime().exec(String.format("/bin/sh -c ls %s", homeDirectory));
}
StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), consumer);
@@ -70,13 +52,34 @@ public class JavaProcessUnitIntegrationTest {
assertEquals(0, exitCode);
}
@Test
public void shouldExecuteCommandWithPipesWithRuntimeProcess(){
Process process;
try {
if (IS_WINDOWS) {
process = Runtime.getRuntime().exec(String.format("cmd.exe /c dir %s | findstr \"Desktop\"", homeDirectory));
} else {
process = Runtime.getRuntime().exec(String.format("/bin/sh -c ls %s | grep \"Desktop\"", homeDirectory));
}
StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), consumer);
Future<?> future = executorService.submit(streamGobbler);
int exitCode = process.waitFor();
// verify the stream output from the process
assertDoesNotThrow(() -> future.get(10, TimeUnit.SECONDS));
assertEquals(0, exitCode);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void givenProcess_whenCreatingViaProcessBuilder_shouldSucceed() throws Exception {
ProcessBuilder builder = new ProcessBuilder();
if (IS_WINDOWS) {
builder.command("cmd.exe", "/c", "dir");
} else {
builder.command("sh", "-c", "ls");
builder.command("/bin/sh", "-c", "ls");
}
builder.directory(new File(homeDirectory));
Process process = builder.start();
@@ -1,15 +1,41 @@
package com.baeldung.system.exit;
import static org.junit.Assert.assertEquals;
import java.security.Permission;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.security.Permission;
import static org.junit.Assert.assertEquals;
@Ignore("This test is ignored because it tests deprecated code")
public class SystemExitUnitTest {
private SecurityManager securityManager;
private SystemExitExample example;
@Before
public void setUp() {
example = new SystemExitExample();
securityManager = System.getSecurityManager();
System.setSecurityManager(new NoExitSecurityManager());
}
@After
public void tearDown() throws Exception {
System.setSecurityManager(securityManager);
}
@Test
public void testExit() throws Exception {
try {
example.readFile();
} catch (ExitException e) {
assertEquals("Exit status", 2, e.status);
}
}
protected static class ExitException extends SecurityException {
private static final long serialVersionUID = 1L;
@@ -35,29 +61,4 @@ public class SystemExitUnitTest {
throw new ExitException(status);
}
}
private SecurityManager securityManager;
private SystemExitExample example;
@Before
public void setUp() throws Exception {
example = new SystemExitExample();
securityManager = System.getSecurityManager();
System.setSecurityManager(new NoExitSecurityManager());
}
@After
public void tearDown() throws Exception {
System.setSecurityManager(securityManager);
}
@Test
public void testExit() throws Exception {
try {
example.readFile();
} catch (ExitException e) {
assertEquals("Exit status", 2, e.status);
}
}
}
@@ -3,8 +3,6 @@ package com.baeldung.uuid;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Random;
import java.util.UUID;
@@ -13,7 +11,8 @@ public final class UUIDGenerator {
private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
private UUIDGenerator() {}
private UUIDGenerator() {
}
/**
* Type 1 UUID Generation
@@ -33,14 +32,12 @@ public final class UUIDGenerator {
}
private static long get64MostSignificantBitsForVersion1() {
final LocalDateTime start = LocalDateTime.of(1582, 10, 15, 0, 0, 0);
final Duration duration = Duration.between(start, LocalDateTime.now());
final long seconds = duration.getSeconds();
final long nanos = duration.getNano();
final long timeForUuidIn100Nanos = seconds * 10000000 + nanos * 100;
final long least12SignificantBitOfTime = (timeForUuidIn100Nanos & 0x000000000000FFFFL) >> 4;
final long timeForUuidIn100Nanos = System.currentTimeMillis();
final long time_low = (timeForUuidIn100Nanos & 0x0000_0000_FFFF_FFFFL) << 32;
final long time_mid = ((timeForUuidIn100Nanos >> 32) & 0xFFFF) << 16;
final long version = 1 << 12;
return (timeForUuidIn100Nanos & 0xFFFFFFFFFFFF0000L) + version + least12SignificantBitOfTime;
final long time_hi = ((timeForUuidIn100Nanos >> 48) & 0x0FFF);
return time_low + time_mid + version + time_hi;
}
/**
@@ -94,32 +91,14 @@ public final class UUIDGenerator {
long lsb = 0;
assert data.length == 16 : "data must be 16 bytes in length";
for (int i = 0; i < 8; i++) {msb = (msb << 8) | (data[i] & 0xff);}
for (int i = 8; i < 16; i++) {lsb = (lsb << 8) | (data[i] & 0xff);}
return new UUID(msb, lsb);
}
/**
* Unique Keys Generation Using Message Digest and Type 4 UUID
* @throws NoSuchAlgorithmException
*/
public static String generateUniqueKeysWithUUIDAndMessageDigest() throws NoSuchAlgorithmException {
final MessageDigest salt = MessageDigest.getInstance("SHA-256");
salt.update(UUID.randomUUID()
.toString()
.getBytes(StandardCharsets.UTF_8));
return bytesToHex(salt.digest());
}
private static String bytesToHex(byte[] bytes) {
final char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
final int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
for (int i = 0; i < 8; i++) {
msb = (msb << 8) | (data[i] & 0xff);
}
return new String(hexChars);
for (int i = 8; i < 16; i++) {
lsb = (lsb << 8) | (data[i] & 0xff);
}
return new UUID(msb, lsb);
}
private static byte[] bytesFromUUID(String uuidHexString) {
@@ -3,6 +3,10 @@ package com.baeldung.uuid;
import org.junit.jupiter.api.Test;
import java.io.UnsupportedEncodingException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -13,17 +17,23 @@ class UUIDGeneratorUnitTest {
private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
@Test
public void version_1_UUID_is_generated_with_correct_length_version_and_variant() {
void shouldGenerateType1UUIDWithCorrectVersionAndVariant() {
UUID uuid = UUIDGenerator.generateType1UUID();
assertEquals(36, uuid.toString().length());
assertEquals(1, uuid.version());
assertEquals(2, uuid.variant());
}
@Test
public void version_3_UUID_is_correctly_generated_for_domain_baeldung_com() throws UnsupportedEncodingException {
void shouldGenerateType1UUIDWithTheCurrentDate() {
UUID uuid = UUIDGenerator.generateType1UUID();
long time = uuid.timestamp();
LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault());
assertEquals(LocalDate.now(), dateTime.toLocalDate());
}
@Test
void version_3_UUID_is_correctly_generated_for_domain_baeldung_com() {
UUID uuid = UUIDGenerator.generateType3UUID(NAMESPACE_DNS, "baeldung.com");
@@ -33,7 +43,7 @@ class UUIDGeneratorUnitTest {
}
@Test
public void version_3_UUID_is_correctly_generated_for_domain_d() throws UnsupportedEncodingException {
void version_3_UUID_is_correctly_generated_for_domain_d() {
UUID uuid = UUIDGenerator.generateType3UUID(NAMESPACE_DNS, "d");