diff --git a/algorithms/README.md b/algorithms/README.md index b0c5ee9d77..5f101c296c 100644 --- a/algorithms/README.md +++ b/algorithms/README.md @@ -14,3 +14,4 @@ - [Bubble Sort in Java](http://www.baeldung.com/java-bubble-sort) - [Introduction to JGraphT](http://www.baeldung.com/jgrapht) - [Introduction to Minimax Algorithm](http://www.baeldung.com/java-minimax-algorithm) +- [How to Calculate Levenshtein Distance in Java?](http://www.baeldung.com/java-levenshtein-distance) diff --git a/apache-spark/README.md b/apache-spark/README.md new file mode 100644 index 0000000000..fb8059eb27 --- /dev/null +++ b/apache-spark/README.md @@ -0,0 +1,3 @@ +### Relevant articles + +- [Introduction to Apache Spark](http://www.baeldung.com/apache-spark) diff --git a/cas/cas-secured-app/pom.xml b/cas/cas-secured-app/pom.xml index f66d54ae67..543354e8b3 100644 --- a/cas/cas-secured-app/pom.xml +++ b/cas/cas-secured-app/pom.xml @@ -65,6 +65,24 @@ org.springframework.boot spring-boot-maven-plugin + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + + + + @@ -107,4 +125,5 @@ + diff --git a/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationTests.java b/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java similarity index 84% rename from cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationTests.java rename to cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java index 09dbaf0c61..2f2644e2ea 100644 --- a/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationTests.java +++ b/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class CasSecuredAppApplicationTests { +public class CasSecuredAppApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/cas/cas-server/src/main/resources/application.properties b/cas/cas-server/src/main/resources/application.properties index afacd4cbc1..018fd351ff 100644 --- a/cas/cas-server/src/main/resources/application.properties +++ b/cas/cas-server/src/main/resources/application.properties @@ -109,7 +109,7 @@ cas.authn.jdbc.query[0].sql=SELECT * FROM users WHERE email = ? cas.authn.jdbc.query[0].url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC cas.authn.jdbc.query[0].dialect=org.hibernate.dialect.MySQLDialect cas.authn.jdbc.query[0].user=root -cas.authn.jdbc.query[0].password= +cas.authn.jdbc.query[0].password=root cas.authn.jdbc.query[0].ddlAuto=none #cas.authn.jdbc.query[0].driverClass=com.mysql.jdbc.Driver cas.authn.jdbc.query[0].driverClass=com.mysql.cj.jdbc.Driver diff --git a/cas/cas-server/src/main/resources/create_test_db_and_users_tbl.sql b/cas/cas-server/src/main/resources/create_test_db_and_users_tbl.sql new file mode 100644 index 0000000000..79a4a48a82 --- /dev/null +++ b/cas/cas-server/src/main/resources/create_test_db_and_users_tbl.sql @@ -0,0 +1,16 @@ +-- Dumping database structure for test +CREATE DATABASE IF NOT EXISTS `test` /*!40100 DEFAULT CHARACTER SET latin1 */; +USE `test`; + +-- Dumping structure for table test.users +CREATE TABLE IF NOT EXISTS `users` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `email` varchar(50) DEFAULT NULL, + `password` text DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; + +/*!40000 ALTER TABLE `users` DISABLE KEYS */; +INSERT INTO `users` (`id`, `email`, `password`) VALUES + (1, 'test@test.com', 'Mellon'); +/*!40000 ALTER TABLE `users` ENABLE KEYS */; \ No newline at end of file diff --git a/core-java-8/README.md b/core-java-8/README.md index 690bd48ed5..540a32b0ba 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -30,3 +30,5 @@ - [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap) - [Merging Streams in Java](http://www.baeldung.com/java-merge-streams) - [“Stream has already been operated upon or closed” Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception) +- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones) +- [Copy a File with Java](http://www.baeldung.com/java-copy-file) diff --git a/core-java-8/src/main/java/com/baeldung/annotations/ClassWithAnnotation.java b/core-java-8/src/main/java/com/baeldung/annotations/ClassWithAnnotation.java new file mode 100644 index 0000000000..034e6785a4 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/ClassWithAnnotation.java @@ -0,0 +1,5 @@ +package com.baeldung.annotations; + +@Deprecated +class ClassWithAnnotation { +} diff --git a/core-java-8/src/main/java/com/baeldung/annotations/ClassWithDeprecatedMethod.java b/core-java-8/src/main/java/com/baeldung/annotations/ClassWithDeprecatedMethod.java new file mode 100644 index 0000000000..6f5da03b74 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/ClassWithDeprecatedMethod.java @@ -0,0 +1,9 @@ +package com.baeldung.annotations; + +class ClassWithDeprecatedMethod { + + @Deprecated + static void deprecatedMethod() { + + } +} diff --git a/core-java-8/src/main/java/com/baeldung/annotations/ClassWithSafeVarargs.java b/core-java-8/src/main/java/com/baeldung/annotations/ClassWithSafeVarargs.java new file mode 100644 index 0000000000..cfa91f5951 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/ClassWithSafeVarargs.java @@ -0,0 +1,11 @@ +package com.baeldung.annotations; + +class ClassWithSafeVarargs { + + @SafeVarargs + final void iterateOverVarargs(T... args) { + for (T x : args) { + // do stuff with x + } + } +} diff --git a/core-java-8/src/main/java/com/baeldung/annotations/ClassWithSuppressWarnings.java b/core-java-8/src/main/java/com/baeldung/annotations/ClassWithSuppressWarnings.java new file mode 100644 index 0000000000..fe22ec1c24 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/ClassWithSuppressWarnings.java @@ -0,0 +1,9 @@ +package com.baeldung.annotations; + +class ClassWithSuppressWarnings { + + @SuppressWarnings("deprecation") + void useDeprecatedMethod() { + ClassWithDeprecatedMethod.deprecatedMethod(); // no warning is generated here + } +} diff --git a/core-java-8/src/main/java/com/baeldung/annotations/IntConsumer.java b/core-java-8/src/main/java/com/baeldung/annotations/IntConsumer.java new file mode 100644 index 0000000000..4f16b27281 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/IntConsumer.java @@ -0,0 +1,8 @@ +package com.baeldung.annotations; + +@FunctionalInterface +interface IntConsumer { + + void accept(Integer number); + +} diff --git a/core-java-8/src/main/java/com/baeldung/annotations/Interval.java b/core-java-8/src/main/java/com/baeldung/annotations/Interval.java new file mode 100644 index 0000000000..f73e6e5b14 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/Interval.java @@ -0,0 +1,8 @@ +package com.baeldung.annotations; + +import java.lang.annotation.Repeatable; + +@Repeatable(Intervals.class) +@interface Interval { + int hour() default 1; +} diff --git a/core-java-8/src/main/java/com/baeldung/annotations/IntervalUsage.java b/core-java-8/src/main/java/com/baeldung/annotations/IntervalUsage.java new file mode 100644 index 0000000000..2e11de8215 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/IntervalUsage.java @@ -0,0 +1,9 @@ +package com.baeldung.annotations; + +public class IntervalUsage { + + @Interval(hour = 17) + @Interval(hour = 13) + void doPeriodicCleanup() { + } +} diff --git a/core-java-8/src/main/java/com/baeldung/annotations/Intervals.java b/core-java-8/src/main/java/com/baeldung/annotations/Intervals.java new file mode 100644 index 0000000000..af469f18cc --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/Intervals.java @@ -0,0 +1,5 @@ +package com.baeldung.annotations; + +@interface Intervals { + Interval[] value(); +} diff --git a/core-java-8/src/main/java/com/baeldung/annotations/MyAnnotation.java b/core-java-8/src/main/java/com/baeldung/annotations/MyAnnotation.java new file mode 100644 index 0000000000..6e71f446b0 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/MyAnnotation.java @@ -0,0 +1,11 @@ +package com.baeldung.annotations; + +import java.lang.annotation.*; + +@Inherited +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.LOCAL_VARIABLE, ElementType.FIELD}) +@interface MyAnnotation { + +} \ No newline at end of file diff --git a/core-java-8/src/main/java/com/baeldung/annotations/MyAnnotationTarget.java b/core-java-8/src/main/java/com/baeldung/annotations/MyAnnotationTarget.java new file mode 100644 index 0000000000..37f40a624e --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/MyAnnotationTarget.java @@ -0,0 +1,16 @@ +package com.baeldung.annotations; + +class MyAnnotationTarget { + + // this is OK + @MyAnnotation + String someField; + + // @MyAnnotation <- this is invalid usage! + void doSomething() { + + // this also works + @MyAnnotation + String localVariable; + } +} diff --git a/core-java-8/src/main/java/com/baeldung/annotations/MyOperation.java b/core-java-8/src/main/java/com/baeldung/annotations/MyOperation.java new file mode 100644 index 0000000000..a4385bc786 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/MyOperation.java @@ -0,0 +1,6 @@ +package com.baeldung.annotations; + +interface MyOperation { + + void perform(); +} \ No newline at end of file diff --git a/core-java-8/src/main/java/com/baeldung/annotations/MyOperationImpl.java b/core-java-8/src/main/java/com/baeldung/annotations/MyOperationImpl.java new file mode 100644 index 0000000000..e6a8ce76d3 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/MyOperationImpl.java @@ -0,0 +1,9 @@ +package com.baeldung.annotations; + +class MyOperationImpl implements MyOperation { + + @Override + public void perform() { + + } +} \ No newline at end of file diff --git a/core-java-8/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplay.java b/core-java-8/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplay.java new file mode 100644 index 0000000000..3a1016c63b --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplay.java @@ -0,0 +1,55 @@ +package com.baeldung.timezonedisplay; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.Comparator; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +public class TimezoneDisplay { + + public enum OffsetBase { + GMT, UTC + } + + public List getTimeZoneList(OffsetBase base) { + Set availableZoneIds = ZoneId.getAvailableZoneIds(); + + LocalDateTime now = LocalDateTime.now(); + return availableZoneIds + .stream() + .map(ZoneId::of) + .sorted(new ZoneComparator()) + .map(id -> String.format("(%s%s) %s", base, getOffset(now, id), id.getId())) + .collect(Collectors.toList()); + } + + private String getOffset(LocalDateTime dateTime, ZoneId id) { + return dateTime + .atZone(id) + .getOffset() + .getId() + .replace("Z", "+00:00"); + } + + private class ZoneComparator implements Comparator { + + @Override + public int compare(ZoneId zoneId1, ZoneId zoneId2) { + LocalDateTime now = LocalDateTime.now(); + + ZoneOffset offset1 = now + .atZone(zoneId1) + .getOffset(); + + ZoneOffset offset2 = now + .atZone(zoneId2) + .getOffset(); + + return offset1.compareTo(offset2); + } + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayApp.java b/core-java-8/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayApp.java new file mode 100644 index 0000000000..aa9f84e21a --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayApp.java @@ -0,0 +1,18 @@ +package com.baeldung.timezonedisplay; + +import java.util.List; + +public class TimezoneDisplayApp { + + public static void main(String... args) { + TimezoneDisplay display = new TimezoneDisplay(); + + System.out.println("Time zones in UTC:"); + List utc = display.getTimeZoneList(TimezoneDisplay.OffsetBase.UTC); + utc.forEach(System.out::println); + + System.out.println("Time zones in GMT:"); + List gmt = display.getTimeZoneList(TimezoneDisplay.OffsetBase.GMT); + gmt.forEach(System.out::println); + } +} 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..c794c57e87 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java @@ -0,0 +1,39 @@ +/** + * + */ +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. + * + * @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 new file mode 100644 index 0000000000..17ca5b1122 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java @@ -0,0 +1,39 @@ +/** + * + */ +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. + * + * @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-9/src/main/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverter.java b/core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverter.java new file mode 100644 index 0000000000..f219dcf038 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverter.java @@ -0,0 +1,27 @@ +/** + * + */ +package com.baeldung.java9.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-9/src/main/java/com/baeldung/java9/datetime/LocalDateToDateConverter.java b/core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateToDateConverter.java new file mode 100644 index 0000000000..f9893da5d0 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateToDateConverter.java @@ -0,0 +1,28 @@ +/** + * + */ +package com.baeldung.java9.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-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..ab69bba359 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterTest.java @@ -0,0 +1,89 @@ +/** + * + */ +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 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 + 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..97c70ee5ac --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterTest.java @@ -0,0 +1,97 @@ +/** + * + */ +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.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); + + // 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/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterTest.java b/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterTest.java new file mode 100644 index 0000000000..2c6898381f --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterTest.java @@ -0,0 +1,61 @@ +/** + * + */ +package com.baeldung.java9.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-9/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterTest.java b/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterTest.java new file mode 100644 index 0000000000..7f20d5d2d2 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterTest.java @@ -0,0 +1,55 @@ +/** + * + */ +package com.baeldung.java9.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)); + } + +} diff --git a/core-java-concurrency/README.md b/core-java-concurrency/README.md index f1d95482d4..48c5f2a50c 100644 --- a/core-java-concurrency/README.md +++ b/core-java-concurrency/README.md @@ -30,3 +30,4 @@ - [Guide to Volatile Keyword in Java](http://www.baeldung.com/java-volatile) - [Overview of the java.util.concurrent](http://www.baeldung.com/java-util-concurrent) - [Semaphores in Java](http://www.baeldung.com/java-semaphore) +- [Daemon Threads in Java](http://www.baeldung.com/java-daemon-thread) diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/stopping/ControlSubThread.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/stopping/ControlSubThread.java new file mode 100644 index 0000000000..0e72821a88 --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/stopping/ControlSubThread.java @@ -0,0 +1,52 @@ +package com.baeldung.concurrent.stopping; + +import java.util.concurrent.atomic.AtomicBoolean; + +public class ControlSubThread implements Runnable { + + private Thread worker; + private int interval = 100; + private AtomicBoolean running = new AtomicBoolean(false); + private AtomicBoolean stopped = new AtomicBoolean(true); + + + public ControlSubThread(int sleepInterval) { + interval = sleepInterval; + } + + public void start() { + worker = new Thread(this); + worker.start(); + } + + public void stop() { + running.set(false); + } + + public void interrupt() { + running.set(false); + worker.interrupt(); + } + + boolean isRunning() { + return running.get(); + } + + boolean isStopped() { + return stopped.get(); + } + + public void run() { + running.set(true); + stopped.set(false); + while (running.get()) { + try { + Thread.sleep(interval); + } catch (InterruptedException e) { + // no-op, just loop again + } + // do something + } + stopped.set(true); + } +} diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/stopping/StopThreadTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/stopping/StopThreadTest.java new file mode 100644 index 0000000000..8c1bdbf787 --- /dev/null +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/stopping/StopThreadTest.java @@ -0,0 +1,50 @@ +package com.baeldung.concurrent.stopping; + +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class StopThreadTest { + + @Test + public void whenStoppedThreadIsStopped() throws InterruptedException { + + int interval = 100; + + ControlSubThread controlSubThread = new ControlSubThread(interval); + controlSubThread.start(); + + // Give things a chance to get set up + Thread.sleep(interval); + assertTrue(controlSubThread.isRunning()); + assertFalse(controlSubThread.isStopped()); + + // Stop it and make sure the flags have been reversed + controlSubThread.stop(); + Thread.sleep(interval); + assertTrue(controlSubThread.isStopped()); + } + + + @Test + public void whenInterruptedThreadIsStopped() throws InterruptedException { + + int interval = 5000; + + ControlSubThread controlSubThread = new ControlSubThread(interval); + controlSubThread.start(); + + // Give things a chance to get set up + Thread.sleep(100); + assertTrue(controlSubThread.isRunning()); + assertFalse(controlSubThread.isStopped()); + + // Stop it and make sure the flags have been reversed + controlSubThread.interrupt(); + + // Wait less than the time we would normally sleep, and make sure we exited. + Thread.sleep(interval/10); + assertTrue(controlSubThread.isStopped()); + } +} diff --git a/core-java/README.md b/core-java/README.md index dcf77ff536..1feee4126e 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -115,4 +115,9 @@ - [Number of Digits in an Integer in Java](http://www.baeldung.com/java-number-of-digits-in-int) - [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns) - [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin) +- [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static) +- [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array) +- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool) +- [Copy a File with Java](http://www.baeldung.com/java-copy-file) +- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns) diff --git a/core-java/pom.xml b/core-java/pom.xml index dbf61c3acf..77000b8741 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -460,7 +460,7 @@ 1.1.7 - 22.0 + 23.0 3.5 1.55 1.10 diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/AbstractFactory.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/AbstractFactory.java new file mode 100644 index 0000000000..46d97d1a15 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/AbstractFactory.java @@ -0,0 +1,6 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +public interface AbstractFactory { + Animal getAnimal(String toyType) ; + Color getColor(String colorType); +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/AbstractPatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/AbstractPatternDriver.java new file mode 100644 index 0000000000..7ab166e16a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/AbstractPatternDriver.java @@ -0,0 +1,18 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +public class AbstractPatternDriver { + public static void main(String[] args) { + AbstractFactory abstractFactory; + + //creating a brown toy dog + abstractFactory = FactoryProvider.getFactory("Toy"); + Animal toy = abstractFactory.getAnimal("Dog"); + + abstractFactory = FactoryProvider.getFactory("Color"); + Color color = abstractFactory.getColor("Brown"); + + String result = "A " + toy.getType() + " with " + color.getColor() + " color " + toy.makeSound(); + + System.out.println(result); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Animal.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Animal.java new file mode 100644 index 0000000000..59c1336053 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Animal.java @@ -0,0 +1,6 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +public interface Animal { + String getType(); + String makeSound(); +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/AnimalFactory.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/AnimalFactory.java new file mode 100644 index 0000000000..49583c3a98 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/AnimalFactory.java @@ -0,0 +1,21 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +public class AnimalFactory implements AbstractFactory { + + @Override + public Animal getAnimal(String animalType) { + if ("Dog".equalsIgnoreCase(animalType)) { + return new Dog(); + } else if ("Duck".equalsIgnoreCase(animalType)) { + return new Duck(); + } + + return null; + } + + @Override + public Color getColor(String color) { + throw new UnsupportedOperationException(); + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Brown.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Brown.java new file mode 100644 index 0000000000..f251285ebf --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Brown.java @@ -0,0 +1,10 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +public class Brown implements Color { + + @Override + public String getColor() { + return "brown"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Color.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Color.java new file mode 100644 index 0000000000..897bb71f38 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Color.java @@ -0,0 +1,5 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +public interface Color { + String getColor(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/ColorFactory.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/ColorFactory.java new file mode 100644 index 0000000000..8f7559ff27 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/ColorFactory.java @@ -0,0 +1,21 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +public class ColorFactory implements AbstractFactory { + + @Override + public Color getColor(String colorType) { + if ("Brown".equalsIgnoreCase(colorType)) { + return new Brown(); + } else if ("White".equalsIgnoreCase(colorType)) { + return new White(); + } + + return null; + } + + @Override + public Animal getAnimal(String toyType) { + throw new UnsupportedOperationException(); + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Dog.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Dog.java new file mode 100644 index 0000000000..002b5665d3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Dog.java @@ -0,0 +1,15 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +public class Dog implements Animal { + + @Override + public String getType() { + return "Dog"; + } + + @Override + public String makeSound() { + return "Barks"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Duck.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Duck.java new file mode 100644 index 0000000000..5603ad6eee --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Duck.java @@ -0,0 +1,15 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +public class Duck implements Animal { + + @Override + public String getType() { + return "Duck"; + } + + @Override + public String makeSound() { + return "Squeks"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/FactoryProvider.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/FactoryProvider.java new file mode 100644 index 0000000000..fcbee1e6de --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/FactoryProvider.java @@ -0,0 +1,15 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +public class FactoryProvider { + public static AbstractFactory getFactory(String choice){ + + if("Toy".equalsIgnoreCase(choice)){ + return new AnimalFactory(); + } + else if("Color".equalsIgnoreCase(choice)){ + return new ColorFactory(); + } + + return null; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/White.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/White.java new file mode 100644 index 0000000000..62ef8048ea --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/White.java @@ -0,0 +1,10 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +public class White implements Color { + + @Override + public String getColor() { + return "White"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/builder/BankAccount.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/builder/BankAccount.java new file mode 100644 index 0000000000..355fa74895 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/builder/BankAccount.java @@ -0,0 +1,64 @@ +package com.baeldung.designpatterns.creational.builder; + +public class BankAccount { + private String name; + private String accountNumber; + private String email; + private boolean newsletter; + + //The constructor that takes a builder from which it will create object + //the access to this is only provided to builder + private BankAccount(BankAccountBuilder builder) { + this.name = builder.name; + this.accountNumber = builder.accountNumber; + this.email = builder.email; + this.newsletter = builder.newsletter; + } + + public static class BankAccountBuilder { + private String name; + private String accountNumber; + private String email; + private boolean newsletter; + + //All Mandatory parameters goes with this constructor + public BankAccountBuilder(String name, String accountNumber) { + this.name = name; + this.accountNumber = accountNumber; + } + + //setters for optional parameters which returns this same builder + //to support fluent design + public BankAccountBuilder withEmail(String email) { + this.email = email; + return this; + } + + public BankAccountBuilder wantNewsletter(boolean newsletter) { + this.newsletter = newsletter; + return this; + } + + //the actual build method that prepares and returns a BankAccount object + public BankAccount build() { + return new BankAccount(this); + } + } + + //getters + public String getName() { + return name; + } + + public String getAccountNumber() { + return accountNumber; + } + + public String getEmail() { + return email; + } + + public boolean isNewsletter() { + return newsletter; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/builder/BuilderPatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/builder/BuilderPatternDriver.java new file mode 100644 index 0000000000..d92a70e664 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/builder/BuilderPatternDriver.java @@ -0,0 +1,16 @@ +package com.baeldung.designpatterns.creational.builder; + +public class BuilderPatternDriver { + public static void main(String[] args) { + BankAccount newAccount = new BankAccount + .BankAccountBuilder("Jon", "22738022275") + .withEmail("jon@example.com") + .wantNewsletter(true) + .build(); + + System.out.println("Name: " + newAccount.getName()); + System.out.println("AccountNumber:" + newAccount.getAccountNumber()); + System.out.println("Email: " + newAccount.getEmail()); + System.out.println("Want News letter?: " + newAccount.isNewsletter()); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/FactoryDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/FactoryDriver.java new file mode 100644 index 0000000000..64ee307bb8 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/FactoryDriver.java @@ -0,0 +1,16 @@ +package com.baeldung.designpatterns.creational.factory; + +public class FactoryDriver { + public static void main(String[] args) { + Polygon p; + PolygonFactory factory = new PolygonFactory(); + + //get the shape which has 4 sides + p = factory.getPolygon(4); + System.out.println("The shape with 4 sides is a " + p.getType()); + + //get the shape which has 4 sides + p = factory.getPolygon(8); + System.out.println("The shape with 8 sides is a " + p.getType()); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Heptagon.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Heptagon.java new file mode 100644 index 0000000000..935fc2f04c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Heptagon.java @@ -0,0 +1,10 @@ +package com.baeldung.designpatterns.creational.factory; + +public class Heptagon implements Polygon { + + @Override + public String getType() { + return "Heptagon"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Octagon.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Octagon.java new file mode 100644 index 0000000000..fc62302dc8 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Octagon.java @@ -0,0 +1,10 @@ +package com.baeldung.designpatterns.creational.factory; + +public class Octagon implements Polygon { + + @Override + public String getType() { + return "Octagon"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Pentagon.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Pentagon.java new file mode 100644 index 0000000000..65d109b10b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Pentagon.java @@ -0,0 +1,10 @@ +package com.baeldung.designpatterns.creational.factory; + +public class Pentagon implements Polygon { + + @Override + public String getType() { + return "Pentagon"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Polygon.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Polygon.java new file mode 100644 index 0000000000..8364e546b0 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Polygon.java @@ -0,0 +1,5 @@ +package com.baeldung.designpatterns.creational.factory; + +public interface Polygon { + String getType(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/PolygonFactory.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/PolygonFactory.java new file mode 100644 index 0000000000..406f0f5274 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/PolygonFactory.java @@ -0,0 +1,22 @@ +package com.baeldung.designpatterns.creational.factory; + +public class PolygonFactory { + public Polygon getPolygon(int numberOfSides) { + if(numberOfSides == 3) { + return new Triangle(); + } + if(numberOfSides == 4) { + return new Square(); + } + if(numberOfSides == 5) { + return new Pentagon(); + } + if(numberOfSides == 4) { + return new Heptagon(); + } + else if(numberOfSides == 8) { + return new Octagon(); + } + return null; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Square.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Square.java new file mode 100644 index 0000000000..805c1c9ae3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Square.java @@ -0,0 +1,10 @@ +package com.baeldung.designpatterns.creational.factory; + +public class Square implements Polygon { + + @Override + public String getType() { + return "Square"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Triangle.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Triangle.java new file mode 100644 index 0000000000..8a8832d8a1 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Triangle.java @@ -0,0 +1,10 @@ +package com.baeldung.designpatterns.creational.factory; + +public class Triangle implements Polygon { + + @Override + public String getType() { + return "Triangle"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/singleton/Singleton.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/singleton/Singleton.java new file mode 100644 index 0000000000..1a5ac82c89 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/singleton/Singleton.java @@ -0,0 +1,13 @@ +package com.baeldung.designpatterns.creational.singleton; + +public class Singleton { + private Singleton() {} + + private static class SingletonHolder { + public static final Singleton instance = new Singleton(); + } + + public static Singleton getInstance() { + return SingletonHolder.instance; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/singleton/SingletonDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/singleton/SingletonDriver.java new file mode 100644 index 0000000000..1955008d3e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/singleton/SingletonDriver.java @@ -0,0 +1,8 @@ +package com.baeldung.designpatterns.creational.singleton; + +public class SingletonDriver { + public static void main(String[] args) { + Singleton instance = Singleton.getInstance(); + System.out.println(instance.toString()); + } +} diff --git a/core-java/src/main/java/com/baeldung/loops/LoopsInJava.java b/core-java/src/main/java/com/baeldung/loops/LoopsInJava.java new file mode 100644 index 0000000000..1b2e621b52 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/loops/LoopsInJava.java @@ -0,0 +1,43 @@ +package com.baeldung.loops; + +public class LoopsInJava { + + public int[] simple_for_loop() { + int[] arr = new int[5]; + for (int i = 0; i < 5; i++) { + arr[i] = i; + System.out.println("Simple for loop: i - " + i); + } + return arr; + } + + public int[] enhanced_for_each_loop() { + int[] intArr = { 0, 1, 2, 3, 4 }; + int[] arr = new int[5]; + for (int num : intArr) { + arr[num] = num; + System.out.println("Enhanced for-each loop: i - " + num); + } + return arr; + } + + public int[] while_loop() { + int i = 0; + int[] arr = new int[5]; + while (i < 5) { + arr[i] = i; + System.out.println("While loop: i - " + i++); + } + return arr; + } + + public int[] do_while_loop() { + int i = 0; + int[] arr = new int[5]; + do { + arr[i] = i; + System.out.println("Do-While loop: i - " + i++); + } while (i < 5); + return arr; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/nestedclass/Enclosing.java b/core-java/src/main/java/com/baeldung/nestedclass/Enclosing.java new file mode 100644 index 0000000000..a9911538b0 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/nestedclass/Enclosing.java @@ -0,0 +1,11 @@ +package com.baeldung.nestedclass; + +public class Enclosing { + + public static class Nested { + + public void test() { + System.out.println("Calling test..."); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/nestedclass/NewEnclosing.java b/core-java/src/main/java/com/baeldung/nestedclass/NewEnclosing.java new file mode 100644 index 0000000000..c7e04e8600 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/nestedclass/NewEnclosing.java @@ -0,0 +1,15 @@ +package com.baeldung.nestedclass; + +public class NewEnclosing { + + void run() { + class Local { + + void run() { + System.out.println("Welcome to Baeldung!"); + } + } + Local local = new Local(); + local.run(); + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/nestedclass/Outer.java b/core-java/src/main/java/com/baeldung/nestedclass/Outer.java new file mode 100644 index 0000000000..ebd6d27293 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/nestedclass/Outer.java @@ -0,0 +1,11 @@ +package com.baeldung.nestedclass; + +public class Outer { + + public class Inner { + + public void test() { + System.out.println("Calling test..."); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/nestedclass/SimpleAbstractClass.java b/core-java/src/main/java/com/baeldung/nestedclass/SimpleAbstractClass.java new file mode 100644 index 0000000000..586e2d12b4 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/nestedclass/SimpleAbstractClass.java @@ -0,0 +1,5 @@ +package com.baeldung.nestedclass; + +abstract class SimpleAbstractClass { + abstract void run(); +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7.java b/core-java/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7.java new file mode 100644 index 0000000000..4882ebe175 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7.java @@ -0,0 +1,43 @@ +package com.baeldung.timezonedisplay; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.TimeZone; +import java.util.concurrent.TimeUnit; + +public class TimezoneDisplayJava7 { + + public enum OffsetBase { + GMT, UTC + } + + public List getTimeZoneList(TimezoneDisplayJava7.OffsetBase base) { + String[] availableZoneIds = TimeZone.getAvailableIDs(); + List result = new ArrayList<>(availableZoneIds.length); + + for (String zoneId : availableZoneIds) { + TimeZone curTimeZone = TimeZone.getTimeZone(zoneId); + + String offset = calculateOffset(curTimeZone.getRawOffset()); + + result.add(String.format("(%s%s) %s", base, offset, zoneId)); + } + + Collections.sort(result); + + return result; + } + + private String calculateOffset(int rawOffset) { + if (rawOffset == 0) { + return "+00:00"; + } + long hours = TimeUnit.MILLISECONDS.toHours(rawOffset); + long minutes = TimeUnit.MILLISECONDS.toMinutes(rawOffset); + minutes = Math.abs(minutes - TimeUnit.HOURS.toMinutes(hours)); + + return String.format("%+03d:%02d", hours, Math.abs(minutes)); + } + +} diff --git a/core-java/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7App.java b/core-java/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7App.java new file mode 100644 index 0000000000..9f20667660 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7App.java @@ -0,0 +1,23 @@ +package com.baeldung.timezonedisplay; + +import java.util.List; + +public class TimezoneDisplayJava7App { + + public static void main(String... args) { + TimezoneDisplayJava7 display = new TimezoneDisplayJava7(); + + System.out.println("Time zones in UTC:"); + List utc = display.getTimeZoneList(TimezoneDisplayJava7.OffsetBase.UTC); + for (String timeZone : utc) { + System.out.println(timeZone); + } + + System.out.println("Time zones in GMT:"); + List gmt = display.getTimeZoneList(TimezoneDisplayJava7.OffsetBase.GMT); + for (String timeZone : gmt) { + System.out.println(timeZone); + } + } + +} diff --git a/core-java/src/test/java/com/baeldung/arraydeque/ArrayDequeTest.java b/core-java/src/test/java/com/baeldung/arraydeque/ArrayDequeTest.java new file mode 100644 index 0000000000..50813a8601 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/arraydeque/ArrayDequeTest.java @@ -0,0 +1,50 @@ +package com.baeldung.arraydeque; + +import java.util.ArrayDeque; +import java.util.Deque; + +import static org.junit.Assert.*; +import org.junit.Test; + +public class ArrayDequeTest { + + @Test + public void whenOffer_addsAtLast() { + final Deque deque = new ArrayDeque<>(); + + deque.offer("first"); + deque.offer("second"); + + assertEquals("second", deque.getLast()); + } + + @Test + public void whenPoll_removesFirst() { + final Deque deque = new ArrayDeque<>(); + + deque.offer("first"); + deque.offer("second"); + + assertEquals("first", deque.poll()); + } + + @Test + public void whenPush_addsAtFirst() { + final Deque deque = new ArrayDeque<>(); + + deque.push("first"); + deque.push("second"); + + assertEquals("second", deque.getFirst()); + } + + @Test + public void whenPop_removesLast() { + final Deque deque = new ArrayDeque<>(); + + deque.push("first"); + deque.push("second"); + + assertEquals("second", deque.pop()); + } +} diff --git a/core-java/src/test/java/com/baeldung/copyfiles/FileCopierTest.java b/core-java/src/test/java/com/baeldung/copyfiles/FileCopierTest.java new file mode 100644 index 0000000000..973436a26a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/copyfiles/FileCopierTest.java @@ -0,0 +1,70 @@ +package com.baeldung.copyfiles; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +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.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; + +import org.apache.commons.io.FileUtils; +import org.junit.Before; +import org.junit.Test; +import static org.assertj.core.api.Assertions.*; + +public class FileCopierTest { + File original = new File("src/test/resources/original.txt"); + + @Before + public void init() throws IOException { + if (!original.exists()) + Files.createFile(original.toPath()); + } + + @Test + public void givenIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException { + File copied = new File("src/test/resources/copiedWithIo.txt"); + try (InputStream in = new BufferedInputStream(new FileInputStream(original)); + OutputStream out = new BufferedOutputStream(new FileOutputStream(copied))) { + byte[] buffer = new byte[1024]; + int lengthRead; + while ((lengthRead = in.read(buffer)) > 0) { + out.write(buffer, 0, lengthRead); + out.flush(); + } + } + assertThat(copied).exists(); + assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath()))); + } + + @Test + public void givenCommonsIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException { + File copied = new File("src/test/resources/copiedWithApacheCommons.txt"); + FileUtils.copyFile(original, copied); + assertThat(copied).exists(); + assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath()))); + } + + @Test + public void givenNIO2_whenCopied_thenCopyExistsWithSameContents() throws IOException { + Path copied = Paths.get("src/test/resources/copiedWithNio.txt"); + Path originalPath = original.toPath(); + Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING); + assertThat(copied).exists(); + assertThat(Files.readAllLines(originalPath).equals(Files.readAllLines(copied))); + } + + @Test + public void givenGuava_whenCopied_thenCopyExistsWithSameContents() throws IOException { + File copied = new File("src/test/resources/copiedWithApacheCommons.txt"); + com.google.common.io.Files.copy(original, copied); + assertThat(copied).exists(); + assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath()))); + } +} diff --git a/core-java/src/test/java/com/baeldung/designpatterns/creational/abstractfactory/AbstractPatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/creational/abstractfactory/AbstractPatternIntegrationTest.java new file mode 100644 index 0000000000..dc02b976a0 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/creational/abstractfactory/AbstractPatternIntegrationTest.java @@ -0,0 +1,23 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class AbstractPatternIntegrationTest { + @Test + public void givenAbstractFactory_whenGettingObjects_thenSuccessful() { + AbstractFactory abstractFactory; + + //creating a brown toy dog + abstractFactory = FactoryProvider.getFactory("Toy"); + Animal toy = abstractFactory.getAnimal("Dog"); + + abstractFactory = FactoryProvider.getFactory("Color"); + Color color = abstractFactory.getColor("Brown"); + + String result = "A " + toy.getType() + " with " + color.getColor() + " color " + toy.makeSound(); + assertEquals("A Dog with brown color Barks", result); + } + +} diff --git a/core-java/src/test/java/com/baeldung/designpatterns/creational/builder/BuilderPatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/creational/builder/BuilderPatternIntegrationTest.java new file mode 100644 index 0000000000..898330b26e --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/creational/builder/BuilderPatternIntegrationTest.java @@ -0,0 +1,33 @@ +package com.baeldung.designpatterns.creational.builder; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class BuilderPatternIntegrationTest { + @Test + public void whenCreatingObjectThroughBuilder_thenObjectValid() { + BankAccount newAccount = new BankAccount + .BankAccountBuilder("Jon", "22738022275") + .withEmail("jon@example.com") + .wantNewsletter(true) + .build(); + + assertEquals(newAccount.getName(), "Jon"); + assertEquals(newAccount.getAccountNumber(), "22738022275"); + assertEquals(newAccount.getEmail(), "jon@example.com"); + assertEquals(newAccount.isNewsletter(), true); + } + + @Test + public void whenSkippingOptionalParameters_thenObjectValid() { + BankAccount newAccount = new BankAccount + .BankAccountBuilder("Jon", "22738022275") + .build(); + + assertEquals(newAccount.getName(), "Jon"); + assertEquals(newAccount.getAccountNumber(), "22738022275"); + assertEquals(newAccount.getEmail(), null); + assertEquals(newAccount.isNewsletter(), false); + } +} diff --git a/core-java/src/test/java/com/baeldung/designpatterns/creational/factory/FactoryIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/creational/factory/FactoryIntegrationTest.java new file mode 100644 index 0000000000..ed0419c16d --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/creational/factory/FactoryIntegrationTest.java @@ -0,0 +1,32 @@ +package com.baeldung.designpatterns.creational.factory; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class FactoryIntegrationTest { + + @Test + public void whenUsingFactoryForSquare_thenCorrectObjectReturned() { + Polygon p; + PolygonFactory factory = new PolygonFactory(); + + //get the shape which has 4 sides + p = factory.getPolygon(4); + String result = "The shape with 4 sides is a " + p.getType(); + + assertEquals("The shape with 4 sides is a Square", result); + } + + @Test + public void whenUsingFactoryForOctagon_thenCorrectObjectReturned() { + Polygon p; + PolygonFactory factory = new PolygonFactory(); + + //get the shape which has 4 sides + p = factory.getPolygon(8); + String result = "The shape with 8 sides is a " + p.getType(); + + assertEquals("The shape with 8 sides is a Octagon", result); + } +} diff --git a/core-java/src/test/java/com/baeldung/designpatterns/creational/singleton/SingletonIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/creational/singleton/SingletonIntegrationTest.java new file mode 100644 index 0000000000..a3d5b7a14d --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/creational/singleton/SingletonIntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.designpatterns.creational.singleton; + +import org.junit.Test; +import static org.junit.Assert.*; + +public class SingletonIntegrationTest { + + @Test + /** + * Although there is absolutely no way to determine whether + * a class is Singleton, in this test case, we will just + * check for two objects if they point to same instance or + * not. We will also check for their hashcode. + */ + public void whenGettingMultipleObjects_thenAllPointToSame() { + //first object + Singleton obj1 = Singleton.getInstance(); + + //Second object + Singleton obj2 = Singleton.getInstance(); + + assertTrue(obj1 == obj2); + assertEquals(obj1.hashCode(), obj2.hashCode()); + } + +} diff --git a/core-java/src/test/java/com/baeldung/loops/WhenUsingLoops.java b/core-java/src/test/java/com/baeldung/loops/WhenUsingLoops.java new file mode 100644 index 0000000000..9590eabfef --- /dev/null +++ b/core-java/src/test/java/com/baeldung/loops/WhenUsingLoops.java @@ -0,0 +1,37 @@ +package com.baeldung.loops; + +import org.junit.Assert; +import org.junit.Test; + +public class WhenUsingLoops { + + private LoopsInJava loops = new LoopsInJava(); + + @Test + public void shouldRunForLoop() { + int[] expected = { 0, 1, 2, 3, 4 }; + int[] actual = loops.simple_for_loop(); + Assert.assertArrayEquals(expected, actual); + } + + @Test + public void shouldRunEnhancedForeachLoop() { + int[] expected = { 0, 1, 2, 3, 4 }; + int[] actual = loops.enhanced_for_each_loop(); + Assert.assertArrayEquals(expected, actual); + } + + @Test + public void shouldRunWhileLoop() { + int[] expected = { 0, 1, 2, 3, 4 }; + int[] actual = loops.while_loop(); + Assert.assertArrayEquals(expected, actual); + } + + @Test + public void shouldRunDoWhileLoop() { + int[] expected = { 0, 1, 2, 3, 4 }; + int[] actual = loops.do_while_loop(); + Assert.assertArrayEquals(expected, actual); + } +} diff --git a/core-java/src/test/java/com/baeldung/nestedclass/AnonymousInnerTest.java b/core-java/src/test/java/com/baeldung/nestedclass/AnonymousInnerTest.java new file mode 100644 index 0000000000..394c0bb57a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/nestedclass/AnonymousInnerTest.java @@ -0,0 +1,16 @@ +package com.baeldung.nestedclass; + +import org.junit.Test; + +public class AnonymousInnerTest { + + @Test + public void whenRunAnonymousClass_thenCorrect() { + SimpleAbstractClass simpleAbstractClass = new SimpleAbstractClass() { + void run() { + System.out.println("Running Anonymous Class..."); + } + }; + simpleAbstractClass.run(); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/nestedclass/InnerClassTest.java b/core-java/src/test/java/com/baeldung/nestedclass/InnerClassTest.java new file mode 100644 index 0000000000..e9cb119ac2 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/nestedclass/InnerClassTest.java @@ -0,0 +1,13 @@ +package com.baeldung.nestedclass; + +import org.junit.Test; + +public class InnerClassTest { + + @Test + public void givenInnerClassWhenInstantiating_thenCorrect() { + Outer outer = new Outer(); + Outer.Inner inner = outer.new Inner(); + inner.test(); + } +} diff --git a/core-java/src/test/java/com/baeldung/nestedclass/LocalClassTest.java b/core-java/src/test/java/com/baeldung/nestedclass/LocalClassTest.java new file mode 100644 index 0000000000..dad19161ad --- /dev/null +++ b/core-java/src/test/java/com/baeldung/nestedclass/LocalClassTest.java @@ -0,0 +1,12 @@ +package com.baeldung.nestedclass; + +import org.junit.Test; + +public class LocalClassTest { + + @Test + public void whenTestingLocalClass_thenCorrect() { + NewEnclosing newEnclosing = new NewEnclosing(); + newEnclosing.run(); + } +} diff --git a/core-java/src/test/java/com/baeldung/nestedclass/NestedClassTest.java b/core-java/src/test/java/com/baeldung/nestedclass/NestedClassTest.java new file mode 100644 index 0000000000..16c883689a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/nestedclass/NestedClassTest.java @@ -0,0 +1,12 @@ +package com.baeldung.nestedclass; + +import org.junit.Test; + +public class NestedClassTest { + + @Test + public void whenInstantiatingStaticNestedClass_thenCorrect() { + Enclosing.Nested nested = new Enclosing.Nested(); + nested.test(); + } +} diff --git a/core-java/src/test/java/com/baeldung/nestedclass/NewOuterTest.java b/core-java/src/test/java/com/baeldung/nestedclass/NewOuterTest.java new file mode 100644 index 0000000000..e883687d33 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/nestedclass/NewOuterTest.java @@ -0,0 +1,32 @@ +package com.baeldung.nestedclass; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; + +public class NewOuterTest { + + int a = 1; + static int b = 2; + + public class InnerClass { + int a = 3; + static final int b = 4; + + @Test + public void whenShadowing_thenCorrect() { + assertEquals(3, a); + assertEquals(4, b); + assertEquals(1, NewOuterTest.this.a); + assertEquals(2, NewOuterTest.b); + assertEquals(2, NewOuterTest.this.b); + } + } + + @Test + public void shadowingTest() { + NewOuterTest outer = new NewOuterTest(); + NewOuterTest.InnerClass inner = outer.new InnerClass(); + inner.whenShadowing_thenCorrect(); + + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleTests.java b/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleTests.java index 5e8d2c4455..ad4f5dce7e 100644 --- a/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleTests.java +++ b/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleTests.java @@ -14,7 +14,8 @@ public class StringFormatterExampleTests { public void givenString_whenFormatSpecifierForCalendar_thenGotExpected() { //Syntax of Format Specifiers for Date/Time Representation Calendar c = new GregorianCalendar(2017, 11, 10); - String s = String.format("The date is: %1$tm %1$te,%1$tY", c); + String s = String.format("The date is: %tm %1$te,%1$tY", c); + assertEquals("The date is: 12 10,2017", s); } @@ -84,7 +85,7 @@ public class StringFormatterExampleTests { public void givenString_whenLineSeparatorConversion_thenConvertedString() { //Line Separator Conversion String s = String.format("First Line %nSecond Line"); - assertEquals("First Line \n" + assertEquals("First Line " + System.getProperty("line.separator") + "Second Line", s); } @@ -114,10 +115,10 @@ public class StringFormatterExampleTests { public void givenString_whenSpecifyArgumentIndex_thenGotExpected() { Calendar c = new GregorianCalendar(2017, 11, 10); //Argument_Index - String s = String.format("The date is: %1$tm %1$te,%1$tY", c); + String s = String.format("The date is: %tm %1$te,%1$tY", c); assertEquals("The date is: 12 10,2017", s); - - s = String.format("The date is: %1$tm %"); - out.println("Users"); out.println(""); - out.println("List of users:"); - out.println(""); for (User user : users) { - out.println(""); - out.print("" + user.getUsername() + ""); - out.print("" + user.getEmail() + ""); - out.println(""); + out.print(user.getUsername()); + out.print(" " + user.getEmail() + " "); } + out.println(""); + out.println("