Merge remote-tracking branch 'upstream/master' into BAEL-3456_Springfox
This commit is contained in:
commit
8826e8a12e
@ -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());
|
||||
}
|
||||
}
|
@ -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;
|
||||
@ -18,6 +19,10 @@ public class User {
|
||||
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);
|
||||
}
|
||||
}
|
@ -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) {
|
||||
}
|
||||
}
|
||||
}
|
@ -19,7 +19,10 @@ public class CounterUnitTest {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
@ -19,7 +19,10 @@ public class ExtrinsicLockCounterUnitTest {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
@ -19,7 +19,10 @@ public class ReentrantLockCounterUnitTest {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
@ -16,11 +16,14 @@ public class ReentrantReadWriteLockCounterUnitTest {
|
||||
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)
|
||||
- [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();
|
@ -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 PersistUserExample {
|
||||
static String persistenceUnit = "com.baeldung.optionalReturnType";
|
||||
static String persistenceUnit = "com.baeldung.optionalreturntype";
|
||||
static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit);
|
||||
|
||||
static EntityManager em = emf.createEntityManager();
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.optionalReturnType;
|
||||
package com.baeldung.optionalreturntype;
|
||||
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.optionalReturnType;
|
||||
package com.baeldung.optionalreturntype;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.optionalReturnType;
|
||||
package com.baeldung.optionalreturntype;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Optional;
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.optionalReturnType;
|
||||
package com.baeldung.optionalreturntype;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Optional;
|
@ -1,20 +1,20 @@
|
||||
package com.baeldung.optionals;
|
||||
package com.baeldung.orelseoptional;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class Optionals {
|
||||
public class OptionalUtils {
|
||||
|
||||
public static <T> Optional<T> or(Optional<T> optional, Optional<T> fallback) {
|
||||
return optional.isPresent() ? optional : fallback;
|
||||
}
|
||||
|
||||
public static Optional<String> getName(Optional<String> name) {
|
||||
return name.or(() -> getCustomMessage());
|
||||
}
|
||||
|
||||
public static com.google.common.base.Optional<String> getOptionalGuavaName(com.google.common.base.Optional<String> name) {
|
||||
return name.or(getCustomMessageGuava());
|
||||
}
|
||||
// public static Optional<String> getName(Optional<String> name) {
|
||||
// return name.or(() -> getCustomMessage());
|
||||
// }
|
||||
//
|
||||
// public static com.google.common.base.Optional<String> getOptionalGuavaName(com.google.common.base.Optional<String> name) {
|
||||
// return name.or(getCustomMessageGuava());
|
||||
// }
|
||||
|
||||
private static Optional<String> getCustomMessage() {
|
||||
return Optional.of("Name not provided");
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung;
|
||||
package com.baeldung.emptystringoptional;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import org.junit.Assert;
|
||||
@ -16,12 +16,13 @@ public class EmptyStringToEmptyOptionalUnitTest {
|
||||
Assert.assertFalse(opt.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyString_whenFilteringOnOptionalInJava11_thenEmptyOptionalIsReturned() {
|
||||
String str = "";
|
||||
Optional<String> opt = Optional.ofNullable(str).filter(Predicate.not(String::isEmpty));
|
||||
Assert.assertFalse(opt.isPresent());
|
||||
}
|
||||
// Uncomment code when code base is compatible with Java 11
|
||||
// @Test
|
||||
// public void givenEmptyString_whenFilteringOnOptionalInJava11_thenEmptyOptionalIsReturned() {
|
||||
// String str = "";
|
||||
// Optional<String> opt = Optional.ofNullable(str).filter(Predicate.not(String::isEmpty));
|
||||
// Assert.assertFalse(opt.isPresent());
|
||||
// }
|
||||
|
||||
@Test
|
||||
public void givenEmptyString_whenPassingResultOfEmptyToNullToOfNullable_thenEmptyOptionalIsReturned() {
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.java9;
|
||||
package com.baeldung.filterstream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@ -47,15 +47,17 @@ public class Java9OptionalsStreamUnitTest {
|
||||
assertEquals("bar", filteredList.get(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterOutPresentOptionalsWithJava9() {
|
||||
assertEquals(4, listOfOptionals.size());
|
||||
|
||||
List<String> filteredList = listOfOptionals.stream().flatMap(Optional::stream).collect(Collectors.toList());
|
||||
|
||||
assertEquals(2, filteredList.size());
|
||||
assertEquals("foo", filteredList.get(0));
|
||||
assertEquals("bar", filteredList.get(1));
|
||||
}
|
||||
// Uncomment code when code base is compatible with Java 9
|
||||
// @Test
|
||||
// public void filterOutPresentOptionalsWithJava9() {
|
||||
// assertEquals(4, listOfOptionals.size());
|
||||
//
|
||||
// List<String> filteredList = listOfOptionals.stream().flatMap(Optional::stream).collect(Collectors.toList());
|
||||
//
|
||||
// assertEquals(2, filteredList.size());
|
||||
// assertEquals("foo", filteredList.get(0));
|
||||
// assertEquals("bar", filteredList.get(1));
|
||||
// }
|
||||
|
||||
}
|
@ -0,0 +1,95 @@
|
||||
package com.baeldung.java9additions;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
// Uncomment code when code base is compatible with Java 9
|
||||
//public class Java9OptionalUnitTest {
|
||||
//
|
||||
// @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);
|
||||
// }
|
||||
//}
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.java8.optional;
|
||||
package com.baeldung.optional;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
@ -1,7 +1,5 @@
|
||||
package com.baeldung.java8.optional;
|
||||
package com.baeldung.optional;
|
||||
|
||||
import com.baeldung.optional.Modem;
|
||||
import com.baeldung.optional.Person;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@ -260,7 +258,7 @@ public class OptionalUnitTest {
|
||||
return "Default Value";
|
||||
}
|
||||
|
||||
// Uncomment code when code base is compatiable with Java 11
|
||||
// Uncomment code when code base is compatible with Java 11
|
||||
// @Test
|
||||
// public void givenAnEmptyOptional_thenIsEmptyBehavesAsExpected() {
|
||||
// Optional<String> opt = Optional.of("Baeldung");
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.java8.optional;
|
||||
package com.baeldung.optional.orelse;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
@ -6,8 +6,6 @@ import org.slf4j.LoggerFactory;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import com.baeldung.optional.OrElseAndOrElseGet;
|
||||
|
||||
public class OrElseAndOrElseGetUnitTest {
|
||||
|
||||
private OrElseAndOrElseGet orElsevsOrElseGet = new OrElseAndOrElseGet();
|
@ -0,0 +1,52 @@
|
||||
package com.baeldung.orelseoptional;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class OrElseOptionalUnitTest {
|
||||
|
||||
@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, OptionalUtils.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, OptionalUtils.or(optionalString, fallbackOptionalString));
|
||||
}
|
||||
|
||||
// Uncomment code when code base is compatible with Java 9
|
||||
// @Test
|
||||
// public void givenOptional_whenEmptyValue_thenCustomMessage() {
|
||||
// assertEquals(Optional.of("Name not provided"), OptionalUtils.getName(Optional.ofNullable(null)));
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// public void givenOptional_whenValue_thenOptional() {
|
||||
// String name = "Filan Fisteku";
|
||||
// Optional<String> optionalString = Optional.ofNullable(name);
|
||||
// assertEquals(optionalString, OptionalUtils.getName(optionalString));
|
||||
// }
|
||||
//
|
||||
// @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, OptionalUtils.getOptionalGuavaName(stringOptional));
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// public void givenGuavaOptional_whenNull_thenDefaultText() {
|
||||
// assertEquals(com.google.common.base.Optional.of("Name not provided"), OptionalUtils.getOptionalGuavaName(com.google.common.base.Optional.fromNullable(null)));
|
||||
// }
|
||||
}
|
@ -23,7 +23,6 @@
|
||||
- [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler)
|
||||
- [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object)
|
||||
- [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions)
|
||||
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
|
||||
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
|
||||
- [Java – Try with Resources](https://www.baeldung.com/java-try-with-resources)
|
||||
- [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding)
|
||||
|
@ -0,0 +1,90 @@
|
||||
package com.baeldung.list;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class CircularLinkedList {
|
||||
|
||||
final Logger LOGGER = LoggerFactory.getLogger(CircularLinkedList.class);
|
||||
|
||||
private Node head = null;
|
||||
private Node tail = null;
|
||||
|
||||
public void addNode(int value) {
|
||||
|
||||
Node newNode = new Node(value);
|
||||
|
||||
if (head == null) {
|
||||
head = newNode;
|
||||
} else {
|
||||
tail.nextNode = newNode;
|
||||
}
|
||||
|
||||
tail = newNode;
|
||||
tail.nextNode = head;
|
||||
}
|
||||
|
||||
public boolean containsNode(int searchValue) {
|
||||
|
||||
Node currentNode = head;
|
||||
|
||||
if (head == null) {
|
||||
return false;
|
||||
} else {
|
||||
do {
|
||||
if (currentNode.value == searchValue) {
|
||||
return true;
|
||||
}
|
||||
currentNode = currentNode.nextNode;
|
||||
} while (currentNode != head);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void deleteNode(int valueToDelete) {
|
||||
|
||||
Node currentNode = head;
|
||||
|
||||
if (head != null) {
|
||||
if (currentNode.value == valueToDelete) {
|
||||
head = head.nextNode;
|
||||
tail.nextNode = head;
|
||||
currentNode = null;
|
||||
} else {
|
||||
do {
|
||||
Node nextNode = currentNode.nextNode;
|
||||
if (nextNode.value == valueToDelete) {
|
||||
currentNode.nextNode = nextNode.nextNode;
|
||||
nextNode = null;
|
||||
break;
|
||||
}
|
||||
currentNode = currentNode.nextNode;
|
||||
} while (currentNode != head);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void traverseList() {
|
||||
|
||||
Node currentNode = head;
|
||||
|
||||
if (head != null) {
|
||||
do {
|
||||
LOGGER.info(currentNode.value + " ");
|
||||
currentNode = currentNode.nextNode;
|
||||
} while (currentNode != head);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class Node {
|
||||
|
||||
int value;
|
||||
Node nextNode;
|
||||
|
||||
public Node(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
package com.baeldung.list;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class CircularLinkedListUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenACircularLinkedList_WhenAddingElements_ThenListContainsThoseElements() {
|
||||
CircularLinkedList cll = createCircularLinkedList();
|
||||
|
||||
assertTrue(cll.containsNode(8));
|
||||
assertTrue(cll.containsNode(37));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACircularLinkedList_WhenLookingForNonExistingElement_ThenReturnsFalse() {
|
||||
CircularLinkedList cll = createCircularLinkedList();
|
||||
|
||||
assertFalse(cll.containsNode(11));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACircularLinkedList_WhenDeletingElements_ThenListDoesNotContainThoseElements() {
|
||||
CircularLinkedList cll = createCircularLinkedList();
|
||||
|
||||
assertTrue(cll.containsNode(13));
|
||||
cll.deleteNode(13);
|
||||
assertFalse(cll.containsNode(13));
|
||||
|
||||
assertTrue(cll.containsNode(1));
|
||||
cll.deleteNode(1);
|
||||
assertFalse(cll.containsNode(1));
|
||||
|
||||
assertTrue(cll.containsNode(46));
|
||||
cll.deleteNode(46);
|
||||
assertFalse(cll.containsNode(46));
|
||||
}
|
||||
|
||||
private CircularLinkedList createCircularLinkedList() {
|
||||
CircularLinkedList cll = new CircularLinkedList();
|
||||
|
||||
cll.addNode(13);
|
||||
cll.addNode(7);
|
||||
cll.addNode(24);
|
||||
cll.addNode(1);
|
||||
cll.addNode(8);
|
||||
cll.addNode(37);
|
||||
cll.addNode(46);
|
||||
|
||||
return cll;
|
||||
}
|
||||
|
||||
}
|
@ -6,10 +6,7 @@ This module contains articles about Jackson.
|
||||
The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||
|
||||
### Relevant Articles:
|
||||
- [Mapping Multiple JSON Fields to a Single Java Field](https://www.baeldung.com/json-multiple-fields-single-java-field)
|
||||
- [How to Process YAML with Jackson](https://www.baeldung.com/jackson-yaml)
|
||||
- [Working with Tree Model Nodes in Jackson](https://www.baeldung.com/jackson-json-node-tree-model)
|
||||
- [Converting JSON to CSV in Java](https://www.baeldung.com/java-converting-json-to-csv)
|
||||
- [Compare Two JSON Objects with Jackson](https://www.baeldung.com/jackson-compare-two-json-objects)
|
||||
- [Calling Default Serializer from Custom Serializer in Jackson](https://www.baeldung.com/jackson-call-default-serializer-from-custom-serializer)
|
||||
- More articles: [[<-- prev]](/../jackson)
|
||||
|
@ -14,20 +14,6 @@
|
||||
|
||||
<dependencies>
|
||||
|
||||
<!-- YAML -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-yaml</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- CSV -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-csv</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Allow use of LocalDate -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
|
@ -18,7 +18,6 @@ import com.baeldung.jackson.ignore.dtos.MyMixInForIgnoreType;
|
||||
import com.baeldung.jackson.ignore.dtos.MyDtoIgnoreField;
|
||||
import com.baeldung.jackson.ignore.dtos.MyDtoIgnoreFieldByName;
|
||||
import com.baeldung.jackson.ignore.dtos.MyDtoIgnoreNull;
|
||||
import com.baeldung.jackson.ignore.dtos.MyDtoNullKeySerializer;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
@ -191,88 +190,4 @@ public class JacksonSerializationIgnoreUnitTest {
|
||||
System.out.println(dtoAsString);
|
||||
}
|
||||
|
||||
// map
|
||||
|
||||
@Test
|
||||
public final void givenIgnoringMapNullValue_whenWritingMapObjectWithNullValue_thenIgnored() throws JsonProcessingException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
// mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
|
||||
mapper.setSerializationInclusion(Include.NON_NULL);
|
||||
|
||||
final MyDto dtoObject1 = new MyDto();
|
||||
|
||||
final Map<String, MyDto> dtoMap = new HashMap<String, MyDto>();
|
||||
dtoMap.put("dtoObject1", dtoObject1);
|
||||
dtoMap.put("dtoObject2", null);
|
||||
|
||||
final String dtoMapAsString = mapper.writeValueAsString(dtoMap);
|
||||
|
||||
assertThat(dtoMapAsString, containsString("dtoObject1"));
|
||||
assertThat(dtoMapAsString, not(containsString("dtoObject2")));
|
||||
System.out.println(dtoMapAsString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenIgnoringMapValueObjectWithNullField_whenWritingMapValueObjectWithNullField_thenIgnored() throws JsonProcessingException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.setSerializationInclusion(Include.NON_NULL);
|
||||
|
||||
final MyDto dtoObject = new MyDto();
|
||||
|
||||
final Map<String, MyDto> dtoMap = new HashMap<String, MyDto>();
|
||||
dtoMap.put("dtoObject", dtoObject);
|
||||
|
||||
final String dtoMapAsString = mapper.writeValueAsString(dtoMap);
|
||||
|
||||
assertThat(dtoMapAsString, containsString("dtoObject"));
|
||||
assertThat(dtoMapAsString, not(containsString("stringValue")));
|
||||
System.out.println(dtoMapAsString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenAllowingMapObjectWithNullKey_whenWriting_thenCorrect() throws JsonProcessingException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.getSerializerProvider()
|
||||
.setNullKeySerializer(new MyDtoNullKeySerializer());
|
||||
|
||||
final MyDto dtoObject1 = new MyDto();
|
||||
dtoObject1.setStringValue("dtoObjectString1");
|
||||
final MyDto dtoObject2 = new MyDto();
|
||||
dtoObject2.setStringValue("dtoObjectString2");
|
||||
|
||||
final Map<String, MyDto> dtoMap = new HashMap<String, MyDto>();
|
||||
dtoMap.put(null, dtoObject1);
|
||||
dtoMap.put("obj2", dtoObject2);
|
||||
|
||||
final String dtoMapAsString = mapper.writeValueAsString(dtoMap);
|
||||
|
||||
System.out.println(dtoMapAsString);
|
||||
assertThat(dtoMapAsString, containsString("\"\""));
|
||||
assertThat(dtoMapAsString, containsString("dtoObjectString1"));
|
||||
assertThat(dtoMapAsString, containsString("obj2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenAllowingMapObjectOneNullKey_whenWritingMapObjectWithTwoNullKeys_thenOverride() throws JsonProcessingException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.getSerializerProvider()
|
||||
.setNullKeySerializer(new MyDtoNullKeySerializer());
|
||||
|
||||
final MyDto dtoObject1 = new MyDto();
|
||||
dtoObject1.setStringValue("dtoObject1String");
|
||||
|
||||
final MyDto dtoObject2 = new MyDto();
|
||||
dtoObject2.setStringValue("dtoObject2String");
|
||||
|
||||
final Map<String, MyDto> dtoMap = new HashMap<String, MyDto>();
|
||||
dtoMap.put(null, dtoObject1);
|
||||
dtoMap.put(null, dtoObject2);
|
||||
|
||||
final String dtoMapAsString = mapper.writeValueAsString(dtoMap);
|
||||
|
||||
assertThat(dtoMapAsString, not(containsString("dtoObject1String")));
|
||||
assertThat(dtoMapAsString, containsString("dtoObject2String"));
|
||||
System.out.println(dtoMapAsString);
|
||||
}
|
||||
|
||||
}
|
||||
|
14
jackson-conversions-2/README.md
Normal file
14
jackson-conversions-2/README.md
Normal file
@ -0,0 +1,14 @@
|
||||
## Jackson Conversions
|
||||
|
||||
This module contains articles about Jackson conversions.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Mapping a Dynamic JSON Object with Jackson](https://www.baeldung.com/jackson-mapping-dynamic-object)
|
||||
- [Jackson Unmarshalling JSON with Unknown Properties](https://www.baeldung.com/jackson-deserialize-json-unknown-properties)
|
||||
- [Ignore Null Fields with Jackson](https://www.baeldung.com/jackson-ignore-null-fields)
|
||||
- [Mapping Multiple JSON Fields to a Single Java Field](https://www.baeldung.com/json-multiple-fields-single-java-field)
|
||||
- [Convert XML to JSON Using Jackson](https://www.baeldung.com/jackson-convert-xml-json)
|
||||
- [Converting JSON to CSV in Java](https://www.baeldung.com/java-converting-json-to-csv)
|
||||
- [How to Process YAML with Jackson](https://www.baeldung.com/jackson-yaml)
|
||||
- [Jackson Streaming API](https://www.baeldung.com/jackson-streaming-api)
|
||||
- More articles: [[<-- prev]](../jackson-conversions)
|
67
jackson-conversions-2/pom.xml
Normal file
67
jackson-conversions-2/pom.xml
Normal file
@ -0,0 +1,67 @@
|
||||
<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>jackson-conversions-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>jackson-conversions-2</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<!--jackson for xml -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-xml</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<!-- YAML -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-yaml</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<!-- Allow use of LocalDate -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||
<version>2.9.8</version>
|
||||
</dependency>
|
||||
<!-- CSV -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-csv</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>jackson-conversions-2</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<assertj.version>3.11.0</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -3,8 +3,6 @@ package com.baeldung.jackson.csv;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import com.baeldung.jackson.entities.OrderLine;
|
||||
import com.baeldung.jackson.mixin.OrderLineForCsv;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.MappingIterator;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.jackson.entities;
|
||||
package com.baeldung.jackson.csv;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.jackson.mixin;
|
||||
package com.baeldung.jackson.csv;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.jackson.deserialization.dynamicobject;
|
||||
package com.baeldung.jackson.dynamicobject;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.jackson.deserialization.dynamicobject;
|
||||
package com.baeldung.jackson.dynamicobject;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.jackson.deserialization.dynamicobject;
|
||||
package com.baeldung.jackson.dynamicobject;
|
||||
|
||||
import java.util.Map;
|
||||
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.jackson.entities;
|
||||
package com.baeldung.jackson.multiplefields;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAlias;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
@ -0,0 +1,54 @@
|
||||
package com.baeldung.jackson.unknownproperties;
|
||||
|
||||
public class MyDto {
|
||||
|
||||
private String stringValue;
|
||||
private int intValue;
|
||||
private boolean booleanValue;
|
||||
|
||||
public MyDto() {
|
||||
super();
|
||||
}
|
||||
|
||||
public MyDto(final String stringValue, final int intValue, final boolean booleanValue) {
|
||||
super();
|
||||
|
||||
this.stringValue = stringValue;
|
||||
this.intValue = intValue;
|
||||
this.booleanValue = booleanValue;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public String getStringValue() {
|
||||
return stringValue;
|
||||
}
|
||||
|
||||
public void setStringValue(final String stringValue) {
|
||||
this.stringValue = stringValue;
|
||||
}
|
||||
|
||||
public int getIntValue() {
|
||||
return intValue;
|
||||
}
|
||||
|
||||
public void setIntValue(final int intValue) {
|
||||
this.intValue = intValue;
|
||||
}
|
||||
|
||||
public boolean isBooleanValue() {
|
||||
return booleanValue;
|
||||
}
|
||||
|
||||
public void setBooleanValue(final boolean booleanValue) {
|
||||
this.booleanValue = booleanValue;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MyDto [stringValue=" + stringValue + ", intValue=" + intValue + ", booleanValue=" + booleanValue + "]";
|
||||
}
|
||||
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.jackson.dtos.ignore;
|
||||
package com.baeldung.jackson.unknownproperties;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.jackson.dtos.ignore;
|
||||
package com.baeldung.jackson.unknownproperties;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.jackson.entities;
|
||||
package com.baeldung.jackson.yaml;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
@ -0,0 +1,49 @@
|
||||
package com.baeldung.jackson.yaml;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public class OrderLine {
|
||||
private String item;
|
||||
private int quantity;
|
||||
private BigDecimal unitPrice;
|
||||
|
||||
public OrderLine() {
|
||||
|
||||
}
|
||||
|
||||
public OrderLine(String item, int quantity, BigDecimal unitPrice) {
|
||||
super();
|
||||
this.item = item;
|
||||
this.quantity = quantity;
|
||||
this.unitPrice = unitPrice;
|
||||
}
|
||||
|
||||
public String getItem() {
|
||||
return item;
|
||||
}
|
||||
|
||||
public void setItem(String item) {
|
||||
this.item = item;
|
||||
}
|
||||
|
||||
public int getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
|
||||
public void setQuantity(int quantity) {
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
public BigDecimal getUnitPrice() {
|
||||
return unitPrice;
|
||||
}
|
||||
|
||||
public void setUnitPrice(BigDecimal unitPrice) {
|
||||
this.unitPrice = unitPrice;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "OrderLine [item=" + item + ", quantity=" + quantity + ", unitPrice=" + unitPrice + "]";
|
||||
}
|
||||
}
|
@ -18,30 +18,30 @@ public class CsvUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenJsonInput_thenWriteCsv() throws JsonParseException, JsonMappingException, IOException {
|
||||
JsonCsvConverter.JsonToCsv(new File("src/main/resources/orderLines.json"),
|
||||
new File("src/main/resources/csvFromJson.csv"));
|
||||
JsonCsvConverter.JsonToCsv(new File("src/main/resources/csv/orderLines.json"),
|
||||
new File("src/main/resources/csv/csvFromJson.csv"));
|
||||
|
||||
assertEquals(readFile("src/main/resources/csvFromJson.csv"),
|
||||
readFile("src/test/resources/expectedCsvFromJson.csv"));
|
||||
assertEquals(readFile("src/main/resources/csv/csvFromJson.csv"),
|
||||
readFile("src/test/resources/csv/expectedCsvFromJson.csv"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCsvInput_thenWritesJson() throws JsonParseException, JsonMappingException, IOException {
|
||||
JsonCsvConverter.csvToJson(new File("src/main/resources/orderLines.csv"),
|
||||
new File("src/main/resources/jsonFromCsv.json"));
|
||||
JsonCsvConverter.csvToJson(new File("src/main/resources/csv/orderLines.csv"),
|
||||
new File("src/main/resources/csv/jsonFromCsv.json"));
|
||||
|
||||
assertEquals(readFile("src/main/resources/jsonFromCsv.json"),
|
||||
readFile("src/test/resources/expectedJsonFromCsv.json"));
|
||||
assertEquals(readFile("src/main/resources/csv/jsonFromCsv.json"),
|
||||
readFile("src/test/resources/csv/expectedJsonFromCsv.json"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJsonInput_thenWriteFormattedCsvOutput() throws JsonParseException, JsonMappingException, IOException {
|
||||
JsonCsvConverter.JsonToFormattedCsv(new File("src/main/resources/orderLines.json"),
|
||||
new File("src/main/resources/formattedCsvFromJson.csv"));
|
||||
JsonCsvConverter.JsonToFormattedCsv(new File("src/main/resources/csv/orderLines.json"),
|
||||
new File("src/main/resources/csv/formattedCsvFromJson.csv"));
|
||||
|
||||
assertEquals(readFile("src/main/resources/formattedCsvFromJson.csv"),
|
||||
readFile("src/test/resources/expectedFormattedCsvFromJson.csv"));
|
||||
assertEquals(readFile("src/main/resources/csv/formattedCsvFromJson.csv"),
|
||||
readFile("src/test/resources/csv/expectedFormattedCsvFromJson.csv"));
|
||||
|
||||
}
|
||||
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.jackson.deserialization.dynamicobject;
|
||||
package com.baeldung.jackson.dynamicobject;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
@ -0,0 +1,52 @@
|
||||
package com.baeldung.jackson.ignorenullfields;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
|
||||
import com.fasterxml.jackson.databind.ser.FilterProvider;
|
||||
import com.fasterxml.jackson.databind.ser.PropertyFilter;
|
||||
import com.fasterxml.jackson.databind.ser.PropertyWriter;
|
||||
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
|
||||
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class IgnoreNullFieldsUnitTest {
|
||||
|
||||
@Test
|
||||
public final void givenNullsIgnoredOnClass_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final MyDtoIgnoreNull dtoObject = new MyDtoIgnoreNull();
|
||||
|
||||
final String dtoAsString = mapper.writeValueAsString(dtoObject);
|
||||
|
||||
assertThat(dtoAsString, containsString("intValue"));
|
||||
assertThat(dtoAsString, containsString("booleanValue"));
|
||||
assertThat(dtoAsString, not(containsString("stringValue")));
|
||||
System.out.println(dtoAsString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenNullsIgnoredGlobally_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.setSerializationInclusion(Include.NON_NULL);
|
||||
final MyDto dtoObject = new MyDto();
|
||||
|
||||
final String dtoAsString = mapper.writeValueAsString(dtoObject);
|
||||
|
||||
assertThat(dtoAsString, containsString("intValue"));
|
||||
assertThat(dtoAsString, containsString("booleanValue"));
|
||||
assertThat(dtoAsString, not(containsString("stringValue")));
|
||||
System.out.println(dtoAsString);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,54 @@
|
||||
package com.baeldung.jackson.ignorenullfields;
|
||||
|
||||
public class MyDto {
|
||||
|
||||
private String stringValue;
|
||||
private int intValue;
|
||||
private boolean booleanValue;
|
||||
|
||||
public MyDto() {
|
||||
super();
|
||||
}
|
||||
|
||||
public MyDto(final String stringValue, final int intValue, final boolean booleanValue) {
|
||||
super();
|
||||
|
||||
this.stringValue = stringValue;
|
||||
this.intValue = intValue;
|
||||
this.booleanValue = booleanValue;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public String getStringValue() {
|
||||
return stringValue;
|
||||
}
|
||||
|
||||
public void setStringValue(final String stringValue) {
|
||||
this.stringValue = stringValue;
|
||||
}
|
||||
|
||||
public int getIntValue() {
|
||||
return intValue;
|
||||
}
|
||||
|
||||
public void setIntValue(final int intValue) {
|
||||
this.intValue = intValue;
|
||||
}
|
||||
|
||||
public boolean isBooleanValue() {
|
||||
return booleanValue;
|
||||
}
|
||||
|
||||
public void setBooleanValue(final boolean booleanValue) {
|
||||
this.booleanValue = booleanValue;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MyDto [stringValue=" + stringValue + ", intValue=" + intValue + ", booleanValue=" + booleanValue + "]";
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,51 @@
|
||||
package com.baeldung.jackson.ignorenullfields;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
|
||||
@JsonInclude(Include.NON_NULL)
|
||||
public class MyDtoIgnoreNull {
|
||||
|
||||
private String stringValue;
|
||||
private int intValue;
|
||||
private boolean booleanValue;
|
||||
|
||||
public MyDtoIgnoreNull() {
|
||||
super();
|
||||
}
|
||||
|
||||
public MyDtoIgnoreNull(final String stringValue, final int intValue, final boolean booleanValue) {
|
||||
super();
|
||||
|
||||
this.stringValue = stringValue;
|
||||
this.intValue = intValue;
|
||||
this.booleanValue = booleanValue;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public String getStringValue() {
|
||||
return stringValue;
|
||||
}
|
||||
|
||||
public void setStringValue(final String stringValue) {
|
||||
this.stringValue = stringValue;
|
||||
}
|
||||
|
||||
public int getIntValue() {
|
||||
return intValue;
|
||||
}
|
||||
|
||||
public void setIntValue(final int intValue) {
|
||||
this.intValue = intValue;
|
||||
}
|
||||
|
||||
public boolean isBooleanValue() {
|
||||
return booleanValue;
|
||||
}
|
||||
|
||||
public void setBooleanValue(final boolean booleanValue) {
|
||||
this.booleanValue = booleanValue;
|
||||
}
|
||||
|
||||
}
|
@ -1,13 +1,12 @@
|
||||
package com.baeldung.jackson.deserialization.jsonalias;
|
||||
package com.baeldung.jackson.multiplefields;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.jackson.entities.Weather;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class JsonAliasUnitTest {
|
||||
public class MapMultipleFieldsToSingleFieldUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTwoJsonFormats_whenDeserialized_thenWeatherObjectsCreated() throws Exception {
|
@ -13,7 +13,7 @@ import static junit.framework.Assert.assertNull;
|
||||
import static junit.framework.Assert.assertTrue;
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class JacksonStreamingAPIUnitTest {
|
||||
public class StreamingAPIUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenJsonGenerator_whenAppendJsonToIt_thenGenerateJson() throws IOException {
|
@ -0,0 +1,80 @@
|
||||
package com.baeldung.jackson.unknownproperties;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class UnknownPropertiesUnitTest {
|
||||
|
||||
@Test
|
||||
public final void givenNotAllFieldsHaveValuesInJson_whenDeserializingAJsonToAClass_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||
final String jsonAsString = "{\"stringValue\":\"a\",\"booleanValue\":true}";
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final MyDto readValue = mapper.readValue(jsonAsString, MyDto.class);
|
||||
|
||||
assertNotNull(readValue);
|
||||
assertThat(readValue.getStringValue(), equalTo("a"));
|
||||
assertThat(readValue.isBooleanValue(), equalTo(true));
|
||||
}
|
||||
|
||||
// tests - json with unknown fields
|
||||
|
||||
@Test(expected = UnrecognizedPropertyException.class)
|
||||
public final void givenJsonHasUnknownValues_whenDeserializingAJsonToAClass_thenExceptionIsThrown() throws JsonParseException, JsonMappingException, IOException {
|
||||
final String jsonAsString = "{\"stringValue\":\"a\",\"intValue\":1,\"booleanValue\":true,\"stringValue2\":\"something\"}";
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final MyDto readValue = mapper.readValue(jsonAsString, MyDto.class);
|
||||
|
||||
assertNotNull(readValue);
|
||||
assertThat(readValue.getStringValue(), equalTo("a"));
|
||||
assertThat(readValue.isBooleanValue(), equalTo(true));
|
||||
assertThat(readValue.getIntValue(), equalTo(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenJsonHasUnknownValuesButJacksonIsIgnoringUnknownFields_whenDeserializing_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||
final String jsonAsString = // @formatter:off
|
||||
"{\"stringValue\":\"a\"," +
|
||||
"\"intValue\":1," +
|
||||
"\"booleanValue\":true," +
|
||||
"\"stringValue2\":\"something\"}"; // @formatter:on
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
|
||||
final MyDto readValue = mapper.readValue(jsonAsString, MyDto.class);
|
||||
|
||||
assertNotNull(readValue);
|
||||
assertThat(readValue.getStringValue(), equalTo("a"));
|
||||
assertThat(readValue.isBooleanValue(), equalTo(true));
|
||||
assertThat(readValue.getIntValue(), equalTo(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenJsonHasUnknownValuesButUnknownFieldsAreIgnoredOnClass_whenDeserializing_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||
final String jsonAsString = // @formatter:off
|
||||
"{\"stringValue\":\"a\"," +
|
||||
"\"intValue\":1," +
|
||||
"\"booleanValue\":true," +
|
||||
"\"stringValue2\":\"something\"}"; // @formatter:on
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final MyDtoIgnoreUnknown readValue = mapper.readValue(jsonAsString, MyDtoIgnoreUnknown.class);
|
||||
|
||||
assertNotNull(readValue);
|
||||
assertThat(readValue.getStringValue(), equalTo("a"));
|
||||
assertThat(readValue.isBooleanValue(), equalTo(true));
|
||||
assertThat(readValue.getIntValue(), equalTo(1));
|
||||
}
|
||||
|
||||
}
|
@ -15,8 +15,6 @@ import java.util.List;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.jackson.entities.Order;
|
||||
import com.baeldung.jackson.entities.OrderLine;
|
||||
import com.fasterxml.jackson.core.JsonGenerationException;
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
@ -37,7 +35,7 @@ public class YamlUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenYamlInput_ObjectCreated() throws JsonParseException, JsonMappingException, IOException {
|
||||
Order order = mapper.readValue(new File("src/main/resources/orderInput.yaml"), Order.class);
|
||||
Order order = mapper.readValue(new File("src/test/resources/yaml/orderInput.yaml"), Order.class);
|
||||
assertEquals("A001", order.getOrderNo());
|
||||
assertEquals(LocalDate.parse("2019-04-17", DateTimeFormatter.ISO_DATE), order.getDate());
|
||||
assertEquals("Customer, Joe", order.getCustomerName());
|
||||
@ -55,9 +53,9 @@ public class YamlUnitTest {
|
||||
LocalDate.parse("2019-04-18", DateTimeFormatter.ISO_DATE),
|
||||
"Customer, Jane",
|
||||
lines);
|
||||
mapper.writeValue(new File("src/main/resources/orderOutput.yaml"), order);
|
||||
mapper.writeValue(new File("src/test/resources/yaml/orderOutput.yaml"), order);
|
||||
|
||||
File outputYaml = new File("src/main/resources/orderOutput.yaml");
|
||||
File outputYaml = new File("src/test/resources/yaml/orderOutput.yaml");
|
||||
assertTrue(outputYaml.exists());
|
||||
}
|
||||
}
|
16
jackson-conversions/README.md
Normal file
16
jackson-conversions/README.md
Normal file
@ -0,0 +1,16 @@
|
||||
## Jackson Conversions
|
||||
|
||||
This module contains articles about Jackson conversions.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Jackson – Unmarshall to Collection/Array](https://www.baeldung.com/jackson-collection-array)
|
||||
- [Jackson Date](https://www.baeldung.com/jackson-serialize-dates)
|
||||
- [Jackson – Working with Maps and Nulls](https://www.baeldung.com/jackson-map-null-values-or-null-key)
|
||||
- [Jackson – Decide What Fields Get Serialized/Deserialized](https://www.baeldung.com/jackson-field-serializable-deserializable-or-not)
|
||||
- [XML Serialization and Deserialization with Jackson](https://www.baeldung.com/jackson-xml-serialization-and-deserialization)
|
||||
- [Map Serialization and Deserialization with Jackson](https://www.baeldung.com/jackson-map)
|
||||
- [How to Serialize and Deserialize Enums with Jackson](https://www.baeldung.com/jackson-serialize-enums)
|
||||
- [Jackson – Marshall String to JsonNode](https://www.baeldung.com/jackson-json-to-jsonnode)
|
||||
- [Mapping Nested Values with Jackson](https://www.baeldung.com/jackson-nested-values)
|
||||
- [Deserialize Immutable Objects with Jackson](https://www.baeldung.com/jackson-deserialize-immutable-objects)
|
||||
- More articles: [[next -->]](../jackson-conversions-2)
|
49
jackson-conversions/pom.xml
Normal file
49
jackson-conversions/pom.xml
Normal file
@ -0,0 +1,49 @@
|
||||
<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>jackson-conversions</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>jackson-conversions</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-joda</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<!--jackson for xml -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-xml</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>jackson-conversions</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
</project>
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.jackson.deserialization.enums;
|
||||
package com.baeldung.jackson.enums.deserialization;
|
||||
|
||||
public class City {
|
||||
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.jackson.deserialization.enums;
|
||||
package com.baeldung.jackson.enums.deserialization;
|
||||
|
||||
public enum Distance {
|
||||
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.jackson.deserialization.enums.customdeserializer;
|
||||
package com.baeldung.jackson.enums.deserialization.customdeserializer;
|
||||
|
||||
public class City {
|
||||
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.jackson.deserialization.enums.customdeserializer;
|
||||
package com.baeldung.jackson.enums.deserialization.customdeserializer;
|
||||
|
||||
import java.io.IOException;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.jackson.deserialization.enums.customdeserializer;
|
||||
package com.baeldung.jackson.enums.deserialization.customdeserializer;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.jackson.deserialization.enums.jsoncreator;
|
||||
package com.baeldung.jackson.enums.deserialization.jsoncreator;
|
||||
|
||||
public class City {
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user