From ff3001386e066b7db58872db9298628b3a9ab965 Mon Sep 17 00:00:00 2001 From: abialas Date: Thu, 16 Nov 2017 22:57:21 +0100 Subject: [PATCH 01/24] BAEL-1344 add java8 convert methods date, localdate, localdatetime --- .../datetime/DateToLocalDateConverter.java | 34 ++++++++ .../DateToLocalDateTimeConverter.java | 34 ++++++++ .../LocalDateTimeToDateConverter.java | 27 +++++++ .../datetime/LocalDateToDateConverter.java | 28 +++++++ .../DateToLocalDateConverterTest.java | 72 +++++++++++++++++ .../DateToLocalDateTimeConverterTest.java | 78 +++++++++++++++++++ .../LocalDateTimeToDateConverterTest.java | 61 +++++++++++++++ .../LocalDateToDateConverterTest.java | 55 +++++++++++++ 8 files changed, 389 insertions(+) create mode 100644 core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateConverter.java create mode 100644 core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateTimeConverter.java create mode 100644 core-java-8/src/main/java/com/baeldung/datetime/LocalDateTimeToDateConverter.java create mode 100644 core-java-8/src/main/java/com/baeldung/datetime/LocalDateToDateConverter.java create mode 100644 core-java-8/src/test/java/com/baeldung/datetime/DateToLocalDateConverterTest.java create mode 100644 core-java-8/src/test/java/com/baeldung/datetime/DateToLocalDateTimeConverterTest.java create mode 100644 core-java-8/src/test/java/com/baeldung/datetime/LocalDateTimeToDateConverterTest.java create mode 100644 core-java-8/src/test/java/com/baeldung/datetime/LocalDateToDateConverterTest.java diff --git a/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateConverter.java b/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateConverter.java new file mode 100644 index 0000000000..1ef77a2960 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateConverter.java @@ -0,0 +1,34 @@ +/** + * + */ +package com.baeldung.datetime; + +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.Date; + +/** + * Class which shows different ways of converting java.util.Date into java.time.LocalDate. + * + * @author abialas + * + */ +public class DateToLocalDateConverter { + + public static LocalDate convertToLocalDateViaInstant(Date dateToConvert) { + return dateToConvert.toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDate(); + } + + public static LocalDate convertToLocalDateViaSqlDate(Date dateToConvert) { + return new java.sql.Date(dateToConvert.getTime()).toLocalDate(); + } + + public static LocalDate convertToLocalDateViaMilisecond(Date dateToConvert) { + return LocalDate.from(Instant.ofEpochMilli(dateToConvert.getTime()) + .atZone(ZoneId.systemDefault())); + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateTimeConverter.java b/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateTimeConverter.java new file mode 100644 index 0000000000..78abb6a94c --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateTimeConverter.java @@ -0,0 +1,34 @@ +/** + * + */ +package com.baeldung.datetime; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Date; + +/** + * Class which shows different ways of converting java.util.Date into java.time.LocalDateTime. + * + * @author abialas + * + */ +public class DateToLocalDateTimeConverter { + + public static LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert) { + return dateToConvert.toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDateTime(); + } + + public static LocalDateTime convertToLocalDateTimeViaSqlTimestamp(Date dateToConvert) { + return new java.sql.Timestamp(dateToConvert.getTime()).toLocalDateTime(); + } + + public static LocalDateTime convertToLocalDateTimeViaMilisecond(Date dateToConvert) { + return LocalDateTime.from(Instant.ofEpochMilli(dateToConvert.getTime()) + .atZone(ZoneId.systemDefault())); + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/datetime/LocalDateTimeToDateConverter.java b/core-java-8/src/main/java/com/baeldung/datetime/LocalDateTimeToDateConverter.java new file mode 100644 index 0000000000..ef72c8b4fb --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/datetime/LocalDateTimeToDateConverter.java @@ -0,0 +1,27 @@ +/** + * + */ +package com.baeldung.datetime; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Date; + +/** + * Class which shows different ways of converting java.time.LocalDateTime into java.util.Date. + * + * @author abialas + * + */ +public class LocalDateTimeToDateConverter { + + public static Date convertToDateViaSqlTimestamp(LocalDateTime dateToConvert) { + return java.sql.Timestamp.valueOf(dateToConvert); + } + + public static Date convertToDateViaInstant(LocalDateTime dateToConvert) { + return java.util.Date.from(dateToConvert.atZone(ZoneId.systemDefault()) + .toInstant()); + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/datetime/LocalDateToDateConverter.java b/core-java-8/src/main/java/com/baeldung/datetime/LocalDateToDateConverter.java new file mode 100644 index 0000000000..8050815799 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/datetime/LocalDateToDateConverter.java @@ -0,0 +1,28 @@ +/** + * + */ +package com.baeldung.datetime; + +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.Date; + +/** + * Class which shows different ways of converting java.time.LocalDate into java.util.Date. + * + * @author abialas + * + */ +public class LocalDateToDateConverter { + + public static Date convertToDateViaSqlDate(LocalDate dateToConvert) { + return java.sql.Date.valueOf(dateToConvert); + } + + public static Date convertToDateViaInstant(LocalDate dateToConvert) { + return java.util.Date.from(dateToConvert.atStartOfDay() + .atZone(ZoneId.systemDefault()) + .toInstant()); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/datetime/DateToLocalDateConverterTest.java b/core-java-8/src/test/java/com/baeldung/datetime/DateToLocalDateConverterTest.java new file mode 100644 index 0000000000..5de6ae3e59 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/datetime/DateToLocalDateConverterTest.java @@ -0,0 +1,72 @@ +/** + * + */ +package com.baeldung.datetime; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDate; +import java.time.temporal.ChronoField; +import java.util.Calendar; +import java.util.Date; + +import org.junit.Test; + +/** + * + * JUnits for {@link DateToLocalDateConverter} class. + * + * @author abialas + * + */ +public class DateToLocalDateConverterTest { + + @Test + public void shouldReturn10thNovember2010WhenConvertViaInstant() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10); + Date dateToConvert = calendar.getTime(); + + // when + LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaInstant(dateToConvert); + + // then + assertEquals(2010, localDate.get(ChronoField.YEAR)); + assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); + } + + @Test + public void shouldReturn10thNovember2010WhenConvertViaMiliseconds() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10); + Date dateToConvert = calendar.getTime(); + + // when + LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaMilisecond(dateToConvert); + + // then + assertEquals(2010, localDate.get(ChronoField.YEAR)); + assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); + } + + @Test + public void shouldReturn10thNovember2010WhenConvertViaSqlDate() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10); + Date dateToConvert = calendar.getTime(); + + // when + LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaSqlDate(dateToConvert); + + // then + assertEquals(2010, localDate.get(ChronoField.YEAR)); + assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/datetime/DateToLocalDateTimeConverterTest.java b/core-java-8/src/test/java/com/baeldung/datetime/DateToLocalDateTimeConverterTest.java new file mode 100644 index 0000000000..6d8fb8ea93 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/datetime/DateToLocalDateTimeConverterTest.java @@ -0,0 +1,78 @@ +/** + * + */ +package com.baeldung.datetime; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDateTime; +import java.time.temporal.ChronoField; +import java.util.Calendar; +import java.util.Date; + +import org.junit.Test; + +/** + * + * JUnits for {@link DateToLocalDateTimeConverter} class. + * + * @author abialas + * + */ +public class DateToLocalDateTimeConverterTest { + + @Test + public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10, 8, 20); + Date dateToConvert = calendar.getTime(); + + // when + LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaInstant(dateToConvert); + + // then + assertEquals(2010, localDateTime.get(ChronoField.YEAR)); + assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); + assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); + assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); + } + + @Test + public void shouldReturn10thNovember2010time8hour20minWhenConvertViaMiliseconds() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10, 8, 20); + Date dateToConvert = calendar.getTime(); + + // when + LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaMilisecond(dateToConvert); + + // then + assertEquals(2010, localDateTime.get(ChronoField.YEAR)); + assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); + assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); + assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); + } + + @Test + public void shouldReturn10thNovember2010time8hour20minWhenConvertViaSqlTimestamp() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10, 8, 20); + Date dateToConvert = calendar.getTime(); + + // when + LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaSqlTimestamp(dateToConvert); + + // then + assertEquals(2010, localDateTime.get(ChronoField.YEAR)); + assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); + assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); + assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/datetime/LocalDateTimeToDateConverterTest.java b/core-java-8/src/test/java/com/baeldung/datetime/LocalDateTimeToDateConverterTest.java new file mode 100644 index 0000000000..519fa69f04 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/datetime/LocalDateTimeToDateConverterTest.java @@ -0,0 +1,61 @@ +/** + * + */ +package com.baeldung.datetime; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDateTime; +import java.util.Calendar; +import java.util.Date; + +import org.junit.Test; + +/** + * + * JUnits for {@link LocalDateTimeToDateConverter} class. + * + * @author abialas + * + */ +public class LocalDateTimeToDateConverterTest { + + @Test + public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() { + // given + LocalDateTime dateToConvert = LocalDateTime.of(2010, 11, 10, 8, 20); + + // when + Date date = LocalDateTimeToDateConverter.convertToDateViaInstant(dateToConvert); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + // then + assertEquals(2010, calendar.get(Calendar.YEAR)); + assertEquals(10, calendar.get(Calendar.MONTH)); + assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); + assertEquals(8, calendar.get(Calendar.HOUR)); + assertEquals(20, calendar.get(Calendar.MINUTE)); + assertEquals(0, calendar.get(Calendar.SECOND)); + } + + @Test + public void shouldReturn10thNovember2010WhenConvertViaSqlTimestamp() { + // given + LocalDateTime dateToConvert = LocalDateTime.of(2010, 11, 10, 8, 20); + + // when + Date date = LocalDateTimeToDateConverter.convertToDateViaSqlTimestamp(dateToConvert); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + // then + assertEquals(2010, calendar.get(Calendar.YEAR)); + assertEquals(10, calendar.get(Calendar.MONTH)); + assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); + assertEquals(8, calendar.get(Calendar.HOUR)); + assertEquals(20, calendar.get(Calendar.MINUTE)); + assertEquals(0, calendar.get(Calendar.SECOND)); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/datetime/LocalDateToDateConverterTest.java b/core-java-8/src/test/java/com/baeldung/datetime/LocalDateToDateConverterTest.java new file mode 100644 index 0000000000..c1da3af052 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/datetime/LocalDateToDateConverterTest.java @@ -0,0 +1,55 @@ +/** + * + */ +package com.baeldung.datetime; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDate; +import java.util.Calendar; +import java.util.Date; + +import org.junit.Test; + +/** + * + * JUnits for {@link LocalDateToDateConverter} class. + * + * @author abialas + * + */ +public class LocalDateToDateConverterTest { + + @Test + public void shouldReturn10thNovember2010WhenConvertViaInstant() { + // given + LocalDate dateToConvert = LocalDate.of(2010, 11, 10); + + // when + Date date = LocalDateToDateConverter.convertToDateViaInstant(dateToConvert); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + // then + assertEquals(2010, calendar.get(Calendar.YEAR)); + assertEquals(10, calendar.get(Calendar.MONTH)); + assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); + } + + @Test + public void shouldReturn10thNovember2010WhenConvertViaSqlDate() { + // given + LocalDate dateToConvert = LocalDate.of(2010, 11, 10); + + // when + Date date = LocalDateToDateConverter.convertToDateViaSqlDate(dateToConvert); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + // then + assertEquals(2010, calendar.get(Calendar.YEAR)); + assertEquals(10, calendar.get(Calendar.MONTH)); + assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); + } + +} From 99ae59b9611c06045f376fc71e622687508d31b7 Mon Sep 17 00:00:00 2001 From: abialas Date: Fri, 17 Nov 2017 23:46:09 +0100 Subject: [PATCH 02/24] BAEL-1344 add java9 example --- .../datetime/DateToLocalDateConverter.java | 5 ++- .../DateToLocalDateTimeConverter.java | 5 ++- .../datetime/DateToLocalDateConverter.java | 22 ++++++++++ .../DateToLocalDateTimeConverter.java | 22 ++++++++++ .../DateToLocalDateConverterTest.java | 41 ++++++++++++++++++ .../DateToLocalDateTimeConverterTest.java | 43 +++++++++++++++++++ 6 files changed, 134 insertions(+), 4 deletions(-) create mode 100644 core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java create mode 100644 core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java create mode 100644 core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterTest.java create mode 100644 core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterTest.java diff --git a/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateConverter.java b/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateConverter.java index 1ef77a2960..8788aac747 100644 --- a/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateConverter.java +++ b/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateConverter.java @@ -27,8 +27,9 @@ public class DateToLocalDateConverter { } public static LocalDate convertToLocalDateViaMilisecond(Date dateToConvert) { - return LocalDate.from(Instant.ofEpochMilli(dateToConvert.getTime()) - .atZone(ZoneId.systemDefault())); + return Instant.ofEpochMilli(dateToConvert.getTime()) + .atZone(ZoneId.systemDefault()) + .toLocalDate(); } } diff --git a/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateTimeConverter.java b/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateTimeConverter.java index 78abb6a94c..f994023526 100644 --- a/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateTimeConverter.java +++ b/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateTimeConverter.java @@ -27,8 +27,9 @@ public class DateToLocalDateTimeConverter { } public static LocalDateTime convertToLocalDateTimeViaMilisecond(Date dateToConvert) { - return LocalDateTime.from(Instant.ofEpochMilli(dateToConvert.getTime()) - .atZone(ZoneId.systemDefault())); + return Instant.ofEpochMilli(dateToConvert.getTime()) + .atZone(ZoneId.systemDefault()) + .toLocalDateTime(); } } diff --git a/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java b/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java new file mode 100644 index 0000000000..bafa9ebff1 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java @@ -0,0 +1,22 @@ +/** + * + */ +package com.baeldung.java9.datetime; + +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.Date; + +/** + * Class which shows a way to convert java.util.Date into java.time.LocalDate with new Java 1.9. + * + * @author abialas + * + */ +public class DateToLocalDateConverter { + + public static LocalDate convertToLocalDate(Date dateToConvert) { + return LocalDate.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault()); + } + +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java b/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java new file mode 100644 index 0000000000..538d5a9f63 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java @@ -0,0 +1,22 @@ +/** + * + */ +package com.baeldung.java9.datetime; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Date; + +/** + * Class which shows a way to convert java.util.Date into java.time.LocalDateTime with new Java 1.9. + * + * @author abialas + * + */ +public class DateToLocalDateTimeConverter { + + public static LocalDateTime convertToLocalDateTime(Date dateToConvert) { + return LocalDateTime.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault()); + } + +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterTest.java b/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterTest.java new file mode 100644 index 0000000000..2e0fb0dedd --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterTest.java @@ -0,0 +1,41 @@ +/** + * + */ +package com.baeldung.java9.datetime; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDate; +import java.time.temporal.ChronoField; +import java.util.Calendar; +import java.util.Date; + +import org.junit.Test; + +import com.baeldung.java9.datetime.DateToLocalDateConverter; + +/** + * JUnits for {@link DateToLocalDateConverter} class. + * + * @author abialas + * + */ +public class DateToLocalDateConverterTest { + + @Test + public void shouldReturn10thNovember2010WhenConvertToLocalDate() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10); + Date dateToConvert = calendar.getTime(); + + // when + LocalDate localDateTime = DateToLocalDateConverter.convertToLocalDate(dateToConvert); + + // then + assertEquals(2010, localDateTime.get(ChronoField.YEAR)); + assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); + } + +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterTest.java b/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterTest.java new file mode 100644 index 0000000000..49988c8b33 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterTest.java @@ -0,0 +1,43 @@ +/** + * + */ +package com.baeldung.java9.datetime; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDateTime; +import java.time.temporal.ChronoField; +import java.util.Calendar; +import java.util.Date; + +import org.junit.Test; + +import com.baeldung.java9.datetime.DateToLocalDateTimeConverter; + +/** + * JUnits for {@link DateToLocalDateTimeConverter} class. + * + * @author abialas + * + */ +public class DateToLocalDateTimeConverterTest { + + @Test + public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10, 8, 20); + Date dateToConvert = calendar.getTime(); + + // when + LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTime(dateToConvert); + + // then + assertEquals(2010, localDateTime.get(ChronoField.YEAR)); + assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); + assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); + assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); + } + +} From d0396880e5871c18035cd7b9aadba617a0e4e9d7 Mon Sep 17 00:00:00 2001 From: abialas Date: Fri, 24 Nov 2017 20:51:02 +0100 Subject: [PATCH 03/24] Move Date to LocalDate and LocalDateTime converters from core-java-8 to core-java-9 --- .../datetime/DateToLocalDateConverter.java | 35 --------- .../DateToLocalDateTimeConverter.java | 35 --------- .../DateToLocalDateConverterTest.java | 72 ----------------- .../DateToLocalDateTimeConverterTest.java | 78 ------------------- .../datetime/DateToLocalDateConverter.java | 19 ++++- .../DateToLocalDateTimeConverter.java | 19 ++++- .../LocalDateTimeToDateConverter.java | 2 +- .../datetime/LocalDateToDateConverter.java | 2 +- .../DateToLocalDateConverterTest.java | 48 ++++++++++++ .../DateToLocalDateTimeConverterTest.java | 54 +++++++++++++ .../LocalDateTimeToDateConverterTest.java | 2 +- .../LocalDateToDateConverterTest.java | 2 +- 12 files changed, 142 insertions(+), 226 deletions(-) delete mode 100644 core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateConverter.java delete mode 100644 core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateTimeConverter.java delete mode 100644 core-java-8/src/test/java/com/baeldung/datetime/DateToLocalDateConverterTest.java delete mode 100644 core-java-8/src/test/java/com/baeldung/datetime/DateToLocalDateTimeConverterTest.java rename {core-java-8/src/main/java/com/baeldung => core-java-9/src/main/java/com/baeldung/java9}/datetime/LocalDateTimeToDateConverter.java (94%) rename {core-java-8/src/main/java/com/baeldung => core-java-9/src/main/java/com/baeldung/java9}/datetime/LocalDateToDateConverter.java (94%) rename {core-java-8/src/test/java/com/baeldung => core-java-9/src/test/java/com/baeldung/java9}/datetime/LocalDateTimeToDateConverterTest.java (97%) rename {core-java-8/src/test/java/com/baeldung => core-java-9/src/test/java/com/baeldung/java9}/datetime/LocalDateToDateConverterTest.java (97%) diff --git a/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateConverter.java b/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateConverter.java deleted file mode 100644 index 8788aac747..0000000000 --- a/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateConverter.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * - */ -package com.baeldung.datetime; - -import java.time.Instant; -import java.time.LocalDate; -import java.time.ZoneId; -import java.util.Date; - -/** - * Class which shows different ways of converting java.util.Date into java.time.LocalDate. - * - * @author abialas - * - */ -public class DateToLocalDateConverter { - - public static LocalDate convertToLocalDateViaInstant(Date dateToConvert) { - return dateToConvert.toInstant() - .atZone(ZoneId.systemDefault()) - .toLocalDate(); - } - - public static LocalDate convertToLocalDateViaSqlDate(Date dateToConvert) { - return new java.sql.Date(dateToConvert.getTime()).toLocalDate(); - } - - public static LocalDate convertToLocalDateViaMilisecond(Date dateToConvert) { - return Instant.ofEpochMilli(dateToConvert.getTime()) - .atZone(ZoneId.systemDefault()) - .toLocalDate(); - } - -} diff --git a/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateTimeConverter.java b/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateTimeConverter.java deleted file mode 100644 index f994023526..0000000000 --- a/core-java-8/src/main/java/com/baeldung/datetime/DateToLocalDateTimeConverter.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * - */ -package com.baeldung.datetime; - -import java.time.Instant; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.Date; - -/** - * Class which shows different ways of converting java.util.Date into java.time.LocalDateTime. - * - * @author abialas - * - */ -public class DateToLocalDateTimeConverter { - - public static LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert) { - return dateToConvert.toInstant() - .atZone(ZoneId.systemDefault()) - .toLocalDateTime(); - } - - public static LocalDateTime convertToLocalDateTimeViaSqlTimestamp(Date dateToConvert) { - return new java.sql.Timestamp(dateToConvert.getTime()).toLocalDateTime(); - } - - public static LocalDateTime convertToLocalDateTimeViaMilisecond(Date dateToConvert) { - return Instant.ofEpochMilli(dateToConvert.getTime()) - .atZone(ZoneId.systemDefault()) - .toLocalDateTime(); - } - -} diff --git a/core-java-8/src/test/java/com/baeldung/datetime/DateToLocalDateConverterTest.java b/core-java-8/src/test/java/com/baeldung/datetime/DateToLocalDateConverterTest.java deleted file mode 100644 index 5de6ae3e59..0000000000 --- a/core-java-8/src/test/java/com/baeldung/datetime/DateToLocalDateConverterTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * - */ -package com.baeldung.datetime; - -import static org.junit.Assert.assertEquals; - -import java.time.LocalDate; -import java.time.temporal.ChronoField; -import java.util.Calendar; -import java.util.Date; - -import org.junit.Test; - -/** - * - * JUnits for {@link DateToLocalDateConverter} class. - * - * @author abialas - * - */ -public class DateToLocalDateConverterTest { - - @Test - public void shouldReturn10thNovember2010WhenConvertViaInstant() { - // given - Calendar calendar = Calendar.getInstance(); - calendar.set(2010, 10, 10); - Date dateToConvert = calendar.getTime(); - - // when - LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaInstant(dateToConvert); - - // then - assertEquals(2010, localDate.get(ChronoField.YEAR)); - assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); - assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); - } - - @Test - public void shouldReturn10thNovember2010WhenConvertViaMiliseconds() { - // given - Calendar calendar = Calendar.getInstance(); - calendar.set(2010, 10, 10); - Date dateToConvert = calendar.getTime(); - - // when - LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaMilisecond(dateToConvert); - - // then - assertEquals(2010, localDate.get(ChronoField.YEAR)); - assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); - assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); - } - - @Test - public void shouldReturn10thNovember2010WhenConvertViaSqlDate() { - // given - Calendar calendar = Calendar.getInstance(); - calendar.set(2010, 10, 10); - Date dateToConvert = calendar.getTime(); - - // when - LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaSqlDate(dateToConvert); - - // then - assertEquals(2010, localDate.get(ChronoField.YEAR)); - assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); - assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); - } - -} diff --git a/core-java-8/src/test/java/com/baeldung/datetime/DateToLocalDateTimeConverterTest.java b/core-java-8/src/test/java/com/baeldung/datetime/DateToLocalDateTimeConverterTest.java deleted file mode 100644 index 6d8fb8ea93..0000000000 --- a/core-java-8/src/test/java/com/baeldung/datetime/DateToLocalDateTimeConverterTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * - */ -package com.baeldung.datetime; - -import static org.junit.Assert.assertEquals; - -import java.time.LocalDateTime; -import java.time.temporal.ChronoField; -import java.util.Calendar; -import java.util.Date; - -import org.junit.Test; - -/** - * - * JUnits for {@link DateToLocalDateTimeConverter} class. - * - * @author abialas - * - */ -public class DateToLocalDateTimeConverterTest { - - @Test - public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() { - // given - Calendar calendar = Calendar.getInstance(); - calendar.set(2010, 10, 10, 8, 20); - Date dateToConvert = calendar.getTime(); - - // when - LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaInstant(dateToConvert); - - // then - assertEquals(2010, localDateTime.get(ChronoField.YEAR)); - assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); - assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); - assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); - assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); - } - - @Test - public void shouldReturn10thNovember2010time8hour20minWhenConvertViaMiliseconds() { - // given - Calendar calendar = Calendar.getInstance(); - calendar.set(2010, 10, 10, 8, 20); - Date dateToConvert = calendar.getTime(); - - // when - LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaMilisecond(dateToConvert); - - // then - assertEquals(2010, localDateTime.get(ChronoField.YEAR)); - assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); - assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); - assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); - assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); - } - - @Test - public void shouldReturn10thNovember2010time8hour20minWhenConvertViaSqlTimestamp() { - // given - Calendar calendar = Calendar.getInstance(); - calendar.set(2010, 10, 10, 8, 20); - Date dateToConvert = calendar.getTime(); - - // when - LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaSqlTimestamp(dateToConvert); - - // then - assertEquals(2010, localDateTime.get(ChronoField.YEAR)); - assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); - assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); - assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); - assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); - } - -} diff --git a/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java b/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java index bafa9ebff1..c794c57e87 100644 --- a/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java +++ b/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java @@ -3,18 +3,35 @@ */ package com.baeldung.java9.datetime; +import java.time.Instant; import java.time.LocalDate; import java.time.ZoneId; import java.util.Date; /** - * Class which shows a way to convert java.util.Date into java.time.LocalDate with new Java 1.9. + * Class which shows a way to convert java.util.Date into java.time.LocalDate. * * @author abialas * */ public class DateToLocalDateConverter { + public static LocalDate convertToLocalDateViaInstant(Date dateToConvert) { + return dateToConvert.toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDate(); + } + + public static LocalDate convertToLocalDateViaSqlDate(Date dateToConvert) { + return new java.sql.Date(dateToConvert.getTime()).toLocalDate(); + } + + public static LocalDate convertToLocalDateViaMilisecond(Date dateToConvert) { + return Instant.ofEpochMilli(dateToConvert.getTime()) + .atZone(ZoneId.systemDefault()) + .toLocalDate(); + } + public static LocalDate convertToLocalDate(Date dateToConvert) { return LocalDate.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault()); } diff --git a/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java b/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java index 538d5a9f63..17ca5b1122 100644 --- a/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java +++ b/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java @@ -3,18 +3,35 @@ */ package com.baeldung.java9.datetime; +import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; /** - * Class which shows a way to convert java.util.Date into java.time.LocalDateTime with new Java 1.9. + * Class which shows a way to convert java.util.Date into java.time.LocalDateTime. * * @author abialas * */ public class DateToLocalDateTimeConverter { + public static LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert) { + return dateToConvert.toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDateTime(); + } + + public static LocalDateTime convertToLocalDateTimeViaSqlTimestamp(Date dateToConvert) { + return new java.sql.Timestamp(dateToConvert.getTime()).toLocalDateTime(); + } + + public static LocalDateTime convertToLocalDateTimeViaMilisecond(Date dateToConvert) { + return Instant.ofEpochMilli(dateToConvert.getTime()) + .atZone(ZoneId.systemDefault()) + .toLocalDateTime(); + } + public static LocalDateTime convertToLocalDateTime(Date dateToConvert) { return LocalDateTime.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault()); } diff --git a/core-java-8/src/main/java/com/baeldung/datetime/LocalDateTimeToDateConverter.java b/core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverter.java similarity index 94% rename from core-java-8/src/main/java/com/baeldung/datetime/LocalDateTimeToDateConverter.java rename to core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverter.java index ef72c8b4fb..f219dcf038 100644 --- a/core-java-8/src/main/java/com/baeldung/datetime/LocalDateTimeToDateConverter.java +++ b/core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverter.java @@ -1,7 +1,7 @@ /** * */ -package com.baeldung.datetime; +package com.baeldung.java9.datetime; import java.time.LocalDateTime; import java.time.ZoneId; diff --git a/core-java-8/src/main/java/com/baeldung/datetime/LocalDateToDateConverter.java b/core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateToDateConverter.java similarity index 94% rename from core-java-8/src/main/java/com/baeldung/datetime/LocalDateToDateConverter.java rename to core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateToDateConverter.java index 8050815799..f9893da5d0 100644 --- a/core-java-8/src/main/java/com/baeldung/datetime/LocalDateToDateConverter.java +++ b/core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateToDateConverter.java @@ -1,7 +1,7 @@ /** * */ -package com.baeldung.datetime; +package com.baeldung.java9.datetime; import java.time.LocalDate; import java.time.ZoneId; diff --git a/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterTest.java b/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterTest.java index 2e0fb0dedd..ab69bba359 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterTest.java @@ -22,6 +22,54 @@ import com.baeldung.java9.datetime.DateToLocalDateConverter; */ public class DateToLocalDateConverterTest { + @Test + public void shouldReturn10thNovember2010WhenConvertViaInstant() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10); + Date dateToConvert = calendar.getTime(); + + // when + LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaInstant(dateToConvert); + + // then + assertEquals(2010, localDate.get(ChronoField.YEAR)); + assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); + } + + @Test + public void shouldReturn10thNovember2010WhenConvertViaMiliseconds() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10); + Date dateToConvert = calendar.getTime(); + + // when + LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaMilisecond(dateToConvert); + + // then + assertEquals(2010, localDate.get(ChronoField.YEAR)); + assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); + } + + @Test + public void shouldReturn10thNovember2010WhenConvertViaSqlDate() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10); + Date dateToConvert = calendar.getTime(); + + // when + LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaSqlDate(dateToConvert); + + // then + assertEquals(2010, localDate.get(ChronoField.YEAR)); + assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); + } + @Test public void shouldReturn10thNovember2010WhenConvertToLocalDate() { // given diff --git a/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterTest.java b/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterTest.java index 49988c8b33..97c70ee5ac 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterTest.java @@ -29,6 +29,60 @@ public class DateToLocalDateTimeConverterTest { calendar.set(2010, 10, 10, 8, 20); Date dateToConvert = calendar.getTime(); + // when + LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaInstant(dateToConvert); + + // then + assertEquals(2010, localDateTime.get(ChronoField.YEAR)); + assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); + assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); + assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); + } + + @Test + public void shouldReturn10thNovember2010time8hour20minWhenConvertViaMiliseconds() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10, 8, 20); + Date dateToConvert = calendar.getTime(); + + // when + LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaMilisecond(dateToConvert); + + // then + assertEquals(2010, localDateTime.get(ChronoField.YEAR)); + assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); + assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); + assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); + } + + @Test + public void shouldReturn10thNovember2010time8hour20minWhenConvertViaSqlTimestamp() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10, 8, 20); + Date dateToConvert = calendar.getTime(); + + // when + LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaSqlTimestamp(dateToConvert); + + // then + assertEquals(2010, localDateTime.get(ChronoField.YEAR)); + assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); + assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); + assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); + } + + @Test + public void shouldReturn10thNovember2010time8hour20minWhenConvertToLocalDateTime() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10, 8, 20); + Date dateToConvert = calendar.getTime(); + // when LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTime(dateToConvert); diff --git a/core-java-8/src/test/java/com/baeldung/datetime/LocalDateTimeToDateConverterTest.java b/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterTest.java similarity index 97% rename from core-java-8/src/test/java/com/baeldung/datetime/LocalDateTimeToDateConverterTest.java rename to core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterTest.java index 519fa69f04..2c6898381f 100644 --- a/core-java-8/src/test/java/com/baeldung/datetime/LocalDateTimeToDateConverterTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterTest.java @@ -1,7 +1,7 @@ /** * */ -package com.baeldung.datetime; +package com.baeldung.java9.datetime; import static org.junit.Assert.assertEquals; diff --git a/core-java-8/src/test/java/com/baeldung/datetime/LocalDateToDateConverterTest.java b/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterTest.java similarity index 97% rename from core-java-8/src/test/java/com/baeldung/datetime/LocalDateToDateConverterTest.java rename to core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterTest.java index c1da3af052..7f20d5d2d2 100644 --- a/core-java-8/src/test/java/com/baeldung/datetime/LocalDateToDateConverterTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterTest.java @@ -1,7 +1,7 @@ /** * */ -package com.baeldung.datetime; +package com.baeldung.java9.datetime; import static org.junit.Assert.assertEquals; From 33198c73e179c4d7b34ec88f1ead04c0489d1fc9 Mon Sep 17 00:00:00 2001 From: "dhrubajyoti.bhattacharjee" Date: Wed, 13 Dec 2017 00:49:49 +0530 Subject: [PATCH 04/24] BAEL-1207 File search using Lucene --- lucene/.gitignore | 1 + .../com/baeldung/lucene/LuceneFileSearch.java | 80 +++++++++++++++++++ .../baeldung/lucene/LuceneFileSearchTest.java | 32 ++++++++ lucene/src/test/resources/data/file1.txt | 3 + 4 files changed, 116 insertions(+) create mode 100644 lucene/.gitignore create mode 100644 lucene/src/main/java/com/baeldung/lucene/LuceneFileSearch.java create mode 100644 lucene/src/test/java/com/baeldung/lucene/LuceneFileSearchTest.java create mode 100644 lucene/src/test/resources/data/file1.txt diff --git a/lucene/.gitignore b/lucene/.gitignore new file mode 100644 index 0000000000..3ed87faec7 --- /dev/null +++ b/lucene/.gitignore @@ -0,0 +1 @@ +/index/ diff --git a/lucene/src/main/java/com/baeldung/lucene/LuceneFileSearch.java b/lucene/src/main/java/com/baeldung/lucene/LuceneFileSearch.java new file mode 100644 index 0000000000..1d090d55fc --- /dev/null +++ b/lucene/src/main/java/com/baeldung/lucene/LuceneFileSearch.java @@ -0,0 +1,80 @@ +package com.baeldung.lucene; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.document.Document; +import org.apache.lucene.document.Field; +import org.apache.lucene.document.StringField; +import org.apache.lucene.document.TextField; +import org.apache.lucene.index.DirectoryReader; +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.IndexWriter; +import org.apache.lucene.index.IndexWriterConfig; +import org.apache.lucene.queryparser.classic.ParseException; +import org.apache.lucene.queryparser.classic.QueryParser; +import org.apache.lucene.search.IndexSearcher; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.ScoreDoc; +import org.apache.lucene.search.TopDocs; +import org.apache.lucene.store.Directory; + +public class LuceneFileSearch { + + private Directory indexDirectory; + private StandardAnalyzer analyzer; + + public LuceneFileSearch(Directory fsDirectory, StandardAnalyzer analyzer) { + super(); + this.indexDirectory = fsDirectory; + this.analyzer = analyzer; + } + + public void addFileToIndex(String filepath) throws IOException, URISyntaxException { + + Path path = Paths.get(getClass().getClassLoader().getResource(filepath).toURI()); + File file = path.toFile(); + IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer); + IndexWriter indexWriter = new IndexWriter(indexDirectory, indexWriterConfig); + Document document = new Document(); + + FileReader fileReader = new FileReader(file); + document.add(new TextField("contents", fileReader)); + document.add(new StringField("path", file.getPath(), Field.Store.YES)); + document.add(new StringField("filename", file.getName(), Field.Store.YES)); + + indexWriter.addDocument(document); + + indexWriter.close(); + } + + public List searchFiles(String inField, String queryString) { + try { + Query query = new QueryParser(inField, analyzer).parse(queryString); + + IndexReader indexReader = DirectoryReader.open(indexDirectory); + IndexSearcher searcher = new IndexSearcher(indexReader); + TopDocs topDocs = searcher.search(query, 10); + List documents = new ArrayList<>(); + for (ScoreDoc scoreDoc : topDocs.scoreDocs) { + documents.add(searcher.doc(scoreDoc.doc)); + } + + return documents; + } catch (IOException | ParseException e) { + e.printStackTrace(); + } + return null; + + } + +} + + diff --git a/lucene/src/test/java/com/baeldung/lucene/LuceneFileSearchTest.java b/lucene/src/test/java/com/baeldung/lucene/LuceneFileSearchTest.java new file mode 100644 index 0000000000..4345057ff7 --- /dev/null +++ b/lucene/src/test/java/com/baeldung/lucene/LuceneFileSearchTest.java @@ -0,0 +1,32 @@ +package com.baeldung.lucene; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Paths; +import java.util.List; + +import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.document.Document; +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.FSDirectory; +import org.junit.Assert; +import org.junit.Test; + +public class LuceneFileSearchTest { + + @Test + public void givenSearchQueryWhenFetchedFileNamehenCorrect() throws IOException, URISyntaxException { + String indexPath = "index"; + String dataPath = "data/file1.txt"; + + Directory directory = FSDirectory.open(Paths.get(indexPath)); + LuceneFileSearch luceneFileSearch = new LuceneFileSearch(directory, new StandardAnalyzer()); + + luceneFileSearch.addFileToIndex(dataPath); + + List docs = luceneFileSearch.searchFiles("contents", "consectetur"); + + Assert.assertEquals("file1.txt", docs.get(0).get("filename")); + } + +} \ No newline at end of file diff --git a/lucene/src/test/resources/data/file1.txt b/lucene/src/test/resources/data/file1.txt new file mode 100644 index 0000000000..6f915d3927 --- /dev/null +++ b/lucene/src/test/resources/data/file1.txt @@ -0,0 +1,3 @@ +Cras auctor viverra arcu, id consequat diam posuere id. Pellentesque hendrerit felis tortor, et ornare nibh ullamcorper sed. Aenean sed mauris vitae purus auctor gravida. Nam aliquam egestas orci, sit amet imperdiet leo porttitor quis. Integer commodo sodales orci, ultrices vulputate arcu vestibulum non. Nunc at tellus id urna tristique ultrices in in massa. Vestibulum laoreet ullamcorper nulla vel porttitor. Duis blandit commodo elit at consequat. Vestibulum faucibus lectus eget mi tincidunt, quis molestie lacus mollis. Duis elementum urna eros, non iaculis est facilisis in. Praesent et neque vel ipsum viverra euismod ac ac metus. Ut vitae libero ex. + +Proin consectetur, neque nec feugiat facilisis, metus libero mollis arcu, id pharetra nibh sapien in elit. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam pulvinar fringilla orci in posuere. Duis ut turpis dignissim nisl eleifend posuere nec a massa. Cras fringilla iaculis ipsum a aliquet. Nunc ultrices nisl ipsum, vitae consectetur tellus vehicula in. Aliquam lacinia elit nec scelerisque dapibus. Duis pharetra mauris vitae quam tincidunt, viverra iaculis orci iaculis. Nunc gravida sem arcu, et mollis leo porttitor nec. Ut dictum tempor est, at fringilla ex feugiat sed. Nullam purus mi, aliquet eu libero ut, finibus efficitur metus. \ No newline at end of file From 9e8e17b6893dad885872a5c5ff01b1670c1c484d Mon Sep 17 00:00:00 2001 From: abialas Date: Wed, 13 Dec 2017 22:45:14 +0100 Subject: [PATCH 05/24] BAEL-1304 --- persistence-modules/spring-data-eclipselink | 1 + 1 file changed, 1 insertion(+) create mode 160000 persistence-modules/spring-data-eclipselink diff --git a/persistence-modules/spring-data-eclipselink b/persistence-modules/spring-data-eclipselink new file mode 160000 index 0000000000..dd02630267 --- /dev/null +++ b/persistence-modules/spring-data-eclipselink @@ -0,0 +1 @@ +Subproject commit dd02630267da27e13452c5f91a0ccf7ed3743cbb From 92770e26eb15335f6215735790dd090af462a535 Mon Sep 17 00:00:00 2001 From: abialas Date: Wed, 13 Dec 2017 23:14:51 +0100 Subject: [PATCH 06/24] remove folder --- persistence-modules/spring-data-eclipselink | 1 - 1 file changed, 1 deletion(-) delete mode 160000 persistence-modules/spring-data-eclipselink diff --git a/persistence-modules/spring-data-eclipselink b/persistence-modules/spring-data-eclipselink deleted file mode 160000 index dd02630267..0000000000 --- a/persistence-modules/spring-data-eclipselink +++ /dev/null @@ -1 +0,0 @@ -Subproject commit dd02630267da27e13452c5f91a0ccf7ed3743cbb From 3210112a451ca39ed997a4d418f5508e8a666126 Mon Sep 17 00:00:00 2001 From: abialas Date: Wed, 13 Dec 2017 23:15:59 +0100 Subject: [PATCH 07/24] BAEL-1304 add files --- .../spring-data-eclipselink/pom.xml | 79 +++++++++++++++++++ .../EclipselinkSpringDataApplication.java | 12 +++ .../springdata/JpaConfiguration.java | 44 +++++++++++ .../eclipselink/springdata/model/Person.java | 43 ++++++++++ .../springdata/repo/PersonsRepository.java | 14 ++++ .../src/main/resources/application.properties | 2 + .../repo/PersonsRepositoryTest.java | 59 ++++++++++++++ 7 files changed, 253 insertions(+) create mode 100644 persistence-modules/spring-data-eclipselink/pom.xml create mode 100644 persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/EclipselinkSpringDataApplication.java create mode 100644 persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/JpaConfiguration.java create mode 100644 persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/model/Person.java create mode 100644 persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/repo/PersonsRepository.java create mode 100644 persistence-modules/spring-data-eclipselink/src/main/resources/application.properties create mode 100644 persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryTest.java diff --git a/persistence-modules/spring-data-eclipselink/pom.xml b/persistence-modules/spring-data-eclipselink/pom.xml new file mode 100644 index 0000000000..147901dc90 --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/pom.xml @@ -0,0 +1,79 @@ + + + 4.0.0 + + com.baeldung + spring-data-eclipselink + 1.0.0-SNAPSHOT + + spring-data-eclipselink + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + + + UTF-8 + UTF-8 + 1.8 + 1.5.9.RELEASE + 2.7.0 + 1.4.196 + + + + + org.springframework.boot + spring-boot-dependencies + ${spring.version} + pom + import + + + org.springframework.boot + spring-boot-starter-data-jpa + ${spring.version} + + + org.hibernate + hibernate-entitymanager + + + org.hibernate + hibernate-core + + + + + org.springframework.boot + spring-boot-starter-test + ${spring.version} + test + + + org.eclipse.persistence + org.eclipse.persistence.jpa + ${eclipselink.version} + + + com.h2database + h2 + runtime + ${h2.version} + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/EclipselinkSpringDataApplication.java b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/EclipselinkSpringDataApplication.java new file mode 100644 index 0000000000..63ce778022 --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/EclipselinkSpringDataApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.eclipselink.springdata; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class EclipselinkSpringDataApplication { + + public static void main(String[] args) { + SpringApplication.run(EclipselinkSpringDataApplication.class, args); + } +} diff --git a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/JpaConfiguration.java b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/JpaConfiguration.java new file mode 100644 index 0000000000..60ff7909be --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/JpaConfiguration.java @@ -0,0 +1,44 @@ +package com.baeldung.eclipselink.springdata; + +import org.eclipse.persistence.config.PersistenceUnitProperties; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration; +import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; +import org.springframework.boot.autoconfigure.transaction.TransactionManagerCustomizers; +import org.springframework.context.annotation.Configuration; +import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver; +import org.springframework.orm.jpa.vendor.AbstractJpaVendorAdapter; +import org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter; +import org.springframework.transaction.jta.JtaTransactionManager; + +import javax.sql.DataSource; +import java.util.HashMap; +import java.util.Map; + +/** + * Created by adam. + */ +@Configuration +public class JpaConfiguration extends JpaBaseConfiguration { + + protected JpaConfiguration(DataSource dataSource, JpaProperties properties, ObjectProvider jtaTransactionManager, ObjectProvider transactionManagerCustomizers) { + super(dataSource, properties, jtaTransactionManager, transactionManagerCustomizers); + } + + @Override + protected AbstractJpaVendorAdapter createJpaVendorAdapter() { + return new EclipseLinkJpaVendorAdapter(); + } + + @Override + protected Map getVendorProperties() { + HashMap map = new HashMap<>(); + map.put(PersistenceUnitProperties.WEAVING, detectWeavingMode()); + map.put(PersistenceUnitProperties.DDL_GENERATION, "drop-and-create-tables"); + return map; + } + + private String detectWeavingMode() { + return InstrumentationLoadTimeWeaver.isInstrumentationAvailable() ? "true" : "static"; + } +} diff --git a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/model/Person.java b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/model/Person.java new file mode 100644 index 0000000000..75161875bd --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/model/Person.java @@ -0,0 +1,43 @@ +package com.baeldung.eclipselink.springdata.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +/** + * Created by adam. + */ +@Entity +public class Person { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private Long id; + private String firstName; + private String lastName; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } +} diff --git a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/repo/PersonsRepository.java b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/repo/PersonsRepository.java new file mode 100644 index 0000000000..86cd85d5fe --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/repo/PersonsRepository.java @@ -0,0 +1,14 @@ +package com.baeldung.eclipselink.springdata.repo; + +import org.springframework.data.repository.CrudRepository; + +import com.baeldung.eclipselink.springdata.model.Person; + +/** + * Created by adam. + */ +public interface PersonsRepository extends CrudRepository { + + Person findByFirstName(String firstName); + +} diff --git a/persistence-modules/spring-data-eclipselink/src/main/resources/application.properties b/persistence-modules/spring-data-eclipselink/src/main/resources/application.properties new file mode 100644 index 0000000000..549c0b4ada --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/main/resources/application.properties @@ -0,0 +1,2 @@ +spring.datasource.url=jdbc:h2:mem:test +spring.jpa.show-sql=true \ No newline at end of file diff --git a/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryTest.java b/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryTest.java new file mode 100644 index 0000000000..4c24df9ee7 --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryTest.java @@ -0,0 +1,59 @@ +package com.baeldung.eclipselink.springdata.repo; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.eclipselink.springdata.model.Person; +import com.baeldung.eclipselink.springdata.repo.PersonsRepository; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsNull.notNullValue; + +/** + * Created by adam. + */ +@RunWith(SpringRunner.class) +@SpringBootTest +@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) +public class PersonsRepositoryTest { + + @Autowired + private PersonsRepository personsRepository; + + @Test + public void shouldAddOnePersonToDB() { + // when + personsRepository.save(new Person()); + + // then + assertThat(personsRepository.findAll() + .spliterator() + .getExactSizeIfKnown(), equalTo(1l)); + } + + @Test + public void shouldFindOnePersonWithNameAdam() { + // given + Person person1 = new Person(); + person1.setFirstName("Adam"); + + Person person2 = new Person(); + person2.setFirstName("Dave"); + + personsRepository.save(person1); + personsRepository.save(person2); + + // when + Person foundPerson = personsRepository.findByFirstName("Adam"); + + // then + assertThat(foundPerson.getFirstName(), equalTo("Adam")); + assertThat(foundPerson.getId(), notNullValue()); + } + +} From b1323faaf37adb8c1416e99c96fa27d4e98d4f04 Mon Sep 17 00:00:00 2001 From: abialas Date: Wed, 13 Dec 2017 23:20:56 +0100 Subject: [PATCH 08/24] BAEL-1304 add module spring-data-eclipselink --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index 2c611e6efe..3e38efec4c 100644 --- a/pom.xml +++ b/pom.xml @@ -172,6 +172,7 @@ persistence-modules/spring-hibernate-3 spring-hibernate4 persistence-modules/spring-hibernate-5 + persistence-modules/spring-data-eclipselink spring-integration spring-jersey spring-jmeter-jenkins From 07efbf9c01baf275cc34a595af9ac9c9357c1757 Mon Sep 17 00:00:00 2001 From: Dominik Date: Wed, 13 Dec 2017 23:53:42 +0100 Subject: [PATCH 09/24] VarHandles --- .../java9/varhandles/VariableHandlesTest.java | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 core-java-9/src/test/java/com/baeldung/java9/varhandles/VariableHandlesTest.java diff --git a/core-java-9/src/test/java/com/baeldung/java9/varhandles/VariableHandlesTest.java b/core-java-9/src/test/java/com/baeldung/java9/varhandles/VariableHandlesTest.java new file mode 100644 index 0000000000..210c4f0654 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/varhandles/VariableHandlesTest.java @@ -0,0 +1,91 @@ +package com.baeldung.java9.varhandles; + +import org.junit.Assert; +import org.junit.Test; + +import java.lang.invoke.MethodHandles; +import java.lang.invoke.VarHandle; + +public class VariableHandlesTest { + public int publicTestVariable = 1; + private int privateTestVariable = 1; + public int variableToSet = 1; + public int variableToCompareAndSet = 1; + public int variableToGetAndAdd = 0; + public byte variableToBitwiseOr = 0; + @Test + public void whenVariableHandleForPublicVariableIsCreated_ThenItIsInitializedProperly() + throws NoSuchFieldException, IllegalAccessException { + VarHandle publicIntHandle = MethodHandles.lookup() + .in(VariableHandlesTest.class) + .findVarHandle(VariableHandlesTest.class,"publicTestVariable", int.class); + Assert.assertEquals(1, publicIntHandle.coordinateTypes().size()); + Assert.assertEquals(VariableHandlesTest.class, publicIntHandle.coordinateTypes().get(0)); + + } + + @Test + public void whenVariableHandleForPrivateVariableIsCreated_ThenItIsInitializedProperly() + throws NoSuchFieldException, IllegalAccessException { + VarHandle privateIntHandle = MethodHandles.privateLookupIn(VariableHandlesTest.class, MethodHandles.lookup()) + .findVarHandle(VariableHandlesTest.class,"privateTestVariable", int.class); + Assert.assertNotNull(privateIntHandle); + Assert.assertEquals(1, privateIntHandle.coordinateTypes().size()); + Assert.assertEquals(VariableHandlesTest.class, privateIntHandle.coordinateTypes().get(0)); + + } + + @Test + public void whenVariableHandleForArrayVariableIsCreated_ThenItIsInitializedProperly() + throws NoSuchFieldException, IllegalAccessException { + VarHandle arrayVarHandle = MethodHandles.arrayElementVarHandle(int[].class); + Assert.assertEquals(2, arrayVarHandle.coordinateTypes().size()); + Assert.assertEquals(int[].class, arrayVarHandle.coordinateTypes().get(0)); + } + + @Test + public void givenVarHandle_whenGetIsInvoked_ThenValueOfVariableIsReturned() throws NoSuchFieldException, IllegalAccessException { + VarHandle publicIntHandle = MethodHandles.lookup() + .in(VariableHandlesTest.class) + .findVarHandle(VariableHandlesTest.class,"publicTestVariable", int.class); + Assert.assertEquals(1, publicIntHandle.get(this)); + } + + @Test + public void givenVarHandle_whenSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException { + VarHandle publicIntHandle = MethodHandles.lookup() + .in(VariableHandlesTest.class) + .findVarHandle(VariableHandlesTest.class,"variableToSet", int.class); + publicIntHandle.set(this, 15); + Assert.assertEquals(15, publicIntHandle.get(this)); + } + + @Test + public void givenVarHandle_whenCompareAndSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException { + VarHandle publicIntHandle = MethodHandles.lookup() + .in(VariableHandlesTest.class) + .findVarHandle(VariableHandlesTest.class,"variableToCompareAndSet", int.class); + publicIntHandle.compareAndSet(this, 1,100); + Assert.assertEquals(100, publicIntHandle.get(this)); + } + + @Test + public void givenVarHandle_whenGetAndAddIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException { + VarHandle publicIntHandle = MethodHandles.lookup() + .in(VariableHandlesTest.class) + .findVarHandle(VariableHandlesTest.class,"variableToGetAndAdd", int.class); + int before = (int) publicIntHandle.getAndAdd(this, 200); + Assert.assertEquals(0, before); + Assert.assertEquals(200, publicIntHandle.get(this)); + } + + @Test + public void givenVarHandle_whenGetAndBitwiseOrIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException { + VarHandle publicIntHandle = MethodHandles.lookup() + .in(VariableHandlesTest.class) + .findVarHandle(VariableHandlesTest.class,"variableToBitwiseOr", byte.class); + byte before = (byte) publicIntHandle.getAndBitwiseOr(this, (byte) 127); + Assert.assertEquals(0, before); + Assert.assertEquals(127, variableToBitwiseOr); + } +} From 0d07e421ff2564c63923c9be1b80519b618787bc Mon Sep 17 00:00:00 2001 From: shouvikbhattacharya Date: Thu, 14 Dec 2017 20:15:00 +0530 Subject: [PATCH 10/24] BAEL-1433: Commit changes for treeset article. --- .../baeldung/collection/WhenUsingTreeSet.java | 105 ++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/collection/WhenUsingTreeSet.java diff --git a/core-java/src/test/java/com/baeldung/collection/WhenUsingTreeSet.java b/core-java/src/test/java/com/baeldung/collection/WhenUsingTreeSet.java new file mode 100644 index 0000000000..48aff4d437 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/collection/WhenUsingTreeSet.java @@ -0,0 +1,105 @@ +package com.baeldung.collection; + +import java.util.ConcurrentModificationException; +import java.util.Iterator; +import java.util.Set; +import java.util.TreeSet; + +import org.junit.Assert; +import org.junit.Test; + +public class WhenUsingTreeSet { + + @Test + public void whenAddingElement_shouldAddElement() { + Set treeSet = new TreeSet<>(); + Assert.assertTrue(treeSet.add("String Added")); + } + + @Test + public void whenCheckingForElement_shouldSearchForElement() { + Set treeSetContains = new TreeSet<>(); + treeSetContains.add("String Added"); + Assert.assertTrue(treeSetContains.contains("String Added")); + } + + @Test + public void whenRemovingElement_shouldRemoveElement() { + Set removeFromTreeSet = new TreeSet<>(); + removeFromTreeSet.add("String Added"); + Assert.assertTrue(removeFromTreeSet.remove("String Added")); + } + + @Test + public void whenClearingTreeSet_shouldClearTreeSet() { + Set clearTreeSet = new TreeSet<>(); + clearTreeSet.add("String Added"); + clearTreeSet.clear(); + Assert.assertTrue(clearTreeSet.isEmpty()); + } + + @Test + public void whenCheckingTheSizeOfTreeSet_shouldReturnThesize() { + Set treeSetSize = new TreeSet<>(); + treeSetSize.add("String Added"); + Assert.assertEquals(1, treeSetSize.size()); + } + + @Test + public void whenCheckingForEmptyTreeSet_shouldCheckForEmpty() { + Set emptyTreeSet = new TreeSet<>(); + Assert.assertTrue(emptyTreeSet.isEmpty()); + } + + @Test + public void whenIteratingTreeSet_shouldIterateTreeSetInAscendingOrder() { + Set treeSet = new TreeSet<>(); + treeSet.add("First"); + treeSet.add("Second"); + treeSet.add("Third"); + Iterator itr = treeSet.iterator(); + while (itr.hasNext()) { + System.out.println(itr.next()); + } + } + + @Test + public void whenIteratingTreeSet_shouldIterateTreeSetInDescendingOrder() { + TreeSet treeSet = new TreeSet<>(); + treeSet.add("First"); + treeSet.add("Second"); + treeSet.add("Third"); + Iterator itr = treeSet.descendingIterator(); + while (itr.hasNext()) { + System.out.println(itr.next()); + } + } + + @Test(expected = ConcurrentModificationException.class) + public void whenModifyingTreeSetWhileIterating_shouldThrowException() { + Set treeSet = new TreeSet<>(); + treeSet.add("First"); + treeSet.add("Second"); + treeSet.add("Third"); + Iterator itr = treeSet.iterator(); + while (itr.hasNext()) { + itr.next(); + treeSet.remove("Second"); + } + } + + @Test + public void whenRemovingElementUsingIterator_shouldRemoveElement() { + Set treeSet = new TreeSet<>(); + treeSet.add("First"); + treeSet.add("Second"); + treeSet.add("Third"); + Iterator itr = treeSet.iterator(); + while (itr.hasNext()) { + String element = itr.next(); + if (element.equals("Second")) + itr.remove(); + } + Assert.assertEquals(2, treeSet.size()); + } +} From ef4b5609653138d7d0d1654737087fd3f334312f Mon Sep 17 00:00:00 2001 From: shouvikbhattacharya Date: Thu, 14 Dec 2017 22:14:58 +0530 Subject: [PATCH 11/24] BAEL-1433: Article complete pushing final code. --- .../baeldung/collection/WhenUsingTreeSet.java | 118 ++++++++++++++++++ 1 file changed, 118 insertions(+) diff --git a/core-java/src/test/java/com/baeldung/collection/WhenUsingTreeSet.java b/core-java/src/test/java/com/baeldung/collection/WhenUsingTreeSet.java index 48aff4d437..887f6eba1d 100644 --- a/core-java/src/test/java/com/baeldung/collection/WhenUsingTreeSet.java +++ b/core-java/src/test/java/com/baeldung/collection/WhenUsingTreeSet.java @@ -1,8 +1,11 @@ package com.baeldung.collection; +import java.util.Comparator; import java.util.ConcurrentModificationException; import java.util.Iterator; +import java.util.NavigableSet; import java.util.Set; +import java.util.SortedSet; import java.util.TreeSet; import org.junit.Assert; @@ -10,6 +13,29 @@ import org.junit.Test; public class WhenUsingTreeSet { + private static class Element { + private Integer id; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @Override + public String toString() { + // TODO Auto-generated method stub + return id.toString(); + } + } + + private Comparator comparator = (ele1, ele2) -> { + return ele1.getId() + .compareTo(ele2.getId()); + }; + @Test public void whenAddingElement_shouldAddElement() { Set treeSet = new TreeSet<>(); @@ -102,4 +128,96 @@ public class WhenUsingTreeSet { } Assert.assertEquals(2, treeSet.size()); } + + @Test(expected = NullPointerException.class) + public void whenAddingNullToNonEmptyTreeSet_shouldThrowException() { + Set treeSet = new TreeSet<>(); + treeSet.add("First"); + treeSet.add(null); + } + + @Test + public void whenCheckingFirstElement_shouldReturnFirstElement() { + TreeSet treeSet = new TreeSet<>(); + treeSet.add("First"); + Assert.assertEquals("First", treeSet.first()); + } + + @Test + public void whenCheckingLastElement_shouldReturnLastElement() { + TreeSet treeSet = new TreeSet<>(); + treeSet.add("First"); + treeSet.add("Last"); + Assert.assertEquals("Last", treeSet.last()); + } + + @Test + public void whenUsingComparator_shouldSortAndInsertElements() { + Set treeSet = new TreeSet<>(comparator); + Element ele1 = new Element(); + ele1.setId(100); + Element ele2 = new Element(); + ele2.setId(200); + + treeSet.add(ele1); + treeSet.add(ele2); + + System.out.println(treeSet); + } + + @Test + public void whenUsingHeadSet_shouldReturnElementsLessThanSpecifiedElement() { + Set treeSet = new TreeSet<>(comparator); + Element ele1 = new Element(); + ele1.setId(100); + Element ele2 = new Element(); + ele2.setId(200); + + treeSet.add(ele1); + treeSet.add(ele2); + + System.out.println(treeSet); + } + + @Test + public void whenUsingSubSet_shouldReturnSubSetElements() { + SortedSet treeSet = new TreeSet<>(); + treeSet.add(1); + treeSet.add(2); + treeSet.add(3); + treeSet.add(4); + treeSet.add(5); + treeSet.add(6); + + Set subSet = treeSet.subSet(2, 6); + System.out.println(subSet); + } + + @Test + public void whenUsingHeadSet_shouldReturnHeadSetElements() { + SortedSet treeSet = new TreeSet<>(); + treeSet.add(1); + treeSet.add(2); + treeSet.add(3); + treeSet.add(4); + treeSet.add(5); + treeSet.add(6); + + Set subSet = treeSet.headSet(6); + Assert.assertEquals(subSet, treeSet.subSet(1, 6)); + } + + @Test + public void whenUsingTailSet_shouldReturnTailSetElements() { + NavigableSet treeSet = new TreeSet<>(); + treeSet.add(1); + treeSet.add(2); + treeSet.add(3); + treeSet.add(4); + treeSet.add(5); + treeSet.add(6); + + Set subSet = treeSet.tailSet(3); + Assert.assertEquals(subSet, treeSet.subSet(3, true, 6, true)); + } } From 6809155a9195fa539071f3593f3c304ec89cfe89 Mon Sep 17 00:00:00 2001 From: ericgoebelbecker <@592Gbetz> Date: Fri, 15 Dec 2017 13:19:43 -0500 Subject: [PATCH 12/24] BAEL-1374 - same search in each loop. --- .../main/java/com/baeldung/array/SearchArrayTest.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java b/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java index 8b44138b32..345e1d48f3 100644 --- a/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java +++ b/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java @@ -26,7 +26,7 @@ public class SearchArrayTest { int count = 1000; String[] strings = seedArray(count); for (int i = 0; i < count; i++) { - searchList(strings, "W"); + searchList(strings, "T"); } } @@ -37,7 +37,7 @@ public class SearchArrayTest { int count = 1000; String[] strings = seedArray(count); for (int i = 0; i < count; i++) { - searchSet(strings, "S"); + searchSet(strings, "T"); } } @@ -51,7 +51,7 @@ public class SearchArrayTest { List asList = Arrays.asList(strings); for (int i = 0; i < count; i++) { - asList.contains("W"); + asList.contains("T"); } } @@ -63,7 +63,7 @@ public class SearchArrayTest { String[] strings = seedArray(count); Set asSet = new HashSet<>(Arrays.asList(strings)); for (int i = 0; i < count; i++) { - asSet.contains("S"); + asSet.contains("T"); } } @@ -77,7 +77,7 @@ public class SearchArrayTest { long startTime = System.nanoTime(); for (int i = 0; i < count; i++) { - Arrays.binarySearch(strings, "A"); + Arrays.binarySearch(strings, "T"); } long duration = System.nanoTime() - startTime; //System.out.println("Binary search: " + duration / 10000); From 15bc3244303470a77481cf338ce3c73f2557475e Mon Sep 17 00:00:00 2001 From: Marcos Date: Fri, 15 Dec 2017 20:26:16 +0100 Subject: [PATCH 13/24] binary tree changed to follow a recursive approach --- .../java/com/baeldung/tree/BinaryTree.java | 185 +++++++++--------- 1 file changed, 94 insertions(+), 91 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/tree/BinaryTree.java b/core-java/src/main/java/com/baeldung/tree/BinaryTree.java index 3cc496e348..0b917ed452 100644 --- a/core-java/src/main/java/com/baeldung/tree/BinaryTree.java +++ b/core-java/src/main/java/com/baeldung/tree/BinaryTree.java @@ -16,29 +16,23 @@ public class BinaryTree { return; } - Node parent = root; - Node current = root; + addRecursive(root, value); + } - while (true) { + private Node addRecursive(Node current, int value) { - if (newNode.value < parent.value) { - current = parent.left; - - if (current == null) { - parent.left = newNode; - break; - } - } else { - current = parent.right; - - if (current == null) { - parent.right = newNode; - break; - } - } - - parent = current; + if (current == null) { + return new Node(value); } + + if (value < current.value) { + current.left = addRecursive(current.left, value); + } else { + current.right = addRecursive(current.right, value); + } + + return current; + } public boolean isEmpty() { @@ -46,115 +40,107 @@ public class BinaryTree { } public boolean containsNode(int value) { + return containsNodeRecursive(root, value); + } - Node current = root; - - while (current != null) { - - if (value == current.value) { - return true; - } - - if (value < current.value) { - current = current.left; - } else { - current = current.right; - } + private boolean containsNodeRecursive(Node current, int value) { + if (current == null) { + return false; + } else if (value == current.value) { + return true; + } else if (value < current.value) { + return containsNodeRecursive(current.left, value); + } else { + return containsNodeRecursive(current.right, value); } - return false; } public void delete(int value) { - Node current = root; - Node parent = root; - Node nodeToDelete = null; - boolean isLeftChild = false; + NodeVO nodeToDeleteAux = findNodeToDelete(root, root, false, value); - while (nodeToDelete == null && current != null) { - - if (value == current.value) { - nodeToDelete = current; - } else if (value < current.value) { - parent = current; - current = current.left; - isLeftChild = true; - } else { - parent = current; - current = current.right; - isLeftChild = false; - } - - } - - if (nodeToDelete == null) { + if (nodeToDeleteAux == null) { return; } // Case 1: no children - if (nodeToDelete.left == null && nodeToDelete.right == null) { - if (nodeToDelete == root) { + if (nodeToDeleteAux.node.left == null && nodeToDeleteAux.node.right == null) { + if (nodeToDeleteAux.node == root) { root = null; - } else if (isLeftChild) { - parent.left = null; + } else if (nodeToDeleteAux.isLeftChild) { + nodeToDeleteAux.parent.left = null; } else { - parent.right = null; + nodeToDeleteAux.parent.right = null; } } // Case 2: only 1 child - else if (nodeToDelete.right == null) { - if (nodeToDelete == root) { - root = nodeToDelete.left; - } else if (isLeftChild) { - parent.left = nodeToDelete.left; + else if (nodeToDeleteAux.node.right == null) { + if (nodeToDeleteAux.node == root) { + root = nodeToDeleteAux.node.left; + } else if (nodeToDeleteAux.isLeftChild) { + nodeToDeleteAux.parent.left = nodeToDeleteAux.node.left; } else { - parent.right = nodeToDelete.left; + nodeToDeleteAux.parent.right = nodeToDeleteAux.node.left; } - } else if (nodeToDelete.left == null) { - if (nodeToDelete == root) { - root = nodeToDelete.right; - } else if (isLeftChild) { - parent.left = nodeToDelete.right; + } else if (nodeToDeleteAux.node.left == null) { + if (nodeToDeleteAux.node == root) { + root = nodeToDeleteAux.node.right; + } else if (nodeToDeleteAux.isLeftChild) { + nodeToDeleteAux.parent.left = nodeToDeleteAux.node.right; } else { - parent.right = nodeToDelete.right; + nodeToDeleteAux.parent.right = nodeToDeleteAux.node.right; } } // Case 3: 2 children - else if (nodeToDelete.left != null && nodeToDelete.right != null) { - Node replacement = findReplacement(nodeToDelete); - if (nodeToDelete == root) { + else if (nodeToDeleteAux.node.left != null && nodeToDeleteAux.node.right != null) { + Node replacement = findReplacement(nodeToDeleteAux.node); + if (nodeToDeleteAux.node == root) { root = replacement; - } else if (isLeftChild) { - parent.left = replacement; + } else if (nodeToDeleteAux.isLeftChild) { + nodeToDeleteAux.parent.left = replacement; } else { - parent.right = replacement; + nodeToDeleteAux.parent.right = replacement; } } } + private NodeVO findNodeToDelete(Node current, Node parent, boolean isLeftChild, int value) { + + if (current == null) { + return null; + } else if (value == current.value) { + return new NodeVO(current, parent, isLeftChild); + } else if (value < current.value) { + return findNodeToDelete(current.left, current, true, value); + } else { + return findNodeToDelete(current.right, current, false, value); + } + } + private Node findReplacement(Node nodeToDelete) { - Node replacement = nodeToDelete; - Node parentReplacement = nodeToDelete; - Node current = nodeToDelete.right; + NodeVO replacementNodeVO = findSmallestNode(nodeToDelete, nodeToDelete); - while (current != null) { - parentReplacement = replacement; - replacement = current; - current = current.left; + if (replacementNodeVO.node != nodeToDelete.right) { + replacementNodeVO.parent.left = replacementNodeVO.node.right; + replacementNodeVO.node.right = nodeToDelete.right; } - if (replacement != nodeToDelete.right) { - parentReplacement.left = replacement.right; - replacement.right = nodeToDelete.right; + replacementNodeVO.node.left = nodeToDelete.left; + + return replacementNodeVO.node; + } + + private NodeVO findSmallestNode(Node root, Node parent) { + + if (root.left == null) { + return new NodeVO(root, parent); } - replacement.left = nodeToDelete.left; - - return replacement; + return findSmallestNode(root.left, root); } public void traverseInOrder(Node node) { @@ -202,6 +188,23 @@ public class BinaryTree { } } + class NodeVO { + Node node; + Node parent; + boolean isLeftChild; + + NodeVO(Node node, Node parent) { + this.node = node; + this.parent = parent; + } + + NodeVO(Node node, Node parent, boolean isLeftChild) { + this.node = node; + this.parent = parent; + this.isLeftChild = isLeftChild; + } + } + class Node { int value; Node left; From 9ead70be1bbab8515d4abdf7205b1eea79f5f11b Mon Sep 17 00:00:00 2001 From: Marcos Date: Fri, 15 Dec 2017 20:42:56 +0100 Subject: [PATCH 14/24] var renamed --- .../java/com/baeldung/tree/BinaryTree.java | 50 +++++++++---------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/tree/BinaryTree.java b/core-java/src/main/java/com/baeldung/tree/BinaryTree.java index 0b917ed452..686136729e 100644 --- a/core-java/src/main/java/com/baeldung/tree/BinaryTree.java +++ b/core-java/src/main/java/com/baeldung/tree/BinaryTree.java @@ -59,49 +59,49 @@ public class BinaryTree { public void delete(int value) { - NodeVO nodeToDeleteAux = findNodeToDelete(root, root, false, value); + NodeVO nodeToDeleteVO = findNodeToDelete(root, root, false, value); - if (nodeToDeleteAux == null) { + if (nodeToDeleteVO == null) { return; } // Case 1: no children - if (nodeToDeleteAux.node.left == null && nodeToDeleteAux.node.right == null) { - if (nodeToDeleteAux.node == root) { + if (nodeToDeleteVO.node.left == null && nodeToDeleteVO.node.right == null) { + if (nodeToDeleteVO.node == root) { root = null; - } else if (nodeToDeleteAux.isLeftChild) { - nodeToDeleteAux.parent.left = null; + } else if (nodeToDeleteVO.isLeftChild) { + nodeToDeleteVO.parent.left = null; } else { - nodeToDeleteAux.parent.right = null; + nodeToDeleteVO.parent.right = null; } } // Case 2: only 1 child - else if (nodeToDeleteAux.node.right == null) { - if (nodeToDeleteAux.node == root) { - root = nodeToDeleteAux.node.left; - } else if (nodeToDeleteAux.isLeftChild) { - nodeToDeleteAux.parent.left = nodeToDeleteAux.node.left; + else if (nodeToDeleteVO.node.right == null) { + if (nodeToDeleteVO.node == root) { + root = nodeToDeleteVO.node.left; + } else if (nodeToDeleteVO.isLeftChild) { + nodeToDeleteVO.parent.left = nodeToDeleteVO.node.left; } else { - nodeToDeleteAux.parent.right = nodeToDeleteAux.node.left; + nodeToDeleteVO.parent.right = nodeToDeleteVO.node.left; } - } else if (nodeToDeleteAux.node.left == null) { - if (nodeToDeleteAux.node == root) { - root = nodeToDeleteAux.node.right; - } else if (nodeToDeleteAux.isLeftChild) { - nodeToDeleteAux.parent.left = nodeToDeleteAux.node.right; + } else if (nodeToDeleteVO.node.left == null) { + if (nodeToDeleteVO.node == root) { + root = nodeToDeleteVO.node.right; + } else if (nodeToDeleteVO.isLeftChild) { + nodeToDeleteVO.parent.left = nodeToDeleteVO.node.right; } else { - nodeToDeleteAux.parent.right = nodeToDeleteAux.node.right; + nodeToDeleteVO.parent.right = nodeToDeleteVO.node.right; } } // Case 3: 2 children - else if (nodeToDeleteAux.node.left != null && nodeToDeleteAux.node.right != null) { - Node replacement = findReplacement(nodeToDeleteAux.node); - if (nodeToDeleteAux.node == root) { + else if (nodeToDeleteVO.node.left != null && nodeToDeleteVO.node.right != null) { + Node replacement = findReplacement(nodeToDeleteVO.node); + if (nodeToDeleteVO.node == root) { root = replacement; - } else if (nodeToDeleteAux.isLeftChild) { - nodeToDeleteAux.parent.left = replacement; + } else if (nodeToDeleteVO.isLeftChild) { + nodeToDeleteVO.parent.left = replacement; } else { - nodeToDeleteAux.parent.right = replacement; + nodeToDeleteVO.parent.right = replacement; } } From 970de8173442a4aef7aaff10b7484c3b55844cf0 Mon Sep 17 00:00:00 2001 From: abialas Date: Fri, 15 Dec 2017 23:43:51 +0100 Subject: [PATCH 15/24] BAEL-1304 changes after code review --- .../spring-data-eclipselink/pom.xml | 1 + .../repo/PersonsRepositoryTest.java | 46 ++++++++----------- 2 files changed, 20 insertions(+), 27 deletions(-) diff --git a/persistence-modules/spring-data-eclipselink/pom.xml b/persistence-modules/spring-data-eclipselink/pom.xml index 147901dc90..65793fd1e0 100644 --- a/persistence-modules/spring-data-eclipselink/pom.xml +++ b/persistence-modules/spring-data-eclipselink/pom.xml @@ -72,6 +72,7 @@ org.springframework.boot spring-boot-maven-plugin + ${spring.version} diff --git a/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryTest.java b/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryTest.java index 4c24df9ee7..5947e6ffa0 100644 --- a/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryTest.java +++ b/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryTest.java @@ -22,38 +22,30 @@ import static org.hamcrest.core.IsNull.notNullValue; @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) public class PersonsRepositoryTest { - @Autowired - private PersonsRepository personsRepository; + @Autowired + private PersonsRepository personsRepository; - @Test - public void shouldAddOnePersonToDB() { - // when - personsRepository.save(new Person()); + @Test + public void givenPerson_whenSave_thenAddOnePersonToDB() { + personsRepository.save(new Person()); + assertThat(personsRepository.findAll().spliterator().getExactSizeIfKnown(), equalTo(1l)); + } - // then - assertThat(personsRepository.findAll() - .spliterator() - .getExactSizeIfKnown(), equalTo(1l)); - } + @Test + public void givenPersonsAdamAndDaveInDB_whenSearchForPersonWithNameAdam_thenFindOnePerson() { + Person person1 = new Person(); + person1.setFirstName("Adam"); - @Test - public void shouldFindOnePersonWithNameAdam() { - // given - Person person1 = new Person(); - person1.setFirstName("Adam"); + Person person2 = new Person(); + person2.setFirstName("Dave"); - Person person2 = new Person(); - person2.setFirstName("Dave"); + personsRepository.save(person1); + personsRepository.save(person2); - personsRepository.save(person1); - personsRepository.save(person2); + Person foundPerson = personsRepository.findByFirstName("Adam"); - // when - Person foundPerson = personsRepository.findByFirstName("Adam"); - - // then - assertThat(foundPerson.getFirstName(), equalTo("Adam")); - assertThat(foundPerson.getId(), notNullValue()); - } + assertThat(foundPerson.getFirstName(), equalTo("Adam")); + assertThat(foundPerson.getId(), notNullValue()); + } } From e20d477733e5563afd006b91b835a5ea408ad54c Mon Sep 17 00:00:00 2001 From: ericgoebelbecker <@592Gbetz> Date: Fri, 15 Dec 2017 18:58:37 -0500 Subject: [PATCH 16/24] BAEL-1374 - reuse array --- .../com/baeldung/array/SearchArrayTest.java | 61 +++++++------------ 1 file changed, 21 insertions(+), 40 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java b/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java index 345e1d48f3..199ebdf036 100644 --- a/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java +++ b/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java @@ -10,47 +10,40 @@ import java.util.concurrent.TimeUnit; @OutputTimeUnit(TimeUnit.MICROSECONDS) public class SearchArrayTest { + @State(Scope.Benchmark) + public static class SearchData { + static int count = 1000; + static String[] strings = seedArray(1000); + } + + @Benchmark public void searchArrayLoop() { - - int count = 1000; - String[] strings = seedArray(count); - for (int i = 0; i < count; i++) { - searchLoop(strings, "T"); + for (int i = 0; i < SearchData.count; i++) { + searchLoop(SearchData.strings, "T"); } } @Benchmark public void searchArrayAllocNewList() { - - int count = 1000; - String[] strings = seedArray(count); - for (int i = 0; i < count; i++) { - searchList(strings, "T"); + for (int i = 0; i < SearchData.count; i++) { + searchList(SearchData.strings, "T"); } } @Benchmark public void searchArrayAllocNewSet() { - - int count = 1000; - String[] strings = seedArray(count); - for (int i = 0; i < count; i++) { - searchSet(strings, "T"); + for (int i = 0; i < SearchData.count; i++) { + searchSet(SearchData.strings, "T"); } } @Benchmark public void searchArrayReuseList() { - - int count = 1000; - String[] strings = seedArray(count); - - List asList = Arrays.asList(strings); - - for (int i = 0; i < count; i++) { + List asList = Arrays.asList(SearchData.strings); + for (int i = 0; i < SearchData.count; i++) { asList.contains("T"); } } @@ -58,11 +51,8 @@ public class SearchArrayTest { @Benchmark public void searchArrayReuseSet() { - - int count = 1000; - String[] strings = seedArray(count); - Set asSet = new HashSet<>(Arrays.asList(strings)); - for (int i = 0; i < count; i++) { + Set asSet = new HashSet<>(Arrays.asList(SearchData.strings)); + for (int i = 0; i < SearchData.count; i++) { asSet.contains("T"); } } @@ -70,18 +60,10 @@ public class SearchArrayTest { @Benchmark public void searchArrayBinarySearch() { - - int count = 1000; - String[] strings = seedArray(count); - Arrays.sort(strings); - - long startTime = System.nanoTime(); - for (int i = 0; i < count; i++) { - Arrays.binarySearch(strings, "T"); + Arrays.sort(SearchData.strings); + for (int i = 0; i < SearchData.count; i++) { + Arrays.binarySearch(SearchData.strings, "T"); } - long duration = System.nanoTime() - startTime; - //System.out.println("Binary search: " + duration / 10000); - } private boolean searchList(String[] strings, String searchString) { @@ -101,8 +83,7 @@ public class SearchArrayTest { return false; } - private String[] seedArray(int length) { - + private static String[] seedArray(int length) { String[] strings = new String[length]; Random random = new Random(); for (int i = 0; i < length; i++) From f7c32aabb179a8b888fa33a21611f5031cee57bf Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 16 Dec 2017 10:39:02 +0200 Subject: [PATCH 17/24] change test name --- .../eclipselink/springdata/repo/PersonsRepositoryTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryTest.java b/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryTest.java index 5947e6ffa0..1a7c28df6c 100644 --- a/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryTest.java +++ b/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryTest.java @@ -32,7 +32,7 @@ public class PersonsRepositoryTest { } @Test - public void givenPersonsAdamAndDaveInDB_whenSearchForPersonWithNameAdam_thenFindOnePerson() { + public void givenPersons_whenSearch_thenFindOk() { Person person1 = new Person(); person1.setFirstName("Adam"); From 7acbc7902d109fb3252fa8518c96e53a1ac8af66 Mon Sep 17 00:00:00 2001 From: Marcos Date: Sat, 16 Dec 2017 12:33:50 +0100 Subject: [PATCH 18/24] recursived deletion binary tree --- .../java/com/baeldung/tree/BinaryTree.java | 119 +++++------------- 1 file changed, 32 insertions(+), 87 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/tree/BinaryTree.java b/core-java/src/main/java/com/baeldung/tree/BinaryTree.java index 686136729e..d5ccd05bdb 100644 --- a/core-java/src/main/java/com/baeldung/tree/BinaryTree.java +++ b/core-java/src/main/java/com/baeldung/tree/BinaryTree.java @@ -58,89 +58,51 @@ public class BinaryTree { } public void delete(int value) { - - NodeVO nodeToDeleteVO = findNodeToDelete(root, root, false, value); - - if (nodeToDeleteVO == null) { - return; - } - - // Case 1: no children - if (nodeToDeleteVO.node.left == null && nodeToDeleteVO.node.right == null) { - if (nodeToDeleteVO.node == root) { - root = null; - } else if (nodeToDeleteVO.isLeftChild) { - nodeToDeleteVO.parent.left = null; - } else { - nodeToDeleteVO.parent.right = null; - } - } - // Case 2: only 1 child - else if (nodeToDeleteVO.node.right == null) { - if (nodeToDeleteVO.node == root) { - root = nodeToDeleteVO.node.left; - } else if (nodeToDeleteVO.isLeftChild) { - nodeToDeleteVO.parent.left = nodeToDeleteVO.node.left; - } else { - nodeToDeleteVO.parent.right = nodeToDeleteVO.node.left; - } - } else if (nodeToDeleteVO.node.left == null) { - if (nodeToDeleteVO.node == root) { - root = nodeToDeleteVO.node.right; - } else if (nodeToDeleteVO.isLeftChild) { - nodeToDeleteVO.parent.left = nodeToDeleteVO.node.right; - } else { - nodeToDeleteVO.parent.right = nodeToDeleteVO.node.right; - } - } - // Case 3: 2 children - else if (nodeToDeleteVO.node.left != null && nodeToDeleteVO.node.right != null) { - Node replacement = findReplacement(nodeToDeleteVO.node); - if (nodeToDeleteVO.node == root) { - root = replacement; - } else if (nodeToDeleteVO.isLeftChild) { - nodeToDeleteVO.parent.left = replacement; - } else { - nodeToDeleteVO.parent.right = replacement; - } - } - + deleteRecursive(root, value); } - private NodeVO findNodeToDelete(Node current, Node parent, boolean isLeftChild, int value) { - + private Node deleteRecursive(Node current, int value) { if (current == null) { return null; - } else if (value == current.value) { - return new NodeVO(current, parent, isLeftChild); + } + + if (value == current.value) { + // Case 1: no children + if (current.left == null && current.right == null) { + return null; + } + + // Case 2: only 1 child + if (current.right == null) { + return current.left; + } + + if (current.left == null) { + return current.right; + } + + // Case 3: 2 children + int smallestValue = findSmallestNode(current.right); + current.value = smallestValue; + current.right = deleteRecursive(current.right, smallestValue); + return current; + } else if (value < current.value) { - return findNodeToDelete(current.left, current, true, value); + current.left = deleteRecursive(current.left, value); + return current; } else { - return findNodeToDelete(current.right, current, false, value); + current.right = deleteRecursive(current.right, value); + return current; } } - private Node findReplacement(Node nodeToDelete) { - - NodeVO replacementNodeVO = findSmallestNode(nodeToDelete, nodeToDelete); - - if (replacementNodeVO.node != nodeToDelete.right) { - replacementNodeVO.parent.left = replacementNodeVO.node.right; - replacementNodeVO.node.right = nodeToDelete.right; - } - - replacementNodeVO.node.left = nodeToDelete.left; - - return replacementNodeVO.node; - } - - private NodeVO findSmallestNode(Node root, Node parent) { + private int findSmallestNode(Node root) { if (root.left == null) { - return new NodeVO(root, parent); + return root.value; } - return findSmallestNode(root.left, root); + return findSmallestNode(root.left); } public void traverseInOrder(Node node) { @@ -188,23 +150,6 @@ public class BinaryTree { } } - class NodeVO { - Node node; - Node parent; - boolean isLeftChild; - - NodeVO(Node node, Node parent) { - this.node = node; - this.parent = parent; - } - - NodeVO(Node node, Node parent, boolean isLeftChild) { - this.node = node; - this.parent = parent; - this.isLeftChild = isLeftChild; - } - } - class Node { int value; Node left; From 959845621fc23dbb411b8f8585042a797dc84dde Mon Sep 17 00:00:00 2001 From: Marcos Date: Sat, 16 Dec 2017 12:37:30 +0100 Subject: [PATCH 19/24] refactor --- core-java/src/main/java/com/baeldung/tree/BinaryTree.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/tree/BinaryTree.java b/core-java/src/main/java/com/baeldung/tree/BinaryTree.java index d5ccd05bdb..285dc12219 100644 --- a/core-java/src/main/java/com/baeldung/tree/BinaryTree.java +++ b/core-java/src/main/java/com/baeldung/tree/BinaryTree.java @@ -82,7 +82,7 @@ public class BinaryTree { } // Case 3: 2 children - int smallestValue = findSmallestNode(current.right); + int smallestValue = findSmallestValue(current.right); current.value = smallestValue; current.right = deleteRecursive(current.right, smallestValue); return current; @@ -96,13 +96,13 @@ public class BinaryTree { } } - private int findSmallestNode(Node root) { + private int findSmallestValue(Node root) { if (root.left == null) { return root.value; } - return findSmallestNode(root.left); + return findSmallestValue(root.left); } public void traverseInOrder(Node node) { From bac07e4dca4b1834038175f6e034ba9ace1d081d Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sat, 16 Dec 2017 13:15:22 +0100 Subject: [PATCH 20/24] Update README.md (#3252) --- libraries/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/README.md b/libraries/README.md index ae2522ca9e..990a50e711 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -30,7 +30,7 @@ - [Introduction to Neuroph](http://www.baeldung.com/neuroph) - [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue) - [Quick Guide to RSS with Rome](http://www.baeldung.com/rome-rss) -- [Introduction to NoException](http://www.baeldung.com/intrduction-to-noexception) +- [Introduction to NoException](http://www.baeldung.com/introduction-to-noexception) - [Introduction to PCollections](http://www.baeldung.com/java-pcollections) - [Introduction to Hoverfly in Java](http://www.baeldung.com/hoverfly) - [Apache Commons Chain](http://www.baeldung.com/apache-commons-chain) From a5f78cf7d5ff4044145e010dc429bf9444bfd128 Mon Sep 17 00:00:00 2001 From: Pazis Date: Sat, 16 Dec 2017 14:18:09 +0200 Subject: [PATCH 21/24] BAEL-1308 - Copy a File with Java (#3000) * Create Student.java * Create ApplicationContextTestBeanInjection.java * Update Student.java * added tests added tests * BAEL-1308 part 1 * Create test_stream.txt * Create test_files.txt * Create test_channel.txt * Create test_apache.txt * Create test.txt * Delete test.txt * Create readme.txt * Delete Student.java * Delete StudentInjectionTest.java * Delete ApplicationContextTestBeanInjection.java --- .../java/com/baeldung/stream/FileCopy.java | 48 +++++++++++++++++++ .../com/baeldung/stream/FileCopyTest.java | 47 ++++++++++++++++++ .../test/resources/copyTest/dest/readme.txt | 2 + .../resources/copyTest/src/test_apache.txt | 1 + .../resources/copyTest/src/test_channel.txt | 1 + .../resources/copyTest/src/test_files.txt | 1 + .../resources/copyTest/src/test_stream.txt | 1 + 7 files changed, 101 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/stream/FileCopy.java create mode 100644 core-java/src/test/java/com/baeldung/stream/FileCopyTest.java create mode 100644 core-java/src/test/resources/copyTest/dest/readme.txt create mode 100644 core-java/src/test/resources/copyTest/src/test_apache.txt create mode 100644 core-java/src/test/resources/copyTest/src/test_channel.txt create mode 100644 core-java/src/test/resources/copyTest/src/test_files.txt create mode 100644 core-java/src/test/resources/copyTest/src/test_stream.txt diff --git a/core-java/src/main/java/com/baeldung/stream/FileCopy.java b/core-java/src/main/java/com/baeldung/stream/FileCopy.java new file mode 100644 index 0000000000..ccc2066b36 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/stream/FileCopy.java @@ -0,0 +1,48 @@ +package com.baeldung.stream; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.channels.FileChannel; +import java.nio.file.Files; + +import org.apache.commons.io.FileUtils; + +public class FileCopy { + + public static void copyFileUsingStream(File source, File dest) throws IOException { + InputStream is = null; + OutputStream os = null; + is = new FileInputStream(source); + os = new FileOutputStream(dest); + byte[] buffer = new byte[1024]; + int length; + while ((length = is.read(buffer)) > 0) { + os.write(buffer, 0, length); + } + is.close(); + os.close(); + } + + public static void copyFileUsingChannel(File source, File dest) throws IOException { + FileChannel sourceChannel = null; + FileChannel destChannel = null; + sourceChannel = new FileInputStream(source).getChannel(); + destChannel = new FileOutputStream(dest).getChannel(); + destChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); + sourceChannel.close(); + destChannel.close(); + } + + public static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException { + FileUtils.copyFile(source, dest); + } + + public static void copyFileUsingJavaFiles(File source, File dest) throws IOException { + Files.copy(source.toPath(), dest.toPath()); + } + +} diff --git a/core-java/src/test/java/com/baeldung/stream/FileCopyTest.java b/core-java/src/test/java/com/baeldung/stream/FileCopyTest.java new file mode 100644 index 0000000000..3b915a3829 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/stream/FileCopyTest.java @@ -0,0 +1,47 @@ +package com.baeldung.stream; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; + +import org.junit.Test; + +public class FileCopyTest { + + @Test + public void whenUsingStream_thenCopyFile() throws IOException { + File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_stream.txt"); + File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_stream.txt"); + FileCopy.copyFileUsingStream(src, dest); + assertTrue(dest.exists()); + dest.delete(); + } + + @Test + public void whenUsingFiles_thenCopyFile() throws IOException { + File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_files.txt"); + File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_files.txt"); + FileCopy.copyFileUsingJavaFiles(src, dest); + assertTrue(dest.exists()); + dest.delete(); + } + + @Test + public void whenUsingChannel_thenCopyFile() throws IOException { + File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_channel.txt"); + File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_channel.txt"); + FileCopy.copyFileUsingChannel(src, dest); + assertTrue(dest.exists()); + dest.delete(); + } + + @Test + public void whenUsingApache_thenCopyFile() throws IOException { + File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_apache.txt"); + File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_apache.txt"); + FileCopy.copyFileUsingApacheCommonsIO(src, dest); + assertTrue(dest.exists()); + dest.delete(); + } +} diff --git a/core-java/src/test/resources/copyTest/dest/readme.txt b/core-java/src/test/resources/copyTest/dest/readme.txt new file mode 100644 index 0000000000..dfda31ee9f --- /dev/null +++ b/core-java/src/test/resources/copyTest/dest/readme.txt @@ -0,0 +1,2 @@ +files will be copied here and then deleted +remove `file.delete()` to see the files here diff --git a/core-java/src/test/resources/copyTest/src/test_apache.txt b/core-java/src/test/resources/copyTest/src/test_apache.txt new file mode 100644 index 0000000000..a6b651973d --- /dev/null +++ b/core-java/src/test/resources/copyTest/src/test_apache.txt @@ -0,0 +1 @@ +apache diff --git a/core-java/src/test/resources/copyTest/src/test_channel.txt b/core-java/src/test/resources/copyTest/src/test_channel.txt new file mode 100644 index 0000000000..6dca835871 --- /dev/null +++ b/core-java/src/test/resources/copyTest/src/test_channel.txt @@ -0,0 +1 @@ +channel diff --git a/core-java/src/test/resources/copyTest/src/test_files.txt b/core-java/src/test/resources/copyTest/src/test_files.txt new file mode 100644 index 0000000000..027271b9b2 --- /dev/null +++ b/core-java/src/test/resources/copyTest/src/test_files.txt @@ -0,0 +1 @@ +files diff --git a/core-java/src/test/resources/copyTest/src/test_stream.txt b/core-java/src/test/resources/copyTest/src/test_stream.txt new file mode 100644 index 0000000000..eac9b41cbe --- /dev/null +++ b/core-java/src/test/resources/copyTest/src/test_stream.txt @@ -0,0 +1 @@ +stream From afb95788476de5d238f71fc4d3d5fd58582c85ca Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 16 Dec 2017 17:46:57 +0200 Subject: [PATCH 22/24] change repo name --- spring-jenkins-pipeline/scripted-pipeline-unix-nonunix | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-jenkins-pipeline/scripted-pipeline-unix-nonunix b/spring-jenkins-pipeline/scripted-pipeline-unix-nonunix index e9cae64d3d..fab940ad3d 100644 --- a/spring-jenkins-pipeline/scripted-pipeline-unix-nonunix +++ b/spring-jenkins-pipeline/scripted-pipeline-unix-nonunix @@ -1,6 +1,6 @@ node { stage 'Clone the project' - git 'https://github.com/dassiorleando/tutorials.git' + git 'https://github.com/eugenp/tutorials.git' dir('spring-jenkins-pipeline') { stage("Compilation and Analysis") { From 6b323c45cc3731d4447412e3b14faef1f3ba890d Mon Sep 17 00:00:00 2001 From: shouvikbhattacharya Date: Sat, 16 Dec 2017 21:28:03 +0530 Subject: [PATCH 23/24] BAEL-1433: Minor changes. --- .../java/com/baeldung/collection/WhenUsingTreeSet.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/collection/WhenUsingTreeSet.java b/core-java/src/test/java/com/baeldung/collection/WhenUsingTreeSet.java index 887f6eba1d..52d5b08813 100644 --- a/core-java/src/test/java/com/baeldung/collection/WhenUsingTreeSet.java +++ b/core-java/src/test/java/com/baeldung/collection/WhenUsingTreeSet.java @@ -26,7 +26,6 @@ public class WhenUsingTreeSet { @Override public String toString() { - // TODO Auto-generated method stub return id.toString(); } } @@ -189,8 +188,14 @@ public class WhenUsingTreeSet { treeSet.add(5); treeSet.add(6); + Set expectedSet = new TreeSet<>(); + expectedSet.add(2); + expectedSet.add(3); + expectedSet.add(4); + expectedSet.add(5); + Set subSet = treeSet.subSet(2, 6); - System.out.println(subSet); + Assert.assertEquals(expectedSet, subSet); } @Test From ec95d9b208cae1d187b8428bbbe94f8982a3c504 Mon Sep 17 00:00:00 2001 From: Dominik Date: Sat, 16 Dec 2017 19:37:43 +0100 Subject: [PATCH 24/24] BAEL1367: VarHandles Article --- .../java9/varhandles/VariableHandlesTest.java | 101 ++++++++++-------- 1 file changed, 58 insertions(+), 43 deletions(-) diff --git a/core-java-9/src/test/java/com/baeldung/java9/varhandles/VariableHandlesTest.java b/core-java-9/src/test/java/com/baeldung/java9/varhandles/VariableHandlesTest.java index 210c4f0654..50766502ec 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/varhandles/VariableHandlesTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/varhandles/VariableHandlesTest.java @@ -1,91 +1,106 @@ package com.baeldung.java9.varhandles; -import org.junit.Assert; import org.junit.Test; import java.lang.invoke.MethodHandles; import java.lang.invoke.VarHandle; +import static org.assertj.core.api.Assertions.assertThat; + public class VariableHandlesTest { + public int publicTestVariable = 1; private int privateTestVariable = 1; public int variableToSet = 1; public int variableToCompareAndSet = 1; public int variableToGetAndAdd = 0; public byte variableToBitwiseOr = 0; + @Test - public void whenVariableHandleForPublicVariableIsCreated_ThenItIsInitializedProperly() - throws NoSuchFieldException, IllegalAccessException { - VarHandle publicIntHandle = MethodHandles.lookup() - .in(VariableHandlesTest.class) - .findVarHandle(VariableHandlesTest.class,"publicTestVariable", int.class); - Assert.assertEquals(1, publicIntHandle.coordinateTypes().size()); - Assert.assertEquals(VariableHandlesTest.class, publicIntHandle.coordinateTypes().get(0)); + public void whenVariableHandleForPublicVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException { + VarHandle publicIntHandle = MethodHandles + .lookup() + .in(VariableHandlesTest.class) + .findVarHandle(VariableHandlesTest.class, "publicTestVariable", int.class); + + assertThat(publicIntHandle.coordinateTypes().size() == 1); + assertThat(publicIntHandle.coordinateTypes().get(0) == VariableHandles.class); } @Test - public void whenVariableHandleForPrivateVariableIsCreated_ThenItIsInitializedProperly() - throws NoSuchFieldException, IllegalAccessException { - VarHandle privateIntHandle = MethodHandles.privateLookupIn(VariableHandlesTest.class, MethodHandles.lookup()) - .findVarHandle(VariableHandlesTest.class,"privateTestVariable", int.class); - Assert.assertNotNull(privateIntHandle); - Assert.assertEquals(1, privateIntHandle.coordinateTypes().size()); - Assert.assertEquals(VariableHandlesTest.class, privateIntHandle.coordinateTypes().get(0)); + public void whenVariableHandleForPrivateVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException { + VarHandle privateIntHandle = MethodHandles + .privateLookupIn(VariableHandlesTest.class, MethodHandles.lookup()) + .findVarHandle(VariableHandlesTest.class, "privateTestVariable", int.class); + + assertThat(privateIntHandle.coordinateTypes().size() == 1); + assertThat(privateIntHandle.coordinateTypes().get(0) == VariableHandlesTest.class); } @Test - public void whenVariableHandleForArrayVariableIsCreated_ThenItIsInitializedProperly() - throws NoSuchFieldException, IllegalAccessException { - VarHandle arrayVarHandle = MethodHandles.arrayElementVarHandle(int[].class); - Assert.assertEquals(2, arrayVarHandle.coordinateTypes().size()); - Assert.assertEquals(int[].class, arrayVarHandle.coordinateTypes().get(0)); + public void whenVariableHandleForArrayVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException { + VarHandle arrayVarHandle = MethodHandles + .arrayElementVarHandle(int[].class); + + assertThat(arrayVarHandle.coordinateTypes().size() == 2); + assertThat(arrayVarHandle.coordinateTypes().get(0) == int[].class); } @Test public void givenVarHandle_whenGetIsInvoked_ThenValueOfVariableIsReturned() throws NoSuchFieldException, IllegalAccessException { - VarHandle publicIntHandle = MethodHandles.lookup() - .in(VariableHandlesTest.class) - .findVarHandle(VariableHandlesTest.class,"publicTestVariable", int.class); - Assert.assertEquals(1, publicIntHandle.get(this)); + VarHandle publicIntHandle = MethodHandles + .lookup() + .in(VariableHandlesTest.class) + .findVarHandle(VariableHandlesTest.class, "publicTestVariable", int.class); + + assertThat((int) publicIntHandle.get(this) == 1); } @Test public void givenVarHandle_whenSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException { - VarHandle publicIntHandle = MethodHandles.lookup() - .in(VariableHandlesTest.class) - .findVarHandle(VariableHandlesTest.class,"variableToSet", int.class); + VarHandle publicIntHandle = MethodHandles + .lookup() + .in(VariableHandlesTest.class) + .findVarHandle(VariableHandlesTest.class, "variableToSet", int.class); publicIntHandle.set(this, 15); - Assert.assertEquals(15, publicIntHandle.get(this)); + + assertThat((int) publicIntHandle.get(this) == 15); } @Test public void givenVarHandle_whenCompareAndSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException { - VarHandle publicIntHandle = MethodHandles.lookup() - .in(VariableHandlesTest.class) - .findVarHandle(VariableHandlesTest.class,"variableToCompareAndSet", int.class); - publicIntHandle.compareAndSet(this, 1,100); - Assert.assertEquals(100, publicIntHandle.get(this)); + VarHandle publicIntHandle = MethodHandles + .lookup() + .in(VariableHandlesTest.class) + .findVarHandle(VariableHandlesTest.class, "variableToCompareAndSet", int.class); + publicIntHandle.compareAndSet(this, 1, 100); + + assertThat((int) publicIntHandle.get(this) == 100); } @Test public void givenVarHandle_whenGetAndAddIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException { - VarHandle publicIntHandle = MethodHandles.lookup() - .in(VariableHandlesTest.class) - .findVarHandle(VariableHandlesTest.class,"variableToGetAndAdd", int.class); + VarHandle publicIntHandle = MethodHandles + .lookup() + .in(VariableHandlesTest.class) + .findVarHandle(VariableHandlesTest.class, "variableToGetAndAdd", int.class); int before = (int) publicIntHandle.getAndAdd(this, 200); - Assert.assertEquals(0, before); - Assert.assertEquals(200, publicIntHandle.get(this)); + + assertThat(before == 0); + assertThat((int) publicIntHandle.get(this) == 200); } @Test public void givenVarHandle_whenGetAndBitwiseOrIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException { - VarHandle publicIntHandle = MethodHandles.lookup() - .in(VariableHandlesTest.class) - .findVarHandle(VariableHandlesTest.class,"variableToBitwiseOr", byte.class); + VarHandle publicIntHandle = MethodHandles + .lookup() + .in(VariableHandlesTest.class) + .findVarHandle(VariableHandlesTest.class, "variableToBitwiseOr", byte.class); byte before = (byte) publicIntHandle.getAndBitwiseOr(this, (byte) 127); - Assert.assertEquals(0, before); - Assert.assertEquals(127, variableToBitwiseOr); + + assertThat(before == 0); + assertThat(variableToBitwiseOr == 127); } }