Merge branch 'master' of https://github.com/psoares/tutorials
This commit is contained in:
@@ -12,3 +12,4 @@ This module contains articles about Java 11 core features
|
||||
- [An Introduction to Epsilon GC: A No-Op Experimental Garbage Collector](https://www.baeldung.com/jvm-epsilon-gc-garbage-collector)
|
||||
- [Guide to jlink](https://www.baeldung.com/jlink)
|
||||
- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference)
|
||||
- [Benchmark JDK Collections vs Eclipse Collections](https://www.baeldung.com/jdk-collections-vs-eclipse-collections)
|
||||
|
||||
@@ -42,12 +42,12 @@
|
||||
<dependency>
|
||||
<groupId>org.eclipse.collections</groupId>
|
||||
<artifactId>eclipse-collections</artifactId>
|
||||
<version>10.0.0</version>
|
||||
<version>${eclipse.collections.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.collections</groupId>
|
||||
<artifactId>eclipse-collections-api</artifactId>
|
||||
<version>10.0.0</version>
|
||||
<version>${eclipse.collections.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
@@ -108,6 +108,7 @@
|
||||
<assertj.version>3.11.1</assertj.version>
|
||||
<uberjar.name>benchmarks</uberjar.name>
|
||||
<jmh.version>1.22</jmh.version>
|
||||
<eclipse.collections.version>10.0.0</eclipse.collections.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.patternreuse;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class PatternJava11UnitTest {
|
||||
|
||||
@Test
|
||||
public void givenPreCompiledPattern_whenCallAsMatchPredicate_thenReturnMatchPredicateToMatchesPattern() {
|
||||
List<String> namesToValidate = Arrays.asList("Fabio Silva", "Fabio Luis Silva");
|
||||
Pattern firstLastNamePreCompiledPattern = Pattern.compile("[a-zA-Z]{3,} [a-zA-Z]{3,}");
|
||||
|
||||
Predicate<String> patternAsMatchPredicate = firstLastNamePreCompiledPattern.asMatchPredicate();
|
||||
List<String> validatedNames = namesToValidate.stream()
|
||||
.filter(patternAsMatchPredicate)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertTrue(validatedNames.contains("Fabio Silva"));
|
||||
assertFalse(validatedNames.contains("Fabio Luis Silva"));
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.0.0-M3</version>
|
||||
<version>${surefire.plugin.version}</version>
|
||||
<configuration>
|
||||
<argLine>--enable-preview</argLine>
|
||||
</configuration>
|
||||
@@ -53,6 +53,7 @@
|
||||
<maven.compiler.source.version>13</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>13</maven.compiler.target.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<surefire.plugin.version>3.0.0-M3</surefire.plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.newfeatures;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class SwitchExpressionsWithYieldUnitTest {
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("preview")
|
||||
public void whenSwitchingOnOperationSquareMe_thenWillReturnSquare() {
|
||||
var me = 4;
|
||||
var operation = "squareMe";
|
||||
var result = switch (operation) {
|
||||
case "doubleMe" -> {
|
||||
yield me * 2;
|
||||
}
|
||||
case "squareMe" -> {
|
||||
yield me * me;
|
||||
}
|
||||
default -> me;
|
||||
};
|
||||
|
||||
assertEquals(16, result);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.newfeatures;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class TextBlocksUnitTest {
|
||||
|
||||
private static final String JSON_STRING = "{\r\n" + "\"name\" : \"Baeldung\",\r\n" + "\"website\" : \"https://www.%s.com/\"\r\n" + "}";
|
||||
|
||||
@SuppressWarnings("preview")
|
||||
private static final String TEXT_BLOCK_JSON = """
|
||||
{
|
||||
"name" : "Baeldung",
|
||||
"website" : "https://www.%s.com/"
|
||||
}
|
||||
""";
|
||||
|
||||
@Test
|
||||
public void whenTextBlocks_thenStringOperationsWork() {
|
||||
|
||||
assertThat(TEXT_BLOCK_JSON.contains("Baeldung")).isTrue();
|
||||
assertThat(TEXT_BLOCK_JSON.indexOf("www")).isGreaterThan(0);
|
||||
assertThat(TEXT_BLOCK_JSON.length()).isGreaterThan(0);
|
||||
|
||||
}
|
||||
|
||||
@SuppressWarnings("removal")
|
||||
@Test
|
||||
public void whenTextBlocks_thenFormattedWorksAsFormat() {
|
||||
assertThat(TEXT_BLOCK_JSON.formatted("baeldung")
|
||||
.contains("www.baeldung.com")).isTrue();
|
||||
|
||||
assertThat(String.format(JSON_STRING, "baeldung")
|
||||
.contains("www.baeldung.com")).isTrue();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
53
core-java-modules/core-java-14/pom.xml
Normal file
53
core-java-modules/core-java-14/pom.xml
Normal file
@@ -0,0 +1,53 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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-14</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<name>core-java-14</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source.version}</source>
|
||||
<target>${maven.compiler.target.version}</target>
|
||||
<compilerArgs>
|
||||
<compilerArg>
|
||||
--enable-preview
|
||||
</compilerArg>
|
||||
</compilerArgs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${surefire.plugin.version}</version>
|
||||
<configuration>
|
||||
<argLine>--enable-preview</argLine>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source.version>14</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>14</maven.compiler.target.version>
|
||||
<surefire.plugin.version>3.0.0-M3</surefire.plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.serial;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.ObjectStreamException;
|
||||
import java.io.ObjectStreamField;
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* Class showcasing the usage of the Java 14 @Serial annotation.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*/
|
||||
public class MySerialClass implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final ObjectStreamField[] serialPersistentFields = null;
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1;
|
||||
|
||||
@Serial
|
||||
private void writeObject(ObjectOutputStream stream) throws IOException {
|
||||
// ...
|
||||
}
|
||||
|
||||
@Serial
|
||||
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
|
||||
// ...
|
||||
}
|
||||
|
||||
@Serial
|
||||
private void readObjectNoData() throws ObjectStreamException {
|
||||
// ...
|
||||
}
|
||||
|
||||
@Serial
|
||||
private Object writeReplace() throws ObjectStreamException {
|
||||
// ...
|
||||
return null;
|
||||
}
|
||||
|
||||
@Serial
|
||||
private Object readResolve() throws ObjectStreamException {
|
||||
// ...
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -61,7 +61,7 @@
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>spring-boot</classifier>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
|
||||
@@ -19,6 +19,16 @@
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
@@ -37,13 +47,39 @@
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>${shade.plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<finalName>benchmarks</finalName>
|
||||
<transformers>
|
||||
<transformer
|
||||
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>org.openjdk.jmh.Main</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<jmh.version>1.19</jmh.version>
|
||||
<!-- util -->
|
||||
<commons-lang3.version>3.9</commons-lang3.version>
|
||||
<!-- testing -->
|
||||
<assertj-core.version>3.10.0</assertj-core.version>
|
||||
<shade.plugin.version>3.2.0</shade.plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.arraysort;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Fork;
|
||||
import org.openjdk.jmh.annotations.Level;
|
||||
import org.openjdk.jmh.annotations.Measurement;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||
import org.openjdk.jmh.annotations.Param;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.Setup;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
import org.openjdk.jmh.annotations.Warmup;
|
||||
import org.openjdk.jmh.infra.Blackhole;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@Warmup(iterations = 5)
|
||||
@Measurement(iterations = 10)
|
||||
@Fork(2)
|
||||
@OutputTimeUnit(TimeUnit.MILLISECONDS)
|
||||
public class ArraySortingBenchmark {
|
||||
|
||||
@State(Scope.Benchmark)
|
||||
public static class ArrayContainer {
|
||||
|
||||
@Param({ "1000", "10000", "100000", "1000000" })
|
||||
int arraySize;
|
||||
|
||||
// initial unsorted array
|
||||
int[] unsortedArray;
|
||||
|
||||
//cloned array to sort
|
||||
int[] arrayToSort;
|
||||
|
||||
@Setup(Level.Trial)
|
||||
public void createUnSortedArray() {
|
||||
unsortedArray = new int[arraySize];
|
||||
for (int i = 0; i < arraySize; i++) {
|
||||
unsortedArray[i] = new Random().nextInt(1000);
|
||||
}
|
||||
}
|
||||
|
||||
@Setup(Level.Invocation)
|
||||
public void createUnSortedArrayCopy() {
|
||||
arrayToSort = unsortedArray.clone();
|
||||
}
|
||||
|
||||
int[] getArrayToSort() {
|
||||
return arrayToSort;
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void benchmark_arrays_parallel_sort(ArrayContainer d, Blackhole b) {
|
||||
int[] arr = d.getArrayToSort();
|
||||
Arrays.parallelSort(arr);
|
||||
b.consume(arr);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void benchmark_arrays_sort(ArrayContainer d, Blackhole b) {
|
||||
int[] arr = d.getArrayToSort();
|
||||
Arrays.sort(arr);
|
||||
b.consume(arr);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package com.baeldung.arraysort;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNotSame;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.FixMethodOrder;
|
||||
import org.junit.Test;
|
||||
import org.junit.runners.MethodSorters;
|
||||
|
||||
/**
|
||||
* Time taken by JUnit test cases can be seen in JUnit Runner
|
||||
* @author rchaudhary23
|
||||
*
|
||||
*/
|
||||
|
||||
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
|
||||
public class SortComparisonUnitTest {
|
||||
|
||||
private int[] sizeOfArrays = { 1000, 10000, 100000, 1000000 };
|
||||
|
||||
private int[] _1000_elements_array;
|
||||
private int[] _10000_elements_array;
|
||||
private int[] _100000_elements_array;
|
||||
private int[] _1000000_elements_array;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
|
||||
_1000_elements_array = new int[sizeOfArrays[0]];
|
||||
_10000_elements_array = new int[sizeOfArrays[1]];
|
||||
_100000_elements_array = new int[sizeOfArrays[2]];
|
||||
_1000000_elements_array = new int[sizeOfArrays[3]];
|
||||
|
||||
Random random = new Random();
|
||||
for (int i = 0; i < sizeOfArrays[0]; i++) {
|
||||
_1000_elements_array[i] = random.nextInt(sizeOfArrays[0]) + random.nextInt(sizeOfArrays[0]);
|
||||
}
|
||||
|
||||
for (int i = 0; i < sizeOfArrays[1]; i++) {
|
||||
_10000_elements_array[i] = random.nextInt(sizeOfArrays[1]) + random.nextInt(sizeOfArrays[1]);
|
||||
}
|
||||
|
||||
for (int i = 0; i < sizeOfArrays[2]; i++) {
|
||||
_100000_elements_array[i] = random.nextInt(sizeOfArrays[2]) + random.nextInt(sizeOfArrays[2]);
|
||||
}
|
||||
|
||||
for (int i = 0; i < sizeOfArrays[3]; i++) {
|
||||
_1000000_elements_array[i] = random.nextInt(sizeOfArrays[3]) + random.nextInt(sizeOfArrays[3]);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayOfIntegers_whenUsingArraysSortMethod_thenSortFullArrayInAscendingOrder() {
|
||||
|
||||
int[] array = { 10, 4, 6, 2, 1, 9, 7, 8, 3, 5 };
|
||||
int[] expected = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
|
||||
|
||||
Arrays.sort(array);
|
||||
|
||||
assertArrayEquals(expected, array);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayOfIntegers_whenUsingArraysSortMethodWithRange_thenSortRangeOfArrayInAscendingOrder() {
|
||||
int[] array = { 10, 4, 6, 2, 1, 9, 7, 8, 3, 5 };
|
||||
int[] expected = { 10, 4, 1, 2, 6, 7, 8, 9, 3, 5 };
|
||||
|
||||
Arrays.sort(array, 2, 8);
|
||||
|
||||
assertArrayEquals(expected, array);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayOfIntegers_whenUsingArraysParallelSortMethod_thenSortFullArrayInAscendingOrder() {
|
||||
int[] array = { 10, 4, 6, 2, 1, 9, 7, 8, 3, 5 };
|
||||
int[] expected = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
|
||||
|
||||
Arrays.parallelSort(array);
|
||||
|
||||
assertArrayEquals(expected, array);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayOfIntegers_whenUsingArraysParallelSortMethodWithRange_thenSortRangeOfArrayInAscendingOrder() {
|
||||
int[] array = { 10, 4, 6, 2, 1, 9, 7, 8, 3, 5 };
|
||||
int[] expected = { 10, 4, 1, 2, 6, 7, 8, 9, 3, 5 };
|
||||
|
||||
Arrays.parallelSort(array, 2, 8);
|
||||
|
||||
assertArrayEquals(expected, array);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntegerArrayOf1000Elements_whenUsingArraysSortMethod_thenSortFullArrayInAscendingOrder() {
|
||||
int[] sequentialDataSet = Arrays.copyOf(_1000_elements_array, _1000_elements_array.length);
|
||||
Arrays.sort(sequentialDataSet);
|
||||
|
||||
assertNotNull(sequentialDataSet);
|
||||
assertNotSame(Arrays.copyOf(_1000_elements_array, _1000_elements_array.length), sequentialDataSet);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntegerArrayOf1000Elements_whenUsingArraysParallelSortMethod_thenSortFullArrayInAscendingOrder() {
|
||||
int[] parallelDataSet = Arrays.copyOf(_1000_elements_array, _1000_elements_array.length);
|
||||
Arrays.parallelSort(parallelDataSet);
|
||||
|
||||
assertNotNull(parallelDataSet);
|
||||
assertNotSame(Arrays.copyOf(_1000_elements_array, _1000_elements_array.length), parallelDataSet);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntegerArrayOf10000Elements_whenUsingArraysSortMethod_thenSortFullArrayInAscendingOrder() {
|
||||
int[] sequentialDataSet = Arrays.copyOf(_10000_elements_array, _10000_elements_array.length);
|
||||
Arrays.sort(sequentialDataSet);
|
||||
|
||||
assertNotNull(sequentialDataSet);
|
||||
assertNotSame(Arrays.copyOf(_10000_elements_array, _10000_elements_array.length), sequentialDataSet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntegerArrayOf10000Elements_whenUsingArraysParallelSortMethod_thenSortFullArrayInAscendingOrder() {
|
||||
int[] parallelDataSet = Arrays.copyOf(_10000_elements_array, _10000_elements_array.length);
|
||||
Arrays.parallelSort(parallelDataSet);
|
||||
|
||||
assertNotNull(parallelDataSet);
|
||||
assertNotSame(Arrays.copyOf(_10000_elements_array, _10000_elements_array.length), parallelDataSet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntegerArrayOf100000Elements_whenUsingArraysSortMethod_thenSortFullArrayInAscendingOrder() {
|
||||
int[] sequentialDataSet = Arrays.copyOf(_100000_elements_array, _100000_elements_array.length);
|
||||
Arrays.sort(sequentialDataSet);
|
||||
|
||||
assertNotNull(sequentialDataSet);
|
||||
assertNotSame(Arrays.copyOf(_100000_elements_array, _100000_elements_array.length), sequentialDataSet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntegerArrayOf100000Elements_whenUsingArraysParallelSortMethod_thenSortFullArrayInAscendingOrder() {
|
||||
int[] parallelDataSet = Arrays.copyOf(_100000_elements_array, _100000_elements_array.length);
|
||||
Arrays.parallelSort(parallelDataSet);
|
||||
|
||||
assertNotNull(parallelDataSet);
|
||||
assertNotSame(Arrays.copyOf(_100000_elements_array, _100000_elements_array.length), parallelDataSet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntegerArrayOf1000000Elements_whenUsingArraysSortMethod_thenSortFullArrayInAscendingOrder() {
|
||||
int[] sequentialDataSet = Arrays.copyOf(_1000000_elements_array, _1000000_elements_array.length);
|
||||
Arrays.sort(sequentialDataSet);
|
||||
|
||||
assertNotNull(sequentialDataSet);
|
||||
assertNotSame(Arrays.copyOf(_1000000_elements_array, _1000000_elements_array.length), sequentialDataSet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntegerArrayOf1000000Elements_whenUsingArraysParallelSortMethod_thenSortFullArrayInAscendingOrder() {
|
||||
int[] parallelDataSet = Arrays.copyOf(_1000000_elements_array, _1000000_elements_array.length);
|
||||
Arrays.parallelSort(parallelDataSet);
|
||||
|
||||
assertNotNull(parallelDataSet);
|
||||
assertNotSame(Arrays.copyOf(_1000000_elements_array, _1000000_elements_array.length), parallelDataSet);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
sizeOfArrays = null;
|
||||
_1000_elements_array = null;
|
||||
_10000_elements_array = null;
|
||||
_100000_elements_array = null;
|
||||
_1000000_elements_array = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -75,7 +75,7 @@
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
<classpathPrefix>libs/</classpathPrefix>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
@@ -94,7 +94,7 @@
|
||||
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
<descriptorRefs>
|
||||
@@ -118,7 +118,7 @@
|
||||
<shadedArtifactAttached>true</shadedArtifactAttached>
|
||||
<transformers>
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
</configuration>
|
||||
@@ -133,7 +133,7 @@
|
||||
<executions>
|
||||
<execution>
|
||||
<configuration>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<attachToBuild>true</attachToBuild>
|
||||
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
|
||||
</configuration>
|
||||
@@ -155,7 +155,7 @@
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>spring-boot</classifier>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
@@ -183,8 +183,8 @@
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
<version>${maven-javadoc-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<source>${source.version}</source>
|
||||
<target>${target.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
@@ -373,6 +373,8 @@
|
||||
<maven-shade-plugin.version>3.1.1</maven-shade-plugin.version>
|
||||
<spring-boot-maven-plugin.version>2.0.3.RELEASE</spring-boot-maven-plugin.version>
|
||||
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
|
||||
<source.version>1.8</source.version>
|
||||
<target.version>1.8</target.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.java.collections;
|
||||
package com.baeldung.collections;
|
||||
|
||||
import com.google.common.collect.Sets;
|
||||
import org.junit.Before;
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.java.collections;
|
||||
package com.baeldung.collections;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import org.apache.commons.collections4.ListUtils;
|
||||
@@ -3,13 +3,13 @@
|
||||
This module contains articles about the Java List collection
|
||||
|
||||
### Relevant Articles:
|
||||
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
|
||||
- [Check If Two Lists are Equal in Java](https://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
|
||||
- [Java 8 Streams: Find Items From One List Based On Values From Another List](https://www.baeldung.com/java-streams-find-list-items)
|
||||
- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist)
|
||||
- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
|
||||
- [A Guide to the Java LinkedList](https://www.baeldung.com/java-linkedlist)
|
||||
- [Java List UnsupportedOperationException](https://www.baeldung.com/java-list-unsupported-operation-exception)
|
||||
- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
|
||||
- [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list)
|
||||
- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)
|
||||
- [Flattening Nested Collections in Java](https://www.baeldung.com/java-flatten-nested-collections)
|
||||
- [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection)
|
||||
- [Searching for a String in an ArrayList](https://www.baeldung.com/java-search-string-arraylist)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-collections-list)[[Next -->]](/core-java-modules/core-java-collections-list-3)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.java.lists;
|
||||
package com.baeldung.java.list;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.java.lists;
|
||||
package com.baeldung.java.list;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.java.lists;
|
||||
package com.baeldung.java.list;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
### Relevant Articles:
|
||||
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
|
||||
@@ -24,11 +24,21 @@ public class DuplicatesCounter {
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
public static <T> Map<T, Long> countByClassicalLoopWithMapCompute(List<T> inputList) {
|
||||
public static <T> Map<T, Long> countByForEachLoopWithGetOrDefault(List<T> inputList) {
|
||||
Map<T, Long> resultMap = new HashMap<>();
|
||||
for (T element : inputList) {
|
||||
resultMap.compute(element, (k, v) -> v == null ? 1 : v + 1);
|
||||
}
|
||||
inputList.forEach(e -> resultMap.put(e, resultMap.getOrDefault(e, 0L) + 1L));
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
public static <T> Map<T, Long> countByForEachLoopWithMapCompute(List<T> inputList) {
|
||||
Map<T, Long> resultMap = new HashMap<>();
|
||||
inputList.forEach(e -> resultMap.compute(e, (k, v) -> v == null ? 1L : v + 1L));
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
public static <T> Map<T, Long> countByForEachLoopWithMapMerge(List<T> inputList) {
|
||||
Map<T, Long> resultMap = new HashMap<>();
|
||||
inputList.forEach(e -> resultMap.merge(e, 1L, Long::sum));
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ import static org.assertj.core.data.MapEntry.entry;
|
||||
|
||||
class DuplicatesCounterUnitTest {
|
||||
|
||||
|
||||
private static List<String> INPUT_LIST = Lists.list(
|
||||
"expect1",
|
||||
"expect2", "expect2",
|
||||
@@ -24,10 +23,21 @@ class DuplicatesCounterUnitTest {
|
||||
verifyResult(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInput_whenCountByForEachLoopWithGetOrDefault_thenGetResultMap() {
|
||||
Map<String, Long> result = DuplicatesCounter.countByForEachLoopWithGetOrDefault(INPUT_LIST);
|
||||
verifyResult(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInput_whenCountByClassicalLoopWithMapCompute_thenGetResultMap() {
|
||||
Map<String, Long> result = DuplicatesCounter.countByClassicalLoopWithMapCompute(INPUT_LIST);
|
||||
void givenInput_whenCountByForEachLoopWithMapCompute_thenGetResultMap() {
|
||||
Map<String, Long> result = DuplicatesCounter.countByForEachLoopWithMapCompute(INPUT_LIST);
|
||||
verifyResult(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInput_whenCountByForEachLoopWithMapMerge_thenGetResultMap() {
|
||||
Map<String, Long> result = DuplicatesCounter.countByForEachLoopWithMapMerge(INPUT_LIST);
|
||||
verifyResult(result);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.java.collections;
|
||||
package com.baeldung.collections;
|
||||
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.junit.Assert.assertThat;
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.baeldung;
|
||||
package com.baeldung.list.random;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import org.junit.Test;
|
||||
@@ -23,6 +23,37 @@
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.jcabi</groupId>
|
||||
<artifactId>jcabi-aspects</artifactId>
|
||||
<version>${jcabi-aspects.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.aspectj</groupId>
|
||||
<artifactId>aspectjrt</artifactId>
|
||||
<version>${aspectjrt.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.cactoos</groupId>
|
||||
<artifactId>cactoos</artifactId>
|
||||
<version>${cactoos.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.ea.async</groupId>
|
||||
<artifactId>ea-async</artifactId>
|
||||
<version>${ea-async.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -36,6 +67,30 @@
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>com.jcabi</groupId>
|
||||
<artifactId>jcabi-maven-plugin</artifactId>
|
||||
<version>${jcabi-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>ajc</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.aspectj</groupId>
|
||||
<artifactId>aspectjtools</artifactId>
|
||||
<version>${aspectjtools.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.aspectj</groupId>
|
||||
<artifactId>aspectjweaver</artifactId>
|
||||
<version>${aspectjweaver.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
</plugins>
|
||||
<resources>
|
||||
<resource>
|
||||
@@ -49,6 +104,14 @@
|
||||
<assertj.version>3.14.0</assertj.version>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<jcabi-aspects.version>0.22.6</jcabi-aspects.version>
|
||||
<aspectjrt.version>1.9.5</aspectjrt.version>
|
||||
<guava.version>28.2-jre</guava.version>
|
||||
<cactoos.version>0.43</cactoos.version>
|
||||
<ea-async.version>1.2.3</ea-async.version>
|
||||
<jcabi-maven-plugin.version>0.14.1</jcabi-maven-plugin.version>
|
||||
<aspectjtools.version>1.9.1</aspectjtools.version>
|
||||
<aspectjweaver.version>1.9.1</aspectjweaver.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.baeldung.async;
|
||||
|
||||
import static com.ea.async.Async.await;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
import com.ea.async.Async;
|
||||
|
||||
public class EAAsyncExample {
|
||||
|
||||
static {
|
||||
Async.init();
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
usingCompletableFuture();
|
||||
usingAsyncAwait();
|
||||
}
|
||||
|
||||
public static void usingCompletableFuture() throws InterruptedException, ExecutionException, Exception {
|
||||
CompletableFuture<Void> completableFuture = hello()
|
||||
.thenComposeAsync(hello -> mergeWorld(hello))
|
||||
.thenAcceptAsync(helloWorld -> print(helloWorld))
|
||||
.exceptionally( throwable -> {
|
||||
System.out.println(throwable.getCause());
|
||||
return null;
|
||||
});
|
||||
completableFuture.get();
|
||||
}
|
||||
|
||||
public static CompletableFuture<String> hello() {
|
||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
|
||||
return completableFuture;
|
||||
}
|
||||
|
||||
public static CompletableFuture<String> mergeWorld(String s) {
|
||||
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
|
||||
return s + " World!";
|
||||
});
|
||||
return completableFuture;
|
||||
}
|
||||
|
||||
public static void print(String str) {
|
||||
CompletableFuture.runAsync(() -> System.out.println(str));
|
||||
}
|
||||
|
||||
private static void usingAsyncAwait() {
|
||||
try {
|
||||
String hello = await(hello());
|
||||
String helloWorld = await(mergeWorld(hello));
|
||||
await(CompletableFuture.runAsync(() -> print(helloWorld)));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package com.baeldung.async;
|
||||
|
||||
import static com.ea.async.Async.await;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import com.google.common.util.concurrent.AsyncCallable;
|
||||
import com.google.common.util.concurrent.Callables;
|
||||
import com.google.common.util.concurrent.Futures;
|
||||
import com.google.common.util.concurrent.ListenableFuture;
|
||||
import com.google.common.util.concurrent.ListeningExecutorService;
|
||||
import com.google.common.util.concurrent.MoreExecutors;
|
||||
import com.jcabi.aspects.Async;
|
||||
import com.jcabi.aspects.Loggable;
|
||||
|
||||
public class JavaAsync {
|
||||
|
||||
static {
|
||||
com.ea.async.Async.init();
|
||||
}
|
||||
|
||||
private static final ExecutorService threadpool = Executors.newCachedThreadPool();
|
||||
|
||||
public static void main (String[] args) throws InterruptedException, ExecutionException {
|
||||
int number = 20;
|
||||
|
||||
//Thread Example
|
||||
factorialUsingThread(number).start();
|
||||
|
||||
//FutureTask Example
|
||||
Future<Long> futureTask = factorialUsingFutureTask(number);
|
||||
System.out.println("Factorial of " + number + " is: " + futureTask.get());
|
||||
|
||||
// CompletableFuture Example
|
||||
Future<Long> completableFuture = factorialUsingCompletableFuture(number);
|
||||
System.out.println("Factorial of " + number + " is: " + completableFuture.get());
|
||||
|
||||
// EA Async example
|
||||
System.out.println("Factorial of " + number + " is: " + factorialUsingEAAsync(number));
|
||||
|
||||
// cactoos async example
|
||||
Future<Long> asyncFuture = factorialUsingCactoos(number);
|
||||
System.out.println("Factorial of " + number + " is: " + asyncFuture.get());
|
||||
|
||||
// Guava example
|
||||
ListenableFuture<Long> guavaFuture = factorialUsingGuavaServiceSubmit(number);
|
||||
System.out.println("Factorial of " + number + " is: " + guavaFuture.get());
|
||||
|
||||
ListenableFuture<Long> guavaFutures = factorialUsingGuavaFutures(number);
|
||||
System.out.println("Factorial of " + number + " is: " + guavaFutures.get());
|
||||
|
||||
// @async jcabi-aspect example
|
||||
Future<Long> aspectFuture = factorialUsingJcabiAspect(number);
|
||||
System.out.println("Factorial of " + number + " is: " + aspectFuture.get());
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds factorial of a number
|
||||
* @param number
|
||||
* @return
|
||||
*/
|
||||
public static long factorial(int number) {
|
||||
long result = 1;
|
||||
for(int i=number;i>0;i--) {
|
||||
result *= i;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds factorial of a number using Thread
|
||||
* @param number
|
||||
* @return
|
||||
*/
|
||||
@Loggable
|
||||
public static Thread factorialUsingThread(int number) {
|
||||
Thread newThread = new Thread(() -> {
|
||||
System.out.println("Factorial of " + number + " is: " + factorial(number));
|
||||
});
|
||||
|
||||
return newThread;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds factorial of a number using FutureTask
|
||||
* @param number
|
||||
* @return
|
||||
*/
|
||||
@Loggable
|
||||
public static Future<Long> factorialUsingFutureTask(int number) {
|
||||
Future<Long> futureTask = threadpool.submit(() -> factorial(number));
|
||||
|
||||
while (!futureTask.isDone()) {
|
||||
System.out.println("FutureTask is not finished yet...");
|
||||
}
|
||||
|
||||
return futureTask;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds factorial of a number using CompletableFuture
|
||||
* @param number
|
||||
* @return
|
||||
*/
|
||||
@Loggable
|
||||
public static Future<Long> factorialUsingCompletableFuture(int number) {
|
||||
CompletableFuture<Long> completableFuture = CompletableFuture.supplyAsync(() -> factorial(number));
|
||||
return completableFuture;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds factorial of a number using EA Async
|
||||
* @param number
|
||||
* @return
|
||||
*/
|
||||
@Loggable
|
||||
public static long factorialUsingEAAsync(int number) {
|
||||
CompletableFuture<Long> completableFuture = CompletableFuture.supplyAsync(() -> factorial(number));
|
||||
long result = await(completableFuture);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds factorial of a number using Async of Cactoos
|
||||
* @param number
|
||||
* @return
|
||||
* @throws InterruptedException
|
||||
* @throws ExecutionException
|
||||
*/
|
||||
@Loggable
|
||||
public static Future<Long> factorialUsingCactoos(int number) throws InterruptedException, ExecutionException {
|
||||
org.cactoos.func.Async<Integer, Long> asyncFunction = new org.cactoos.func.Async<Integer, Long>(input -> factorial(input));
|
||||
Future<Long> asyncFuture = asyncFunction.apply(number);
|
||||
return asyncFuture;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds factorial of a number using Guava's ListeningExecutorService.submit()
|
||||
* @param number
|
||||
* @return
|
||||
*/
|
||||
@Loggable
|
||||
public static ListenableFuture<Long> factorialUsingGuavaServiceSubmit(int number) {
|
||||
ListeningExecutorService service = MoreExecutors.listeningDecorator(threadpool);
|
||||
ListenableFuture<Long> factorialFuture = (ListenableFuture<Long>) service.submit(()-> factorial(number));
|
||||
return factorialFuture;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds factorial of a number using Guava's Futures.submitAsync()
|
||||
* @param number
|
||||
* @return
|
||||
*/
|
||||
@Loggable
|
||||
public static ListenableFuture<Long> factorialUsingGuavaFutures(int number) {
|
||||
ListeningExecutorService service = MoreExecutors.listeningDecorator(threadpool);
|
||||
AsyncCallable<Long> asyncCallable = Callables.asAsyncCallable(new Callable<Long>() {
|
||||
public Long call() {
|
||||
return factorial(number);
|
||||
}
|
||||
}, service);
|
||||
return Futures.submitAsync(asyncCallable, service);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds factorial of a number using @Async of jcabi-aspects
|
||||
* @param number
|
||||
* @return
|
||||
*/
|
||||
@Async
|
||||
@Loggable
|
||||
public static Future<Long> factorialUsingJcabiAspect(int number) {
|
||||
Future<Long> factorialFuture = CompletableFuture.supplyAsync(() -> factorial(number));
|
||||
return factorialFuture;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.baeldung.workstealing;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ForkJoinTask;
|
||||
import java.util.concurrent.RecursiveAction;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class PrimeNumbers extends RecursiveAction {
|
||||
|
||||
private int lowerBound;
|
||||
private int upperBound;
|
||||
private int granularity;
|
||||
static final List<Integer> GRANULARITIES
|
||||
= Arrays.asList(1, 10, 100, 1000, 10000);
|
||||
private AtomicInteger noOfPrimeNumbers;
|
||||
|
||||
PrimeNumbers(int lowerBound, int upperBound, int granularity, AtomicInteger noOfPrimeNumbers) {
|
||||
this.lowerBound = lowerBound;
|
||||
this.upperBound = upperBound;
|
||||
this.granularity = granularity;
|
||||
this.noOfPrimeNumbers = noOfPrimeNumbers;
|
||||
}
|
||||
|
||||
PrimeNumbers(int upperBound) {
|
||||
this(1, upperBound, 100, new AtomicInteger(0));
|
||||
}
|
||||
|
||||
private PrimeNumbers(int lowerBound, int upperBound, AtomicInteger noOfPrimeNumbers) {
|
||||
this(lowerBound, upperBound, 100, noOfPrimeNumbers);
|
||||
}
|
||||
|
||||
private List<PrimeNumbers> subTasks() {
|
||||
List<PrimeNumbers> subTasks = new ArrayList<>();
|
||||
|
||||
for (int i = 1; i <= this.upperBound / granularity; i++) {
|
||||
int upper = i * granularity;
|
||||
int lower = (upper - granularity) + 1;
|
||||
subTasks.add(new PrimeNumbers(lower, upper, noOfPrimeNumbers));
|
||||
}
|
||||
return subTasks;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void compute() {
|
||||
if (((upperBound + 1) - lowerBound) > granularity) {
|
||||
ForkJoinTask.invokeAll(subTasks());
|
||||
} else {
|
||||
findPrimeNumbers();
|
||||
}
|
||||
}
|
||||
|
||||
void findPrimeNumbers() {
|
||||
for (int num = lowerBound; num <= upperBound; num++) {
|
||||
if (isPrime(num)) {
|
||||
noOfPrimeNumbers.getAndIncrement();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isPrime(int number) {
|
||||
if (number == 2) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (number == 1 || number % 2 == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
int noOfNaturalNumbers = 0;
|
||||
|
||||
for (int i = 1; i <= number; i++) {
|
||||
if (number % i == 0) {
|
||||
noOfNaturalNumbers++;
|
||||
}
|
||||
}
|
||||
|
||||
return noOfNaturalNumbers == 2;
|
||||
}
|
||||
|
||||
public int noOfPrimeNumbers() {
|
||||
return noOfPrimeNumbers.intValue();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.baeldung.rejection;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@@ -28,24 +29,26 @@ public class SaturationPolicyUnitTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Ignore
|
||||
@Test
|
||||
public void givenAbortPolicy_WhenSaturated_ThenShouldThrowRejectedExecutionException() {
|
||||
executor = new ThreadPoolExecutor(1, 1, 0, MILLISECONDS, new SynchronousQueue<>(), new AbortPolicy());
|
||||
executor.execute(() -> waitFor(100));
|
||||
executor.execute(() -> waitFor(250));
|
||||
|
||||
assertThatThrownBy(() -> executor.execute(() -> System.out.println("Will be rejected"))).isInstanceOf(RejectedExecutionException.class);
|
||||
}
|
||||
|
||||
@Ignore
|
||||
@Test
|
||||
public void givenCallerRunsPolicy_WhenSaturated_ThenTheCallerThreadRunsTheTask() {
|
||||
executor = new ThreadPoolExecutor(1, 1, 0, MILLISECONDS, new SynchronousQueue<>(), new CallerRunsPolicy());
|
||||
executor.execute(() -> waitFor(100));
|
||||
executor.execute(() -> waitFor(250));
|
||||
|
||||
long startTime = System.nanoTime();
|
||||
executor.execute(() -> waitFor(100));
|
||||
double blockedDuration = (System.nanoTime() - startTime) / 1_000_000.0;
|
||||
long startTime = System.currentTimeMillis();
|
||||
executor.execute(() -> waitFor(500));
|
||||
long blockedDuration = System.currentTimeMillis() - startTime;
|
||||
|
||||
assertThat(blockedDuration).isGreaterThanOrEqualTo(100);
|
||||
assertThat(blockedDuration).isGreaterThanOrEqualTo(500);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package com.baeldung.workstealing;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.RunnerException;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ForkJoinPool;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
public class PrimeNumbersUnitTest {
|
||||
|
||||
private static Logger logger = Logger.getAnonymousLogger();
|
||||
|
||||
@Test
|
||||
public void givenPrimesCalculated_whenUsingPoolsAndOneThread_thenOneThreadSlowest() {
|
||||
Options opt = new OptionsBuilder()
|
||||
.include(Benchmarker.class.getSimpleName())
|
||||
.forks(1)
|
||||
.build();
|
||||
|
||||
try {
|
||||
new Runner(opt).run();
|
||||
} catch (RunnerException e) {
|
||||
fail();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNewWorkStealingPool_whenGettingPrimes_thenStealCountChanges() {
|
||||
StringBuilder info = new StringBuilder();
|
||||
|
||||
for (int granularity : PrimeNumbers.GRANULARITIES) {
|
||||
int parallelism = ForkJoinPool.getCommonPoolParallelism();
|
||||
ForkJoinPool pool =
|
||||
(ForkJoinPool) Executors.newWorkStealingPool(parallelism);
|
||||
|
||||
stealCountInfo(info, granularity, pool);
|
||||
}
|
||||
logger.info("\nExecutors.newWorkStealingPool ->" + info.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCommonPool_whenGettingPrimes_thenStealCountChangesSlowly() {
|
||||
StringBuilder info = new StringBuilder();
|
||||
|
||||
for (int granularity : PrimeNumbers.GRANULARITIES) {
|
||||
ForkJoinPool pool = ForkJoinPool.commonPool();
|
||||
stealCountInfo(info, granularity, pool);
|
||||
}
|
||||
logger.info("\nForkJoinPool.commonPool ->" + info.toString());
|
||||
}
|
||||
|
||||
private void stealCountInfo(StringBuilder info, int granularity, ForkJoinPool forkJoinPool) {
|
||||
PrimeNumbers primes = new PrimeNumbers(1, 10000, granularity, new AtomicInteger(0));
|
||||
forkJoinPool.invoke(primes);
|
||||
forkJoinPool.shutdown();
|
||||
|
||||
long steals = forkJoinPool.getStealCount();
|
||||
String output = "\nGranularity: [" + granularity + "], Steals: [" + steals + "]";
|
||||
info.append(output);
|
||||
}
|
||||
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.MILLISECONDS)
|
||||
@State(Scope.Benchmark)
|
||||
@Fork(value = 2, warmups = 1, jvmArgs = {"-Xms2G", "-Xmx2G"})
|
||||
public static class Benchmarker {
|
||||
|
||||
@Benchmark
|
||||
public void singleThread() {
|
||||
PrimeNumbers primes = new PrimeNumbers(10000);
|
||||
primes.findPrimeNumbers(); // get prime numbers using a single thread
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void commonPoolBenchmark() {
|
||||
PrimeNumbers primes = new PrimeNumbers(10000);
|
||||
ForkJoinPool pool = ForkJoinPool.commonPool();
|
||||
pool.invoke(primes);
|
||||
pool.shutdown();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void newWorkStealingPoolBenchmark() {
|
||||
PrimeNumbers primes = new PrimeNumbers(10000);
|
||||
int parallelism = ForkJoinPool.getCommonPoolParallelism();
|
||||
ForkJoinPool stealer = (ForkJoinPool) Executors.newWorkStealingPool(parallelism);
|
||||
stealer.invoke(primes);
|
||||
stealer.shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.java.streams;
|
||||
package com.baeldung.java.stream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
## Java Date/time computations Cookbooks and Examples
|
||||
|
||||
This module contains articles about date and time computations in Java.
|
||||
## Core Date Operations (Part 1)
|
||||
This module contains articles about date operations in Java.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference)
|
||||
@@ -13,3 +12,4 @@ This module contains articles about date and time computations in Java.
|
||||
- [Increment Date in Java](http://www.baeldung.com/java-increment-date)
|
||||
- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date)
|
||||
- [Introduction to Joda-Time](http://www.baeldung.com/joda-time)
|
||||
- [[Next -->]](/core-java-modules/core-java-date-operations-2)
|
||||
@@ -2,9 +2,9 @@
|
||||
<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>
|
||||
<artifactId>core-java-datetime-computations</artifactId>
|
||||
<artifactId>core-java-date-operations-1</artifactId>
|
||||
<version>${project.parent.version}</version>
|
||||
<name>core-java-datetime-computations</name>
|
||||
<name>core-java-date-operations-1</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
@@ -41,7 +41,7 @@
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-datetime-computations</finalName>
|
||||
<finalName>core-java-date-operations-1</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
@@ -1,4 +1,4 @@
|
||||
## Core Date Operations
|
||||
## Core Date Operations (Part 2)
|
||||
This module contains articles about date operations in Java.
|
||||
|
||||
### Relevant Articles:
|
||||
@@ -6,3 +6,4 @@ This module contains articles about date operations in Java.
|
||||
- [Skipping Weekends While Adding Days to LocalDate in Java 8](https://www.baeldung.com/java-localdate-add-days-skip-weekends)
|
||||
- [Checking If Two Java Dates Are on the Same Day](https://www.baeldung.com/java-check-two-dates-on-same-day)
|
||||
- [Converting Java Date to OffsetDateTime](https://www.baeldung.com/java-convert-date-to-offsetdatetime)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-date-operations-1)
|
||||
@@ -3,9 +3,9 @@
|
||||
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>
|
||||
<artifactId>core-java-date-operations</artifactId>
|
||||
<artifactId>core-java-date-operations-2</artifactId>
|
||||
<version>${project.parent.version}</version>
|
||||
<name>core-java-date-operations</name>
|
||||
<name>core-java-date-operations-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
@@ -31,11 +31,18 @@
|
||||
<artifactId>hirondelle-date4j</artifactId>
|
||||
<version>${hirondelle-date4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<joda-time.version>2.10</joda-time.version>
|
||||
<hirondelle-date4j.version>1.5.1</hirondelle-date4j.version>
|
||||
<assertj.version>3.14.0</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -1,55 +1,65 @@
|
||||
package com.baeldung.date.comparison;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.apache.commons.lang3.time.DateUtils;
|
||||
|
||||
import hirondelle.date4j.DateTime;
|
||||
|
||||
public class DateComparisonUtils {
|
||||
|
||||
public static boolean isSameDayUsingLocalDate(Date date1, Date date2) {
|
||||
LocalDate localDate1 = date1.toInstant()
|
||||
.atZone(ZoneId.systemDefault())
|
||||
.toLocalDate();
|
||||
LocalDate localDate2 = date2.toInstant()
|
||||
.atZone(ZoneId.systemDefault())
|
||||
.toLocalDate();
|
||||
return localDate1.isEqual(localDate2);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingSimpleDateFormat(Date date1, Date date2) {
|
||||
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
|
||||
return fmt.format(date1)
|
||||
.equals(fmt.format(date2));
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingCalendar(Date date1, Date date2) {
|
||||
Calendar calendar1 = Calendar.getInstance();
|
||||
calendar1.setTime(date1);
|
||||
Calendar calendar2 = Calendar.getInstance();
|
||||
calendar2.setTime(date2);
|
||||
return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR) && calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH) && calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingApacheCommons(Date date1, Date date2) {
|
||||
return DateUtils.isSameDay(date1, date2);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingJoda(Date date1, Date date2) {
|
||||
org.joda.time.LocalDate localDate1 = new org.joda.time.LocalDate(date1);
|
||||
org.joda.time.LocalDate localDate2 = new org.joda.time.LocalDate(date2);
|
||||
return localDate1.equals(localDate2);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingDate4j(Date date1, Date date2) {
|
||||
DateTime dateObject1 = DateTime.forInstant(date1.getTime(), TimeZone.getDefault());
|
||||
DateTime dateObject2 = DateTime.forInstant(date2.getTime(), TimeZone.getDefault());
|
||||
return dateObject1.isSameDayAs(dateObject2);
|
||||
}
|
||||
}
|
||||
package com.baeldung.date.comparison;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.apache.commons.lang3.time.DateUtils;
|
||||
|
||||
import hirondelle.date4j.DateTime;
|
||||
|
||||
public class DateComparisonUtils {
|
||||
|
||||
public static boolean isSameDayUsingLocalDate(Date date1, Date date2) {
|
||||
LocalDate localDate1 = date1.toInstant()
|
||||
.atZone(ZoneId.systemDefault())
|
||||
.toLocalDate();
|
||||
LocalDate localDate2 = date2.toInstant()
|
||||
.atZone(ZoneId.systemDefault())
|
||||
.toLocalDate();
|
||||
return localDate1.isEqual(localDate2);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingInstant(Date date1, Date date2) {
|
||||
Instant instant1 = date1.toInstant()
|
||||
.truncatedTo(ChronoUnit.DAYS);
|
||||
Instant instant2 = date2.toInstant()
|
||||
.truncatedTo(ChronoUnit.DAYS);
|
||||
return instant1.equals(instant2);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingSimpleDateFormat(Date date1, Date date2) {
|
||||
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
|
||||
return fmt.format(date1)
|
||||
.equals(fmt.format(date2));
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingCalendar(Date date1, Date date2) {
|
||||
Calendar calendar1 = Calendar.getInstance();
|
||||
calendar1.setTime(date1);
|
||||
Calendar calendar2 = Calendar.getInstance();
|
||||
calendar2.setTime(date2);
|
||||
return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR) && calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH) && calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingApacheCommons(Date date1, Date date2) {
|
||||
return DateUtils.isSameDay(date1, date2);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingJoda(Date date1, Date date2) {
|
||||
org.joda.time.LocalDate localDate1 = new org.joda.time.LocalDate(date1);
|
||||
org.joda.time.LocalDate localDate2 = new org.joda.time.LocalDate(date2);
|
||||
return localDate1.equals(localDate2);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingDate4j(Date date1, Date date2) {
|
||||
DateTime dateObject1 = DateTime.forInstant(date1.getTime(), TimeZone.getDefault());
|
||||
DateTime dateObject2 = DateTime.forInstant(date2.getTime(), TimeZone.getDefault());
|
||||
return dateObject1.isSameDayAs(dateObject2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.timer;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.TimerTask;
|
||||
|
||||
public class DatabaseMigrationTask extends TimerTask {
|
||||
private List<String> oldDatabase;
|
||||
private List<String> newDatabase;
|
||||
|
||||
public DatabaseMigrationTask(List<String> oldDatabase, List<String> newDatabase) {
|
||||
this.oldDatabase = oldDatabase;
|
||||
this.newDatabase = newDatabase;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
newDatabase.addAll(oldDatabase);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.timer;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.TimerTask;
|
||||
|
||||
public class NewsletterTask extends TimerTask {
|
||||
@Override
|
||||
public void run() {
|
||||
System.out.println("Email sent at: "
|
||||
+ LocalDateTime.ofInstant(Instant.ofEpochMilli(scheduledExecutionTime()), ZoneId.systemDefault()));
|
||||
}
|
||||
}
|
||||
@@ -1,53 +1,57 @@
|
||||
package com.baeldung.date.comparison;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class DateComparisonUtilsUnitTest {
|
||||
|
||||
private Date day1Morning = toDate(LocalDateTime.of(2019, 10, 19, 6, 30, 40));
|
||||
private Date day1Evening = toDate(LocalDateTime.of(2019, 10, 19, 18, 30, 50));
|
||||
private Date day2Morning = toDate(LocalDateTime.of(2019, 10, 20, 6, 30, 50));
|
||||
|
||||
private Date toDate(LocalDateTime localDateTime) {
|
||||
return Date.from(localDateTime.atZone(ZoneId.systemDefault())
|
||||
.toInstant());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDatesWithDifferentTime_whenIsSameDay_thenReturnsTrue() {
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingLocalDate(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingCalendar(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingApacheCommons(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingJoda(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingDate4j(day1Morning, day1Evening));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDates_whenIsDifferentDay_thenReturnsFalse() {
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingLocalDate(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingLocalDate(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingCalendar(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingCalendar(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingApacheCommons(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingApacheCommons(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingJoda(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingJoda(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingDate4j(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingDate4j(day1Evening, day2Morning));
|
||||
}
|
||||
}
|
||||
package com.baeldung.date.comparison;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class DateComparisonUtilsUnitTest {
|
||||
|
||||
private Date day1Morning = toDate(LocalDateTime.of(2019, 10, 19, 6, 30, 40));
|
||||
private Date day1Evening = toDate(LocalDateTime.of(2019, 10, 19, 18, 30, 50));
|
||||
private Date day2Morning = toDate(LocalDateTime.of(2019, 10, 20, 6, 30, 50));
|
||||
|
||||
private Date toDate(LocalDateTime localDateTime) {
|
||||
return Date.from(localDateTime.atZone(ZoneId.systemDefault())
|
||||
.toInstant());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDatesWithDifferentTime_whenIsSameDay_thenReturnsTrue() {
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingLocalDate(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingInstant(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingCalendar(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingApacheCommons(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingJoda(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingDate4j(day1Morning, day1Evening));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDates_whenIsDifferentDay_thenReturnsFalse() {
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingLocalDate(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingLocalDate(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingInstant(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingInstant(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingCalendar(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingCalendar(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingApacheCommons(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingApacheCommons(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingJoda(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingJoda(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingDate4j(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingDate4j(day1Evening, day2Morning));
|
||||
}
|
||||
}
|
||||
@@ -9,12 +9,6 @@ import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class DateUtilsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTimeMillis_thenDateIsReturned() {
|
||||
Date now = DateUtils.getNow();
|
||||
assertEquals(DateUtils.getDate(now.getTime()), now);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateAndPattern_thenDateIsCorrectlyReturned() throws ParseException {
|
||||
long milliseconds = new Date(2020 - 1900, 0, 1).getTime();
|
||||
@@ -9,11 +9,6 @@ import org.junit.Test;
|
||||
|
||||
public class DateUtilsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenCurrentDate_thenTodayIsReturned() {
|
||||
assertEquals(DateUtils.getNow().toLocalDate(), LocalDate.now());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void givenDateAsString_whenPatternIsNotRespected_thenExceptionIsThrown() {
|
||||
DateUtils.getDate("2020 01 01");
|
||||
@@ -1,22 +1,13 @@
|
||||
package com.baeldung.datetime.sql;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.datetime.sql.TimestampUtils;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.util.Date;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class TimestampUtilsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenCurrentTimestamp_thenNowIsReturned() {
|
||||
assertEquals(TimestampUtils.getNow()
|
||||
.getTime(), new Date().getTime());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void givenTimestampAsString_whenPatternIsNotRespected_thenExceptionIsThrown() {
|
||||
TimestampUtils.getTimestamp("2020/01/01 10:11-12");
|
||||
@@ -1,9 +1,8 @@
|
||||
package com.baeldung.timezone;
|
||||
package com.baeldung.jvmtimezone;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
@@ -13,9 +12,7 @@ public class ModifyDefaultTimezoneUnitTest {
|
||||
@Test
|
||||
public void givenDefaultTimezoneSet_thenDateTimezoneIsCorrect() {
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("Portugal"));
|
||||
Date date = new Date();
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
assertEquals(calendar.getTimeZone(), TimeZone.getTimeZone("Portugal"));
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.timezone;
|
||||
package com.baeldung.jvmtimezone;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
@@ -14,7 +14,7 @@ public class ModifyTimezonePropertyUnitTest {
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
System.setProperty("user.timezone", "IST");
|
||||
System.setProperty("user.timezone", "Asia/Kolkata");
|
||||
TimeZone.setDefault(null);
|
||||
}
|
||||
|
||||
@@ -25,10 +25,8 @@ public class ModifyTimezonePropertyUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTimezonePropertySet_thenDateTimezoneIsCorrect() {
|
||||
Date date = new Date();
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
assertEquals(calendar.getTimeZone(), TimeZone.getTimeZone("IST"));
|
||||
assertEquals(calendar.getTimeZone(), TimeZone.getTimeZone("Asia/Kolkata"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.timer;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.*;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class DatabaseMigrationTaskUnitTest {
|
||||
@Test
|
||||
void givenDatabaseMigrationTask_whenTimerScheduledForNowPlusTwoSeconds_thenDataMigratedAfterTwoSeconds() throws Exception {
|
||||
List<String> oldDatabase = Arrays.asList("Harrison Ford", "Carrie Fisher", "Mark Hamill");
|
||||
List<String> newDatabase = new ArrayList<>();
|
||||
|
||||
LocalDateTime twoSecondsLater = LocalDateTime.now().plusSeconds(2);
|
||||
Date twoSecondsLaterAsDate = Date.from(twoSecondsLater.atZone(ZoneId.systemDefault()).toInstant());
|
||||
|
||||
new Timer().schedule(new DatabaseMigrationTask(oldDatabase, newDatabase), twoSecondsLaterAsDate);
|
||||
|
||||
while (LocalDateTime.now().isBefore(twoSecondsLater)) {
|
||||
assertThat(newDatabase).isEmpty();
|
||||
Thread.sleep(500);
|
||||
}
|
||||
assertThat(newDatabase).containsExactlyElementsOf(oldDatabase);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDatabaseMigrationTask_whenTimerScheduledInTwoSeconds_thenDataMigratedAfterTwoSeconds() throws Exception {
|
||||
List<String> oldDatabase = Arrays.asList("Harrison Ford", "Carrie Fisher", "Mark Hamill");
|
||||
List<String> newDatabase = new ArrayList<>();
|
||||
|
||||
new Timer().schedule(new DatabaseMigrationTask(oldDatabase, newDatabase), 2000);
|
||||
|
||||
LocalDateTime twoSecondsLater = LocalDateTime.now().plusSeconds(2);
|
||||
|
||||
while (LocalDateTime.now().isBefore(twoSecondsLater)) {
|
||||
assertThat(newDatabase).isEmpty();
|
||||
Thread.sleep(500);
|
||||
}
|
||||
assertThat(newDatabase).containsExactlyElementsOf(oldDatabase);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.timer;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Timer;
|
||||
|
||||
class NewsletterTaskUnitTest {
|
||||
private final Timer timer = new Timer();
|
||||
|
||||
@AfterEach
|
||||
void afterEach() {
|
||||
timer.cancel();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNewsletterTask_whenTimerScheduledEachSecondFixedDelay_thenNewsletterSentEachSecond() throws Exception {
|
||||
timer.schedule(new NewsletterTask(), 0, 1000);
|
||||
|
||||
for (int i = 0; i < 3; i++) {
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNewsletterTask_whenTimerScheduledEachSecondFixedRate_thenNewsletterSentEachSecond() throws Exception {
|
||||
timer.scheduleAtFixedRate(new NewsletterTask(), 0, 1000);
|
||||
|
||||
for (int i = 0; i < 3; i++) {
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
72
core-java-modules/core-java-datetime-java8-2/pom.xml
Normal file
72
core-java-modules/core-java-datetime-java8-2/pom.xml
Normal file
@@ -0,0 +1,72 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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>
|
||||
<artifactId>core-java-datetime-java8</artifactId>
|
||||
<version>${project.parent.version}</version>
|
||||
<name>core-java-datetime-java8</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>${joda-time.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-datetime-java8</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
<joda-time.version>2.10</joda-time.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.localdate;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.Month;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
public class LocalDateExample {
|
||||
public LocalDate getCustomDateOne(int year, int month, int dayOfMonth) {
|
||||
return LocalDate.of(year, month, dayOfMonth);
|
||||
}
|
||||
|
||||
public LocalDate getCustomDateTwo(int year, Month month, int dayOfMonth) {
|
||||
return LocalDate.of(year, month, dayOfMonth);
|
||||
}
|
||||
|
||||
public LocalDate getDateFromEpochDay(long epochDay) {
|
||||
return LocalDate.ofEpochDay(epochDay);
|
||||
}
|
||||
|
||||
public LocalDate getDateFromYearAndDayOfYear(int year, int dayOfYear) {
|
||||
return LocalDate.ofYearDay(year, dayOfYear);
|
||||
}
|
||||
|
||||
public LocalDate getDateFromString(String date) {
|
||||
return LocalDate.parse(date);
|
||||
}
|
||||
|
||||
public LocalDate getDateFromStringAndFormatter(String date, String pattern) {
|
||||
return LocalDate.parse(date, DateTimeFormatter.ofPattern(pattern));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.localdate;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.time.Month;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class LocalDateExampleUnitTest {
|
||||
private LocalDateExample date = new LocalDateExample();
|
||||
|
||||
@Test
|
||||
public void givenValues_whenUsingOfMethod_thenLocalDate() {
|
||||
assertEquals("2020-01-08", date.getCustomDateOne(2020, 1, 8));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValuesWithMonthEnum_whenUsingOfMethod_thenLocalDate() {
|
||||
assertEquals("2020-01-08", date.getCustomDateTwo(2020, Month.JANUARY, 8));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValues_whenUsingEpochDay_thenLocalDate() {
|
||||
assertEquals("2020-01-08", date.getDateFromEpochDay(18269));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValues_whenUsingYearDay_thenLocalDate() {
|
||||
assertEquals("2020-01-08", date.getDateFromYearAndDayOfYear(2020, 8));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValues_whenUsingParse_thenLocalDate() {
|
||||
assertEquals("2020-01-08", date.getDateFromString("2020-01-08"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValuesWithFormatter_whenUsingParse_thenLocalDate() {
|
||||
assertEquals("2020-01-08", date.getDateFromStringAndFormatter("8-Jan-2020", "d-MMM-yyyy"));
|
||||
}
|
||||
}
|
||||
@@ -13,12 +13,24 @@
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<description> </description>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<!-- testing -->
|
||||
<assertj-core.version>3.10.0</assertj-core.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.exceptions;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
public class CatchingThrowable {
|
||||
|
||||
class CapacityException extends Exception {
|
||||
CapacityException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
class StorageAPI {
|
||||
|
||||
public void addIDsToStorage(int capacity, Set<String> storage) throws CapacityException {
|
||||
if (capacity < 1) {
|
||||
throw new CapacityException("Capacity of less than 1 is not allowed");
|
||||
}
|
||||
int count = 0;
|
||||
while (count < capacity) {
|
||||
storage.add(UUID.randomUUID().toString());
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
// other methods go here ...
|
||||
}
|
||||
|
||||
public void add(StorageAPI api, int capacity, Set<String> storage) {
|
||||
try {
|
||||
api.addIDsToStorage(capacity, storage);
|
||||
} catch (Throwable throwable) {
|
||||
// do something here
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.exceptions;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.net.UnknownHostException;
|
||||
|
||||
public class UnknownHostExceptionHandling {
|
||||
|
||||
public static int getResponseCode(String hostname) throws IOException {
|
||||
URL url = new URL(hostname.trim());
|
||||
HttpURLConnection con = (HttpURLConnection) url.openConnection();
|
||||
int resCode = -1;
|
||||
try {
|
||||
resCode = con.getResponseCode();
|
||||
} catch (UnknownHostException e){
|
||||
con.disconnect();
|
||||
}
|
||||
return resCode;
|
||||
}
|
||||
|
||||
public static int getResponseCodeUnhandled(String hostname) throws IOException {
|
||||
URL url = new URL(hostname.trim());
|
||||
HttpURLConnection con = (HttpURLConnection) url.openConnection();
|
||||
int resCode = con.getResponseCode();
|
||||
return resCode;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.exceptions;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.UnknownHostException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class UnknownHostExceptionHandlingUnitTest {
|
||||
|
||||
@Test(expected = UnknownHostException.class)
|
||||
public void givenUnknownHost_whenResolve_thenUnknownHostException() throws IOException {
|
||||
UnknownHostExceptionHandling.getResponseCodeUnhandled("http://locaihost");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.baeldung.file;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.*;
|
||||
@@ -73,6 +74,7 @@ public class FileClassUnitTest {
|
||||
assertFalse(writable);
|
||||
}
|
||||
|
||||
@Ignore
|
||||
@Test
|
||||
public void givenWriteOnlyFile_whenCreateNewFile_thenCantReadFile() {
|
||||
File parentDir = makeDir("writeDir");
|
||||
|
||||
@@ -99,7 +99,7 @@
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
<classpathPrefix>libs/</classpathPrefix>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
@@ -118,7 +118,7 @@
|
||||
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
<descriptorRefs>
|
||||
@@ -142,7 +142,7 @@
|
||||
<shadedArtifactAttached>true</shadedArtifactAttached>
|
||||
<transformers>
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
</configuration>
|
||||
@@ -157,7 +157,7 @@
|
||||
<executions>
|
||||
<execution>
|
||||
<configuration>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<attachToBuild>true</attachToBuild>
|
||||
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
|
||||
</configuration>
|
||||
@@ -179,7 +179,7 @@
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>spring-boot</classifier>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<mainClass>com.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
@@ -207,8 +207,8 @@
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
<version>${maven-javadoc-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<source>${source.version}</source>
|
||||
<target>${target.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
@@ -397,6 +397,8 @@
|
||||
<maven-shade-plugin.version>3.1.1</maven-shade-plugin.version>
|
||||
<spring-boot-maven-plugin.version>2.0.3.RELEASE</spring-boot-maven-plugin.version>
|
||||
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
|
||||
<source.version>1.8</source.version>
|
||||
<target.version>1.8</target.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -9,44 +9,54 @@
|
||||
<name>core-java-jndi</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.5.1</version>
|
||||
<version>${jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>${jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>${jupiter.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>5.0.9.RELEASE</version>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>5.0.9.RELEASE</version>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-jdbc</artifactId>
|
||||
<version>5.0.9.RELEASE</version>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>5.0.9.RELEASE</version>
|
||||
<version>${spring.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>1.4.199</version>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
@@ -56,11 +66,19 @@
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<source>${source.version}</source>
|
||||
<target>${target.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<spring.version>5.0.9.RELEASE</spring.version>
|
||||
<h2.version>1.4.199</h2.version>
|
||||
<jupiter.version>5.5.1</jupiter.version>
|
||||
<source.version>1.8</source.version>
|
||||
<target.version>1.8</target.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
package com.baeldung.jndi.exceptions;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import javax.naming.InitialContext;
|
||||
import javax.naming.NameNotFoundException;
|
||||
import javax.naming.NoInitialContextException;
|
||||
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -7,12 +14,6 @@ import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.jndi.JndiTemplate;
|
||||
import org.springframework.mock.jndi.SimpleNamingContextBuilder;
|
||||
|
||||
import javax.naming.InitialContext;
|
||||
import javax.naming.NameNotFoundException;
|
||||
import javax.naming.NoInitialContextException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
public class JndiExceptionsUnitTest {
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
<dependency>
|
||||
<groupId>com.baeldung.servicemodule</groupId>
|
||||
<artifactId>servicemodule</artifactId>
|
||||
<version>1.0</version>
|
||||
<version>${servicemodule.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
@@ -29,4 +29,8 @@
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<servicemodule.version>1.0</servicemodule.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -19,10 +19,10 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.8.0</version>
|
||||
<version>${compiler.plugin.version}</version>
|
||||
<configuration>
|
||||
<source>11</source>
|
||||
<target>11</target>
|
||||
<source>${source.version}</source>
|
||||
<target>${target.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
@@ -31,6 +31,9 @@
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<compiler.plugin.version>3.8.0</compiler.plugin.version>
|
||||
<source.version>11</source.version>
|
||||
<target.version>11</target.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -2,7 +2,6 @@
|
||||
<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.servicemodule</groupId>
|
||||
<artifactId>servicemodule</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
<version>1.0</version>
|
||||
|
||||
<parent>
|
||||
<groupId>decoupling-pattern2</groupId>
|
||||
<artifactId>com.baeldung.decoupling-pattern2</artifactId>
|
||||
<groupId>com.baeldung.decoupling-pattern2</groupId>
|
||||
<artifactId>decoupling-pattern2</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
@@ -17,12 +17,12 @@
|
||||
<dependency>
|
||||
<groupId>com.baeldung.servicemodule</groupId>
|
||||
<artifactId>servicemodule</artifactId>
|
||||
<version>1.0</version>
|
||||
<version>${servicemodule.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baeldung.providermodule</groupId>
|
||||
<artifactId>providermodule</artifactId>
|
||||
<version>1.0</version>
|
||||
<version>${providermodule.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
@@ -34,5 +34,10 @@
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<servicemodule.version>1.0</servicemodule.version>
|
||||
<providermodule.version>1.0</providermodule.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -20,14 +20,20 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.8.0</version>
|
||||
<version>${compiler.plugin.version}</version>
|
||||
<configuration>
|
||||
<source>11</source>
|
||||
<target>11</target>
|
||||
<source>${source.version}</source>
|
||||
<target>${target.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<compiler.plugin.version>3.8.0</compiler.plugin.version>
|
||||
<source.version>11</source.version>
|
||||
<target.version>11</target.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -8,8 +8,8 @@
|
||||
<version>1.0</version>
|
||||
|
||||
<parent>
|
||||
<groupId>decoupling-pattern2</groupId>
|
||||
<artifactId>com.baeldung.decoupling-pattern2</artifactId>
|
||||
<groupId>com.baeldung.decoupling-pattern2</groupId>
|
||||
<artifactId>decoupling-pattern2</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
<dependency>
|
||||
<groupId>com.baeldung.servicemodule</groupId>
|
||||
<artifactId>servicemodule</artifactId>
|
||||
<version>1.0</version>
|
||||
<version>${servicemodule.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
@@ -30,4 +30,9 @@
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<servicemodule.version>1.0</servicemodule.version>
|
||||
</properties>
|
||||
|
||||
|
||||
</project>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user