This commit is contained in:
Seun Matt 2017-08-24 16:20:38 +01:00
commit 0d79d018b5
339 changed files with 5543 additions and 2194 deletions

View File

@ -1,11 +1,11 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class BinarySearch {
public int runBinarySearch() {
int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
int key = 6;
public int runBinarySearchIteratively(int[] sortedArray, int key, int low, int high) {
int low = 0;
int high = sortedArray.length - 1;
int index = Integer.MAX_VALUE;
while (low <= high) {
@ -23,4 +23,31 @@ public class BinarySearch {
}
return index;
}
public int runBinarySearchRecursively(int[] sortedArray, int key, int low, int high) {
int middle = (low + high) / 2;
if (high < low) {
return -1;
}
if (key == sortedArray[middle]) {
return middle;
} else if (key < sortedArray[middle]) {
return runBinarySearchRecursively(sortedArray, key, low, middle - 1);
} else {
return runBinarySearchRecursively(sortedArray, key, middle + 1, high);
}
}
public int runBinarySearchUsingJavaArrays(int[] sortedArray, Integer key) {
int index = Arrays.binarySearch(sortedArray, key);
return index;
}
public int runBinarySearchUsingJavaCollections(List<Integer> sortedList, Integer key) {
int index = Collections.binarySearch(sortedList, key);
return index;
}
}

View File

@ -1,14 +1,41 @@
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
public class BinarySearchTest {
int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
int key = 6;
int expectedIndexForSearchKey = 7;
int low = 0;
int high = sortedArray.length - 1;
List<Integer> sortedList = Arrays.asList(0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9);
@Test
public void givenASortedArrayOfIntegers_whenBinarySearchRunForANumber_thenGetIndexOfTheNumber() {
public void givenASortedArrayOfIntegers_whenBinarySearchRunIterativelyForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch();
int expectedIndexForSearchKey = 7;
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearch());
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high));
}
@Test
public void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch();
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high));
}
@Test
public void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch();
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key));
}
@Test
public void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch();
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key));
}
}

View File

@ -1,3 +1,4 @@
### Relevant articles
- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor)
- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor)
- [Generating a Book with Asciidoctor](http://www.baeldung.com/asciidoctor-book)

View File

@ -19,13 +19,15 @@ public class NumbersProducer implements Runnable {
try {
generateNumbers();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
Thread.currentThread()
.interrupt();
}
}
private void generateNumbers() throws InterruptedException {
for (int i = 0; i < 100; i++) {
numbersQueue.put(ThreadLocalRandom.current().nextInt(100));
numbersQueue.put(ThreadLocalRandom.current()
.nextInt(100));
}
for (int j = 0; j < poisonPillPerProducer; j++) {
numbersQueue.put(poisonPill);

View File

@ -27,9 +27,6 @@ public class DelayObject implements Delayed {
@Override
public String toString() {
return "{" +
"data='" + data + '\'' +
", startTime=" + startTime +
'}';
return "{" + "data='" + data + '\'' + ", startTime=" + startTime + '}';
}
}

View File

@ -4,11 +4,11 @@ public class LuxuryCarsSpeed {
public double bugattiVeyronInMPH() {
return 268;
}
public double mcLarenInMPH() {
return 241;
}
public double astonMartinInMPH() {
return 220;
}

View File

@ -2,6 +2,8 @@ package com.baeldung.designpatterns.adapter;
public interface LuxuryCarsSpeedAdapter {
public double bugattiVeyronInKMPH();
public double mcLarenInKMPH();
public double astonMartinInKMPH();
}

View File

@ -5,7 +5,7 @@ import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class Blue implements Color {
@Override
public void fillColor() {
public void fillColor() {
LOG.info("Color : Blue");
}

View File

@ -5,16 +5,14 @@ import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class DecoratorPatternDriver {
public static void main(String[] args) {
//christmas tree with just one Garland
// christmas tree with just one Garland
ChristmasTree tree1 = new Garland(new ChristmasTreeImpl());
LOG.info(tree1.decorate());
//christmas tree with two Garlands and one Bubble lights
ChristmasTree tree2 = new BubbleLights(new Garland(
new Garland(new ChristmasTreeImpl()))
);
// christmas tree with two Garlands and one Bubble lights
ChristmasTree tree2 = new BubbleLights(new Garland(new Garland(new ChristmasTreeImpl())));
LOG.info(tree2.decorate());
}
}

View File

@ -7,14 +7,14 @@ public class ExpensiveObjectImpl implements ExpensiveObject {
public ExpensiveObjectImpl() {
heavyInitialConfiguration();
}
@Override
public void process() {
LOG.info("processing complete.");
}
private void heavyInitialConfiguration() {
LOG.info("Loading initial configuration...");
}
}

View File

@ -43,6 +43,7 @@ public class CustomRecursiveAction extends RecursiveAction {
private void processing(String work) {
String result = work.toUpperCase();
logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread().getName());
logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread()
.getName());
}
}

View File

@ -5,6 +5,6 @@ import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Greeter {
public String greet() default "";
public String greet() default "";
}

View File

@ -44,7 +44,8 @@ public class MapIteration {
}
public void iterateUsingIteratorAndEntry(Map<String, Integer> map) {
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet()
.iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> pair = iterator.next();
System.out.println(pair.getKey() + ":" + pair.getValue());
@ -58,7 +59,9 @@ public class MapIteration {
}
public void iterateUsingStreamAPI(Map<String, Integer> map) {
map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
map.entrySet()
.stream()
.forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
}
public void iterateKeys(Map<String, Integer> map) {

View File

@ -8,7 +8,7 @@ public class BigIntegerImpl {
BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476");
BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476");
BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda);
}

View File

@ -9,7 +9,8 @@ public class PersistentCookieStore implements CookieStore, Runnable {
public PersistentCookieStore() {
store = new CookieManager().getCookieStore();
// deserialize cookies into store
Runtime.getRuntime().addShutdownHook(new Thread(this));
Runtime.getRuntime()
.addShutdownHook(new Thread(this));
}
@Override

View File

@ -14,7 +14,8 @@ public class Screenshot {
}
public void getScreenshot(int timeToWait) throws Exception {
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit()
.getScreenSize());
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(rectangle);
ImageIO.write(img, "jpg", new File(path));

View File

@ -6,16 +6,16 @@ import java.security.NoSuchAlgorithmException;
import java.util.UUID;
public class UUIDGenerator {
/**
* These are predefined UUID for name spaces
*/
private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
private static final String NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
private static final String NAMESPACE_OID = "6ba7b812-9dad-11d1-80b4-00c04fd430c8";
private static final String NAMESPACE_X500 = "6ba7b814-9dad-11d1-80b4-00c04fd430c8";
private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
private static final String NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
private static final String NAMESPACE_OID = "6ba7b812-9dad-11d1-80b4-00c04fd430c8";
private static final String NAMESPACE_X500 = "6ba7b814-9dad-11d1-80b4-00c04fd430c8";
private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
public static void main(String[] args) {
try {
@ -35,7 +35,7 @@ public class UUIDGenerator {
UUID uuid = UUID.randomUUID();
return uuid;
}
/**
* Type 3 UUID Generation
*
@ -47,7 +47,7 @@ public class UUIDGenerator {
UUID uuid = UUID.nameUUIDFromBytes(bytes);
return uuid;
}
/**
* Type 5 UUID Generation
*
@ -59,8 +59,7 @@ public class UUIDGenerator {
UUID uuid = type5UUIDFromBytes(bytes);
return uuid;
}
public static UUID type5UUIDFromBytes(byte[] name) {
MessageDigest md;
try {
@ -69,27 +68,26 @@ public class UUIDGenerator {
throw new InternalError("MD5 not supported", nsae);
}
byte[] bytes = md.digest(name);
bytes[6] &= 0x0f; /* clear version */
bytes[6] |= 0x50; /* set to version 5 */
bytes[8] &= 0x3f; /* clear variant */
bytes[8] |= 0x80; /* set to IETF variant */
bytes[6] &= 0x0f; /* clear version */
bytes[6] |= 0x50; /* set to version 5 */
bytes[8] &= 0x3f; /* clear variant */
bytes[8] |= 0x80; /* set to IETF variant */
return constructType5UUID(bytes);
}
private static UUID constructType5UUID(byte[] data) {
long msb = 0;
long lsb = 0;
assert data.length == 16 : "data must be 16 bytes in length";
for (int i=0; i<8; i++)
for (int i = 0; i < 8; i++)
msb = (msb << 8) | (data[i] & 0xff);
for (int i=8; i<16; i++)
for (int i = 8; i < 16; i++)
lsb = (lsb << 8) | (data[i] & 0xff);
return new UUID(msb, lsb);
}
/**
* Unique Keys Generation Using Message Digest and Type 4 UUID
*

View File

@ -15,7 +15,6 @@ public class CompletableFutureLongRunningUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(CompletableFutureLongRunningUnitTest.class);
@Test
public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException {
Future<String> completableFuture = calculateAsync();
@ -27,11 +26,12 @@ public class CompletableFutureLongRunningUnitTest {
private Future<String> calculateAsync() throws InterruptedException {
CompletableFuture<String> completableFuture = new CompletableFuture<>();
Executors.newCachedThreadPool().submit(() -> {
Thread.sleep(500);
completableFuture.complete("Hello");
return null;
});
Executors.newCachedThreadPool()
.submit(() -> {
Thread.sleep(500);
completableFuture.complete("Hello");
return null;
});
return completableFuture;
}
@ -47,11 +47,12 @@ public class CompletableFutureLongRunningUnitTest {
private Future<String> calculateAsyncWithCancellation() throws InterruptedException {
CompletableFuture<String> completableFuture = new CompletableFuture<>();
Executors.newCachedThreadPool().submit(() -> {
Thread.sleep(500);
completableFuture.cancel(false);
return null;
});
Executors.newCachedThreadPool()
.submit(() -> {
Thread.sleep(500);
completableFuture.cancel(false);
return null;
});
return completableFuture;
}
@ -98,21 +99,24 @@ public class CompletableFutureLongRunningUnitTest {
@Test
public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello")
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));
assertEquals("Hello World", completableFuture.get());
}
@Test
public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2);
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello")
.thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2);
assertEquals("Hello World", completableFuture.get());
}
@Test
public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
CompletableFuture.supplyAsync(() -> "Hello").thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> LOG.debug(s1 + s2));
CompletableFuture.supplyAsync(() -> "Hello")
.thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> LOG.debug(s1 + s2));
}
@Test
@ -131,7 +135,9 @@ public class CompletableFutureLongRunningUnitTest {
assertTrue(future2.isDone());
assertTrue(future3.isDone());
String combined = Stream.of(future1, future2, future3).map(CompletableFuture::join).collect(Collectors.joining(" "));
String combined = Stream.of(future1, future2, future3)
.map(CompletableFuture::join)
.collect(Collectors.joining(" "));
assertEquals("Hello Beautiful World", combined);
}
@ -147,7 +153,8 @@ public class CompletableFutureLongRunningUnitTest {
throw new RuntimeException("Computation error!");
}
return "Hello, " + name;
}).handle((s, t) -> s != null ? s : "Hello, Stranger!");
})
.handle((s, t) -> s != null ? s : "Hello, Stranger!");
assertEquals("Hello, Stranger!", completableFuture.get());
}

View File

@ -15,7 +15,9 @@ public class UseLocalDateTimeUnitTest {
@Test
public void givenString_whenUsingParse_thenLocalDateTime() {
assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate());
assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime());
assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30")
.toLocalDate());
assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30")
.toLocalTime());
}
}

View File

@ -15,12 +15,14 @@ public class UseLocalDateUnitTest {
@Test
public void givenValues_whenUsingFactoryOf_thenLocalDate() {
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10).toString());
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10)
.toString());
}
@Test
public void givenString_whenUsingParse_thenLocalDate() {
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString());
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10")
.toString());
}
@Test
@ -30,12 +32,14 @@ public class UseLocalDateUnitTest {
@Test
public void givenDate_whenUsingPlus_thenNextDay() {
assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
assertEquals(LocalDate.now()
.plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
}
@Test
public void givenDate_whenUsingMinus_thenPreviousDay() {
assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
assertEquals(LocalDate.now()
.minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
}
@Test
@ -45,7 +49,8 @@ public class UseLocalDateUnitTest {
@Test
public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() {
assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth());
assertEquals(1, useLocalDate.getFirstDayOfMonth()
.getDayOfMonth());
}
@Test

View File

@ -21,7 +21,6 @@ public class FunctionalInterfaceUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(FunctionalInterfaceUnitTest.class);
@Test
public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
Map<String, Integer> nameMap = new HashMap<>();
@ -83,7 +82,8 @@ public class FunctionalInterfaceUnitTest {
return result;
});
List<Integer> fibonacci5 = fibonacci.limit(5).collect(Collectors.toList());
List<Integer> fibonacci5 = fibonacci.limit(5)
.collect(Collectors.toList());
assertEquals(new Integer(1), fibonacci5.get(0));
assertEquals(new Integer(1), fibonacci5.get(1));
@ -112,7 +112,9 @@ public class FunctionalInterfaceUnitTest {
public void whenUsingPredicateInFilter_thenListValuesAreFilteredOut() {
List<String> names = Arrays.asList("Angela", "Aaron", "Bob", "Claire", "David");
List<String> namesWithA = names.stream().filter(name -> name.startsWith("A")).collect(Collectors.toList());
List<String> namesWithA = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
assertEquals(2, namesWithA.size());
assertTrue(namesWithA.contains("Angela"));
@ -135,7 +137,8 @@ public class FunctionalInterfaceUnitTest {
List<Integer> values = Arrays.asList(3, 5, 8, 9, 12);
int sum = values.stream().reduce(0, (i1, i2) -> i1 + i2);
int sum = values.stream()
.reduce(0, (i1, i2) -> i1 + i2);
assertEquals(37, sum);

View File

@ -47,7 +47,8 @@ public class ConcurrentMapAggregateStatusManualTest {
executorService.awaitTermination(1, TimeUnit.MINUTES);
for (int i = 1; i <= MAX_SIZE; i++) {
assertEquals("map size should be consistently reliable", i, mapSizes.get(i - 1).intValue());
assertEquals("map size should be consistently reliable", i, mapSizes.get(i - 1)
.intValue());
}
assertEquals(MAX_SIZE, concurrentMap.size());
}
@ -69,7 +70,8 @@ public class ConcurrentMapAggregateStatusManualTest {
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);
assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes.get(MAX_SIZE - 1).intValue());
assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes.get(MAX_SIZE - 1)
.intValue());
assertEquals(MAX_SIZE, concurrentMap.size());
}

View File

@ -16,8 +16,12 @@ public class ConcurretMapMemoryConsistencyManualTest {
public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception {
Map<String, Integer> map = new ConcurrentHashMap<>();
List<Integer> sumList = parallelSum100(map, 1000);
assertEquals(1, sumList.stream().distinct().count());
long wrongResultCount = sumList.stream().filter(num -> num != 100).count();
assertEquals(1, sumList.stream()
.distinct()
.count());
long wrongResultCount = sumList.stream()
.filter(num -> num != 100)
.count();
assertEquals(0, wrongResultCount);
}
@ -25,8 +29,12 @@ public class ConcurretMapMemoryConsistencyManualTest {
public void givenHashtable_whenSumParallel_thenCorrect() throws Exception {
Map<String, Integer> map = new Hashtable<>();
List<Integer> sumList = parallelSum100(map, 1000);
assertEquals(1, sumList.stream().distinct().count());
long wrongResultCount = sumList.stream().filter(num -> num != 100).count();
assertEquals(1, sumList.stream()
.distinct()
.count());
long wrongResultCount = sumList.stream()
.filter(num -> num != 100)
.count();
assertEquals(0, wrongResultCount);
}
@ -34,8 +42,12 @@ public class ConcurretMapMemoryConsistencyManualTest {
public void givenHashMap_whenSumParallel_thenError() throws Exception {
Map<String, Integer> map = new HashMap<>();
List<Integer> sumList = parallelSum100(map, 100);
assertNotEquals(1, sumList.stream().distinct().count());
long wrongResultCount = sumList.stream().filter(num -> num != 100).count();
assertNotEquals(1, sumList.stream()
.distinct()
.count());
long wrongResultCount = sumList.stream()
.filter(num -> num != 100)
.count();
assertTrue(wrongResultCount > 0);
}

View File

@ -13,35 +13,26 @@ import static org.junit.Assert.*;
public class Java8GroupingByCollectorUnitTest {
private static final List<BlogPost> posts = Arrays.asList(
new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15),
new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5),
new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20),
new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35),
new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15));
private static final List<BlogPost> posts = Arrays.asList(new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5),
new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15));
@Test
public void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() {
Map<BlogPostType, List<BlogPost>> postsPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType));
Map<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType));
assertEquals(2, postsPerType
.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType
.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType
.get(BlogPostType.REVIEW)
.size());
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
.size());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() {
Map<BlogPostType, String> postsPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]"))));
Map<BlogPostType, String> postsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]"))));
assertEquals("Post titles: [News item 1, News item 2]", postsPerType.get(BlogPostType.NEWS));
assertEquals("Post titles: [Programming guide]", postsPerType.get(BlogPostType.GUIDE));
@ -50,174 +41,135 @@ public class Java8GroupingByCollectorUnitTest {
@Test
public void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() {
Map<BlogPostType, Integer> likesPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes)));
Map<BlogPostType, Integer> likesPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes)));
assertEquals(50, likesPerType
.get(BlogPostType.NEWS)
.intValue());
assertEquals(20, likesPerType
.get(BlogPostType.REVIEW)
.intValue());
assertEquals(20, likesPerType
.get(BlogPostType.GUIDE)
.intValue());
assertEquals(50, likesPerType.get(BlogPostType.NEWS)
.intValue());
assertEquals(20, likesPerType.get(BlogPostType.REVIEW)
.intValue());
assertEquals(20, likesPerType.get(BlogPostType.GUIDE)
.intValue());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() {
EnumMap<BlogPostType, List<BlogPost>> postsPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList()));
EnumMap<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList()));
assertEquals(2, postsPerType
.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType
.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType
.get(BlogPostType.REVIEW)
.size());
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
.size());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() {
Map<BlogPostType, Set<BlogPost>> postsPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType, toSet()));
Map<BlogPostType, Set<BlogPost>> postsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, toSet()));
assertEquals(2, postsPerType
.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType
.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType
.get(BlogPostType.REVIEW)
.size());
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
.size());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() {
ConcurrentMap<BlogPostType, List<BlogPost>> postsPerType = posts
.parallelStream()
.collect(groupingByConcurrent(BlogPost::getType));
ConcurrentMap<BlogPostType, List<BlogPost>> postsPerType = posts.parallelStream()
.collect(groupingByConcurrent(BlogPost::getType));
assertEquals(2, postsPerType
.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType
.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType
.get(BlogPostType.REVIEW)
.size());
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
.size());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() {
Map<BlogPostType, Double> averageLikesPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes)));
Map<BlogPostType, Double> averageLikesPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes)));
assertEquals(25, averageLikesPerType
.get(BlogPostType.NEWS)
.intValue());
assertEquals(20, averageLikesPerType
.get(BlogPostType.GUIDE)
.intValue());
assertEquals(10, averageLikesPerType
.get(BlogPostType.REVIEW)
.intValue());
assertEquals(25, averageLikesPerType.get(BlogPostType.NEWS)
.intValue());
assertEquals(20, averageLikesPerType.get(BlogPostType.GUIDE)
.intValue());
assertEquals(10, averageLikesPerType.get(BlogPostType.REVIEW)
.intValue());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() {
Map<BlogPostType, Long> numberOfPostsPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType, counting()));
Map<BlogPostType, Long> numberOfPostsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, counting()));
assertEquals(2, numberOfPostsPerType
.get(BlogPostType.NEWS)
.intValue());
assertEquals(1, numberOfPostsPerType
.get(BlogPostType.GUIDE)
.intValue());
assertEquals(2, numberOfPostsPerType
.get(BlogPostType.REVIEW)
.intValue());
assertEquals(2, numberOfPostsPerType.get(BlogPostType.NEWS)
.intValue());
assertEquals(1, numberOfPostsPerType.get(BlogPostType.GUIDE)
.intValue());
assertEquals(2, numberOfPostsPerType.get(BlogPostType.REVIEW)
.intValue());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() {
Map<BlogPostType, Optional<BlogPost>> maxLikesPerPostType = posts
.stream()
.collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes))));
Map<BlogPostType, Optional<BlogPost>> maxLikesPerPostType = posts.stream()
.collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes))));
assertTrue(maxLikesPerPostType
.get(BlogPostType.NEWS)
.isPresent());
assertEquals(35, maxLikesPerPostType
.get(BlogPostType.NEWS)
.get()
.getLikes());
assertTrue(maxLikesPerPostType.get(BlogPostType.NEWS)
.isPresent());
assertEquals(35, maxLikesPerPostType.get(BlogPostType.NEWS)
.get()
.getLikes());
assertTrue(maxLikesPerPostType
.get(BlogPostType.GUIDE)
.isPresent());
assertEquals(20, maxLikesPerPostType
.get(BlogPostType.GUIDE)
.get()
.getLikes());
assertTrue(maxLikesPerPostType.get(BlogPostType.GUIDE)
.isPresent());
assertEquals(20, maxLikesPerPostType.get(BlogPostType.GUIDE)
.get()
.getLikes());
assertTrue(maxLikesPerPostType
.get(BlogPostType.REVIEW)
.isPresent());
assertEquals(15, maxLikesPerPostType
.get(BlogPostType.REVIEW)
.get()
.getLikes());
assertTrue(maxLikesPerPostType.get(BlogPostType.REVIEW)
.isPresent());
assertEquals(15, maxLikesPerPostType.get(BlogPostType.REVIEW)
.get()
.getLikes());
}
@Test
public void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() {
Map<String, Map<BlogPostType, List<BlogPost>>> map = posts
.stream()
.collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType)));
Map<String, Map<BlogPostType, List<BlogPost>>> map = posts.stream()
.collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType)));
assertEquals(1, map
.get("Author 1")
.get(BlogPostType.NEWS)
.size());
assertEquals(1, map
.get("Author 1")
.get(BlogPostType.GUIDE)
.size());
assertEquals(1, map
.get("Author 1")
.get(BlogPostType.REVIEW)
.size());
assertEquals(1, map.get("Author 1")
.get(BlogPostType.NEWS)
.size());
assertEquals(1, map.get("Author 1")
.get(BlogPostType.GUIDE)
.size());
assertEquals(1, map.get("Author 1")
.get(BlogPostType.REVIEW)
.size());
assertEquals(1, map
.get("Author 2")
.get(BlogPostType.NEWS)
.size());
assertEquals(1, map
.get("Author 2")
.get(BlogPostType.REVIEW)
.size());
assertNull(map
.get("Author 2")
.get(BlogPostType.GUIDE));
assertEquals(1, map.get("Author 2")
.get(BlogPostType.NEWS)
.size());
assertEquals(1, map.get("Author 2")
.get(BlogPostType.REVIEW)
.size());
assertNull(map.get("Author 2")
.get(BlogPostType.GUIDE));
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() {
Map<BlogPostType, IntSummaryStatistics> likeStatisticsPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes)));
Map<BlogPostType, IntSummaryStatistics> likeStatisticsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes)));
IntSummaryStatistics newsLikeStatistics = likeStatisticsPerType.get(BlogPostType.NEWS);

View File

@ -17,8 +17,8 @@ public class Java8MapAndFlatMap {
@Test
public void givenStream_whenCalledMap_thenProduceList() {
List<String> myList = Stream.of("a", "b")
.map(String::toUpperCase)
.collect(Collectors.toList());
.map(String::toUpperCase)
.collect(Collectors.toList());
assertEquals(asList("A", "B"), myList);
}
@ -27,9 +27,9 @@ public class Java8MapAndFlatMap {
List<List<String>> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b"));
System.out.println(list);
System.out.println(list
.stream().flatMap(Collection::stream)
.collect(Collectors.toList()));
System.out.println(list.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList()));
}
@Test
@ -40,13 +40,11 @@ public class Java8MapAndFlatMap {
@Test
public void givenOptional_whenCalledFlatMap_thenProduceFlattenedOptional() {
assertEquals(Optional.of(Optional.of("STRING")), Optional
.of("string")
.map(s -> Optional.of("STRING")));
assertEquals(Optional.of(Optional.of("STRING")), Optional.of("string")
.map(s -> Optional.of("STRING")));
assertEquals(Optional.of("STRING"), Optional
.of("string")
.flatMap(s -> Optional.of("STRING")));
assertEquals(Optional.of("STRING"), Optional.of("string")
.flatMap(s -> Optional.of("STRING")));
}
}

View File

@ -55,7 +55,12 @@ public class JavaFolderSizeUnitTest {
@Test
public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException {
final Path folder = Paths.get(path);
final long size = Files.walk(folder).filter(p -> p.toFile().isFile()).mapToLong(p -> p.toFile().length()).sum();
final long size = Files.walk(folder)
.filter(p -> p.toFile()
.isFile())
.mapToLong(p -> p.toFile()
.length())
.sum();
assertEquals(EXPECTED_SIZE, size);
}
@ -72,8 +77,12 @@ public class JavaFolderSizeUnitTest {
public void whenGetFolderSizeUsingGuava_thenCorrect() {
final File folder = new File(path);
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder);
final long size = StreamSupport.stream(files.spliterator(), false).filter(File::isFile).mapToLong(File::length).sum();
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser()
.breadthFirstTraversal(folder);
final long size = StreamSupport.stream(files.spliterator(), false)
.filter(File::isFile)
.mapToLong(File::length)
.sum();
assertEquals(EXPECTED_SIZE, size);
}

View File

@ -1,4 +1,5 @@
package com.baeldung.java8.comparator;
import java.util.Arrays;
import java.util.Comparator;
@ -25,44 +26,32 @@ public class Java8ComparatorUnitTest {
@Before
public void initData() {
employees = new Employee[] { new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001),
new Employee("Keith", 35, 4000, 3924401) };
employeesArrayWithNulls = new Employee[] { new Employee("John", 25, 3000, 9922001), null, new Employee("Ace", 22, 2000, 5924001),
null, new Employee("Keith", 35, 4000, 3924401) };
employees = new Employee[] { new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001), new Employee("Keith", 35, 4000, 3924401) };
employeesArrayWithNulls = new Employee[] { new Employee("John", 25, 3000, 9922001), null, new Employee("Ace", 22, 2000, 5924001), null, new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByName = new Employee[] { new Employee("Ace", 22, 2000, 5924001),
new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByNameDesc = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("John", 25, 3000, 9922001),
new Employee("Ace", 22, 2000, 5924001) };
sortedEmployeesByName = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByNameDesc = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001) };
sortedEmployeesByAge = new Employee[] { new Employee("Ace", 22, 2000, 5924001),
new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByAge = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByMobile = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("Ace", 22, 2000, 5924001),
new Employee("John", 25, 3000, 9922001), };
sortedEmployeesByMobile = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), };
sortedEmployeesBySalary = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001),
new Employee("Keith", 35, 4000, 3924401), };
sortedEmployeesBySalary = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), };
sortedEmployeesArray_WithNullsFirst = new Employee[] { null, null, new Employee("Ace", 22, 2000, 5924001),
new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesArray_WithNullsLast = new Employee[] { new Employee("Ace", 22, 2000, 5924001),
new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), null, null };
sortedEmployeesArray_WithNullsFirst = new Employee[] { null, null, new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesArray_WithNullsLast = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), null, null };
someMoreEmployees = new Employee[] { new Employee("Jake", 25, 3000, 9922001), new Employee("Jake", 22, 2000, 5924001),
new Employee("Ace", 22, 3000, 6423001), new Employee("Keith", 35, 4000, 3924401) };
someMoreEmployees = new Employee[] { new Employee("Jake", 25, 3000, 9922001), new Employee("Jake", 22, 2000, 5924001), new Employee("Ace", 22, 3000, 6423001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByAgeName = new Employee[] { new Employee("Ace", 22, 3000, 6423001),
new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByNameAge = new Employee[] { new Employee("Ace", 22, 3000, 6423001),
new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByAgeName = new Employee[] { new Employee("Ace", 22, 3000, 6423001), new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByNameAge = new Employee[] { new Employee("Ace", 22, 3000, 6423001), new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
}
@Test
public void whenComparing_thenSortedByName() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees));
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByName));
}
@ -72,16 +61,16 @@ public class Java8ComparatorUnitTest {
return s2.compareTo(s1);
});
Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees));
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
}
@Test
public void whenReversed_thenSortedByNameDesc() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparatorReversed = employeeNameComparator.reversed();
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparatorReversed = employeeNameComparator.reversed();
Arrays.sort(employees, employeeNameComparatorReversed);
// System.out.println(Arrays.toString(employees));
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
}
@ -89,7 +78,7 @@ public class Java8ComparatorUnitTest {
public void whenComparingInt_thenSortedByAge() {
Comparator<Employee> employeeAgeComparator = Comparator.comparingInt(Employee::getAge);
Arrays.sort(employees, employeeAgeComparator);
// System.out.println(Arrays.toString(employees));
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByAge));
}
@ -97,7 +86,7 @@ public class Java8ComparatorUnitTest {
public void whenComparingLong_thenSortedByMobile() {
Comparator<Employee> employeeMobileComparator = Comparator.comparingLong(Employee::getMobile);
Arrays.sort(employees, employeeMobileComparator);
// System.out.println(Arrays.toString(employees));
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByMobile));
}
@ -105,7 +94,7 @@ public class Java8ComparatorUnitTest {
public void whenComparingDouble_thenSortedBySalary() {
Comparator<Employee> employeeSalaryComparator = Comparator.comparingDouble(Employee::getSalary);
Arrays.sort(employees, employeeSalaryComparator);
// System.out.println(Arrays.toString(employees));
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesBySalary));
}
@ -113,7 +102,7 @@ public class Java8ComparatorUnitTest {
public void whenNaturalOrder_thenSortedByName() {
Comparator<Employee> employeeNameComparator = Comparator.<Employee> naturalOrder();
Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees));
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByName));
}
@ -121,7 +110,7 @@ public class Java8ComparatorUnitTest {
public void whenReverseOrder_thenSortedByNameDesc() {
Comparator<Employee> employeeNameComparator = Comparator.<Employee> reverseOrder();
Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees));
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
}
@ -130,7 +119,7 @@ public class Java8ComparatorUnitTest {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparator_nullFirst = Comparator.nullsFirst(employeeNameComparator);
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullFirst);
// System.out.println(Arrays.toString(employeesArrayWithNulls));
// System.out.println(Arrays.toString(employeesArrayWithNulls));
assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsFirst));
}
@ -139,27 +128,28 @@ public class Java8ComparatorUnitTest {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparator_nullLast = Comparator.nullsLast(employeeNameComparator);
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullLast);
// System.out.println(Arrays.toString(employeesArrayWithNulls));
// System.out.println(Arrays.toString(employeesArrayWithNulls));
assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsLast));
}
@Test
public void whenThenComparing_thenSortedByAgeName() {
Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge).thenComparing(Employee::getName);
Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge)
.thenComparing(Employee::getName);
Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator);
// System.out.println(Arrays.toString(someMoreEmployees));
// System.out.println(Arrays.toString(someMoreEmployees));
assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByAgeName));
}
@Test
public void whenThenComparing_thenSortedByNameAge() {
Comparator<Employee> employee_Name_Age_Comparator = Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge);
Comparator<Employee> employee_Name_Age_Comparator = Comparator.comparing(Employee::getName)
.thenComparingInt(Employee::getAge);
Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator);
// System.out.println(Arrays.toString(someMoreEmployees));
// System.out.println(Arrays.toString(someMoreEmployees));
assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByNameAge));
}
}

View File

@ -17,7 +17,6 @@ public class OptionalUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(OptionalUnitTest.class);
// creating Optional
@Test
public void whenCreatesEmptyOptional_thenCorrect() {
@ -94,9 +93,11 @@ public class OptionalUnitTest {
public void whenOptionalFilterWorks_thenCorrect() {
Integer year = 2016;
Optional<Integer> yearOptional = Optional.of(year);
boolean is2016 = yearOptional.filter(y -> y == 2016).isPresent();
boolean is2016 = yearOptional.filter(y -> y == 2016)
.isPresent();
assertTrue(is2016);
boolean is2017 = yearOptional.filter(y -> y == 2017).isPresent();
boolean is2017 = yearOptional.filter(y -> y == 2017)
.isPresent();
assertFalse(is2017);
}
@ -128,7 +129,11 @@ public class OptionalUnitTest {
}
public boolean priceIsInRange2(Modem modem2) {
return Optional.ofNullable(modem2).map(Modem::getPrice).filter(p -> p >= 10).filter(p -> p <= 15).isPresent();
return Optional.ofNullable(modem2)
.map(Modem::getPrice)
.filter(p -> p >= 10)
.filter(p -> p <= 15)
.isPresent();
}
// Transforming Value With map()
@ -137,7 +142,8 @@ public class OptionalUnitTest {
List<String> companyNames = Arrays.asList("paypal", "oracle", "", "microsoft", "", "apple");
Optional<List<String>> listOptional = Optional.of(companyNames);
int size = listOptional.map(List::size).orElse(0);
int size = listOptional.map(List::size)
.orElse(0);
assertEquals(6, size);
}
@ -146,7 +152,8 @@ public class OptionalUnitTest {
String name = "baeldung";
Optional<String> nameOptional = Optional.of(name);
int len = nameOptional.map(String::length).orElse(0);
int len = nameOptional.map(String::length)
.orElse(0);
assertEquals(8, len);
}
@ -154,10 +161,13 @@ public class OptionalUnitTest {
public void givenOptional_whenMapWorksWithFilter_thenCorrect() {
String password = " password ";
Optional<String> passOpt = Optional.of(password);
boolean correctPassword = passOpt.filter(pass -> pass.equals("password")).isPresent();
boolean correctPassword = passOpt.filter(pass -> pass.equals("password"))
.isPresent();
assertFalse(correctPassword);
correctPassword = passOpt.map(String::trim).filter(pass -> pass.equals("password")).isPresent();
correctPassword = passOpt.map(String::trim)
.filter(pass -> pass.equals("password"))
.isPresent();
assertTrue(correctPassword);
}
@ -172,7 +182,8 @@ public class OptionalUnitTest {
String name1 = nameOptional.orElseThrow(IllegalArgumentException::new);
assertEquals("john", name1);
String name = personOptional.flatMap(Person::getName).orElseThrow(IllegalArgumentException::new);
String name = personOptional.flatMap(Person::getName)
.orElseThrow(IllegalArgumentException::new);
assertEquals("john", name);
}
@ -182,7 +193,9 @@ public class OptionalUnitTest {
person.setPassword("password");
Optional<Person> personOptional = Optional.of(person);
String password = personOptional.flatMap(Person::getPassword).filter(cleanPass -> cleanPass.equals("password")).orElseThrow(IllegalArgumentException::new);
String password = personOptional.flatMap(Person::getPassword)
.filter(cleanPass -> cleanPass.equals("password"))
.orElseThrow(IllegalArgumentException::new);
assertEquals("password", password);
}
@ -190,7 +203,8 @@ public class OptionalUnitTest {
@Test
public void whenOrElseWorks_thenCorrect() {
String nullName = null;
String name = Optional.ofNullable(nullName).orElse("john");
String name = Optional.ofNullable(nullName)
.orElse("john");
assertEquals("john", name);
}
@ -198,7 +212,8 @@ public class OptionalUnitTest {
@Test
public void whenOrElseGetWorks_thenCorrect() {
String nullName = null;
String name = Optional.ofNullable(nullName).orElseGet(() -> "john");
String name = Optional.ofNullable(nullName)
.orElseGet(() -> "john");
assertEquals("john", name);
}
@ -207,11 +222,13 @@ public class OptionalUnitTest {
public void whenOrElseGetAndOrElseOverlap_thenCorrect() {
String text = null;
LOG.debug("Using orElseGet:");
String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault);
String defaultText = Optional.ofNullable(text)
.orElseGet(this::getMyDefault);
assertEquals("Default Value", defaultText);
LOG.debug("Using orElse:");
defaultText = Optional.ofNullable(text).orElse(getMyDefault());
defaultText = Optional.ofNullable(text)
.orElse(getMyDefault());
assertEquals("Default Value", defaultText);
}
@ -219,11 +236,13 @@ public class OptionalUnitTest {
public void whenOrElseGetAndOrElseDiffer_thenCorrect() {
String text = "Text present";
LOG.debug("Using orElseGet:");
String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault);
String defaultText = Optional.ofNullable(text)
.orElseGet(this::getMyDefault);
assertEquals("Text present", defaultText);
LOG.debug("Using orElse:");
defaultText = Optional.ofNullable(text).orElse(getMyDefault());
defaultText = Optional.ofNullable(text)
.orElse(getMyDefault());
assertEquals("Text present", defaultText);
}
@ -231,7 +250,8 @@ public class OptionalUnitTest {
@Test(expected = IllegalArgumentException.class)
public void whenOrElseThrowWorks_thenCorrect() {
String nullName = null;
String name = Optional.ofNullable(nullName).orElseThrow(IllegalArgumentException::new);
String name = Optional.ofNullable(nullName)
.orElseThrow(IllegalArgumentException::new);
}
public String getMyDefault() {

View File

@ -43,6 +43,8 @@ public class FlattenNestedListUnitTest {
}
private <T> List<T> flattenListOfListsStream(List<List<T>> list) {
return list.stream().flatMap(Collection::stream).collect(Collectors.toList());
return list.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
}

View File

@ -15,56 +15,56 @@ public class RoundTest {
private double expected = 2.03d;
@Test
public void givenDecimalNumber_whenRoundToNDecimalPlaces_thenGetExpectedResult() {
public void givenDecimalNumber_whenRoundToNDecimalPlaces_thenGetExpectedResult() {
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
Assert.assertEquals(expected, Round.roundAvoid(value, places), delta);
Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
places = 3;
expected = 2.035d;
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
Assert.assertEquals(expected, Round.roundAvoid(value, places), delta);
Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
value = 1000.0d;
places = 17;
expected = 1000.0d;
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 92.23372036854776 !
Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
value = 256.025d;
places = 2;
expected = 256.03d;
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertNotEquals(expected, Round.roundNotPrecise(value, places), delta); // Returns: 256.02 !
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 256.02 !
Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertNotEquals(expected, DoubleRounder.round(value, places), delta); // Returns: 256.02 !
value = 260.775d;
value = 260.775d;
places = 2;
expected = 260.78d;
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertNotEquals(expected, Round.roundNotPrecise(value, places), delta); // Returns: 260.77 !
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 260.77 !
Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertNotEquals(expected, DoubleRounder.round(value, places), delta); // Returns: 260.77 !
value = 90080070060.1d;
places = 9;
expected = 90080070060.1d;
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 9.223372036854776E9 !

View File

@ -14,7 +14,8 @@ public class EchoIntegrationTest {
@BeforeClass
public static void start() throws InterruptedException {
Executors.newSingleThreadExecutor().submit(() -> new EchoServer().start(PORT));
Executors.newSingleThreadExecutor()
.submit(() -> new EchoServer().start(PORT));
Thread.sleep(500);
}

View File

@ -17,7 +17,8 @@ public class GreetServerIntegrationTest {
@BeforeClass
public static void start() throws InterruptedException {
Executors.newSingleThreadExecutor().submit(() -> new GreetServer().start(PORT));
Executors.newSingleThreadExecutor()
.submit(() -> new GreetServer().start(PORT));
Thread.sleep(500);
}

View File

@ -0,0 +1,47 @@
package com.baeldung.string;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class CharSequenceVsStringUnitTest {
@Test
public void givenUsingString_whenInstantiatingString_thenWrong() {
CharSequence firstString = "bealdung";
String secondString = "baeldung";
assertNotEquals(firstString, secondString);
}
@Test
public void givenIdenticalCharSequences_whenCastToString_thenEqual() {
CharSequence charSequence1 = "baeldung_1";
CharSequence charSequence2 = "baeldung_2";
assertTrue(charSequence1.toString().compareTo(charSequence2.toString()) > 0);
}
@Test
public void givenString_whenAppended_thenUnmodified() {
String test = "a";
int firstAddressOfTest = System.identityHashCode(test);
test += "b";
int secondAddressOfTest = System.identityHashCode(test);
assertEquals(firstAddressOfTest, secondAddressOfTest);
}
@Test
public void givenStringBuilder_whenAppended_thenModified() {
StringBuilder test = new StringBuilder();
test.append("a");
int firstAddressOfTest = System.identityHashCode(test);
test.append("b");
int secondAddressOfTest = System.identityHashCode(test);
assertEquals(firstAddressOfTest, secondAddressOfTest);
}
}

View File

@ -96,9 +96,12 @@ public class JavaIoUnitTest {
// utils
private final void logMemory() {
logger.info("Max Memory: {} Mb", Runtime.getRuntime().maxMemory() / 1048576);
logger.info("Total Memory: {} Mb", Runtime.getRuntime().totalMemory() / 1048576);
logger.info("Free Memory: {} Mb", Runtime.getRuntime().freeMemory() / 1048576);
logger.info("Max Memory: {} Mb", Runtime.getRuntime()
.maxMemory() / 1048576);
logger.info("Total Memory: {} Mb", Runtime.getRuntime()
.totalMemory() / 1048576);
logger.info("Free Memory: {} Mb", Runtime.getRuntime()
.freeMemory() / 1048576);
}
}

View File

@ -13,7 +13,6 @@ public class JavaRandomUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(JavaRandomUnitTest.class);
// tests - random long
@Test
@ -25,7 +24,8 @@ public class JavaRandomUnitTest {
@Test
public void givenUsingApacheCommons_whenGeneratingRandomLongUnbounded_thenCorrect() {
final long generatedLong = new RandomDataGenerator().getRandomGenerator().nextLong();
final long generatedLong = new RandomDataGenerator().getRandomGenerator()
.nextLong();
LOG.debug("{}", generatedLong);
}
@ -68,7 +68,8 @@ public class JavaRandomUnitTest {
@Test
public void givenUsingApache_whenGeneratingRandomIntegerUnbounded_thenCorrect() {
final Integer generatedInteger = new RandomDataGenerator().getRandomGenerator().nextInt();
final Integer generatedInteger = new RandomDataGenerator().getRandomGenerator()
.nextInt();
LOG.debug("{}", generatedInteger);
}
@ -93,7 +94,8 @@ public class JavaRandomUnitTest {
@Test
public void givenUsingApache_whenGeneratingRandomFloatUnbounded_thenCorrect() {
final float generatedFloat = new RandomDataGenerator().getRandomGenerator().nextFloat();
final float generatedFloat = new RandomDataGenerator().getRandomGenerator()
.nextFloat();
LOG.debug("{}", generatedFloat);
}
@ -111,7 +113,8 @@ public class JavaRandomUnitTest {
public void givenUsingApache_whenGeneratingRandomFloatBounded_thenCorrect() {
final float leftLimit = 1F;
final float rightLimit = 10F;
final float randomFloat = new RandomDataGenerator().getRandomGenerator().nextFloat();
final float randomFloat = new RandomDataGenerator().getRandomGenerator()
.nextFloat();
final float generatedFloat = leftLimit + randomFloat * (rightLimit - leftLimit);
LOG.debug("{}", generatedFloat);
@ -128,7 +131,8 @@ public class JavaRandomUnitTest {
@Test
public void givenUsingApache_whenGeneratingRandomDoubleUnbounded_thenCorrect() {
final double generatedDouble = new RandomDataGenerator().getRandomGenerator().nextDouble();
final double generatedDouble = new RandomDataGenerator().getRandomGenerator()
.nextDouble();
LOG.debug("{}", generatedDouble);
}

View File

@ -15,7 +15,6 @@ public class JavaTimerLongRunningUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(JavaTimerLongRunningUnitTest.class);
// tests
@Test
@ -23,7 +22,8 @@ public class JavaTimerLongRunningUnitTest {
final TimerTask timerTask = new TimerTask() {
@Override
public void run() {
LOG.debug("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread().getName());
LOG.debug("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread()
.getName());
}
};
final Timer timer = new Timer("Timer");

View File

@ -0,0 +1,31 @@
package org.baeldung.java.lists;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
public class ListToSTring {
@Test
public void whenListToString_thenPrintDefault() {
List<Integer> intLIst = Arrays.asList(1, 2, 3);
System.out.println(intLIst);
}
@Test
public void whenCollectorsJoining_thenPrintCustom() {
List<Integer> intList = Arrays.asList(1, 2, 3);
System.out.println(intList.stream()
.map(n -> String.valueOf(n))
.collect(Collectors.joining("-", "{", "}")));
}
@Test
public void whenStringUtilsJoin_thenPrintCustom() {
List<Integer> intList = Arrays.asList(1, 2, 3);
System.out.println(StringUtils.join(intList, "|"));
}
}

View File

@ -38,7 +38,8 @@ public class Employee implements Comparable {
@Override
public boolean equals(Object obj) {
return ((Employee) obj).getName().equals(getName());
return ((Employee) obj).getName()
.equals(getName());
}
@Override
@ -49,7 +50,13 @@ public class Employee implements Comparable {
@Override
public String toString() {
return new StringBuffer().append("(").append(getName()).append(getAge()).append(",").append(getSalary()).append(")").toString();
return new StringBuffer().append("(")
.append(getName())
.append(getAge())
.append(",")
.append(getSalary())
.append(")")
.toString();
}
}

View File

@ -113,7 +113,8 @@ public class JavaSortingUnitTest {
sortedMap.put(entry.getKey(), entry.getValue());
}
assertTrue(Arrays.equals(sortedMap.keySet().toArray(), sortedKeys));
assertTrue(Arrays.equals(sortedMap.keySet()
.toArray(), sortedKeys));
}
@Test
@ -127,7 +128,8 @@ public class JavaSortingUnitTest {
sortedMap.put(entry.getKey(), entry.getValue());
}
assertTrue(Arrays.equals(sortedMap.values().toArray(), sortedValues));
assertTrue(Arrays.equals(sortedMap.values()
.toArray(), sortedValues));
}
@Test

View File

@ -14,6 +14,12 @@ public class BookControllerFeignClientBuilder {
private BookClient bookClient = createClient(BookClient.class, "http://localhost:8081/api/books");
private static <T> T createClient(Class<T> type, String uri) {
return Feign.builder().client(new OkHttpClient()).encoder(new GsonEncoder()).decoder(new GsonDecoder()).logger(new Slf4jLogger(type)).logLevel(Logger.Level.FULL).target(type, uri);
return Feign.builder()
.client(new OkHttpClient())
.encoder(new GsonEncoder())
.decoder(new GsonDecoder())
.logger(new Slf4jLogger(type))
.logLevel(Logger.Level.FULL)
.target(type, uri);
}
}

View File

@ -34,25 +34,31 @@ public class BookClientLiveTest {
@Test
public void givenBookClient_shouldRunSuccessfully() throws Exception {
List<Book> books = bookClient.findAll().stream().map(BookResource::getBook).collect(Collectors.toList());
List<Book> books = bookClient.findAll()
.stream()
.map(BookResource::getBook)
.collect(Collectors.toList());
assertTrue(books.size() > 2);
log.info("{}", books);
}
@Test
public void givenBookClient_shouldFindOneBook() throws Exception {
Book book = bookClient.findByIsbn("0151072558").getBook();
Book book = bookClient.findByIsbn("0151072558")
.getBook();
assertThat(book.getAuthor(), containsString("Orwell"));
log.info("{}", book);
}
@Test
public void givenBookClient_shouldPostBook() throws Exception {
String isbn = UUID.randomUUID().toString();
String isbn = UUID.randomUUID()
.toString();
Book book = new Book(isbn, "Me", "It's me!", null, null);
bookClient.create(book);
book = bookClient.findByIsbn(isbn).getBook();
book = bookClient.findByIsbn(isbn)
.getBook();
assertThat(book.getAuthor(), is("Me"));
log.info("{}", book);
}

View File

@ -0,0 +1,41 @@
<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.stackify</groupId>
<artifactId>logback-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.codehaus.janino</groupId>
<artifactId>janino</artifactId>
<version>3.0.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,28 @@
package com.stackify.logging;
import org.slf4j.Marker;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.turbo.TurboFilter;
import ch.qos.logback.core.spi.FilterReply;
public class IgnoreLoggerFilter extends TurboFilter {
private String loggerName;
@Override
public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) {
if (loggerName == null) {
return FilterReply.NEUTRAL;
} else if (loggerName.equals(logger.getName())) {
return FilterReply.DENY;
} else
return FilterReply.NEUTRAL;
}
public void setLoggerName(String loggerName) {
this.loggerName = loggerName;
}
}

View File

@ -0,0 +1,43 @@
package com.stackify.models;
public class Employee {
private String email;
private String name;
private double salary;
public Employee() {
}
public Employee(String email, String name, double salary) {
this.email = email;
this.name = name;
this.salary = salary;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}

View File

@ -0,0 +1,11 @@
package com.stackify.services;
import com.stackify.models.Employee;
public class EmployeeService {
public double calculateBonus(Employee user) {
return 0.1 * user.getSalary();
}
}

View File

@ -0,0 +1 @@
env=dev

View File

@ -0,0 +1,151 @@
<configuration debug="true">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
<target>System.out</target>
</appender>
<property name="fileName" value="file.log" />
<property scope="context" resource="application.properties" />
<!-- configure appenders -->
<appender name="rollingFileAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>log-%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
<totalSizeCap>3GB</totalSizeCap>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>3MB</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%d [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<appender name="roleSiftingAppender" class="ch.qos.logback.classic.sift.SiftingAppender">
<discriminator>
<key>userRole</key>
<defaultValue>ANONYMOUS</defaultValue>
</discriminator>
<sift>
<appender name="fileAppender" class="ch.qos.logback.core.FileAppender">
<file>${userRole}.log</file>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d [%thread] %level %mdc %logger{50} - %msg%n</pattern>
</layout>
</appender>
</sift>
</appender>
<!-- configure layouts -->
<appender name="colorAppender" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d %green([%thread]) %highlight(%level) %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<appender name="htmlAppender" class="ch.qos.logback.core.FileAppender">
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="ch.qos.logback.classic.html.HTMLLayout">
<pattern>%thread%level%logger%msg</pattern>
</layout>
</encoder>
<file>log.html</file>
</appender>
<!-- configure filters -->
<appender name="STDOUT_LEVEL_FILTER_APPENDER" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
<target>System.err</target>
</appender>
<appender name="STDOUT_THRESHOLD_FILTER_APPENDER" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>WARN</level>
</filter>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<appender name="STDOUT_EVALUATOR_FILTER_APPENDER" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
<evaluator class="ch.qos.logback.classic.boolex.JaninoEventEvaluator">
<expression>return (level > DEBUG &amp;&amp; message.toLowerCase().contains("employee"));</expression>
</evaluator>
<OnMismatch>DENY</OnMismatch>
<OnMatch>NEUTRAL</OnMatch>
</filter>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<!-- configure turbo filters -->
<turboFilter class="ch.qos.logback.classic.turbo.DuplicateMessageFilter">
<AllowedRepetitions>2</AllowedRepetitions>
</turboFilter>
<turboFilter class="com.stackify.logging.IgnoreLoggerFilter">
<LoggerName>ignoredColorLogger</LoggerName>
</turboFilter>
<!-- configure loggers -->
<logger level="info" name="rollingFileLogger" additivity="false">
<appender-ref ref="rollingFileAppender" />
</logger>
<logger level="info" name="htmlLogger" additivity="false">
<appender-ref ref="htmlAppender" />
</logger>
<logger level="info" name="roleSiftingLogger" additivity="false">
<appender-ref ref="roleSiftingAppender" />
</logger>
<logger level="info" name="colorLogger" additivity="false">
<appender-ref ref="colorAppender" />
</logger>
<logger level="info" name="ignoredColorLogger">
<appender-ref ref="colorAppender" />
</logger>
<logger level="info" name="levelFilterLogger" additivity="false">
<appender-ref ref="STDOUT_LEVEL_FILTER_APPENDER" />
</logger>
<logger level="info" name="thresholdFilterLogger" additivity="false">
<appender-ref ref="STDOUT_THRESHOLD_FILTER_APPENDER" />
</logger>
<logger level="info" name="evaluatorFilterLogger" additivity="false">
<appender-ref ref="STDOUT_EVALUATOR_FILTER_APPENDER" />
</logger>
<!-- configure root logger -->
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
<!-- configure root logger conditionally -->
<property scope="context" resource="application.properties" />
<if condition='property("env").equals("dev")'>
<then>
<root level="TRACE">
<appender-ref ref="STDOUT" />
</root>
</then>
</if>
</configuration>

View File

@ -0,0 +1,74 @@
package com.stackify.services;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import com.stackify.models.Employee;
import ch.qos.logback.classic.Level;
public class EmployeeServiceTest {
private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
private EmployeeService employeeService = new EmployeeService();
@Test
public void testAppenders() {
Logger rollingFileLogger = LoggerFactory.getLogger("rollingFileLogger");
rollingFileLogger.info("Testing rolling file logger");
MDC.put("userRole", "ADMIN");
Logger siftingLogger = LoggerFactory.getLogger("roleSiftingLogger");
siftingLogger.info("Admin Action");
}
@Test
public void testLayouts() {
Logger htmlLogger = LoggerFactory.getLogger("htmlLogger");
htmlLogger.error("Employee Information Update Failed");
htmlLogger.info("New Account Created");
Logger colorLogger = LoggerFactory.getLogger("colorLogger");
colorLogger.error("Employee Information Update Failed");
colorLogger.info("New Account Created");
}
@Test
public void testLogLevel() {
ch.qos.logback.classic.Logger rollingFileLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("rollingFileLogger");
rollingFileLogger.setLevel(Level.DEBUG);
rollingFileLogger.debug("Testing Log Level");
}
@Test
public void testParameter() {
Employee employee = new Employee("john@gmail.com", "John", 2000);
if (logger.isDebugEnabled()) {
logger.debug("The bonus for employee: " + employee.getName() + " is " + employeeService.calculateBonus(employee));
}
logger.debug("The bonus for employee {} is {}", employee.getName(), employeeService.calculateBonus(employee));
}
@Test
public void testFilters() {
Logger levelFilterLogger = LoggerFactory.getLogger("levelFilterLogger");
levelFilterLogger.error("Employee Information Update Failed");
Logger thresholdFilterLogger = LoggerFactory.getLogger("thresholdFilterLogger");
thresholdFilterLogger.trace("Employee record inserted");
Logger evaluatorFilterLogger = LoggerFactory.getLogger("evaluatorFilterLogger");
evaluatorFilterLogger.debug("Employee account deactivated");
}
@Test
public void testIgnoredLogger() {
Logger colorLogger = LoggerFactory.getLogger("ignoredColorLogger");
colorLogger.info("Ignored Log Message");
}
@Test
public void testConditionalConfiguration() {
logger.trace("Employee record updated");
}
}

View File

@ -0,0 +1,28 @@
<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.stackify</groupId>
<artifactId>thread-pools</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,28 @@
package com.stackify.models;
public class Employee {
private String name;
private double salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Employee(String name, double salary) {
super();
this.name = name;
this.salary = salary;
}
}

View File

@ -0,0 +1,9 @@
package com.stackify.services;
import com.stackify.models.Employee;
public class EmployeeService {
public double calculateBonus(Employee employee) {
return 0.1 * employee.getSalary();
}
}

View File

@ -0,0 +1,64 @@
package com.stackify.threadpools;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.IntStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FactorialTask extends RecursiveTask<BigInteger> {
private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
private static final long serialVersionUID = 1L;
private int start = 1;
private int n;
private static final int THRESHOLD = 20;
public FactorialTask(int n) {
this.n = n;
}
public FactorialTask(int start, int n) {
logger.info("New FactorialTask Created");
this.start = start;
this.n = n;
}
@Override
protected BigInteger compute() {
if ((n - start) >= THRESHOLD) {
return ForkJoinTask.invokeAll(createSubtasks())
.stream()
.map(ForkJoinTask::join)
.reduce(BigInteger.ONE, BigInteger::multiply);
} else {
return calculate(start, n);
}
}
private Collection<FactorialTask> createSubtasks() {
List<FactorialTask> dividedTasks = new ArrayList<>();
int mid = (start + n) / 2;
dividedTasks.add(new FactorialTask(start, mid));
dividedTasks.add(new FactorialTask(mid + 1, n));
return dividedTasks;
}
private BigInteger calculate(int start, int n) {
logger.info("Calculate factorial from " + start + " to " + n);
return IntStream.rangeClosed(start, n)
.mapToObj(BigInteger::valueOf)
.reduce(BigInteger.ONE, BigInteger::multiply);
}
}

View File

@ -0,0 +1,102 @@
package com.stackify.threadpools;
import java.math.BigInteger;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.stackify.models.Employee;
import com.stackify.services.EmployeeService;
public class ThreadsApplication {
private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
public static void main(String[] args) {
testExecutor();
testExecutorService();
testScheduledExecutorService();
testThreadPoolExecutor();
testForkJoinPool();
}
private static EmployeeService employeeService = new EmployeeService();
public static void testExecutor() {
Executor executor = Executors.newSingleThreadExecutor();
executor.execute(() -> System.out.println("Single thread pool test"));
}
public static void testExecutorService() {
Employee employee = new Employee("John", 2000);
ExecutorService executor = Executors.newFixedThreadPool(10);
Callable<Double> callableTask = () -> {
return employeeService.calculateBonus(employee);
};
Future<Double> future = executor.submit(callableTask);
try {
if (future.isDone()) {
double result = future.get();
System.out.println("Bonus is:" + result);
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executor.shutdown();
}
public static void testScheduledExecutorService() {
Employee employee = new Employee("John", 2000);
ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
Callable<Double> callableTask = () -> {
return employeeService.calculateBonus(employee);
};
Future<Double> futureScheduled = executor.schedule(callableTask, 2, TimeUnit.MILLISECONDS);
try {
System.out.println("Bonus:" + futureScheduled.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executor.scheduleAtFixedRate(() -> System.out.println("Fixed Rate Scheduled"), 2, 2000, TimeUnit.MILLISECONDS);
executor.scheduleWithFixedDelay(() -> System.out.println("Fixed Delay Scheduled"), 2, 2000, TimeUnit.MILLISECONDS);
}
public static void testThreadPoolExecutor() {
ThreadPoolExecutor fixedPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
ThreadPoolExecutor cachedPoolExecutor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 6, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
executor.setMaximumPoolSize(8);
ScheduledThreadPoolExecutor scheduledExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(5);
}
public static void testForkJoinPool() {
ForkJoinPool pool = ForkJoinPool.commonPool();
logger.info("Thread Pool Created");
BigInteger result = pool.invoke(new FactorialTask(100));
System.out.println(result.toString());
}
}

View File

@ -129,7 +129,7 @@
<properties>
<!-- marshalling -->
<jackson.version>2.8.7</jackson.version>
<jackson.version>2.9.0</jackson.version>
<!-- util -->
<guava.version>19.0</guava.version>

View File

@ -9,7 +9,8 @@ public class Author extends Person {
List<Item> items = new ArrayList<>();
public Author(){}
public Author() {
}
public Author(String firstName, String lastName) {
super(firstName, lastName);

View File

@ -11,7 +11,7 @@ public class Person {
private String firstName;
private String lastName;
public Person(){
public Person() {
}

View File

@ -1,6 +1,5 @@
package com.baeldung.jackson.deserialization.jsoncreator;
import com.baeldung.jackson.domain.Person;
import com.baeldung.jackson.domain.Item;
import com.fasterxml.jackson.annotation.JsonCreator;
@ -14,9 +13,7 @@ public class Author extends Person {
List<Item> items = new ArrayList<>();
@JsonCreator
public Author(
@JsonProperty("christianName") String firstName,
@JsonProperty("surname") String lastName) {
public Author(@JsonProperty("christianName") String firstName, @JsonProperty("surname") String lastName) {
super(firstName, lastName);
}

View File

@ -13,7 +13,8 @@ public class Book extends Item {
private Date published;
private BigDecimal pages;
public Book() {}
public Book() {
}
public Book(String title, Author author) {
super(title, author);

View File

@ -11,8 +11,7 @@ import java.util.Date;
public class CustomDateDeserializer extends StdDeserializer<Date> {
private static SimpleDateFormat formatter =
new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
public CustomDateDeserializer() {
this(null);
@ -23,8 +22,7 @@ public class CustomDateDeserializer extends StdDeserializer<Date> {
}
@Override
public Date deserialize(JsonParser jsonparser, DeserializationContext context)
throws IOException {
public Date deserialize(JsonParser jsonparser, DeserializationContext context) throws IOException {
String date = jsonparser.getText();
try {
return formatter.parse(date);

View File

@ -19,7 +19,8 @@ public class Item {
private List<Person> authors = new ArrayList<>();
private float price;
public Item(){}
public Item() {
}
public Item(String title, Author author) {
this.id = UUID.randomUUID();

View File

@ -18,7 +18,8 @@ public class Author extends Person {
private List<Item> items = new ArrayList<>();
public Author(){}
public Author() {
}
public Author(String firstName, String lastName) {
super(firstName, lastName);

View File

@ -15,7 +15,7 @@ public class Book extends Item {
private Date published;
private BigDecimal pages;
public Book(){
public Book() {
}
public Book(String title, Author author) {

View File

@ -10,7 +10,9 @@ import java.util.List;
*/
public class Course extends Item {
public enum Medium {CLASSROOM, ONLINE}
public enum Medium {
CLASSROOM, ONLINE
}
public enum Level {
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);

View File

@ -17,7 +17,8 @@ public class Item {
private List<Person> authors = new ArrayList<>();
private float price;
public Item(){}
public Item() {
}
public Item(String title, Author author) {
this.id = UUID.randomUUID();

View File

@ -14,7 +14,8 @@ public class Person {
private String firstName;
private String lastName;
public Person(){}
public Person() {
}
public Person(String firstName, String lastName) {
this.id = UUID.randomUUID();

View File

@ -9,16 +9,16 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
public class ClassWithAMap {
@JsonProperty("map")
@JsonDeserialize(keyUsing = MyPairDeserializer.class)
private final Map<MyPair, String> map;
@JsonProperty("map")
@JsonDeserialize(keyUsing = MyPairDeserializer.class)
private final Map<MyPair, String> map;
@JsonCreator
public ClassWithAMap(Map<MyPair, String> map) {
this.map = map;
}
@JsonCreator
public ClassWithAMap(Map<MyPair, String> map) {
this.map = map;
}
public Map<MyPair, String> getMap() {
return map;
}
public Map<MyPair, String> getMap() {
return map;
}
}

View File

@ -4,77 +4,77 @@ import com.fasterxml.jackson.annotation.JsonValue;
public class MyPair {
private String first;
private String second;
private String first;
private String second;
public MyPair(String first, String second) {
this.first = first;
this.second = second;
}
public MyPair(String first, String second) {
this.first = first;
this.second = second;
}
public MyPair(String both) {
String[] pairs = both.split("and");
this.first = pairs[0].trim();
this.second = pairs[1].trim();
}
public MyPair(String both) {
String[] pairs = both.split("and");
this.first = pairs[0].trim();
this.second = pairs[1].trim();
}
@Override
@JsonValue
public String toString() {
return first + " and " + second;
}
@Override
@JsonValue
public String toString() {
return first + " and " + second;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((first == null) ? 0 : first.hashCode());
result = prime * result + ((second == null) ? 0 : second.hashCode());
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((first == null) ? 0 : first.hashCode());
result = prime * result + ((second == null) ? 0 : second.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof MyPair)) {
return false;
}
MyPair other = (MyPair) obj;
if (first == null) {
if (other.first != null) {
return false;
}
} else if (!first.equals(other.first)) {
return false;
}
if (second == null) {
if (other.second != null) {
return false;
}
} else if (!second.equals(other.second)) {
return false;
}
return true;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof MyPair)) {
return false;
}
MyPair other = (MyPair) obj;
if (first == null) {
if (other.first != null) {
return false;
}
} else if (!first.equals(other.first)) {
return false;
}
if (second == null) {
if (other.second != null) {
return false;
}
} else if (!second.equals(other.second)) {
return false;
}
return true;
}
public String getFirst() {
return first;
}
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public void setFirst(String first) {
this.first = first;
}
public String getSecond() {
return second;
}
public String getSecond() {
return second;
}
public void setSecond(String second) {
this.second = second;
}
public void setSecond(String second) {
this.second = second;
}
}

View File

@ -13,28 +13,25 @@ public class User extends Person {
private String firstName;
private String lastName;
@JsonFormat(shape = JsonFormat.Shape.STRING,
pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ")
private Date createdDate;
public User(String firstName,String lastName) {
super(firstName, lastName);
this.createdDate = new Date();
public User(String firstName, String lastName) {
super(firstName, lastName);
this.createdDate = new Date();
}
public Date getCreatedDate() {
return createdDate;
}
@JsonFormat(shape = JsonFormat.Shape.STRING,
pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ",
locale = "en_GB")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ", locale = "en_GB")
public Date getCurrentDate() {
return new Date();
return new Date();
}
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
public Date getDateNum() {
return new Date();
return new Date();
}
}

View File

@ -17,7 +17,8 @@ public class Person {
private String firstName;
private String lastName;
public Person(){}
public Person() {
}
public Person(String firstName, String lastName) {
this.id = UUID.randomUUID();

View File

@ -12,10 +12,12 @@ import java.util.List;
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
@JsonIgnoreProperties({"medium"})
@JsonIgnoreProperties({ "medium" })
public class Course extends Item {
public enum Medium {CLASSROOM, ONLINE}
public enum Medium {
CLASSROOM, ONLINE
}
public enum Level {
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);

View File

@ -12,10 +12,7 @@ public class ItemIdAddedToUser extends Event {
private final Long quantity;
@JsonCreator
public ItemIdAddedToUser(@JsonProperty("id") String id,
@JsonProperty("timestamp") Long timestamp,
@JsonProperty("itemId") String itemId,
@JsonProperty("quantity") Long quantity) {
public ItemIdAddedToUser(@JsonProperty("id") String id, @JsonProperty("timestamp") Long timestamp, @JsonProperty("itemId") String itemId, @JsonProperty("quantity") Long quantity) {
super(id, timestamp);
this.itemId = itemId;
this.quantity = quantity;

View File

@ -10,10 +10,7 @@ public class ItemIdRemovedFromUser extends Event {
private final Long quantity;
@JsonCreator
public ItemIdRemovedFromUser(@JsonProperty("id") String id,
@JsonProperty("timestamp") Long timestamp,
@JsonProperty("itemId") String itemId,
@JsonProperty("quantity") Long quantity) {
public ItemIdRemovedFromUser(@JsonProperty("id") String id, @JsonProperty("timestamp") Long timestamp, @JsonProperty("itemId") String itemId, @JsonProperty("quantity") Long quantity) {
super(id, timestamp);
this.itemId = itemId;
this.quantity = quantity;

View File

@ -13,7 +13,9 @@ import java.util.List;
@CustomCourseAnnotation
public class Course extends Item {
public enum Medium {CLASSROOM, ONLINE}
public enum Medium {
CLASSROOM, ONLINE
}
public enum Level {
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);

View File

@ -14,7 +14,7 @@ import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"title", "price", "id", "duration", "authors", "level"})
@JsonIgnoreProperties({"prerequisite"})
@JsonPropertyOrder({ "title", "price", "id", "duration", "authors", "level" })
@JsonIgnoreProperties({ "prerequisite" })
public @interface CustomCourseAnnotation {
}

View File

@ -20,7 +20,8 @@ public class Item {
private List<Person> authors = new ArrayList<>();
private float price;
public Item(){}
public Item() {
}
public Item(String title, Author author) {
this.id = UUID.randomUUID();

View File

@ -16,7 +16,7 @@ import java.util.List;
* @version 1.0
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"lastName", "items", "firstName", "id"})
@JsonPropertyOrder({ "lastName", "items", "firstName", "id" })
public class Author extends Person {
@JsonIgnore

View File

@ -18,12 +18,8 @@ public class Order {
private Type type;
private int internalAudit;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "ordertype")
@JsonSubTypes({
@JsonSubTypes.Type(value = InternalType.class, name = "internal")
})
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "ordertype")
@JsonSubTypes({ @JsonSubTypes.Type(value = InternalType.class, name = "internal") })
public static class Type {
public long id;
public String name;

View File

@ -24,8 +24,11 @@ public class ActorJacksonSerializer extends StdSerializer<ActorJackson> {
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("imdbId", actor.getImdbId());
jsonGenerator.writeObjectField("dateOfBirth", actor.getDateOfBirth() != null ? sdf.format(actor.getDateOfBirth()) : null);
jsonGenerator.writeNumberField("N° Film: ", actor.getFilmography() != null ? actor.getFilmography().size() : null);
jsonGenerator.writeStringField("filmography", actor.getFilmography().stream().collect(Collectors.joining("-")));
jsonGenerator.writeNumberField("N° Film: ", actor.getFilmography() != null ? actor.getFilmography()
.size() : null);
jsonGenerator.writeStringField("filmography", actor.getFilmography()
.stream()
.collect(Collectors.joining("-")));
jsonGenerator.writeEndObject();
}
}

View File

@ -9,10 +9,9 @@ import com.fasterxml.jackson.databind.KeyDeserializer;
public class MyPairDeserializer extends KeyDeserializer {
@Override
public MyPair deserializeKey(String key, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
@Override
public MyPair deserializeKey(String key, DeserializationContext ctxt) throws IOException, JsonProcessingException {
return new MyPair(key);
}
return new MyPair(key);
}
}

View File

@ -12,14 +12,12 @@ import com.fasterxml.jackson.databind.SerializerProvider;
public class MyPairSerializer extends JsonSerializer<MyPair> {
private final ObjectMapper mapper = new ObjectMapper();
private final ObjectMapper mapper = new ObjectMapper();
@Override
public void serialize(MyPair value, JsonGenerator gen,
SerializerProvider serializers) throws IOException,
JsonProcessingException {
StringWriter writer = new StringWriter();
mapper.writeValue(writer, value);
gen.writeFieldName(writer.toString());
}
@Override
public void serialize(MyPair value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
StringWriter writer = new StringWriter();
mapper.writeValue(writer, value);
gen.writeFieldName(writer.toString());
}
}

View File

@ -1,6 +1,5 @@
package com.baeldung.jackson.serialization.jsongetter;
import com.baeldung.jackson.domain.Item;
import com.baeldung.jackson.domain.Person;
import com.fasterxml.jackson.annotation.JsonGetter;

View File

@ -1,6 +1,5 @@
package com.baeldung.jackson.serialization.jsonpropertyorder;
import com.baeldung.jackson.domain.Item;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@ -13,7 +12,7 @@ import java.util.List;
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
@JsonPropertyOrder({"items", "firstName", "lastName", "id"})
@JsonPropertyOrder({ "items", "firstName", "lastName", "id" })
public class Author extends Person {
List<Item> items = new ArrayList<>();

View File

@ -19,7 +19,8 @@ public class Book extends Item {
private Date published;
private BigDecimal pages;
public Book(){}
public Book() {
}
public Book(String title, Author author) {
super(title, author);

View File

@ -17,8 +17,7 @@ import java.util.Date;
*/
public class CustomDateSerializer extends StdSerializer<Date> {
private static SimpleDateFormat formatter =
new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
public CustomDateSerializer() {
this(null);
@ -29,8 +28,7 @@ public class CustomDateSerializer extends StdSerializer<Date> {
}
@Override
public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2)
throws IOException, JsonProcessingException {
public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) throws IOException, JsonProcessingException {
gen.writeString(formatter.format(value));
}
}

View File

@ -19,7 +19,8 @@ public class Item {
private List<Person> authors = new ArrayList<>();
private float price;
public Item(){}
public Item() {
}
public Item(String title, Author author) {
this.id = UUID.randomUUID();

View File

@ -14,7 +14,9 @@ import java.util.List;
*/
public class Course extends Item {
public enum Medium {CLASSROOM, ONLINE}
public enum Medium {
CLASSROOM, ONLINE
}
public enum Level {
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);

View File

@ -47,9 +47,10 @@ public class ExtraAnnotationUnitTest {
ObjectMapper mapper = new ObjectMapper();
BeanWithoutAppend bean = new BeanWithoutAppend(2, "Bean Without Append Annotation");
ObjectWriter writer = mapper.writerFor(BeanWithoutAppend.class).withAttribute("version", "1.0");
ObjectWriter writer = mapper.writerFor(BeanWithoutAppend.class)
.withAttribute("version", "1.0");
String jsonString = writer.writeValueAsString(bean);
assertThat(jsonString, not(containsString("version")));
assertThat(jsonString, not(containsString("1.0")));
}
@ -59,9 +60,10 @@ public class ExtraAnnotationUnitTest {
ObjectMapper mapper = new ObjectMapper();
BeanWithAppend bean = new BeanWithAppend(2, "Bean With Append Annotation");
ObjectWriter writer = mapper.writerFor(BeanWithAppend.class).withAttribute("version", "1.0");
ObjectWriter writer = mapper.writerFor(BeanWithAppend.class)
.withAttribute("version", "1.0");
String jsonString = writer.writeValueAsString(bean);
assertThat(jsonString, containsString("version"));
assertThat(jsonString, containsString("1.0"));
}
@ -71,7 +73,7 @@ public class ExtraAnnotationUnitTest {
ObjectMapper mapper = new ObjectMapper();
NamingBean bean = new NamingBean(3, "Naming Bean");
String jsonString = mapper.writeValueAsString(bean);
assertThat(jsonString, containsString("bean_name"));
}

View File

@ -4,7 +4,6 @@ import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIdentityReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
public class IdentityReferenceBeans {
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public static class BeanWithoutIdentityReference {
@ -32,7 +31,7 @@ public class IdentityReferenceBeans {
this.name = name;
}
}
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = true)
public static class BeanWithIdentityReference {

View File

@ -20,6 +20,7 @@ public class CustomListSerializer extends StdSerializer<List<ItemWithSerializer>
public CustomListSerializer(final Class<List<ItemWithSerializer>> t) {
super(t);
}
@Override
public void serialize(final List<ItemWithSerializer> items, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException {
final List<Integer> ids = new ArrayList<Integer>();

View File

@ -11,7 +11,6 @@ import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class CustomLocalDateTimeSerializer extends StdSerializer<LocalDateTime> {
private static final long serialVersionUID = -7449444168934819290L;
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

View File

@ -28,9 +28,11 @@ public class ItemDeserializer extends StdDeserializer<Item> {
*/
@Override
public Item deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
final JsonNode node = jp.getCodec().readTree(jp);
final JsonNode node = jp.getCodec()
.readTree(jp);
final int id = (Integer) ((IntNode) node.get("id")).numberValue();
final String itemName = node.get("itemName").asText();
final String itemName = node.get("itemName")
.asText();
final int userId = (Integer) ((IntNode) node.get("createdBy")).numberValue();
return new Item(id, itemName, new User(userId, null));

View File

@ -28,9 +28,11 @@ public class ItemDeserializerOnClass extends StdDeserializer<ItemWithSerializer>
*/
@Override
public ItemWithSerializer deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
final JsonNode node = jp.getCodec().readTree(jp);
final JsonNode node = jp.getCodec()
.readTree(jp);
final int id = (Integer) ((IntNode) node.get("id")).numberValue();
final String itemName = node.get("itemName").asText();
final String itemName = node.get("itemName")
.asText();
final int userId = (Integer) ((IntNode) node.get("owner")).numberValue();
return new ItemWithSerializer(id, itemName, new User(userId, null));

View File

@ -16,54 +16,49 @@ import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonMapDeserializeUnitTest {
private Map<MyPair, String> map;
private Map<MyPair, MyPair> cmap;
final ObjectMapper mapper = new ObjectMapper();
private Map<MyPair, String> map;
private Map<MyPair, MyPair> cmap;
final ObjectMapper mapper = new ObjectMapper();
@Test
public void whenSimpleMapDeserialize_thenCorrect()
throws JsonParseException, JsonMappingException, IOException {
@Test
public void whenSimpleMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
final String jsonInput = "{\"key\": \"value\"}";
TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String, String>>() {
};
final String jsonInput = "{\"key\": \"value\"}";
TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String, String>>() {
};
final Map<String, String> map = mapper.readValue(jsonInput, typeRef);
final Map<String, String> map = mapper.readValue(jsonInput, typeRef);
Assert.assertEquals("value", map.get("key"));
}
Assert.assertEquals("value", map.get("key"));
}
@Test
public void whenObjectStringMapDeserialize_thenCorrect()
throws JsonParseException, JsonMappingException, IOException {
@Test
public void whenObjectStringMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
final String jsonInput = "{\"Abbott and Costello\":\"Comedy\"}";
final String jsonInput = "{\"Abbott and Costello\":\"Comedy\"}";
TypeReference<HashMap<MyPair, String>> typeRef = new TypeReference<HashMap<MyPair, String>>() {
};
TypeReference<HashMap<MyPair, String>> typeRef = new TypeReference<HashMap<MyPair, String>>() {
};
map = mapper.readValue(jsonInput, typeRef);
map = mapper.readValue(jsonInput, typeRef);
Assert.assertEquals("Comedy", map.get(new MyPair("Abbott", "Costello")));
Assert.assertEquals("Comedy", map.get(new MyPair("Abbott", "Costello")));
ClassWithAMap classWithMap = mapper.readValue(jsonInput,
ClassWithAMap.class);
ClassWithAMap classWithMap = mapper.readValue(jsonInput, ClassWithAMap.class);
Assert.assertEquals("Comedy",
classWithMap.getMap().get(new MyPair("Abbott", "Costello")));
}
Assert.assertEquals("Comedy", classWithMap.getMap()
.get(new MyPair("Abbott", "Costello")));
}
@Test
public void whenObjectObjectMapDeserialize_thenCorrect()
throws JsonParseException, JsonMappingException, IOException {
@Test
public void whenObjectObjectMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
final String jsonInput = "{\"Abbott and Costello\" : \"Comedy and 1940s\"}";
TypeReference<HashMap<MyPair, MyPair>> typeRef = new TypeReference<HashMap<MyPair, MyPair>>() {
};
final String jsonInput = "{\"Abbott and Costello\" : \"Comedy and 1940s\"}";
TypeReference<HashMap<MyPair, MyPair>> typeRef = new TypeReference<HashMap<MyPair, MyPair>>() {
};
cmap = mapper.readValue(jsonInput, typeRef);
cmap = mapper.readValue(jsonInput, typeRef);
Assert.assertEquals(new MyPair("Comedy", "1940s"),
cmap.get(new MyPair("Abbott", "Costello")));
}
Assert.assertEquals(new MyPair("Comedy", "1940s"), cmap.get(new MyPair("Abbott", "Costello")));
}
}

View File

@ -27,7 +27,9 @@ public class JacksonInjectUnitTest {
// act
InjectableValues inject = new InjectableValues.Std().addValue(UUID.class, id);
Author author = new ObjectMapper().reader(inject).forType(Author.class).readValue(authorJson);
Author author = new ObjectMapper().reader(inject)
.forType(Author.class)
.readValue(authorJson);
// assert
assertThat(author.getId()).isEqualTo(id);

View File

@ -23,15 +23,28 @@ public class JsonAnySetterUnitTest {
String json = "{\"USA\":10.00,\"UK\":15.00,\"China\":23.00,\"Brazil\":12.00,\"France\":8.00,\"Russia\":18.00}";
// act
Inventory inventory = new ObjectMapper().readerFor(Inventory.class).readValue(json);
Inventory inventory = new ObjectMapper().readerFor(Inventory.class)
.readValue(json);
// assert
assertThat(from(json).getMap(".").get("USA")).isEqualTo(inventory.getCountryDeliveryCost().get("USA"));
assertThat(from(json).getMap(".").get("UK")).isEqualTo(inventory.getCountryDeliveryCost().get("UK"));
assertThat(from(json).getMap(".").get("China")).isEqualTo(inventory.getCountryDeliveryCost().get("China"));
assertThat(from(json).getMap(".").get("Brazil")).isEqualTo(inventory.getCountryDeliveryCost().get("Brazil"));
assertThat(from(json).getMap(".").get("France")).isEqualTo(inventory.getCountryDeliveryCost().get("France"));
assertThat(from(json).getMap(".").get("Russia")).isEqualTo(inventory.getCountryDeliveryCost().get("Russia"));
assertThat(from(json).getMap(".")
.get("USA")).isEqualTo(inventory.getCountryDeliveryCost()
.get("USA"));
assertThat(from(json).getMap(".")
.get("UK")).isEqualTo(inventory.getCountryDeliveryCost()
.get("UK"));
assertThat(from(json).getMap(".")
.get("China")).isEqualTo(inventory.getCountryDeliveryCost()
.get("China"));
assertThat(from(json).getMap(".")
.get("Brazil")).isEqualTo(inventory.getCountryDeliveryCost()
.get("Brazil"));
assertThat(from(json).getMap(".")
.get("France")).isEqualTo(inventory.getCountryDeliveryCost()
.get("France"));
assertThat(from(json).getMap(".")
.get("Russia")).isEqualTo(inventory.getCountryDeliveryCost()
.get("Russia"));
}
}

View File

@ -20,14 +20,11 @@ public class JsonCreatorUnitTest {
public void whenDeserializingUsingJsonCreator_thenCorrect() throws IOException {
// arrange
String authorJson =
"{" +
" \"christianName\": \"Alex\"," +
" \"surname\": \"Theedom\"" +
"}";
String authorJson = "{" + " \"christianName\": \"Alex\"," + " \"surname\": \"Theedom\"" + "}";
// act
final Author author = new ObjectMapper().readerFor(Author.class).readValue(authorJson);
final Author author = new ObjectMapper().readerFor(Author.class)
.readValue(authorJson);
// assert
assertThat(from(authorJson).getString("christianName")).isEqualTo(author.getFirstName());

View File

@ -24,7 +24,8 @@ public class JsonDeserializeUnitTest {
String bookJson = "{\"id\":\"957c43f2-fa2e-42f9-bf75-6e3d5bb6960a\",\"title\":\"Effective Java\",\"authors\":[{\"id\":\"9bcd817d-0141-42e6-8f04-e5aaab0980b6\",\"firstName\":\"Joshua\",\"lastName\":\"Bloch\"}],\"price\":0,\"published\":\"25-12-2017 13:30:25\",\"pages\":null,\"isbn\":null}";
// act
Book book = new ObjectMapper().readerFor(Book.class).readValue(bookJson);
Book book = new ObjectMapper().readerFor(Book.class)
.readValue(bookJson);
// assert
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

View File

@ -23,10 +23,13 @@ public class JsonSetterUnitTest {
String json = "{\"firstName\":\"Alex\",\"lastName\":\"Theedom\",\"publications\":[{\"title\":\"Professional Java EE Design Patterns\"}]}";
// act
Author author = new ObjectMapper().readerFor(Author.class).readValue(json);
Author author = new ObjectMapper().readerFor(Author.class)
.readValue(json);
// assert
assertThat(from(json).getList("publications").size()).isEqualTo(author.getItems().size());
assertThat(from(json).getList("publications")
.size()).isEqualTo(author.getItems()
.size());
}
}

View File

@ -1,6 +1,5 @@
package com.baeldung.jackson.dynamicIgnore;
public class Address implements Hidable {
private String city;
private String country;

View File

@ -2,7 +2,6 @@ package com.baeldung.jackson.dynamicIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties("hidden")
public interface Hidable {
boolean isHidden();

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