diff --git a/core-java-modules/core-java-concurrency-advanced-5/src/test/java/com/baeldung/exceptions_completablefuture/CompletableFutureExceptionsHandlingUnitTest.java b/core-java-modules/core-java-concurrency-advanced-5/src/test/java/com/baeldung/exceptions_completablefuture/CompletableFutureExceptionsHandlingUnitTest.java new file mode 100644 index 0000000000..afb31f7617 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-5/src/test/java/com/baeldung/exceptions_completablefuture/CompletableFutureExceptionsHandlingUnitTest.java @@ -0,0 +1,126 @@ +package com.baeldung.exceptions_completablefuture; + +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.stream.Stream; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +public class CompletableFutureExceptionsHandlingUnitTest { + + @ParameterizedTest + @MethodSource("parametersSource_handle") + void whenCompletableFutureIsScheduled_thenHandleStageIsAlwaysInvoked(int radius, long expected) + throws ExecutionException, InterruptedException { + long actual = CompletableFuture + .supplyAsync(() -> { + if (radius <= 0) { + throw new IllegalArgumentException("Supplied with non-positive radius '%d'"); + } + return Math.round(Math.pow(radius, 2) * Math.PI); + }) + .handle((result, ex) -> { + if (ex == null) { + return result; + } else { + return -1L; + } + }) + .get(); + + Assertions.assertThat(actual).isEqualTo(expected); + } + + @ParameterizedTest + @MethodSource("parametersSource_exceptionally") + void whenCompletableFutureIsScheduled_thenExceptionallyExecutedOnlyOnFailure(int a, int b, int c, long expected) + throws ExecutionException, InterruptedException { + long actual = CompletableFuture + .supplyAsync(() -> { + if (a <= 0 || b <= 0 || c <= 0) { + throw new IllegalArgumentException(String.format("Supplied with incorrect edge length [%s]", List.of(a, b, c))); + } + return a * b * c; + }) + .exceptionally((ex) -> -1) + .get(); + + Assertions.assertThat(actual).isEqualTo(expected); + } + + @ParameterizedTest + @MethodSource("parametersSource_exceptionally") + void givenCompletableFutureIsScheduled_whenHandleIsAlreadyPresent_thenExceptionallyIsNotExecuted(int a, int b, int c, long expected) + throws ExecutionException, InterruptedException { + long actual = CompletableFuture + .supplyAsync(() -> { + if (a <= 0 || b <= 0 || c <= 0) { + throw new IllegalArgumentException(String.format("Supplied with incorrect edge length [%s]", List.of(a, b, c))); + } + return a * b * c; + }) + .handle((result, throwable) -> { + if (throwable != null) { + return -1; + } + return result; + }) + .exceptionally((ex) -> { + System.exit(1); + return 0; + }) + .get(); + + Assertions.assertThat(actual).isEqualTo(expected); + } + + @ParameterizedTest + @MethodSource("parametersSource_whenComplete") + void whenCompletableFutureIsScheduled_thenWhenCompletedExecutedAlways(Double a, long expected, Class ifAny) { + try { + CountDownLatch countDownLatch = new CountDownLatch(1); + + long actual = CompletableFuture + .supplyAsync(() -> { + if (a.isNaN()) { + throw new IllegalArgumentException("Supplied value is NaN"); + } + return Math.round(Math.pow(a, 2)); + }) + .whenComplete((result, exception) -> countDownLatch.countDown()) + .get(); + + Assertions.assertThat(countDownLatch.await(20L, java.util.concurrent.TimeUnit.SECONDS)); + Assertions.assertThat(actual).isEqualTo(expected); + } catch (Exception e) { + Assertions.assertThat(e.getClass()).isSameAs(ExecutionException.class); + Assertions.assertThat(e.getCause().getClass()).isSameAs(ifAny); + } + } + + static Stream parametersSource_handle() { + return Stream.of( + Arguments.of(1, 3), + Arguments.of(-1, -1) + ); + } + + static Stream parametersSource_exceptionally() { + return Stream.of( + Arguments.of(1, 5, 5, 25), + Arguments.of(-1, 10, 15, -1) + ); + } + + static Stream parametersSource_whenComplete() { + return Stream.of( + Arguments.of(2d, 4, null), + Arguments.of(Double.NaN, 1, IllegalArgumentException.class) + ); + } +} diff --git a/core-java-modules/core-java-datetime-conversion/src/main/java/com/baeldung/timestamptolong/TimestampToLong.java b/core-java-modules/core-java-datetime-conversion/src/main/java/com/baeldung/timestamptolong/TimestampToLong.java new file mode 100644 index 0000000000..2ebe30f4ff --- /dev/null +++ b/core-java-modules/core-java-datetime-conversion/src/main/java/com/baeldung/timestamptolong/TimestampToLong.java @@ -0,0 +1,32 @@ +package com.baeldung.timestamptolong; + +import java.sql.Timestamp; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Date; + +public class TimestampToLong { + public void usingSimpleDateFormat() throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String currentDateString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); + long actualTimestamp = sdf.parse(currentDateString).getTime(); + } + + public void usingInstantClass() { + Instant instant = Instant.now(); + long actualTimestamp = instant.toEpochMilli(); + } + + public void usingTimestamp() { + Timestamp timestamp = new Timestamp(System.currentTimeMillis()); + long actualTimestamp = timestamp.getTime(); + } + + public void usingJava8DateTime() { + LocalDateTime localDateTime = LocalDateTime.now(); + long actualTimestamp = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/timestamptolong/TimestampToLongUnitTest.java b/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/timestamptolong/TimestampToLongUnitTest.java new file mode 100644 index 0000000000..ede8f7792d --- /dev/null +++ b/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/timestamptolong/TimestampToLongUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.timestamptolong; + +import org.junit.Test; + +import java.sql.Timestamp; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Date; + +import static org.junit.Assert.assertTrue; + +public class TimestampToLongUnitTest { + + private static final long TOLERANCE = 1000; + + @Test + public void givenSimpleDateFormat_whenFormattingDate_thenTConvertToLong() throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + String currentDateString = sdf.format(new Date()); + long actualTimestamp = sdf.parse(currentDateString).getTime(); + + assertTrue(Math.abs(System.currentTimeMillis() - actualTimestamp) < TOLERANCE); + } + + @Test + public void givenInstantClass_whenGettingTimestamp_thenTConvertToLong() { + Instant instant = Instant.now(); + long actualTimestamp = instant.toEpochMilli(); + + assertTrue(Math.abs(System.currentTimeMillis() - actualTimestamp) < TOLERANCE); + } + + @Test + public void givenTimestamp_whenCreatingTimestamp_thenTConvertToLong() { + Timestamp timestamp = new Timestamp(System.currentTimeMillis()); + long actualTimestamp = timestamp.getTime(); + + assertTrue(Math.abs(System.currentTimeMillis() - actualTimestamp) < TOLERANCE); + } + + @Test + public void givenJava8DateTime_whenGettingTimestamp_thenTConvertToLong() { + LocalDateTime localDateTime = LocalDateTime.now(); + long actualTimestamp = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); + + assertTrue(Math.abs(System.currentTimeMillis() - actualTimestamp) < TOLERANCE); + } +}