Merge remote-tracking branch 'upstream/master' into BAEL-3456_Springfox

This commit is contained in:
Anshul BANSAL
2019-11-29 10:48:32 +02:00
413 changed files with 2259 additions and 4146 deletions
@@ -0,0 +1,67 @@
package com.baeldung.algorithms.combinatorics;
import java.util.*;
import static java.util.Collections.swap;
public class Combinatorics {
public static List<List<Integer>> permutations(List<Integer> sequence) {
List<List<Integer>> results = new ArrayList<>();
permutationsInternal(sequence, results, 0);
return results;
}
private static void permutationsInternal(List<Integer> sequence, List<List<Integer>> results, int index) {
if (index == sequence.size() - 1) {
results.add(new ArrayList<>(sequence));
}
for (int i = index; i < sequence.size(); i++) {
swap(sequence, i, index);
permutationsInternal(sequence, results, index + 1);
swap(sequence, i, index);
}
}
public static List<List<Integer>> combinations(List<Integer> inputSet, int k) {
List<List<Integer>> results = new ArrayList<>();
combinationsInternal(inputSet, k, results, new ArrayList<>(), 0);
return results;
}
private static void combinationsInternal(
List<Integer> inputSet, int k, List<List<Integer>> results, ArrayList<Integer> accumulator, int index) {
int leftToAccumulate = k - accumulator.size();
int possibleToAcculumate = inputSet.size() - index;
if (accumulator.size() == k) {
results.add(new ArrayList<>(accumulator));
} else if (leftToAccumulate <= possibleToAcculumate) {
combinationsInternal(inputSet, k, results, accumulator, index + 1);
accumulator.add(inputSet.get(index));
combinationsInternal(inputSet, k, results, accumulator, index + 1);
accumulator.remove(accumulator.size() - 1);
}
}
public static List<List<Character>> powerSet(List<Character> sequence) {
List<List<Character>> results = new ArrayList<>();
powerSetInternal(sequence, results, new ArrayList<>(), 0);
return results;
}
private static void powerSetInternal(
List<Character> set, List<List<Character>> powerSet, List<Character> accumulator, int index) {
if (index == set.size()) {
powerSet.add(new ArrayList<>(accumulator));
} else {
accumulator.add(set.get(index));
powerSetInternal(set, powerSet, accumulator, index + 1);
accumulator.remove(accumulator.size() - 1);
powerSetInternal(set, powerSet, accumulator, index + 1);
}
}
}
@@ -0,0 +1,80 @@
package com.baeldung.algorithms.combinatorics;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
public class CombinatoricsUnitTest {
@Test
public void givenEmptySequence_whenCallingPermutations_ShouldReturnEmptyList() {
List<Integer> sequence = Arrays.asList();
List<List<Integer>> permutations = Combinatorics.permutations(sequence);
assertEquals(0, permutations.size());
}
@Test
public void givenOneElementSequence_whenCallingPermutations_ShouldReturnPermutations() {
List<Integer> sequence = Arrays.asList(1);
List<List<Integer>> permutations = Combinatorics.permutations(sequence);
assertEquals(1, permutations.size());
assertEquals(1, permutations.get(0).size());
assertSame(1, permutations.get(0).get(0));
}
@Test
public void givenFourElementsSequence_whenCallingPermutations_ShouldReturnPermutations() {
List<Integer> sequence = Arrays.asList(1, 2, 3, 4);
List<List<Integer>> permutations = Combinatorics.permutations(sequence);
assertEquals(24, permutations.size());
assertEquals(24, new HashSet<>(permutations).size());
}
@Test
public void givenTwoElements_whenCalling3Combinations_ShouldReturnEmptyList() {
List<Integer> set = Arrays.asList(1, 2);
List<List<Integer>> combinations = Combinatorics.combinations(set, 3);
assertEquals(0, combinations.size());
}
@Test
public void givenThreeElements_whenCalling3Combinations_ShouldReturnOneCombination() {
List<Integer> set = Arrays.asList(1, 2, 3);
List<List<Integer>> combinations = Combinatorics.combinations(set, 3);
assertEquals(1, combinations.size());
assertEquals(combinations.get(0), Arrays.asList(1, 2, 3));
}
@Test
public void givenFourElements_whenCalling2Combinations_ShouldReturnCombinations() {
List<Integer> set = Arrays.asList(1, 2, 3, 4);
List<List<Integer>> combinations = Combinatorics.combinations(set, 2);
assertEquals(6, combinations.size());
assertEquals(6, new HashSet<>(combinations).size());
}
@Test
public void givenFourElements_whenCallingPowerSet_ShouldReturn15Sets() {
List<Character> sequence = Arrays.asList('a', 'b', 'c', 'd');
List<List<Character>> combinations = Combinatorics.powerSet(sequence);
assertEquals(16, combinations.size());
}
}
-1
View File
@@ -12,4 +12,3 @@ 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)
- [Transforming an Empty String into an Empty Optional](https://www.baeldung.com/java-empty-string-to-empty-optional)
@@ -5,14 +5,14 @@
version="2.0">
<persistence-unit
name="com.baeldung.optionalReturnType"
name="com.baeldung.optionalreturntype"
transaction-type="RESOURCE_LOCAL">
<description>Persist Optional Return Type Demo</description>
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.optionalReturnType.User</class>
<class>com.baeldung.optionalReturnType.UserOptional</class>
<class>com.baeldung.optionalreturntype.User</class>
<class>com.baeldung.optionalreturntype.UserOptional</class>
<!--
<class>com.baeldung.optionalReturnType.UserOptionalField</class>
<class>com.baeldung.optionalreturntype.UserOptionalField</class>
-->
<exclude-unlisted-classes>true</exclude-unlisted-classes>
@@ -0,0 +1,39 @@
package com.baeldung.streamreduce.entities;
import java.util.ArrayList;
import java.util.List;
public class Rating {
double points;
List<Review> reviews = new ArrayList<>();
public Rating() {}
public void add(Review review) {
reviews.add(review);
computeRating();
}
private double computeRating() {
double totalPoints = reviews.stream().map(Review::getPoints).reduce(0, Integer::sum);
this.points = totalPoints / reviews.size();
return this.points;
}
public static Rating average(Rating r1, Rating r2) {
Rating combined = new Rating();
combined.reviews = new ArrayList<>(r1.reviews);
combined.reviews.addAll(r2.reviews);
combined.computeRating();
return combined;
}
public double getPoints() {
return points;
}
public List<Review> getReviews() {
return reviews;
}
}
@@ -0,0 +1,28 @@
package com.baeldung.streamreduce.entities;
public class Review {
int points;
String review;
public Review(int points, String review) {
this.points = points;
this.review = review;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public String getReview() {
return review;
}
public void setReview(String review) {
this.review = review;
}
}
@@ -4,6 +4,7 @@ public class User {
private final String name;
private final int age;
private final Rating rating = new Rating();
public User(String name, int age) {
this.name = name;
@@ -17,7 +18,11 @@ public class User {
public int getAge() {
return age;
}
public Rating getRating() {
return rating;
}
@Override
public String toString() {
return "User{" + "name=" + name + ", age=" + age + '}';
@@ -1,5 +1,7 @@
package com.baeldung.streamreduce.tests;
import com.baeldung.streamreduce.entities.Rating;
import com.baeldung.streamreduce.entities.Review;
import com.baeldung.streamreduce.entities.User;
import com.baeldung.streamreduce.utilities.NumberUtils;
import java.util.ArrayList;
@@ -64,6 +66,31 @@ public class StreamReduceManualTest {
assertThat(result).isEqualTo(65);
}
@Test
public void givenUserList_whenReduceWithGreaterAgeAccumulator_thenFindsOldest() {
List<User> users = Arrays.asList(new User("John", 30), new User("Alex", 40), new User("Julie", 35));
User oldest = users.stream().reduce(users.get(0), (user1, user2) -> user1.getAge() >= user2.getAge() ? user1 : user2);
assertThat(oldest).isEqualTo(users.get(1));
}
@Test
public void givenUserListWithRatings_whenReduceWithGreaterAgeAccumulator_thenFindsOldest() {
User john = new User("John", 30);
john.getRating().add(new Review(5, ""));
john.getRating().add(new Review(3, "not bad"));
User julie = new User("Julie", 35);
john.getRating().add(new Review(4, "great!"));
john.getRating().add(new Review(2, "terrible experience"));
john.getRating().add(new Review(4, ""));
List<User> users = Arrays.asList(john, julie);
Rating averageRating = users.stream().reduce(new Rating(), (rating, user) -> Rating.average(rating, user.getRating()), Rating::average);
assertThat(averageRating.getPoints()).isEqualTo(3.6);
}
@Test
public void givenStringList_whenReduceWithParallelStream_thenCorrect() {
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
@@ -5,7 +5,6 @@ This module contains articles about the improvements to core Java features intro
### Relevant Articles:
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
- [Java 9 Optional API Additions](https://www.baeldung.com/java-9-optional)
- [Java 9 Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods)
- [Java 9 Stream API Improvements](https://www.baeldung.com/java-9-stream-api)
- [Java 9 java.util.Objects Additions](https://www.baeldung.com/java-9-objects-new)
@@ -1,85 +0,0 @@
package com.baeldung.java9;
public class Java9OptionalTest {
@Test
public void givenOptionalOfSome_whenToStream_thenShouldTreatItAsOneElementStream() {
//given
Optional<String> value = Optional.of("a");
//when
List<String> collect = value.stream().map(String::toUpperCase).collect(Collectors.toList());
//then
assertThat(collect).hasSameElementsAs(List.of("A"));
}
@Test
public void givenOptionalOfNone_whenToStream_thenShouldTreatItAsZeroElementStream() {
//given
Optional<String> value = Optional.empty();
//when
List<String> collect = value.stream().map(String::toUpperCase).collect(Collectors.toList());
//then
assertThat(collect).isEmpty();
}
@Test
public void givenOptional_whenPresent_thenShouldExecuteProperCallback() {
//given
Optional<String> value = Optional.of("properValue");
AtomicInteger successCounter = new AtomicInteger(0);
AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0);
//when
value.ifPresentOrElse((v) -> successCounter.incrementAndGet(), onEmptyOptionalCounter::incrementAndGet);
//then
assertThat(successCounter.get()).isEqualTo(1);
assertThat(onEmptyOptionalCounter.get()).isEqualTo(0);
}
@Test
public void givenOptional_whenNotPresent_thenShouldExecuteProperCallback() {
//given
Optional<String> value = Optional.empty();
AtomicInteger successCounter = new AtomicInteger(0);
AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0);
//when
value.ifPresentOrElse((v) -> successCounter.incrementAndGet(), onEmptyOptionalCounter::incrementAndGet);
//then
assertThat(successCounter.get()).isEqualTo(0);
assertThat(onEmptyOptionalCounter.get()).isEqualTo(1);
}
@Test
public void givenOptional_whenPresent_thenShouldTakeAValueFromIt() {
//given
String expected = "properValue";
Optional<String> value = Optional.of(expected);
Optional<String> defaultValue = Optional.of("default");
//when
Optional<String> result = value.or(() -> defaultValue);
//then
assertThat(result.get()).isEqualTo(expected);
}
@Test
public void givenOptional_whenEmpty_thenShouldTakeAValueFromOr() {
//given
String defaultString = "default";
Optional<String> value = Optional.empty();
Optional<String> defaultValue = Optional.of(defaultString);
//when
Optional<String> result = value.or(() -> defaultValue);
//then
assertThat(result.get()).isEqualTo(defaultString);
}
}
+2 -4
View File
@@ -4,13 +4,11 @@ This module contains articles about Java 9 core features
### Relevant Articles:
- [Method Handles in Java](http://www.baeldung.com/java-method-handles)
- [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue)
- [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional)
- [Method Handles in Java](https://www.baeldung.com/java-method-handles)
- [Introduction to Chronicle Queue](https://www.baeldung.com/java-chronicle-queue)
- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
- [Immutable Set in Java](https://www.baeldung.com/java-immutable-set)
- [Filtering a Stream of Optionals in Java](https://www.baeldung.com/java-filter-stream-of-optional)
Note: also contains part of the code for the article
[How to Filter a Collection in Java](https://www.baeldung.com/java-collection-filtering).
@@ -1,51 +0,0 @@
package com.baeldung.optionals;
import static org.junit.Assert.assertEquals;
import java.util.Optional;
import org.junit.Test;
public class OptionalsTest {
@Test
public void givenOptional_whenEmptyValue_thenCustomMessage() {
assertEquals(Optional.of("Name not provided"), Optionals.getName(Optional.ofNullable(null)));
}
@Test
public void givenOptional_whenValue_thenOptional() {
String name = "Filan Fisteku";
Optional<String> optionalString = Optional.ofNullable(name);
assertEquals(optionalString, Optionals.getName(optionalString));
}
@Test
public void givenOptional_whenValue_thenOptionalGeneralMethod() {
String name = "Filan Fisteku";
String missingOptional = "Name not provided";
Optional<String> optionalString = Optional.ofNullable(name);
Optional<String> fallbackOptionalString = Optional.ofNullable(missingOptional);
assertEquals(optionalString, Optionals.or(optionalString, fallbackOptionalString));
}
@Test
public void givenEmptyOptional_whenValue_thenOptionalGeneralMethod() {
String missingOptional = "Name not provided";
Optional<String> optionalString = Optional.empty();
Optional<String> fallbackOptionalString = Optional.ofNullable(missingOptional);
assertEquals(fallbackOptionalString, Optionals.or(optionalString, fallbackOptionalString));
}
@Test
public void givenGuavaOptional_whenInvoke_thenOptional() {
String name = "Filan Fisteku";
com.google.common.base.Optional<String> stringOptional = com.google.common.base.Optional.of(name);
assertEquals(stringOptional, Optionals.getOptionalGuavaName(stringOptional));
}
@Test
public void givenGuavaOptional_whenNull_thenDefaultText() {
assertEquals(com.google.common.base.Optional.of("Name not provided"), Optionals.getOptionalGuavaName(com.google.common.base.Optional.fromNullable(null)));
}
}
@@ -1,7 +1,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">
<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-concurrency-advanced-3</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-advanced-3</name>
@@ -14,6 +16,15 @@
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-concurrency-advanced-3</finalName>
<plugins>
@@ -35,6 +46,7 @@
</build>
<properties>
<assertj.version>3.14.0</assertj.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
@@ -0,0 +1,136 @@
package com.baeldung.rejection;
import org.junit.After;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.ThreadPoolExecutor.AbortPolicy;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy;
import java.util.concurrent.ThreadPoolExecutor.DiscardPolicy;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class SaturationPolicyUnitTest {
private ThreadPoolExecutor executor;
@After
public void shutdownExecutor() {
if (executor != null && !executor.isTerminated()) {
executor.shutdownNow();
}
}
@Test
public void givenAbortPolicy_WhenSaturated_ThenShouldThrowRejectedExecutionException() {
executor = new ThreadPoolExecutor(1, 1, 0, MILLISECONDS, new SynchronousQueue<>(), new AbortPolicy());
executor.execute(() -> waitFor(100));
assertThatThrownBy(() -> executor.execute(() -> System.out.println("Will be rejected"))).isInstanceOf(RejectedExecutionException.class);
}
@Test
public void givenCallerRunsPolicy_WhenSaturated_ThenTheCallerThreadRunsTheTask() {
executor = new ThreadPoolExecutor(1, 1, 0, MILLISECONDS, new SynchronousQueue<>(), new CallerRunsPolicy());
executor.execute(() -> waitFor(100));
long startTime = System.nanoTime();
executor.execute(() -> waitFor(100));
double blockedDuration = (System.nanoTime() - startTime) / 1_000_000.0;
assertThat(blockedDuration).isGreaterThanOrEqualTo(100);
}
@Test
public void givenDiscardPolicy_WhenSaturated_ThenExecutorDiscardsTheNewTask() throws InterruptedException {
executor = new ThreadPoolExecutor(1, 1, 0, MILLISECONDS, new SynchronousQueue<>(), new DiscardPolicy());
executor.execute(() -> waitFor(100));
BlockingQueue<String> queue = new LinkedBlockingDeque<>();
executor.execute(() -> queue.offer("Result"));
assertThat(queue.poll(200, MILLISECONDS)).isNull();
}
@Test
public void givenDiscardOldestPolicy_WhenSaturated_ThenExecutorDiscardsTheOldestTask() {
executor = new ThreadPoolExecutor(1, 1, 0, MILLISECONDS, new ArrayBlockingQueue<>(2), new DiscardOldestPolicy());
executor.execute(() -> waitFor(100));
BlockingQueue<String> queue = new LinkedBlockingDeque<>();
executor.execute(() -> queue.offer("First"));
executor.execute(() -> queue.offer("Second"));
executor.execute(() -> queue.offer("Third"));
waitFor(150);
List<String> results = new ArrayList<>();
queue.drainTo(results);
assertThat(results).containsExactlyInAnyOrder("Second", "Third");
}
@Test
public void givenGrowPolicy_WhenSaturated_ThenExecutorIncreaseTheMaxPoolSize() {
executor = new ThreadPoolExecutor(1, 1, 0, MILLISECONDS, new ArrayBlockingQueue<>(2), new GrowPolicy());
executor.execute(() -> waitFor(100));
BlockingQueue<String> queue = new LinkedBlockingDeque<>();
executor.execute(() -> queue.offer("First"));
executor.execute(() -> queue.offer("Second"));
executor.execute(() -> queue.offer("Third"));
waitFor(150);
List<String> results = new ArrayList<>();
queue.drainTo(results);
assertThat(results).containsExactlyInAnyOrder("First", "Second", "Third");
}
@Test
public void givenExecutorIsTerminated_WhenSubmittedNewTask_ThenTheSaturationPolicyApplies() {
ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0, MILLISECONDS, new LinkedBlockingQueue<>());
executor.shutdownNow();
assertThatThrownBy(() -> executor.execute(() -> {
})).isInstanceOf(RejectedExecutionException.class);
}
@Test
public void givenExecutorIsTerminating_WhenSubmittedNewTask_ThenTheSaturationPolicyApplies() {
ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0, MILLISECONDS, new LinkedBlockingQueue<>());
executor.execute(() -> waitFor(100));
executor.shutdown();
assertThatThrownBy(() -> executor.execute(() -> {
})).isInstanceOf(RejectedExecutionException.class);
}
private static class GrowPolicy implements RejectedExecutionHandler {
private final Lock lock = new ReentrantLock();
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
lock.lock();
try {
executor.setMaximumPoolSize(executor.getMaximumPoolSize() + 1);
} finally {
lock.unlock();
}
executor.submit(r);
}
}
private void waitFor(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException ignored) {
}
}
}
@@ -18,8 +18,11 @@ public class CounterUnitTest {
Counter counter = new Counter();
Future<Integer> future1 = (Future<Integer>) executorService.submit(new CounterCallable(counter));
Future<Integer> future2 = (Future<Integer>) executorService.submit(new CounterCallable(counter));
assertThat(future1.get()).isEqualTo(1);
assertThat(future2.get()).isEqualTo(2);
// Just to make sure both are completed
future1.get();
future2.get();
assertThat(counter.getCounter()).isEqualTo(2);
}
}
@@ -18,8 +18,11 @@ public class ExtrinsicLockCounterUnitTest {
ExtrinsicLockCounter counter = new ExtrinsicLockCounter();
Future<Integer> future1 = (Future<Integer>) executorService.submit(new ExtrinsicLockCounterCallable(counter));
Future<Integer> future2 = (Future<Integer>) executorService.submit(new ExtrinsicLockCounterCallable(counter));
assertThat(future1.get()).isEqualTo(1);
assertThat(future2.get()).isEqualTo(2);
// Just to make sure both are completed
future1.get();
future2.get();
assertThat(counter.getCounter()).isEqualTo(2);
}
}
@@ -11,15 +11,18 @@ import java.util.concurrent.Future;
import static org.assertj.core.api.Assertions.assertThat;
public class ReentrantLockCounterUnitTest {
@Test
public void whenCalledIncrementCounter_thenCorrect() throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(2);
ReentrantLockCounter counter = new ReentrantLockCounter();
Future<Integer> future1 = (Future<Integer>) executorService.submit(new ReentrantLockCounterCallable(counter));
Future<Integer> future2 = (Future<Integer>) executorService.submit(new ReentrantLockCounterCallable(counter));
assertThat(future1.get()).isEqualTo(1);
assertThat(future2.get()).isEqualTo(2);
// Just to make sure both are completed
future1.get();
future2.get();
assertThat(counter.getCounter()).isEqualTo(2);
}
}
@@ -11,16 +11,19 @@ import java.util.concurrent.Future;
import static org.assertj.core.api.Assertions.assertThat;
public class ReentrantReadWriteLockCounterUnitTest {
@Test
public void whenCalledIncrementCounter_thenCorrect() throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(2);
ReentrantReadWriteLockCounter counter = new ReentrantReadWriteLockCounter();
Future<Integer> future1 = (Future<Integer>) executorService.submit(new ReentranReadWriteLockCounterCallable(counter));
Future<Integer> future2 = (Future<Integer>) executorService.submit(new ReentranReadWriteLockCounterCallable(counter));
Future<Integer> future1 = (Future<Integer>) executorService.submit(new ReentranReadWriteLockCounterCallable(counter));
Future<Integer> future2 = (Future<Integer>) executorService.submit(new ReentranReadWriteLockCounterCallable(counter));
assertThat(future2.get()).isEqualTo(2);
assertThat(future1.get()).isEqualTo(1);
// Just to make sure both are completed
future1.get();
future2.get();
assertThat(counter.getCounter()).isEqualTo(2);
}
}
@@ -2,18 +2,16 @@ package com.baeldung.datetime.sql;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.baeldung.datetime.sql.DateUtils;
import java.text.ParseException;
import java.util.Date;
import java.time.LocalDate;
import org.junit.Test;
public class DateUtilsUnitTest {
@Test
public void givenCurrentDate_thenTodayIsReturned() {
assertEquals(DateUtils.getNow(), new Date());
assertEquals(DateUtils.getNow().toLocalDate(), LocalDate.now());
}
@Test(expected = IllegalArgumentException.class)
@@ -0,0 +1,22 @@
package com.baeldung.timezone;
import org.junit.Test;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import static org.junit.Assert.assertEquals;
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"));
}
}
@@ -0,0 +1,34 @@
package com.baeldung.timezone;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import static org.junit.Assert.assertEquals;
public class ModifyTimezonePropertyUnitTest {
@Before
public void setup() {
System.setProperty("user.timezone", "IST");
TimeZone.setDefault(null);
}
@After
public void teardown() {
System.clearProperty("user.timezone");
}
@Test
public void givenTimezonePropertySet_thenDateTimezoneIsCorrect() {
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
assertEquals(calendar.getTimeZone(), TimeZone.getTimeZone("IST"));
}
}
@@ -15,6 +15,5 @@ This module contains articles about core java exceptions
- [Java – Try with Resources](https://www.baeldung.com/java-try-with-resources)
- [Java Global Exception Handler](https://www.baeldung.com/java-global-exception-handler)
- [Common Java Exceptions](https://www.baeldung.com/java-common-exceptions)
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
- [How to Find an Exception’s Root Cause in Java](https://www.baeldung.com/java-exception-root-cause)
- [Is It a Bad Practice to Catch Throwable?](https://www.baeldung.com/java-catch-throwable-bad-practice)
@@ -1,8 +1,13 @@
=========
## Java Optional
## Core Java Optional
This module contains articles about Java Optional.
### Relevant Articles:
- [Java Optional as Return Type](https://www.baeldung.com/java-optional-return)
- [Guide To Java 8 Optional](https://www.baeldung.com/java-optional)
- [Java Optional – orElse() vs orElseGet()](https://www.baeldung.com/java-optional-or-else-vs-or-else-get)
- [Guide to Java 8 Optional](https://www.baeldung.com/java-optional)
- [Java Optional – orElse() vs orElseGet()](https://www.baeldung.com/java-optional-or-else-vs-or-else-get)
- [Transforming an Empty String into an Empty Optional](https://www.baeldung.com/java-empty-string-to-empty-optional)
- [Filtering a Stream of Optionals in Java](https://www.baeldung.com/java-filter-stream-of-optional)
- [Java 9 Optional API Additions](https://www.baeldung.com/java-9-optional)
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
- [Optional orElse Optional](https://www.baeldung.com/java-optional-or-else-optional)
@@ -42,11 +42,31 @@
<artifactId>jmh-generator-bytecode</artifactId>
<version>${jmh-generator.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-path</artifactId>
<version>${rest-assured.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<hibernate.core.version>5.4.0.Final</hibernate.core.version>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator.version>1.19</jmh-generator.version>
<guava.version>27.1-jre</guava.version>
<assertj.version>3.10.0</assertj.version>
<rest-assured.version>3.1.1</rest-assured.version>
</properties>
</project>
@@ -1,4 +1,4 @@
package com.baeldung.optional;
package com.baeldung.optional.orelse;
import java.util.Arrays;
import java.util.List;
@@ -1,4 +1,4 @@
package com.baeldung.optional;
package com.baeldung.optional.orelse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
@@ -1,4 +1,4 @@
package com.baeldung.optionalReturnType;
package com.baeldung.optionalreturntype;
import java.util.HashMap;
import java.util.Map;
@@ -1,4 +1,4 @@
package com.baeldung.optionalReturnType;
package com.baeldung.optionalreturntype;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -1,4 +1,4 @@
package com.baeldung.optionalReturnType;
package com.baeldung.optionalreturntype;
import java.util.Optional;
@@ -7,13 +7,13 @@ import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class PersistOptionalTypeExample {
static String persistenceUnit = "com.baeldung.optionalReturnType";
static String persistenceUnit = "com.baeldung.optionalreturntype";
static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit);
static EntityManager entityManager = emf.createEntityManager();
// to run this app, uncomment the follow line in META-INF/persistence.xml
// <class>com.baeldung.optionalReturnType.UserOptionalField</class>
// <class>com.baeldung.optionalreturntype.UserOptionalField</class>
public static void main(String[] args) {
UserOptionalField user1 = new UserOptionalField();
user1.setUserId(1l);
@@ -1,11 +1,11 @@
package com.baeldung.optionalReturnType;
package com.baeldung.optionalreturntype;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class PersistOptionalTypeExample2 {
static String persistenceUnit = "com.baeldung.optionalReturnType";
static String persistenceUnit = "com.baeldung.optionalreturntype";
static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit);
static EntityManager em = emf.createEntityManager();

Some files were not shown because too many files have changed in this diff Show More