Merge branch 'master' into javabeanconstraints

This commit is contained in:
Alejandro Gervasio 2018-10-10 16:20:17 -03:00 committed by GitHub
commit 6b55a62038
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
26 changed files with 1019 additions and 216 deletions

2
.gitignore vendored
View File

@ -62,3 +62,5 @@ jmeter/src/main/resources/*-JMeter.csv
**/dist
**/tmp
**/out-tsc
**/nbproject/
**/nb-configuration.xml

View File

@ -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);
}
}

View File

@ -1,90 +1,83 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>core-java-collections</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>core-java-collections</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>net.sourceforge.collections</groupId>
<artifactId>collections-generic</artifactId>
<version>${collections-generic.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${avaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.collections</groupId>
<artifactId>eclipse-collections</artifactId>
<version>${eclipse.collections.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${openjdk.jmh.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${openjdk.jmh.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-exec</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>0.6.5</version>
</dependency>
</dependencies>
<properties>
<openjdk.jmh.version>1.19</openjdk.jmh.version>
<junit.platform.version>1.2.0</junit.platform.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<avaitility.version>1.7.0</avaitility.version>
<assertj.version>3.6.1</assertj.version>
<eclipse.collections.version>7.1.0</eclipse.collections.version>
</properties>
</project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>core-java-collections</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>core-java-collections</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>net.sourceforge.collections</groupId>
<artifactId>collections-generic</artifactId>
<version>${collections-generic.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${avaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.collections</groupId>
<artifactId>eclipse-collections</artifactId>
<version>${eclipse.collections.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${openjdk.jmh.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${openjdk.jmh.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-exec</artifactId>
<version>1.3</version>
</dependency>
</dependencies>
<properties>
<openjdk.jmh.version>1.19</openjdk.jmh.version>
<junit.platform.version>1.2.0</junit.platform.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<avaitility.version>1.7.0</avaitility.version>
<assertj.version>3.6.1</assertj.version>
<eclipse.collections.version>7.1.0</eclipse.collections.version>
</properties>
</project>

View File

@ -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);
}
}

View File

@ -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<Integer> syncCollection = Collections.synchronizedList(Arrays.asList(1, 2, 3, 4, 5, 6));
synchronized (syncCollection) {
syncCollection.forEach((e) -> {LOGGER.info(e.toString());});
}
}
}

View File

@ -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<Foo> 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<Foo> newList = new ArrayList<>(srcCollection);
verifyShallowCopy(srcCollection, newList);
}
/**
* Section 4. Using the Streams API
*/
@Test
public void whenUsingStream_thenVerifyShallowCopy() {
ArrayList<Foo> newList = srcCollection.stream().collect(toCollection(ArrayList::new));
verifyShallowCopy(srcCollection, newList);
}
/**
* Section 5. Deep Copy
*/
@Test
public void whenUsingDeepCopy_thenVerifyDeepCopy() {
ArrayList<Foo> 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<Foo> 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<Foo> iterA = a.iterator();
Iterator<Foo> 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<Foo> iterA = a.iterator();
Iterator<Foo> 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<Foo> c) {
String prevName = null;
for (Foo foo : c) {
if (prevName == null || foo.getName().compareTo(prevName) > 0) {
prevName = foo.getName();
} else {
return false;
}
}
return true;
}
}

View File

@ -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<String, String> map = Collections.singletonMap("key", "value");
assertTrue(map.containsKey("key"));
assertFalse(map.containsKey("missing"));
}
@Test
public void whenKeyHasNullValue_thenGetStillWorks() {
Map<String, String> map = Collections.singletonMap("nothing", null);
assertTrue(map.containsKey("nothing"));
assertNull(map.get("nothing"));
}
}

View File

@ -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<String, String> map = Collections.singletonMap("key", "value");
assertTrue(map.containsKey("key"));
assertFalse(map.containsKey("missing"));
}
@Test
public void whenKeyHasNullValue_thenGetStillWorks() {
Map<String, String> map = Collections.singletonMap("nothing", null);
assertTrue(map.containsKey("nothing"));
assertNull(map.get("nothing"));
}
}

View File

@ -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<Integer> 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);
}
}

View File

@ -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<Integer> 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<String> syncCollection = Collections.synchronizedList(Arrays.asList("a", "b", "c"));
List<String> 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");
}
}

View File

@ -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<Integer, String> 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);
}
}

View File

@ -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<Integer> 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);
}
}

View File

@ -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<Integer, String> 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);
}
}

View File

@ -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<Integer> 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);
}
}

View File

@ -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);
}

View File

@ -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();

View File

@ -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() {

View File

@ -80,7 +80,7 @@
<joda-time.version>2.10</joda-time.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<maven.compiler.source>9</maven.compiler.source>
<maven.compiler.target>9</maven.compiler.target>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
</properties>
</project>

View File

@ -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"));
}
}

View File

@ -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));
}
}

View File

@ -24,6 +24,17 @@
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>${javax.el-api.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>${javax.el.version}</version>
</dependency>
@ -58,4 +69,4 @@
<junit.version>4.12</junit.version>
<assertj.version>3.11.1</assertj.version>
</properties>
</project>
</project>

View File

@ -0,0 +1,76 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>versions-maven-plugin-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<commons-compress-version>1.15</commons-compress-version>
</properties>
<dependencies>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>${commons-compress-version}</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.1-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>versions-maven-plugin</artifactId>
<version>2.7</version>
<configuration>
<excludes>
<exclude>org.apache.commons:commons-collections4</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>apache.snapshots</id>
<name>Apache Development Snapshot Repository</name>
<url>https://repository.apache.org/content/repositories/snapshots/</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
</project>

View File

@ -0,0 +1,76 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>versions-maven-plugin-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<commons-compress-version>1.15</commons-compress-version>
</properties>
<dependencies>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>${commons-compress-version}</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.1-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>versions-maven-plugin</artifactId>
<version>2.7</version>
<configuration>
<excludes>
<exclude>org.apache.commons:commons-collections4</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>apache.snapshots</id>
<name>Apache Development Snapshot Repository</name>
<url>https://repository.apache.org/content/repositories/snapshots/</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
</project>

View File

@ -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"

53
pom.xml
View File

@ -526,31 +526,6 @@
<!-- <module>spring-rest</module> --> <!-- temporarily disabled -->
<!-- <module>spring-rest-simple</module> --> <!-- temporarily disabled -->
<module>spring-resttemplate</module>
<module>spring-security-acl</module>
<module>spring-security-cache-control</module>
<module>spring-security-client/spring-security-jsp-authentication</module>
<module>spring-security-client/spring-security-jsp-authorize</module>
<module>spring-security-client/spring-security-jsp-config</module>
<module>spring-security-client/spring-security-mvc</module>
<module>spring-security-client/spring-security-thymeleaf-authentication</module>
<module>spring-security-client/spring-security-thymeleaf-authorize</module>
<module>spring-security-client/spring-security-thymeleaf-config</module>
<module>spring-security-core</module>
<module>spring-security-mvc-boot</module>
<module>spring-security-mvc-custom</module>
<module>spring-security-mvc-digest-auth</module>
<module>spring-security-mvc-ldap</module>
<module>spring-security-mvc-login</module>
<module>spring-security-mvc-persisted-remember-me</module>
<module>spring-security-mvc-session</module>
<module>spring-security-mvc-socket</module>
<module>spring-security-openid</module>
<!--<module>spring-security-react</module> -->
<module>spring-security-rest-basic-auth</module>
<module>spring-security-rest-custom</module>
<module>spring-security-rest</module>
<module>spring-security-sso</module>
<module>spring-security-x509</module>
</modules>
</profile>
@ -719,7 +694,33 @@
<!-- <module>guest\webservices\rest-client</module> --><!-- guest post on different site -->
<!-- <module>guest\webservices\rest-server</module> --><!-- guest post on different site -->
<!-- <module>guest\webservices\spring-rest-service</module> --><!-- guest post on different site -->
<module>flyway-cdi-extension</module>
<module>flyway-cdi-extension</module>
<module>spring-security-acl</module>
<module>spring-security-cache-control</module>
<module>spring-security-client/spring-security-jsp-authentication</module>
<module>spring-security-client/spring-security-jsp-authorize</module>
<module>spring-security-client/spring-security-jsp-config</module>
<module>spring-security-client/spring-security-mvc</module>
<module>spring-security-client/spring-security-thymeleaf-authentication</module>
<module>spring-security-client/spring-security-thymeleaf-authorize</module>
<module>spring-security-client/spring-security-thymeleaf-config</module>
<module>spring-security-core</module>
<module>spring-security-mvc-boot</module>
<module>spring-security-mvc-custom</module>
<module>spring-security-mvc-digest-auth</module>
<module>spring-security-mvc-ldap</module>
<module>spring-security-mvc-login</module>
<module>spring-security-mvc-persisted-remember-me</module>
<module>spring-security-mvc-session</module>
<module>spring-security-mvc-socket</module>
<module>spring-security-openid</module>
<!--<module>spring-security-react</module> -->
<module>spring-security-rest-basic-auth</module>
<module>spring-security-rest-custom</module>
<module>spring-security-rest</module>
<module>spring-security-sso</module>
<module>spring-security-x509</module>
</modules>
</profile>

View File

@ -34,6 +34,12 @@
<version>${mongodb-reactivestreams.version}</version>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
<version>${projectreactor.version}</version>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
@ -109,6 +115,7 @@
<spring.version>5.1.0.RELEASE</spring.version>
<mongodb-reactivestreams.version>1.9.2</mongodb-reactivestreams.version>
<projectreactor.version>3.2.0.RELEASE</projectreactor.version>
</properties>
</project>