diff --git a/.gitignore b/.gitignore index 180462a32f..7fe2778755 100644 --- a/.gitignore +++ b/.gitignore @@ -62,3 +62,5 @@ jmeter/src/main/resources/*-JMeter.csv **/dist **/tmp **/out-tsc +**/nbproject/ +**/nb-configuration.xml \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/internationalization/DateTimeFormatterUnitTest.java b/core-java-8/src/test/java/com/baeldung/internationalization/DateTimeFormatterUnitTest.java deleted file mode 100644 index 4d95bc82e1..0000000000 --- a/core-java-8/src/test/java/com/baeldung/internationalization/DateTimeFormatterUnitTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.internationalization; - -import org.junit.Assert; -import org.junit.Test; - -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.FormatStyle; -import java.util.Locale; -import java.util.TimeZone; - -public class DateTimeFormatterUnitTest { - - @Test - public void givenDefaultUsLocaleAndDateTimeAndPattern_whenFormatWithDifferentLocales_thenGettingLocalizedDateTimes() { - Locale.setDefault(Locale.US); - LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 1, 10, 15, 50, 500); - String pattern = "dd-MMMM-yyyy HH:mm:ss.SSS"; - - DateTimeFormatter defaultTimeFormatter = DateTimeFormatter.ofPattern(pattern); - DateTimeFormatter plTimeFormatter = DateTimeFormatter.ofPattern(pattern, new Locale("pl", "PL")); - DateTimeFormatter deTimeFormatter = DateTimeFormatter.ofPattern(pattern).withLocale(Locale.GERMANY); - - Assert.assertEquals("01-January-2018 10:15:50.000", defaultTimeFormatter.format(localDateTime)); - Assert.assertEquals("01-stycznia-2018 10:15:50.000", plTimeFormatter.format(localDateTime)); - Assert.assertEquals("01-Januar-2018 10:15:50.000", deTimeFormatter.format(localDateTime)); - } - - @Test - public void givenDateTimeAndTimeZone_whenFormatWithDifferentLocales_thenGettingLocalizedZonedDateTimes() { - Locale.setDefault(Locale.US); - LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 1, 10, 15, 50, 500); - ZoneId losAngelesTimeZone = TimeZone.getTimeZone("America/Los_Angeles").toZoneId(); - - DateTimeFormatter localizedFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL); - DateTimeFormatter frLocalizedFormatter = - DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(Locale.FRANCE); - String formattedDateTime = localizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone)); - String frFormattedDateTime = frLocalizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone)); - - Assert.assertEquals("Monday, January 1, 2018 10:15:50 AM PST", formattedDateTime); - Assert.assertEquals("lundi 1 janvier 2018 10 h 15 PST", frFormattedDateTime); - } -} diff --git a/core-java-collections/pom.xml b/core-java-collections/pom.xml index 06b79fff22..694d2da5eb 100644 --- a/core-java-collections/pom.xml +++ b/core-java-collections/pom.xml @@ -1,90 +1,83 @@ - - 4.0.0 - com.baeldung - core-java-collections - 0.1.0-SNAPSHOT - jar - core-java-collections - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - net.sourceforge.collections - collections-generic - ${collections-generic.version} - - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - - - com.jayway.awaitility - awaitility - ${avaitility.version} - test - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - org.eclipse.collections - eclipse-collections - ${eclipse.collections.version} - - - org.assertj - assertj-core - ${assertj.version} - test - - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - - - org.openjdk.jmh - jmh-core - ${openjdk.jmh.version} - - - org.openjdk.jmh - jmh-generator-annprocess - ${openjdk.jmh.version} - - - org.apache.commons - commons-exec - 1.3 - - - one.util - streamex - 0.6.5 - - - - - - - 1.19 - 1.2.0 - 3.5 - 4.1 - 4.01 - 1.7.0 - 3.6.1 - 7.1.0 - - + + 4.0.0 + com.baeldung + core-java-collections + 0.1.0-SNAPSHOT + jar + core-java-collections + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + net.sourceforge.collections + collections-generic + ${collections-generic.version} + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + com.jayway.awaitility + awaitility + ${avaitility.version} + test + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.eclipse.collections + eclipse-collections + ${eclipse.collections.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + org.openjdk.jmh + jmh-core + ${openjdk.jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${openjdk.jmh.version} + + + org.apache.commons + commons-exec + 1.3 + + + + + 1.19 + 1.2.0 + 3.5 + 4.1 + 4.01 + 1.7.0 + 3.6.1 + 7.1.0 + + diff --git a/core-java-collections/src/main/java/com/baeldung/convertcollectiontoarraylist/Foo.java b/core-java-collections/src/main/java/com/baeldung/convertcollectiontoarraylist/Foo.java new file mode 100644 index 0000000000..5c9464182e --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/convertcollectiontoarraylist/Foo.java @@ -0,0 +1,52 @@ +package com.baeldung.convertcollectiontoarraylist; + +/** + * This POJO is the element type of our collection. It has a deepCopy() method. + * + * @author chris + */ +public class Foo { + + private int id; + private String name; + private Foo parent; + + public Foo() { + } + + public Foo(int id, String name, Foo parent) { + this.id = id; + this.name = name; + this.parent = parent; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Foo getParent() { + return parent; + } + + public void setParent(Foo parent) { + this.parent = parent; + } + + public Foo deepCopy() { + return new Foo( + this.id, this.name, this.parent != null ? this.parent.deepCopy() : null); + } + +} diff --git a/core-java-collections/src/main/java/com/baeldung/synchronizedcollections/application/Application.java b/core-java-collections/src/main/java/com/baeldung/synchronizedcollections/application/Application.java new file mode 100644 index 0000000000..1840c125d0 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/synchronizedcollections/application/Application.java @@ -0,0 +1,18 @@ +package com.baeldung.synchronizedcollections.application; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.logging.Logger; + +public class Application { + + private static final Logger LOGGER = Logger.getLogger(Application.class.getName()); + + public static void main(String[] args) throws InterruptedException { + List syncCollection = Collections.synchronizedList(Arrays.asList(1, 2, 3, 4, 5, 6)); + synchronized (syncCollection) { + syncCollection.forEach((e) -> {LOGGER.info(e.toString());}); + } + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java b/core-java-collections/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java new file mode 100644 index 0000000000..5be4121bc7 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java @@ -0,0 +1,148 @@ +package com.baeldung.convertcollectiontoarraylist; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Iterator; +import static java.util.stream.Collectors.toCollection; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author chris + */ +public class FooUnitTest { + private static Collection srcCollection = new HashSet<>(); + + public FooUnitTest() { + } + + @BeforeClass + public static void setUpClass() { + int i = 0; + Foo john = new Foo(i++, "John", null); + Foo mary = new Foo(i++, "Mary", null); + Foo sam = new Foo(i++, "Sam", john); + Foo alice = new Foo(i++, "Alice", john); + Foo buffy = new Foo(i++, "Buffy", sam); + srcCollection.add(john); + srcCollection.add(mary); + srcCollection.add(sam); + srcCollection.add(alice); + srcCollection.add(buffy); + + // make sure the collection isn't sorted accidentally + assertFalse("Oops: source collection is already sorted!", isSorted(srcCollection)); + } + + /** + * Section 3. Using the ArrayList Constructor + */ + @Test + public void whenUsingConstructor_thenVerifyShallowCopy() { + ArrayList newList = new ArrayList<>(srcCollection); + verifyShallowCopy(srcCollection, newList); + } + + /** + * Section 4. Using the Streams API + */ + @Test + public void whenUsingStream_thenVerifyShallowCopy() { + ArrayList newList = srcCollection.stream().collect(toCollection(ArrayList::new)); + + verifyShallowCopy(srcCollection, newList); + } + + /** + * Section 5. Deep Copy + */ + @Test + public void whenUsingDeepCopy_thenVerifyDeepCopy() { + ArrayList newList = srcCollection.stream() + .map(foo -> foo.deepCopy()) + .collect(toCollection(ArrayList::new)); + + verifyDeepCopy(srcCollection, newList); + } + + /** + * Section 6. Controlling the List Order + */ + @Test + public void whenUsingSortedStream_thenVerifySortOrder() { + ArrayList newList = srcCollection.stream() + .sorted(Comparator.comparing(Foo::getName)) + .collect(toCollection(ArrayList::new)); + + assertTrue("ArrayList is not sorted by name", isSorted(newList)); + } + + /** + * Verify that the contents of the two collections are the same + * @param a + * @param b + */ + private void verifyShallowCopy(Collection a, Collection b) { + assertEquals("Collections have different lengths", a.size(), b.size()); + Iterator iterA = a.iterator(); + Iterator iterB = b.iterator(); + while (iterA.hasNext()) { + // use '==' to test instance identity + assertTrue("Foo instances differ!", iterA.next() == iterB.next()); + } + } + + /** + * Verify that the contents of the two collections are the same + * @param a + * @param b + */ + private void verifyDeepCopy(Collection a, Collection b) { + assertEquals("Collections have different lengths", a.size(), b.size()); + Iterator iterA = a.iterator(); + Iterator iterB = b.iterator(); + while (iterA.hasNext()) { + Foo nextA = iterA.next(); + Foo nextB = iterB.next(); + // should not be same instance + assertFalse("Foo instances are the same!", nextA == nextB); + // but should have same content + assertFalse("Foo instances have different content!", fooDiff(nextA, nextB)); + } + } + + /** + * Return true if the contents of a and b differ. Test parent recursively + * @param a + * @param b + * @return False if the two items are the same + */ + private boolean fooDiff(Foo a, Foo b) { + if (a != null && b != null) { + return a.getId() != b.getId() + || !a.getName().equals(b.getName()) + || fooDiff(a.getParent(), b.getParent()); + } + return !(a == null && b == null); + } + + /** + * @param c collection of Foo + * @return true if the collection is sorted by name + */ + private static boolean isSorted(Collection c) { + String prevName = null; + for (Foo foo : c) { + if (prevName == null || foo.getName().compareTo(prevName) > 0) { + prevName = foo.getName(); + } else { + return false; + } + } + return true; + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/java/map/KeyCheckTest.java b/core-java-collections/src/test/java/com/baeldung/java/map/KeyCheckTest.java deleted file mode 100644 index 024b2973d2..0000000000 --- a/core-java-collections/src/test/java/com/baeldung/java/map/KeyCheckTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.java.map; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.collections4.MultiMap; -import org.apache.commons.collections4.MultiMapUtils; -import org.apache.commons.collections4.MultiValuedMap; -import org.apache.commons.collections4.map.MultiValueMap; -import org.apache.commons.collections4.multimap.ArrayListValuedHashMap; -import org.apache.commons.collections4.multimap.HashSetValuedHashMap; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.LinkedHashMultimap; -import com.google.common.collect.Multimap; -import com.google.common.collect.TreeMultimap; - - -public class KeyCheckTest { - - @Test - public void whenKeyIsPresent_thenContainsKeyReturnsTrue() { - Map map = Collections.singletonMap("key", "value"); - - assertTrue(map.containsKey("key")); - assertFalse(map.containsKey("missing")); - } - - @Test - public void whenKeyHasNullValue_thenGetStillWorks() { - Map map = Collections.singletonMap("nothing", null); - - assertTrue(map.containsKey("nothing")); - assertNull(map.get("nothing")); - } -} \ No newline at end of file diff --git a/core-java-collections/src/test/java/com/baeldung/java/map/KeyCheckUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/map/KeyCheckUnitTest.java new file mode 100644 index 0000000000..2c97a97690 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/java/map/KeyCheckUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.java.map; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.Collections; +import java.util.Map; + +import org.junit.Test; + +public class KeyCheckUnitTest { + + @Test + public void whenKeyIsPresent_thenContainsKeyReturnsTrue() { + Map map = Collections.singletonMap("key", "value"); + + assertTrue(map.containsKey("key")); + assertFalse(map.containsKey("missing")); + } + + @Test + public void whenKeyHasNullValue_thenGetStillWorks() { + Map map = Collections.singletonMap("nothing", null); + + assertTrue(map.containsKey("nothing")); + assertNull(map.get("nothing")); + } +} \ No newline at end of file diff --git a/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedCollectionUnitTest.java b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedCollectionUnitTest.java new file mode 100644 index 0000000000..84feeb6eaa --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedCollectionUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.synchronizedcollections.test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class SynchronizedCollectionUnitTest { + + @Test + public void givenSynchronizedCollection_whenTwoThreadsAddElements_thenCorrectCollectionSize() throws InterruptedException { + Collection syncCollection = Collections.synchronizedCollection(new ArrayList<>()); + + Runnable listOperations = () -> { + syncCollection.addAll(Arrays.asList(1, 2, 3, 4, 5, 6)); + }; + Thread thread1 = new Thread(listOperations); + Thread thread2 = new Thread(listOperations); + thread1.start(); + thread2.start(); + thread1.join(); + thread2.join(); + + assertThat(syncCollection.size()).isEqualTo(12); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedListUnitTest.java b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedListUnitTest.java new file mode 100644 index 0000000000..68fc3becd4 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedListUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.synchronizedcollections.test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import org.junit.Test; +import static org.assertj.core.api.Assertions.*; + +public class SynchronizedListUnitTest { + + @Test + public void givenSynchronizedList_whenTwoThreadsAddElements_thenCorrectListSize() throws InterruptedException { + List syncList = Collections.synchronizedList(new ArrayList<>()); + + Runnable listOperations = () -> { + syncList.addAll(Arrays.asList(1, 2, 3, 4, 5, 6)); + }; + Thread thread1 = new Thread(listOperations); + Thread thread2 = new Thread(listOperations); + thread1.start(); + thread2.start(); + thread1.join(); + thread2.join(); + + assertThat(syncList.size()).isEqualTo(12); + } + + @Test + public void givenStringList_whenTwoThreadsIterateOnSynchronizedList_thenCorrectResult() throws InterruptedException { + List syncCollection = Collections.synchronizedList(Arrays.asList("a", "b", "c")); + List uppercasedCollection = new ArrayList<>(); + + Runnable listOperations = () -> { + synchronized (syncCollection) { + syncCollection.forEach((e) -> { + uppercasedCollection.add(e.toUpperCase()); + }); + } + }; + + Thread thread1 = new Thread(listOperations); + Thread thread2 = new Thread(listOperations); + thread1.start(); + thread2.start(); + thread1.join(); + thread2.join(); + + assertThat(uppercasedCollection.get(0)).isEqualTo("A"); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedMapUnitTest.java b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedMapUnitTest.java new file mode 100644 index 0000000000..abfb866e9c --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedMapUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.synchronizedcollections.test; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import org.junit.Test; +import static org.assertj.core.api.Assertions.*; + +public class SynchronizedMapUnitTest { + + @Test + public void givenSynchronizedMap_whenTwoThreadsAddElements_thenCorrectMapSize() throws InterruptedException { + Map syncMap = Collections.synchronizedMap(new HashMap<>()); + + Runnable mapOperations = () -> { + syncMap.put(1, "one"); + syncMap.put(2, "two"); + syncMap.put(3, "three"); + + }; + Thread thread1 = new Thread(mapOperations); + Thread thread2 = new Thread(mapOperations); + thread1.start(); + thread2.start(); + thread1.join(); + thread2.join(); + + assertThat(syncMap.size()).isEqualTo(3); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedSetUnitTest.java b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedSetUnitTest.java new file mode 100644 index 0000000000..58a33b207d --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedSetUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.synchronizedcollections.test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import org.junit.Test; +import static org.assertj.core.api.Assertions.*; + +public class SynchronizedSetUnitTest { + + @Test + public void givenSynchronizedSet_whenTwoThreadsAddElements_thenCorrectSetSize() throws InterruptedException { + Set syncSet = Collections.synchronizedSet(new HashSet<>()); + + Runnable setOperations = () -> {syncSet.addAll(Arrays.asList(1, 2, 3, 4, 5, 6));}; + Thread thread1 = new Thread(setOperations); + Thread thread2 = new Thread(setOperations); + thread1.start(); + thread2.start(); + thread1.join(); + thread2.join(); + + assertThat(syncSet.size()).isEqualTo(6); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedSortedMapUnitTest.java b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedSortedMapUnitTest.java new file mode 100644 index 0000000000..4b0ed6d8c8 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedSortedMapUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.synchronizedcollections.test; + +import java.util.Collections; +import java.util.Map; +import java.util.TreeMap; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class SynchronizedSortedMapUnitTest { + + @Test + public void givenSynchronizedSorteMap_whenTwoThreadsAddElements_thenCorrectSortedMapSize() throws InterruptedException { + Map syncSortedMap = Collections.synchronizedSortedMap(new TreeMap<>()); + + Runnable sortedMapOperations = () -> { + syncSortedMap.put(1, "One"); + syncSortedMap.put(2, "Two"); + syncSortedMap.put(3, "Three"); + }; + Thread thread1 = new Thread(sortedMapOperations); + Thread thread2 = new Thread(sortedMapOperations); + thread1.start(); + thread2.start(); + thread1.join(); + thread2.join(); + + assertThat(syncSortedMap.size()).isEqualTo(3); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedSortedSetUnitTest.java b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedSortedSetUnitTest.java new file mode 100644 index 0000000000..0e26c6eb1c --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedSortedSetUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.synchronizedcollections.test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.SortedSet; +import java.util.TreeSet; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class SynchronizedSortedSetUnitTest { + + @Test + public void givenSynchronizedSortedSet_whenTwoThreadsAddElements_thenCorrectSortedSetSize() throws InterruptedException { + SortedSet syncSortedSet = Collections.synchronizedSortedSet(new TreeSet<>()); + + Runnable sortedSetOperations = () -> {syncSortedSet.addAll(Arrays.asList(1, 2, 3, 4, 5, 6));}; + sortedSetOperations.run(); + sortedSetOperations.run(); + Thread thread1 = new Thread(sortedSetOperations); + Thread thread2 = new Thread(sortedSetOperations); + thread1.start(); + thread2.start(); + thread1.join(); + thread2.join(); + + assertThat(syncSortedSet.size()).isEqualTo(6); + } +} diff --git a/core-java/src/main/java/com/baeldung/classloader/CustomClassLoader.java b/core-java/src/main/java/com/baeldung/classloader/CustomClassLoader.java index c44e863776..532adce1ab 100644 --- a/core-java/src/main/java/com/baeldung/classloader/CustomClassLoader.java +++ b/core-java/src/main/java/com/baeldung/classloader/CustomClassLoader.java @@ -1,11 +1,14 @@ package com.baeldung.classloader; -import java.io.*; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; public class CustomClassLoader extends ClassLoader { - - public Class getClass(String name) throws ClassNotFoundException { + @Override + public Class findClass(String name) throws ClassNotFoundException { byte[] b = loadClassFromFile(name); return defineClass(name, b, 0, b.length); } diff --git a/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java b/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java index ec35885b84..cabf9f7bdb 100644 --- a/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java +++ b/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java @@ -11,7 +11,7 @@ public class CustomClassLoaderUnitTest { public void customLoader() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { CustomClassLoader customClassLoader = new CustomClassLoader(); - Class c = customClassLoader.getClass(PrintClassLoader.class.getName()); + Class c = customClassLoader.findClass(PrintClassLoader.class.getName()); Object ob = c.newInstance(); diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java index 90203d29ec..ccbdf80bf1 100644 --- a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java @@ -4,13 +4,23 @@ import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; -import javax.persistence.SequenceGenerator; + +import org.hibernate.annotations.GenericGenerator; +import org.hibernate.annotations.Parameter; @Entity public class User { @Id - @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence-generator") - @SequenceGenerator(name = "sequence-generator", sequenceName = "user_sequence", initialValue = 4) + @GeneratedValue(generator = "sequence-generator") + @GenericGenerator( + name = "sequence-generator", + strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", + parameters = { + @Parameter(name = "sequence_name", value = "user_sequence"), + @Parameter(name = "initial_value", value = "4"), + @Parameter(name = "increment_size", value = "1") + } + ) private long userId; public long getUserId() { diff --git a/java-dates/pom.xml b/java-dates/pom.xml index 13e2a077e1..2618fad1d4 100644 --- a/java-dates/pom.xml +++ b/java-dates/pom.xml @@ -80,7 +80,7 @@ 2.10 3.6.1 - 9 - 9 + 1.9 + 1.9 diff --git a/java-dates/src/test/java/com/baeldung/datetime/DateTimeFormatterUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/DateTimeFormatterUnitTest.java new file mode 100644 index 0000000000..f3b2b11893 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/datetime/DateTimeFormatterUnitTest.java @@ -0,0 +1,158 @@ +package com.baeldung.datetime; + +import org.junit.Assert; +import org.junit.Test; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.time.format.FormatStyle; +import java.time.temporal.ChronoUnit; +import java.util.Locale; +import java.util.TimeZone; + +public class DateTimeFormatterUnitTest { + + @Test + public void givenDefaultUsLocaleAndDateTimeAndPattern_whenFormatWithDifferentLocales_thenGettingLocalizedDateTimes() { + Locale.setDefault(Locale.US); + LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 1, 10, 15, 50, 500); + String pattern = "dd-MMMM-yyyy HH:mm:ss.SSS"; + + DateTimeFormatter defaultTimeFormatter = DateTimeFormatter.ofPattern(pattern); + DateTimeFormatter plTimeFormatter = DateTimeFormatter.ofPattern(pattern, new Locale("pl", "PL")); + DateTimeFormatter deTimeFormatter = DateTimeFormatter.ofPattern(pattern).withLocale(Locale.GERMANY); + + Assert.assertEquals("01-January-2018 10:15:50.000", defaultTimeFormatter.format(localDateTime)); + Assert.assertEquals("01-stycznia-2018 10:15:50.000", plTimeFormatter.format(localDateTime)); + Assert.assertEquals("01-Januar-2018 10:15:50.000", deTimeFormatter.format(localDateTime)); + } + + @Test + public void givenDateTimeAndTimeZone_whenFormatWithDifferentLocales_thenGettingLocalizedZonedDateTimes() { + Locale.setDefault(Locale.US); + LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 1, 10, 15, 50, 500); + ZoneId losAngelesTimeZone = TimeZone.getTimeZone("America/Los_Angeles").toZoneId(); + + DateTimeFormatter localizedFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL); + DateTimeFormatter frLocalizedFormatter = + DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(Locale.FRANCE); + String formattedDateTime = localizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone)); + String frFormattedDateTime = frLocalizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone)); + + Assert.assertEquals("Monday, January 1, 2018 10:15:50 AM PST", formattedDateTime); + Assert.assertEquals("lundi 1 janvier 2018 10 h 15 PST", frFormattedDateTime); + } + + @Test + public void shouldPrintFormattedDate() { + String europeanDatePattern = "dd.MM.yyyy"; + DateTimeFormatter europeanDateFormatter = DateTimeFormatter.ofPattern(europeanDatePattern); + LocalDate summerDay = LocalDate.of(2016, 7, 31); + Assert.assertEquals("31.07.2016", europeanDateFormatter.format(summerDay)); + } + + @Test + public void shouldPrintFormattedTime24() { + String timeColonPattern = "HH:mm:ss"; + DateTimeFormatter timeColonFormatter = DateTimeFormatter.ofPattern(timeColonPattern); + LocalTime colonTime = LocalTime.of(17, 35, 50); + Assert.assertEquals("17:35:50", timeColonFormatter.format(colonTime)); + } + + @Test + public void shouldPrintFormattedTimeWithMillis() { + String timeColonPattern = "HH:mm:ss SSS"; + DateTimeFormatter timeColonFormatter = DateTimeFormatter.ofPattern(timeColonPattern); + LocalTime colonTime = LocalTime.of(17, 35, 50).plus(329, ChronoUnit.MILLIS); + Assert.assertEquals("17:35:50 329", timeColonFormatter.format(colonTime)); + } + + @Test + public void shouldPrintFormattedTimePM() { + String timeColonPattern = "hh:mm:ss a"; + DateTimeFormatter timeColonFormatter = DateTimeFormatter.ofPattern(timeColonPattern); + LocalTime colonTime = LocalTime.of(17, 35, 50); + Assert.assertEquals("05:35:50 PM", timeColonFormatter.format(colonTime)); + } + + @Test + public void shouldPrintFormattedUTCRelatedZonedDateTime() { + String newYorkDateTimePattern = "dd.MM.yyyy HH:mm z"; + DateTimeFormatter newYorkDateFormatter = DateTimeFormatter.ofPattern(newYorkDateTimePattern); + LocalDateTime summerDay = LocalDateTime.of(2016, 7, 31, 14, 15); + Assert.assertEquals("31.07.2016 14:15 UTC-04:00", newYorkDateFormatter.format(ZonedDateTime.of(summerDay, ZoneId.of("UTC-4")))); + } + + @Test + public void shouldPrintFormattedNewYorkZonedDateTime() { + String newYorkDateTimePattern = "dd.MM.yyyy HH:mm z"; + DateTimeFormatter newYorkDateFormatter = DateTimeFormatter.ofPattern(newYorkDateTimePattern); + LocalDateTime summerDay = LocalDateTime.of(2016, 7, 31, 14, 15); + Assert.assertEquals("31.07.2016 14:15 EDT", newYorkDateFormatter.format(ZonedDateTime.of(summerDay, ZoneId.of("America/New_York")))); + } + + @Test + public void shouldPrintStyledDate() { + LocalDate anotherSummerDay = LocalDate.of(2016, 8, 23); + Assert.assertEquals("Tuesday, August 23, 2016", DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).format(anotherSummerDay)); + Assert.assertEquals("August 23, 2016", DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG).format(anotherSummerDay)); + Assert.assertEquals("Aug 23, 2016", DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).format(anotherSummerDay)); + Assert.assertEquals("8/23/16", DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).format(anotherSummerDay)); + } + + @Test + public void shouldPrintStyledDateTime() { + LocalDateTime anotherSummerDay = LocalDateTime.of(2016, 8, 23, 13, 12, 45); + Assert.assertEquals("Tuesday, August 23, 2016 1:12:45 PM EET", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay)); + Assert.assertEquals("August 23, 2016 1:12:45 PM EET", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay)); + Assert.assertEquals("Aug 23, 2016 1:12:45 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay)); + Assert.assertEquals("8/23/16 1:12 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay)); + } + + @Test + public void shouldPrintFormattedDateTimeWithPredefined() { + Assert.assertEquals("2018-03-09", DateTimeFormatter.ISO_LOCAL_DATE.format(LocalDate.of(2018, 3, 9))); + Assert.assertEquals("2018-03-09-03:00", DateTimeFormatter.ISO_OFFSET_DATE.format(LocalDate.of(2018, 3, 9).atStartOfDay(ZoneId.of("UTC-3")))); + Assert.assertEquals("Fri, 9 Mar 2018 00:00:00 -0300", DateTimeFormatter.RFC_1123_DATE_TIME.format(LocalDate.of(2018, 3, 9).atStartOfDay(ZoneId.of("UTC-3")))); + } + + @Test + public void shouldParseDateTime() { + Assert.assertEquals(LocalDate.of(2018, 3, 12), LocalDate.from(DateTimeFormatter.ISO_LOCAL_DATE.parse("2018-03-09")).plusDays(3)); + } + + @Test + public void shouldParseFormatStyleFull() { + ZonedDateTime dateTime = ZonedDateTime.from(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).parse("Tuesday, August 23, 2016 1:12:45 PM EET")); + Assert.assertEquals(ZonedDateTime.of(LocalDateTime.of(2016, 8, 23, 22, 12, 45), ZoneId.of("Europe/Bucharest")), dateTime.plusHours(9)); + } + + @Test + public void shouldParseDateWithCustomFormatter() { + DateTimeFormatter europeanDateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy"); + Assert.assertFalse(LocalDate.from(europeanDateFormatter.parse("15.08.2014")).isLeapYear()); + } + + @Test + public void shouldParseTimeWithCustomFormatter() { + DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm:ss a"); + Assert.assertTrue(LocalTime.from(timeFormatter.parse("12:25:30 AM")).isBefore(LocalTime.NOON)); + } + + @Test + public void shouldParseZonedDateTimeWithCustomFormatter() { + DateTimeFormatter zonedFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm z"); + Assert.assertEquals(7200, ZonedDateTime.from(zonedFormatter.parse("31.07.2016 14:15 GMT+02:00")).getOffset().getTotalSeconds()); + } + + @Test(expected = DateTimeParseException.class) + public void shouldExpectAnExceptionIfDateTimeStringNotMatchPattern() { + DateTimeFormatter zonedFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm z"); + ZonedDateTime.from(zonedFormatter.parse("31.07.2016 14:15")); + } +} diff --git a/java-dates/src/test/java/com/baeldung/zoneddatetime/ZonedDateTimeUnitTest.java b/java-dates/src/test/java/com/baeldung/zoneddatetime/ZonedDateTimeUnitTest.java new file mode 100644 index 0000000000..355fef35c6 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/zoneddatetime/ZonedDateTimeUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.zoneddatetime; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.logging.Logger; + +import org.junit.Test; + +public class ZonedDateTimeUnitTest { + + private static final Logger log = Logger.getLogger(ZonedDateTimeUnitTest.class.getName()); + + @Test + public void testZonedDateTimeToString() { + + ZonedDateTime zonedDateTimeNow = ZonedDateTime.now(ZoneId.of("UTC")); + ZonedDateTime zonedDateTimeOf = ZonedDateTime.of(2018, 01, 01, 0, 0, 0, 0, ZoneId.of("UTC")); + + LocalDateTime localDateTime = LocalDateTime.now(); + ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("UTC")); + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy - hh:mm:ss Z"); + String formattedString = zonedDateTime.format(formatter); + + DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("MM/dd/yyyy - hh:mm:ss z"); + String formattedString2 = zonedDateTime.format(formatter2); + + log.info(formattedString); + log.info(formattedString2); + + } + + @Test + public void testZonedDateTimeFromString() { + + ZonedDateTime zonedDateTime = ZonedDateTime.parse("2011-12-03T10:15:30+01:00", DateTimeFormatter.ISO_ZONED_DATE_TIME); + + log.info(zonedDateTime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME)); + } + +} diff --git a/javaxval/pom.xml b/javaxval/pom.xml index bf27b01775..46122af06b 100644 --- a/javaxval/pom.xml +++ b/javaxval/pom.xml @@ -24,6 +24,17 @@ org.glassfish.web + org.hibernate + hibernate-validator-annotation-processor + ${hibernate-validator.version} + + + javax.el + javax.el-api + ${javax.el-api.version} + + + org.glassfish javax.el ${javax.el.version} @@ -58,4 +69,4 @@ 4.12 3.11.1 - + \ No newline at end of file diff --git a/maven/versions-maven-plugin/original/pom.xml b/maven/versions-maven-plugin/original/pom.xml new file mode 100644 index 0000000000..295c77b860 --- /dev/null +++ b/maven/versions-maven-plugin/original/pom.xml @@ -0,0 +1,76 @@ + + 4.0.0 + com.baeldung + versions-maven-plugin-example + 0.0.1-SNAPSHOT + + + 1.15 + + + + + + commons-io + commons-io + 2.3 + + + + org.apache.commons + commons-collections4 + 4.0 + + + + org.apache.commons + commons-lang3 + 3.0 + + + + org.apache.commons + commons-compress + ${commons-compress-version} + + + + commons-beanutils + commons-beanutils + 1.9.1-SNAPSHOT + + + + + + + + org.codehaus.mojo + versions-maven-plugin + 2.7 + + + org.apache.commons:commons-collections4 + + + + + + + + + apache.snapshots + Apache Development Snapshot Repository + https://repository.apache.org/content/repositories/snapshots/ + + false + + + true + + + + + \ No newline at end of file diff --git a/maven/versions-maven-plugin/pom.xml b/maven/versions-maven-plugin/pom.xml new file mode 100644 index 0000000000..295c77b860 --- /dev/null +++ b/maven/versions-maven-plugin/pom.xml @@ -0,0 +1,76 @@ + + 4.0.0 + com.baeldung + versions-maven-plugin-example + 0.0.1-SNAPSHOT + + + 1.15 + + + + + + commons-io + commons-io + 2.3 + + + + org.apache.commons + commons-collections4 + 4.0 + + + + org.apache.commons + commons-lang3 + 3.0 + + + + org.apache.commons + commons-compress + ${commons-compress-version} + + + + commons-beanutils + commons-beanutils + 1.9.1-SNAPSHOT + + + + + + + + org.codehaus.mojo + versions-maven-plugin + 2.7 + + + org.apache.commons:commons-collections4 + + + + + + + + + apache.snapshots + Apache Development Snapshot Repository + https://repository.apache.org/content/repositories/snapshots/ + + false + + + true + + + + + \ No newline at end of file diff --git a/maven/versions-maven-plugin/run-the-demo.sh b/maven/versions-maven-plugin/run-the-demo.sh new file mode 100755 index 0000000000..89ca871e01 --- /dev/null +++ b/maven/versions-maven-plugin/run-the-demo.sh @@ -0,0 +1,74 @@ +#!/bin/bash +#function to display commands +exe() { echo -e "\$ $@\n" ; "$@" ; } + +TEXT_COLOR='\033[1;33m' #Yellow +NO_COLOR='\033[0m' # No Color + +clear + +echo -e "======================================================================================" +echo -e " Showcase for the BAELDUNG tutorial \"Use the latest version of a dependency in Maven\"" +echo -e " Author: Andrea Ligios" +echo -e "======================================================================================" + +echo -e "${TEXT_COLOR}\n--------------------------------------------------------------------------------------" +echo -e " Resetting the demo environment (which will be altered during the run): " +echo -e "--------------------------------------------------------------------------------------${NO_COLOR}" +rm -f pom.xml.versionsBackup +cp original/pom.xml pom.xml +ls -lt pom.* +echo -e "${TEXT_COLOR}\n--------------------------------------------------------------------------------------" +echo -e " Checking for newer versions of the Maven dependencies:" +echo -e "--------------------------------------------------------------------------------------${NO_COLOR}" +exe mvn versions:display-dependency-updates +echo +read -p "Press enter to continue" + +echo -e "${TEXT_COLOR}\n--------------------------------------------------------------------------------------" +echo -e " Updating SNAPSHOT dependencies to their RELEASE version, if any:" +echo -e "--------------------------------------------------------------------------------------${NO_COLOR}" +exe mvn versions:use-releases +echo -e "${TEXT_COLOR}\n--------------------------------------------------------------------------------------" +echo -e " A backup has been created automatically:" +echo -e "--------------------------------------------------------------------------------------${NO_COLOR}" +ls -lt pom.* +echo +read -p "Press enter to continue" + +echo -e "${TEXT_COLOR}\n--------------------------------------------------------------------------------------" +echo -e " Updating RELEASE dependencies to their *next* RELEASE version:" +echo -e "--------------------------------------------------------------------------------------${NO_COLOR}" +exe mvn versions:use-next-releases +echo +read -p "Press enter to continue" + +echo -e "${TEXT_COLOR}\n--------------------------------------------------------------------------------------" +echo -e " Reverting every modification made since the beginning:" +echo -e "--------------------------------------------------------------------------------------${NO_COLOR}" +exe mvn versions:revert +echo -e "${TEXT_COLOR}\n--------------------------------------------------------------------------------------" +echo -e " The backup is gone, and the pom.xml contains the initial dependencies:" +echo -e "--------------------------------------------------------------------------------------${NO_COLOR}" +ls -lt pom.* +echo +read -p "Press enter to continue" + +echo -e "${TEXT_COLOR}\n--------------------------------------------------------------------------------------" +echo -e " Updating RELEASE dependencies to their *latest* RELEASE version:" +echo -e "--------------------------------------------------------------------------------------${NO_COLOR}" +exe mvn versions:use-latest-releases +echo +read -p "Press enter to continue" + +echo -e "${TEXT_COLOR}\n--------------------------------------------------------------------------------------" +echo -e " Committing the modifications to pom.xml:" +echo -e "--------------------------------------------------------------------------------------${NO_COLOR}" +exe mvn versions:commit +echo -e "${TEXT_COLOR}\n--------------------------------------------------------------------------------------" +echo -e " The backup is gone, and the pom.xml contains the latest dependencies:" +echo -e "--------------------------------------------------------------------------------------${NO_COLOR}" +ls -lt pom.* +echo + +echo -e "${TEXT_COLOR}\nThat's all folks!${NO_COLOR}\n" diff --git a/pom.xml b/pom.xml index 008d0aeac3..e6618da0a2 100644 --- a/pom.xml +++ b/pom.xml @@ -526,31 +526,6 @@ spring-resttemplate - spring-security-acl - spring-security-cache-control - spring-security-client/spring-security-jsp-authentication - spring-security-client/spring-security-jsp-authorize - spring-security-client/spring-security-jsp-config - spring-security-client/spring-security-mvc - spring-security-client/spring-security-thymeleaf-authentication - spring-security-client/spring-security-thymeleaf-authorize - spring-security-client/spring-security-thymeleaf-config - spring-security-core - spring-security-mvc-boot - spring-security-mvc-custom - spring-security-mvc-digest-auth - spring-security-mvc-ldap - spring-security-mvc-login - spring-security-mvc-persisted-remember-me - spring-security-mvc-session - spring-security-mvc-socket - spring-security-openid - - spring-security-rest-basic-auth - spring-security-rest-custom - spring-security-rest - spring-security-sso - spring-security-x509 @@ -719,7 +694,33 @@ - flyway-cdi-extension + flyway-cdi-extension + + spring-security-acl + spring-security-cache-control + spring-security-client/spring-security-jsp-authentication + spring-security-client/spring-security-jsp-authorize + spring-security-client/spring-security-jsp-config + spring-security-client/spring-security-mvc + spring-security-client/spring-security-thymeleaf-authentication + spring-security-client/spring-security-thymeleaf-authorize + spring-security-client/spring-security-thymeleaf-config + spring-security-core + spring-security-mvc-boot + spring-security-mvc-custom + spring-security-mvc-digest-auth + spring-security-mvc-ldap + spring-security-mvc-login + spring-security-mvc-persisted-remember-me + spring-security-mvc-session + spring-security-mvc-socket + spring-security-openid + + spring-security-rest-basic-auth + spring-security-rest-custom + spring-security-rest + spring-security-sso + spring-security-x509 diff --git a/spring-data-mongodb/pom.xml b/spring-data-mongodb/pom.xml index ad70d987bb..072ed7a2ac 100644 --- a/spring-data-mongodb/pom.xml +++ b/spring-data-mongodb/pom.xml @@ -34,6 +34,12 @@ ${mongodb-reactivestreams.version} + + io.projectreactor + reactor-core + ${projectreactor.version} + + io.projectreactor reactor-test @@ -109,6 +115,7 @@ 5.1.0.RELEASE 1.9.2 3.2.0.RELEASE +