Merge branch 'master' into pr/884-tim

This commit is contained in:
slavisa-baeldung 2016-12-08 22:28:12 +01:00
commit e75e0097a3
278 changed files with 8629 additions and 2390 deletions

View File

@ -98,13 +98,14 @@
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- <plugin>
<!--
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.10</version>
@ -113,7 +114,8 @@
<useSystemClassLoader>true</useSystemClassLoader>
<forkMode>always</forkMode>
</configuration>
</plugin> -->
</plugin>
-->
</plugins>
</build>

View File

@ -4,10 +4,10 @@ public class Account {
int balance = 20;
public boolean withdraw(int amount) {
if (balance - amount > 0) {
balance = balance - amount;
return true;
} else
if (balance < amount) {
return false;
}
balance = balance - amount;
return true;
}
}

View File

@ -16,12 +16,11 @@ public aspect AccountAspect {
}
boolean around(int amount, Account account) : callWithDraw(amount, account) {
if (account.balance - amount >= MIN_BALANCE)
return proceed(amount, account);
else {
if (account.balance < amount) {
logger.info("Withdrawal Rejected!");
return false;
}
return proceed(amount, account);
}
after(int amount, Account balance) : callWithDraw(amount, balance) {

View File

@ -0,0 +1,12 @@
package com.baeldung.generics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Building {
private static final Logger LOGGER = LoggerFactory.getLogger(Building.class);
public void paint() {
LOGGER.info("Painting Building");
}
}

View File

@ -1,23 +1,31 @@
package com.baeldung.generics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Generics {
// definition of a generic method
public static <T> List<T> fromArrayToList(T[] a) {
List<T> list = new ArrayList<>();
Arrays.stream(a).forEach(list::add);
return list;
return Arrays.stream(a).collect(Collectors.toList());
}
// definition of a generic method
public static <T, G> List<G> fromArrayToList(T[] a, Function<T, G> mapperFunction) {
return Arrays.stream(a).map(mapperFunction).collect(Collectors.toList());
}
// example of a generic method that has Number as an upper bound for T
public static <T extends Number> List<T> fromArrayToListWithUpperBound(T[] a) {
List<T> list = new ArrayList<>();
Arrays.stream(a).forEach(list::add);
return list;
return Arrays.stream(a).collect(Collectors.toList());
}
}
// example of a generic method with a wild card, this method can be used
// with a list of any subtype of Building
public static void paintAllBuildings(List<? extends Building> buildings) {
buildings.forEach(Building::paint);
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.generics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class House extends Building {
private static final Logger LOGGER = LoggerFactory.getLogger(House.class);
public void paint() {
LOGGER.info("Painting House");
}
}

View File

@ -1,6 +1,5 @@
package com.baeldung.hashing;
import com.google.common.hash.Hashing;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.util.encoders.Hex;
@ -11,17 +10,14 @@ import java.security.NoSuchAlgorithmException;
public class SHA256Hashing {
public static String HashWithJavaMessageDigest(final String originalString)
throws NoSuchAlgorithmException {
public static String HashWithJavaMessageDigest(final String originalString) throws NoSuchAlgorithmException {
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
final byte[] encodedhash = digest.digest(
originalString.getBytes(StandardCharsets.UTF_8));
final byte[] encodedhash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8));
return bytesToHex(encodedhash);
}
public static String HashWithGuava(final String originalString) {
final String sha256hex = Hashing.sha256().hashString(
originalString, StandardCharsets.UTF_8).toString();
final String sha256hex = Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString();
return sha256hex;
}
@ -30,11 +26,9 @@ public class SHA256Hashing {
return sha256hex;
}
public static String HashWithBouncyCastle(final String originalString)
throws NoSuchAlgorithmException {
public static String HashWithBouncyCastle(final String originalString) throws NoSuchAlgorithmException {
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
final byte[] hash = digest.digest(
originalString.getBytes(StandardCharsets.UTF_8));
final byte[] hash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8));
final String sha256hex = new String(Hex.encode(hash));
return sha256hex;
}
@ -43,7 +37,8 @@ public class SHA256Hashing {
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1) hexString.append('0');
if (hex.length() == 1)
hexString.append('0');
hexString.append(hex);
}
return hexString.toString();

View File

@ -0,0 +1,56 @@
package com.baeldung.java.nio2.visitor;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import static java.nio.file.FileVisitResult.CONTINUE;
import static java.nio.file.FileVisitResult.TERMINATE;
public class FileSearchExample implements FileVisitor<Path> {
private final String fileName;
private final Path startDir;
public FileSearchExample(String fileName, Path startingDir) {
this.fileName = fileName;
startDir = startingDir;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
return CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String fileName = file.getFileName().toString();
if (this.fileName.equals(fileName)) {
System.out.println("File found: " + file.toString());
return TERMINATE;
}
return CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
System.out.println("Failed to access file: " + file.toString());
return CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
boolean finishedSearch = Files.isSameFile(dir, startDir);
if (finishedSearch) {
System.out.println("File:" + fileName + " not found");
return TERMINATE;
}
return CONTINUE;
}
public static void main(String[] args) throws IOException {
Path startingDir = Paths.get("C:/Users/new/Desktop");
FileSearchExample crawler = new FileSearchExample("hibernate.txt", startingDir);
Files.walkFileTree(startingDir, crawler);
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.java.nio2.visitor;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
public class FileVisitorImpl implements FileVisitor<Path> {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
return null;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
return null;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
return null;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
return null;
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.java.nio2.watcher;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class DirectoryWatcherExample {
public static void main(String[] args) throws IOException, InterruptedException {
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get(System.getProperty("user.home"));
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
System.out.println("Event kind:" + event.kind() + ". File affected: " + event.context() + ".");
}
key.reset();
}
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.optional;
public class Modem {
private Double price;
public Modem(Double price) {
this.price = price;
}
public Double getPrice() {
return price;
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.optional;
import java.util.Optional;
public class Person {
private String name;
private int age;
private String password;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Optional<String> getName() {
return Optional.ofNullable(name);
}
public void setName(String name) {
this.name = name;
}
public Optional<Integer> getAge() {
return Optional.ofNullable(age);
}
public void setAge(int age) {
this.age = age;
}
public void setPassword(String password) {
this.password = password;
}
public Optional<String> getPassword() {
return Optional.ofNullable(password);
}
}

View File

@ -7,9 +7,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
@ -20,7 +18,7 @@ import static java.util.stream.Collectors.joining;
public class EncoderDecoderUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(EncoderDecoderUnitTest.class);
private static final String testUrl = "http://www.baeldung.com?key1=value+1&key2=value%40%21%242&key3=value%253";
private static final String testUrl = "http://www.baeldung.com/path+1?key1=value+1&key2=value%40%21%242&key3=value%253#dummy+Fragment";
private String encodeValue(String value) {
String encoded = null;
@ -44,11 +42,13 @@ public class EncoderDecoderUnitTest {
@Test
public void givenURL_whenAnalyze_thenCorrect() throws Exception {
URL url = new URL(testUrl);
URI uri = new URI(testUrl);
Assert.assertThat(url.getProtocol(), CoreMatchers.is("http"));
Assert.assertThat(url.getHost(), CoreMatchers.is("www.baeldung.com"));
Assert.assertThat(url.getQuery(), CoreMatchers.is("key1=value+1&key2=value%40%21%242&key3=value%253"));
Assert.assertThat(uri.getScheme(), CoreMatchers.is("http"));
Assert.assertThat(uri.getHost(), CoreMatchers.is("www.baeldung.com"));
Assert.assertThat(uri.getRawPath(), CoreMatchers.is("/path+1"));
Assert.assertThat(uri.getRawQuery(), CoreMatchers.is("key1=value+1&key2=value%40%21%242&key3=value%253"));
Assert.assertThat(uri.getRawFragment(), CoreMatchers.is("dummy+Fragment"));
}
@Test
@ -58,20 +58,44 @@ public class EncoderDecoderUnitTest {
requestParams.put("key2", "value@!$2");
requestParams.put("key3", "value%3");
String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com?", ""));
String path = "path+1";
String fragment = "dummy Fragment";
String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com/" + getPath(path) + "?", "#" + encodeValue(fragment)));
Assert.assertThat(testUrl, CoreMatchers.is(encodedURL));
}
@Test
public void givenRequestParam_whenUTF8Scheme_thenDecodeRequestParams() throws Exception {
URL url = new URL(testUrl);
URI uri = new URI(testUrl);
String query = url.getQuery();
String scheme = uri.getScheme();
String host = uri.getHost();
String query = uri.getRawQuery();
String path = uri.getRawPath();
String fragment = uri.getRawFragment();
String decodedQuery = Arrays.stream(query.split("&")).map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1])).collect(joining("&"));
String decodedPath = Arrays.stream(path.split("/")).map(param -> getPath(param)).collect(joining("/"));
Assert.assertEquals("http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery);
Assert.assertEquals("http://www.baeldung.com/path+1?key1=value 1&key2=value@!$2&key3=value%3#dummy Fragment", scheme + "://" + host + decodedPath + "?" + decodedQuery + "#" + decode(fragment));
}
private String getPath(String path) {
try {
path = new URI(null, null, path, null).getPath();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return path;
}
@Test
public void givenPath_thenEncodeDecodePath() throws URISyntaxException {
URI uri = new URI(null, null, "/Path 1/Path+2", null);
Assert.assertEquals("/Path 1/Path+2", uri.getPath());
Assert.assertEquals("/Path%201/Path+2", uri.getRawPath());
}
}

View File

@ -1,11 +1,12 @@
package com.baeldung.file;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.io.FileUtils;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
@ -14,12 +15,6 @@ import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
import org.apache.commons.io.FileUtils;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
public class FileOperationsUnitTest {
@Test
@ -58,9 +53,9 @@ public class FileOperationsUnitTest {
@Test
public void givenURLName_whenUsingURL_thenFileData() throws IOException {
String expectedData = "Baeldung";
String expectedData = "Example Domain";
URL urlObject = new URL("http://www.baeldung.com/");
URL urlObject = new URL("http://www.example.com/");
URLConnection urlConnection = urlObject.openConnection();

View File

@ -2,26 +2,36 @@ package com.baeldung.generics;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;
public class GenericsTest {
// testing the generic method with Integer
@Test
public void givenArrayOfIntegers_thanListOfIntegersReturnedOK() {
Integer[] intArray = {1, 2, 3, 4, 5};
Integer[] intArray = { 1, 2, 3, 4, 5 };
List<Integer> list = Generics.fromArrayToList(intArray);
assertThat(list, hasItems(intArray));
}
// testing the generic method with Integer and String type
@Test
public void givenArrayOfIntegers_thanListOfStringReturnedOK() {
Integer[] intArray = { 1, 2, 3, 4, 5 };
List<String> stringList = Generics.fromArrayToList(intArray, Object::toString);
assertThat(stringList, hasItems("1", "2", "3", "4", "5"));
}
// testing the generic method with String
@Test
public void givenArrayOfStrings_thanListOfStringsReturnedOK() {
String[] stringArray = {"hello1", "hello2", "hello3", "hello4", "hello5"};
String[] stringArray = { "hello1", "hello2", "hello3", "hello4", "hello5" };
List<String> list = Generics.fromArrayToList(stringArray);
assertThat(list, hasItems(stringArray));
@ -32,10 +42,28 @@ public class GenericsTest {
// extend Number it will fail to compile
@Test
public void givenArrayOfIntegersAndNumberUpperBound_thanListOfIntegersReturnedOK() {
Integer[] intArray = {1, 2, 3, 4, 5};
Integer[] intArray = { 1, 2, 3, 4, 5 };
List<Integer> list = Generics.fromArrayToListWithUpperBound(intArray);
assertThat(list, hasItems(intArray));
}
}
// testing paintAllBuildings method with a subtype of Building, the method
// will work with all subtypes of Building
@Test
public void givenSubTypeOfWildCardBoundedGenericType_thanPaintingOK() {
try {
List<Building> subBuildingsList = new ArrayList<>();
subBuildingsList.add(new Building());
subBuildingsList.add(new House());
// prints
// Painting Building
// Painting House
Generics.paintAllBuildings(subBuildingsList);
} catch (Exception e) {
fail();
}
}
}

View File

@ -4,12 +4,10 @@ import org.junit.Test;
import static org.junit.Assert.*;
public class SHA256HashingTest {
private static String originalValue = "abc123";
private static String hashedValue =
"6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090";
private static String hashedValue = "6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090";
@Test
public void testHashWithJavaMessageDigest() throws Exception {

View File

@ -119,8 +119,7 @@ public class StringConversionTest {
int afterConvCalendarDay = 03;
Month afterConvCalendarMonth = Month.DECEMBER;
int afterConvCalendarYear = 2007;
LocalDateTime afterConvDate
= new UseLocalDateTime().getLocalDateTimeUsingParseMethod(str);
LocalDateTime afterConvDate = new UseLocalDateTime().getLocalDateTimeUsingParseMethod(str);
assertEquals(afterConvDate.getDayOfMonth(), afterConvCalendarDay);
assertEquals(afterConvDate.getMonth(), afterConvCalendarMonth);

View File

@ -0,0 +1,86 @@
package com.baeldung.java.nio2.async;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class AsyncEchoClient {
private AsynchronousSocketChannel client;
private Future<Void> future;
private static AsyncEchoClient instance;
private AsyncEchoClient() {
try {
client = AsynchronousSocketChannel.open();
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
future = client.connect(hostAddress);
start();
} catch (IOException e) {
e.printStackTrace();
}
}
public static AsyncEchoClient getInstance() {
if (instance == null)
instance = new AsyncEchoClient();
return instance;
}
private void start() {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
public String sendMessage(String message) {
byte[] byteMsg = message.getBytes();
ByteBuffer buffer = ByteBuffer.wrap(byteMsg);
Future<Integer> writeResult = client.write(buffer);
try {
writeResult.get();
} catch (Exception e) {
e.printStackTrace();
}
buffer.flip();
Future<Integer> readResult = client.read(buffer);
try {
readResult.get();
} catch (Exception e) {
e.printStackTrace();
}
String echo = new String(buffer.array()).trim();
buffer.clear();
return echo;
}
public void stop() {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
AsyncEchoClient client = AsyncEchoClient.getInstance();
client.start();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
System.out.println("Message to server:");
while ((line = br.readLine()) != null) {
String response = client.sendMessage(line);
System.out.println("response from server: " + response);
System.out.println("Message to server:");
}
}
}

View File

@ -0,0 +1,80 @@
package com.baeldung.java.nio2.async;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class AsyncEchoServer {
private AsynchronousServerSocketChannel serverChannel;
private Future<AsynchronousSocketChannel> acceptResult;
private AsynchronousSocketChannel clientChannel;
public AsyncEchoServer() {
try {
serverChannel = AsynchronousServerSocketChannel.open();
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
serverChannel.bind(hostAddress);
acceptResult = serverChannel.accept();
} catch (IOException e) {
e.printStackTrace();
}
}
public void runServer() {
try {
clientChannel = acceptResult.get();
if ((clientChannel != null) && (clientChannel.isOpen())) {
while (true) {
ByteBuffer buffer = ByteBuffer.allocate(32);
Future<Integer> readResult = clientChannel.read(buffer);
// do some computation
readResult.get();
buffer.flip();
String message = new String(buffer.array()).trim();
if (message.equals("bye")) {
break; // while loop
}
buffer = ByteBuffer.wrap(new String(message).getBytes());
Future<Integer> writeResult = clientChannel.write(buffer);
// do some computation
writeResult.get();
buffer.clear();
} // while()
clientChannel.close();
serverChannel.close();
}
} catch (InterruptedException | ExecutionException | IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
AsyncEchoServer server = new AsyncEchoServer();
server.runServer();
}
public static Process start() throws IOException, InterruptedException {
String javaHome = System.getProperty("java.home");
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
String classpath = System.getProperty("java.class.path");
String className = AsyncEchoServer.class.getCanonicalName();
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
return builder.start();
}
}

View File

@ -0,0 +1,99 @@
package com.baeldung.java.nio2.async;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.HashMap;
import java.util.Map;
public class AsyncEchoServer2 {
private AsynchronousServerSocketChannel serverChannel;
private AsynchronousSocketChannel clientChannel;
public AsyncEchoServer2() {
try {
serverChannel = AsynchronousServerSocketChannel.open();
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
serverChannel.bind(hostAddress);
while (true) {
serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
@Override
public void completed(AsynchronousSocketChannel result, Object attachment) {
if (serverChannel.isOpen())
serverChannel.accept(null, this);
clientChannel = result;
if ((clientChannel != null) && (clientChannel.isOpen())) {
ReadWriteHandler handler = new ReadWriteHandler();
ByteBuffer buffer = ByteBuffer.allocate(32);
Map<String, Object> readInfo = new HashMap<>();
readInfo.put("action", "read");
readInfo.put("buffer", buffer);
clientChannel.read(buffer, readInfo, handler);
}
}
@Override
public void failed(Throwable exc, Object attachment) {
// process error
}
});
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
class ReadWriteHandler implements CompletionHandler<Integer, Map<String, Object>> {
@Override
public void completed(Integer result, Map<String, Object> attachment) {
Map<String, Object> actionInfo = attachment;
String action = (String) actionInfo.get("action");
if ("read".equals(action)) {
ByteBuffer buffer = (ByteBuffer) actionInfo.get("buffer");
buffer.flip();
actionInfo.put("action", "write");
clientChannel.write(buffer, actionInfo, this);
buffer.clear();
} else if ("write".equals(action)) {
ByteBuffer buffer = ByteBuffer.allocate(32);
actionInfo.put("action", "read");
actionInfo.put("buffer", buffer);
clientChannel.read(buffer, actionInfo, this);
}
}
@Override
public void failed(Throwable exc, Map<String, Object> attachment) {
}
}
public static void main(String[] args) {
new AsyncEchoServer2();
}
public static Process start() throws IOException, InterruptedException {
String javaHome = System.getProperty("java.home");
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
String classpath = System.getProperty("java.class.path");
String className = AsyncEchoServer2.class.getCanonicalName();
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
return builder.start();
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.java.nio2.async;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class AsyncEchoTest {
Process server;
AsyncEchoClient client;
@Before
public void setup() throws IOException, InterruptedException {
server = AsyncEchoServer2.start();
client = AsyncEchoClient.getInstance();
}
@Test
public void givenServerClient_whenServerEchosMessage_thenCorrect() throws Exception {
String resp1 = client.sendMessage("hello");
String resp2 = client.sendMessage("world");
assertEquals("hello", resp1);
assertEquals("world", resp2);
}
@After
public void teardown() throws IOException {
server.destroy();
client.stop();
}
}

View File

@ -0,0 +1,126 @@
package com.baeldung.java.nio2.async;
import org.junit.Test;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import static org.junit.Assert.assertEquals;
public class AsyncFileTest {
@Test
public void givenPath_whenReadsContentWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException {
Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString()));
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(1024);
Future<Integer> operation = fileChannel.read(buffer, 0);
operation.get();
String fileContent = new String(buffer.array()).trim();
buffer.clear();
assertEquals(fileContent, "baeldung.com");
}
@Test
public void givenPath_whenReadsContentWithCompletionHandler_thenCorrect() throws IOException {
Path path = Paths.get(URI.create(AsyncFileTest.class.getResource("/file.txt").toString()));
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(1024);
fileChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
// result is number of bytes read
// attachment is the buffer
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
}
});
}
@Test
public void givenPathAndContent_whenWritesToFileWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException {
String fileName = "temp";
Path path = Paths.get(fileName);
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
ByteBuffer buffer = ByteBuffer.allocate(1024);
long position = 0;
buffer.put("hello world".getBytes());
buffer.flip();
Future<Integer> operation = fileChannel.write(buffer, position);
buffer.clear();
operation.get();
String content = readContent(path);
assertEquals("hello world", content);
}
@Test
public void givenPathAndContent_whenWritesToFileWithHandler_thenCorrect() throws IOException {
String fileName = UUID.randomUUID().toString();
Path path = Paths.get(fileName);
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE);
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put("hello world".getBytes());
buffer.flip();
fileChannel.write(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
// result is number of bytes written
// attachment is the buffer
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
}
});
}
public static String readContent(Path file) throws ExecutionException, InterruptedException {
AsynchronousFileChannel fileChannel = null;
try {
fileChannel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteBuffer buffer = ByteBuffer.allocate(1024);
Future<Integer> operation = fileChannel.read(buffer, 0);
operation.get();
String fileContent = new String(buffer.array()).trim();
buffer.clear();
return fileContent;
}
}

View File

@ -0,0 +1,69 @@
package com.baeldung.java.nio2.attributes;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class BasicAttribsTest {
private static final String HOME = System.getProperty("user.home");
private static BasicFileAttributes basicAttribs;
@BeforeClass
public static void setup() throws IOException {
Path home = Paths.get(HOME);
BasicFileAttributeView basicView = Files.getFileAttributeView(home, BasicFileAttributeView.class);
basicAttribs = basicView.readAttributes();
}
@Test
public void givenFileTimes_whenComparesThem_ThenCorrect() {
FileTime created = basicAttribs.creationTime();
FileTime modified = basicAttribs.lastModifiedTime();
FileTime accessed = basicAttribs.lastAccessTime();
System.out.println("Created: " + created);
System.out.println("Modified: " + modified);
System.out.println("Accessed: " + accessed);
}
@Test
public void givenPath_whenGetsFileSize_thenCorrect() {
long size = basicAttribs.size();
assertTrue(size > 0);
}
@Test
public void givenPath_whenChecksIfDirectory_thenCorrect() {
boolean isDir = basicAttribs.isDirectory();
assertTrue(isDir);
}
@Test
public void givenPath_whenChecksIfFile_thenCorrect() {
boolean isFile = basicAttribs.isRegularFile();
assertFalse(isFile);
}
@Test
public void givenPath_whenChecksIfSymLink_thenCorrect() {
boolean isSymLink = basicAttribs.isSymbolicLink();
assertFalse(isSymLink);
}
@Test
public void givenPath_whenChecksIfOther_thenCorrect() {
boolean isOther = basicAttribs.isOther();
assertFalse(isOther);
}
}

View File

@ -0,0 +1,237 @@
package com.baeldung.java8.optional;
import com.baeldung.optional.Modem;
import com.baeldung.optional.Person;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import static org.junit.Assert.*;
public class OptionalTest {
// creating Optional
@Test
public void whenCreatesEmptyOptional_thenCorrect() {
Optional<String> empty = Optional.empty();
assertFalse(empty.isPresent());
}
@Test
public void givenNonNull_whenCreatesNonNullable_thenCorrect() {
String name = "baeldung";
Optional.of(name);
}
@Test(expected = NullPointerException.class)
public void givenNull_whenThrowsErrorOnCreate_thenCorrect() {
String name = null;
Optional<String> opt = Optional.of(name);
}
@Test
public void givenNonNull_whenCreatesOptional_thenCorrect() {
String name = "baeldung";
Optional<String> opt = Optional.of(name);
assertEquals("Optional[baeldung]", opt.toString());
}
@Test
public void givenNonNull_whenCreatesNullable_thenCorrect() {
String name = "baeldung";
Optional<String> opt = Optional.ofNullable(name);
assertEquals("Optional[baeldung]", opt.toString());
}
@Test
public void givenNull_whenCreatesNullable_thenCorrect() {
String name = null;
Optional<String> opt = Optional.ofNullable(name);
assertEquals("Optional.empty", opt.toString());
}
// Checking Value With isPresent()
@Test
public void givenOptional_whenIsPresentWorks_thenCorrect() {
Optional<String> opt = Optional.of("Baeldung");
assertTrue(opt.isPresent());
opt = Optional.ofNullable(null);
assertFalse(opt.isPresent());
}
// Condition Action With ifPresent()
@Test
public void givenOptional_whenIfPresentWorks_thenCorrect() {
Optional<String> opt = Optional.of("baeldung");
opt.ifPresent(name -> System.out.println(name.length()));
}
// returning Value With get()
@Test
public void givenOptional_whenGetsValue_thenCorrect() {
Optional<String> opt = Optional.of("baeldung");
String name = opt.get();
assertEquals("baeldung", name);
}
@Test(expected = NoSuchElementException.class)
public void givenOptionalWithNull_whenGetThrowsException_thenCorrect() {
Optional<String> opt = Optional.ofNullable(null);
String name = opt.get();
}
// Conditional Return With filter()
@Test
public void whenOptionalFilterWorks_thenCorrect() {
Integer year = 2016;
Optional<Integer> yearOptional = Optional.of(year);
boolean is2016 = yearOptional.filter(y -> y == 2016).isPresent();
assertTrue(is2016);
boolean is2017 = yearOptional.filter(y -> y == 2017).isPresent();
assertFalse(is2017);
}
@Test
public void whenFiltersWithoutOptional_thenCorrect() {
assertTrue(priceIsInRange1(new Modem(10.0)));
assertFalse(priceIsInRange1(new Modem(9.9)));
assertFalse(priceIsInRange1(new Modem(null)));
assertFalse(priceIsInRange1(new Modem(15.5)));
assertFalse(priceIsInRange1(null));
}
@Test
public void whenFiltersWithOptional_thenCorrect() {
assertTrue(priceIsInRange2(new Modem(10.0)));
assertFalse(priceIsInRange2(new Modem(9.9)));
assertFalse(priceIsInRange2(new Modem(null)));
assertFalse(priceIsInRange2(new Modem(15.5)));
assertFalse(priceIsInRange1(null));
}
public boolean priceIsInRange1(Modem modem) {
boolean isInRange = false;
if (modem != null && modem.getPrice() != null && (modem.getPrice() >= 10 && modem.getPrice() <= 15)) {
isInRange = true;
}
return isInRange;
}
public boolean priceIsInRange2(Modem modem2) {
return Optional.ofNullable(modem2)
.map(Modem::getPrice)
.filter(p -> p >= 10)
.filter(p -> p <= 15)
.isPresent();
}
// Transforming Value With map()
@Test
public void givenOptional_whenMapWorks_thenCorrect() {
List<String> companyNames = Arrays.asList("paypal", "oracle", "", "microsoft", "", "apple");
Optional<List<String>> listOptional = Optional.of(companyNames);
int size = listOptional.map(List::size).orElse(0);
assertEquals(6, size);
}
@Test
public void givenOptional_whenMapWorks_thenCorrect2() {
String name = "baeldung";
Optional<String> nameOptional = Optional.of(name);
int len = nameOptional.map(String::length).orElse(0);
assertEquals(8, len);
}
@Test
public void givenOptional_whenMapWorksWithFilter_thenCorrect() {
String password = " password ";
Optional<String> passOpt = Optional.of(password);
boolean correctPassword = passOpt.filter(pass -> pass.equals("password")).isPresent();
assertFalse(correctPassword);
correctPassword = passOpt.map(String::trim).filter(pass -> pass.equals("password")).isPresent();
assertTrue(correctPassword);
}
// Transforming Value With flatMap()
@Test
public void givenOptional_whenFlatMapWorks_thenCorrect2() {
Person person = new Person("john", 26);
Optional<Person> personOptional = Optional.of(person);
Optional<Optional<String>> nameOptionalWrapper = personOptional.map(Person::getName);
Optional<String> nameOptional = nameOptionalWrapper.orElseThrow(IllegalArgumentException::new);
String name1 = nameOptional.orElseThrow(IllegalArgumentException::new);
assertEquals("john", name1);
String name = personOptional.flatMap(Person::getName).orElseThrow(IllegalArgumentException::new);
assertEquals("john", name);
}
@Test
public void givenOptional_whenFlatMapWorksWithFilter_thenCorrect() {
Person person = new Person("john", 26);
person.setPassword("password");
Optional<Person> personOptional = Optional.of(person);
String password = personOptional.flatMap(Person::getPassword).filter(cleanPass -> cleanPass.equals("password")).orElseThrow(IllegalArgumentException::new);
assertEquals("password", password);
}
// Default Value With orElse
@Test
public void whenOrElseWorks_thenCorrect() {
String nullName = null;
String name = Optional.ofNullable(nullName).orElse("john");
assertEquals("john", name);
}
// Default Value With orElseGet
@Test
public void whenOrElseGetWorks_thenCorrect() {
String nullName = null;
String name = Optional.ofNullable(nullName).orElseGet(() -> "john");
assertEquals("john", name);
}
@Test
public void whenOrElseGetAndOrElseOverlap_thenCorrect() {
String text = null;
System.out.println("Using orElseGet:");
String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault);
assertEquals("Default Value", defaultText);
System.out.println("Using orElse:");
defaultText = Optional.ofNullable(text).orElse(getMyDefault());
assertEquals("Default Value", defaultText);
}
@Test
public void whenOrElseGetAndOrElseDiffer_thenCorrect() {
String text = "Text present";
System.out.println("Using orElseGet:");
String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault);
assertEquals("Text present", defaultText);
System.out.println("Using orElse:");
defaultText = Optional.ofNullable(text).orElse(getMyDefault());
assertEquals("Text present", defaultText);
}
// Exceptions With orElseThrow
@Test(expected = IllegalArgumentException.class)
public void whenOrElseThrowWorks_thenCorrect() {
String nullName = null;
String name = Optional.ofNullable(nullName).orElseThrow(IllegalArgumentException::new);
}
public String getMyDefault() {
System.out.println("Getting default value...");
return "Default Value";
}
}

View File

@ -1,21 +1,15 @@
package org.baeldung.java.collections;
import static java.util.Arrays.asList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Assert;
import org.junit.Test;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
public class CollectionsConcatenateUnitTest {
@ -63,16 +57,16 @@ public class CollectionsConcatenateUnitTest {
Assert.assertEquals(Arrays.asList("S", "T", "U", "V"), collectionCombined);
}
public static <E> Iterable<E> concat(Iterable<? extends E> list1, Iterable<? extends E> list2) {
public static <E> Iterable<E> concat(Iterable<? extends E> i1, Iterable<? extends E> i2) {
return new Iterable<E>() {
public Iterator<E> iterator() {
return new Iterator<E>() {
protected Iterator<? extends E> listIterator = list1.iterator();
protected Boolean checkedHasNext;
protected E nextValue;
Iterator<? extends E> listIterator = i1.iterator();
Boolean checkedHasNext;
E nextValue;
private boolean startTheSecond;
public void theNext() {
void theNext() {
if (listIterator.hasNext()) {
checkedHasNext = true;
nextValue = listIterator.next();
@ -80,7 +74,7 @@ public class CollectionsConcatenateUnitTest {
checkedHasNext = false;
else {
startTheSecond = true;
listIterator = list2.iterator();
listIterator = i2.iterator();
theNext();
}
}
@ -107,7 +101,7 @@ public class CollectionsConcatenateUnitTest {
}
public static <E> List<E> makeListFromIterable(Iterable<E> iter) {
List<E> list = new ArrayList<E>();
List<E> list = new ArrayList<>();
for (E item : iter) {
list.add(item);
}

View File

@ -0,0 +1,154 @@
package org.baeldung.java.collections;
import org.junit.Test;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.*;
public class JoinSplitCollectionsUnitTest {
@Test
public void whenJoiningTwoArrays_thenJoined() {
String[] animals1 = new String[] { "Dog", "Cat" };
String[] animals2 = new String[] { "Bird", "Cow" };
String[] result = Stream.concat(Arrays.stream(animals1), Arrays.stream(animals2)).toArray(String[]::new);
assertArrayEquals(result, new String[] { "Dog", "Cat", "Bird", "Cow" });
}
@Test
public void whenJoiningTwoCollections_thenJoined() {
Collection<Integer> collection1 = Arrays.asList(7, 8, 9);
Collection<Integer> collection2 = Arrays.asList(10, 11, 12);
Collection<Integer> result = Stream.concat(collection1.stream(), collection2.stream()).collect(Collectors.toList());
assertTrue(result.equals(Arrays.asList(7, 8, 9, 10, 11, 12)));
}
@Test
public void whenJoiningTwoCollectionsWithFilter_thenJoined() {
Collection<Integer> collection1 = Arrays.asList(7, 8, 11);
Collection<Integer> collection2 = Arrays.asList(9, 12, 10);
Collection<Integer> result = Stream.concat(collection1.stream(), collection2.stream()).filter(next -> next <= 10).collect(Collectors.toList());
assertTrue(result.equals(Arrays.asList(7, 8, 9, 10)));
}
@Test
public void whenConvertArrayToString_thenConverted() {
String[] colors = new String[] { "Red", "Blue", "Green", "Yellow" };
String result = Arrays.stream(colors).collect(Collectors.joining(", "));
assertEquals(result, "Red, Blue, Green, Yellow");
}
@Test
public void whenConvertCollectionToString_thenConverted() {
Collection<String> directions = Arrays.asList("Left", "Right", "Top", "Bottom");
String result = directions.stream().collect(Collectors.joining(", "));
assertEquals(result, "Left, Right, Top, Bottom");
}
@Test
public void whenConvertMapToString_thenConverted() {
Map<Integer, String> users = new HashMap<>();
users.put(1, "John Doe");
users.put(2, "Paul Smith");
users.put(3, "Susan Anderson");
String result = users.entrySet().stream().map(entry -> entry.getKey() + " = " + entry.getValue()).collect(Collectors.joining(", "));
assertEquals(result, "1 = John Doe, 2 = Paul Smith, 3 = Susan Anderson");
}
@Test
public void whenConvertNestedCollectionToString_thenConverted() {
Collection<List<String>> nested = new ArrayList<>();
nested.add(Arrays.asList("Left", "Right", "Top", "Bottom"));
nested.add(Arrays.asList("Red", "Blue", "Green", "Yellow"));
String result = nested.stream().map(nextList -> nextList.stream().collect(Collectors.joining("-"))).collect(Collectors.joining("; "));
assertEquals(result, "Left-Right-Top-Bottom; Red-Blue-Green-Yellow");
}
@Test
public void whenConvertCollectionToStringAndSkipNull_thenConverted() {
Collection<String> fruits = Arrays.asList("Apple", "Orange", null, "Grape");
String result = fruits.stream().filter(Objects::nonNull).collect(Collectors.joining(", "));
assertEquals(result, "Apple, Orange, Grape");
}
@Test
public void whenSplitCollectionHalf_thenConverted() {
Collection<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Collection<Integer> result1 = new ArrayList<>();
Collection<Integer> result2 = new ArrayList<>();
AtomicInteger count = new AtomicInteger();
int midpoint = Math.round(numbers.size() / 2);
numbers.forEach(next -> {
int index = count.getAndIncrement();
if (index < midpoint) {
result1.add(next);
} else {
result2.add(next);
}
});
assertTrue(result1.equals(Arrays.asList(1, 2, 3, 4, 5)));
assertTrue(result2.equals(Arrays.asList(6, 7, 8, 9, 10)));
}
@Test
public void whenSplitArrayByWordLength_thenConverted() {
String[] words = new String[] { "bye", "cold", "it", "and", "my", "word" };
Map<Integer, List<String>> result = Arrays.stream(words).collect(Collectors.groupingBy(String::length));
assertTrue(result.get(2).equals(Arrays.asList("it", "my")));
assertTrue(result.get(3).equals(Arrays.asList("bye", "and")));
assertTrue(result.get(4).equals(Arrays.asList("cold", "word")));
}
@Test
public void whenConvertStringToArray_thenConverted() {
String colors = "Red, Blue, Green, Yellow";
String[] result = colors.split(", ");
assertArrayEquals(result, new String[] { "Red", "Blue", "Green", "Yellow" });
}
@Test
public void whenConvertStringToCollection_thenConverted() {
String colors = "Left, Right, Top, Bottom";
Collection<String> result = Arrays.asList(colors.split(", "));
assertTrue(result.equals(Arrays.asList("Left", "Right", "Top", "Bottom")));
}
@Test
public void whenConvertStringToMap_thenConverted() {
String users = "1 = John Doe, 2 = Paul Smith, 3 = Susan Anderson";
Map<Integer, String> result = Arrays.stream(users.split(", ")).map(next -> next.split(" = ")).collect(Collectors.toMap(entry -> Integer.parseInt(entry[0]), entry -> entry[1]));
assertEquals(result.get(1), "John Doe");
assertEquals(result.get(2), "Paul Smith");
assertEquals(result.get(3), "Susan Anderson");
}
@Test
public void whenConvertCollectionToStringMultipleSeparators_thenConverted() {
String fruits = "Apple. , Orange, Grape. Lemon";
Collection<String> result = Arrays.stream(fruits.split("[,|.]")).map(String::trim).filter(next -> !next.isEmpty()).collect(Collectors.toList());
assertTrue(result.equals(Arrays.asList("Apple", "Orange", "Grape", "Lemon")));
}
}

View File

@ -20,7 +20,6 @@ public class JavaFileUnitTest {
private static final String TEMP_DIR = "src/test/resources/temp" + UUID.randomUUID().toString();
@BeforeClass
public static void setup() throws IOException {
Files.createDirectory(Paths.get(TEMP_DIR));

View File

@ -0,0 +1,55 @@
package org.baeldung.java.sorting;
public class Employee implements Comparable {
private String name;
private int age;
private double salary;
public Employee(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public boolean equals(Object obj) {
return ((Employee) obj).getName().equals(getName());
}
@Override
public int compareTo(Object o) {
Employee e = (Employee) o;
return getName().compareTo(e.getName());
}
@Override
public String toString() {
return new StringBuffer().append("(").append(getName()).append(getAge()).append(",").append(getSalary()).append(")").toString();
}
}

View File

@ -0,0 +1,186 @@
package org.baeldung.java.sorting;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.Before;
import org.junit.Test;
import com.google.common.primitives.Ints;
public class JavaSorting {
private int[] toSort;
private int[] sortedInts;
private int[] sortedRangeInts;
// private Integer [] integers;
// private Integer [] sortedIntegers;
// private List<Integer> integersList;
// private List<Integer> sortedIntegersList;
private Employee[] employees;
private Employee[] employeesSorted;
private Employee[] employeesSortedByAge;
private HashMap<Integer, String> map;
@Before
public void initVariables() {
toSort = new int[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 };
sortedInts = new int[] { 1, 5, 7, 66, 88, 89, 123, 200, 255 };
sortedRangeInts = new int[] { 5, 1, 89, 7, 88, 200, 255, 123, 66 };
// integers = new Integer[]
// { 5, 1, 89, 255, 7, 88, 200, 123, 66 };
// sortedIntegers = new Integer[]
// {1, 5, 7, 66, 88, 89, 123, 200, 255};
//
// integersList = Arrays.asList(new Integer[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 });
// sortedIntegersList = Arrays.asList(new Integer[] {1, 5, 7, 66, 88, 89, 123, 200, 255});
employees = new Employee[] { new Employee("John", 23, 5000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 7000), new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), new Employee("Pearl", 33, 6000) };
employeesSorted = new Employee[] { new Employee("Earl", 43, 10000), new Employee("Frank", 33, 70000), new Employee("Jessica", 23, 4000), new Employee("John", 23, 5000), new Employee("Pearl", 33, 4000), new Employee("Steve", 26, 6000) };
employeesSortedByAge = new Employee[] { new Employee("John", 23, 5000), new Employee("Jessica", 23, 4000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 70000), new Employee("Pearl", 33, 4000), new Employee("Earl", 43, 10000) };
HashMap<Integer, String> map = new HashMap<>();
map.put(55, "John");
map.put(22, "Apple");
map.put(66, "Earl");
map.put(77, "Pearl");
map.put(12, "George");
map.put(6, "Rocky");
}
@Test
public void givenIntArray_whenUsingSort_thenSortedArray() {
Arrays.sort(toSort);
assertTrue(Arrays.equals(toSort, sortedInts));
}
@Test
public void givenIntegerArray_whenUsingSort_thenSortedArray() {
Integer[] integers = ArrayUtils.toObject(toSort);
Arrays.sort(integers, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return a - b;
}
});
assertTrue(Arrays.equals(integers, ArrayUtils.toObject(sortedInts)));
}
@Test
public void givenArray_whenUsingSortWithLambdas_thenSortedArray() {
Integer[] integersToSort = ArrayUtils.toObject(toSort);
Arrays.sort(integersToSort, (a, b) -> {
return a - b;
});
assertTrue(Arrays.equals(integersToSort, ArrayUtils.toObject(sortedInts)));
}
@Test
public void givenEmpArray_SortEmpArray_thenSortedArrayinNaturalOrder() {
Arrays.sort(employees);
assertTrue(Arrays.equals(employees, employeesSorted));
}
@Test
public void givenIntArray_whenUsingRangeSort_thenRangeSortedArray() {
Arrays.sort(toSort, 3, 7);
assertTrue(Arrays.equals(toSort, sortedRangeInts));
}
@Test
public void givenIntArray_whenUsingParallelSort_thenArraySorted() {
Arrays.parallelSort(toSort);
assertTrue(Arrays.equals(toSort, sortedInts));
}
@Test
public void givenArrayObjects_whenUsingComparing_thenSortedArrayObjects() {
List<Employee> employeesList = Arrays.asList(employees);
employeesList.sort(Comparator.comparing(Employee::getAge));// .thenComparing(Employee::getName));
assertTrue(Arrays.equals(employeesList.toArray(), employeesSortedByAge));
}
@Test
public void givenList_whenUsingSort_thenSortedList() {
List<Integer> toSortList = Ints.asList(toSort);
Collections.sort(toSortList);
assertTrue(Arrays.equals(toSortList.toArray(), ArrayUtils.toObject(sortedInts)));
}
@Test
public void givenMap_whenSortingByKeys_thenSortedMap() {
Integer[] sortedKeys = new Integer[] { 6, 12, 22, 55, 66, 77 };
List<Map.Entry<Integer, String>> entries = new ArrayList<>(map.entrySet());
Collections.sort(entries, new Comparator<Entry<Integer, String>>() {
@Override
public int compare(Entry<Integer, String> o1, Entry<Integer, String> o2) {
return o1.getKey().compareTo(o2.getKey());
}
});
HashMap<Integer, String> sortedMap = new LinkedHashMap<>();
for (Map.Entry<Integer, String> entry : entries) {
sortedMap.put(entry.getKey(), entry.getValue());
}
assertTrue(Arrays.equals(sortedMap.keySet().toArray(), sortedKeys));
}
@Test
public void givenMap_whenSortingByValues_thenSortedMap() {
String[] sortedValues = new String[] { "Apple", "Earl", "George", "John", "Pearl", "Rocky" };
List<Map.Entry<Integer, String>> entries = new ArrayList<>(map.entrySet());
Collections.sort(entries, new Comparator<Entry<Integer, String>>() {
@Override
public int compare(Entry<Integer, String> o1, Entry<Integer, String> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
HashMap<Integer, String> sortedMap = new LinkedHashMap<>();
for (Map.Entry<Integer, String> entry : entries) {
sortedMap.put(entry.getKey(), entry.getValue());
}
assertTrue(Arrays.equals(sortedMap.values().toArray(), sortedValues));
}
@Test
public void givenSet_whenUsingSort_thenSortedSet() {
HashSet<Integer> integersSet = new LinkedHashSet<>(Ints.asList(toSort));
HashSet<Integer> descSortedIntegersSet = new LinkedHashSet<>(Arrays.asList(new Integer[] { 255, 200, 123, 89, 88, 66, 7, 5, 1 }));
ArrayList<Integer> list = new ArrayList<Integer>(integersSet);
Collections.sort(list, (i1, i2) -> {
return i2 - i1;
});
integersSet = new LinkedHashSet<>(list);
assertTrue(Arrays.equals(integersSet.toArray(), descSortedIntegersSet.toArray()));
}
}

View File

@ -0,0 +1 @@
baeldung.com

235
jackson-annotations/pom.xml Normal file
View File

@ -0,0 +1,235 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>jackson-annotations</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>jackson-annotations</name>
<dependencies>
<!-- utils -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<!--jackson for xml-->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- marshalling -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jsonSchema</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda-time.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>3.0.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>3.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-path</artifactId>
<version>3.0.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.fge</groupId>
<artifactId>json-schema-validator</artifactId>
<version>2.2.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.6.1</version>
<scope>test</scope>
</dependency>
<!-- logging -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
</dependencies>
<build>
<finalName>jackson</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven-compiler-plugin.source}</source>
<target>${maven-compiler-plugin.source}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</plugins>
</build>
<properties>
<!-- persistence -->
<hibernate.version>4.3.11.Final</hibernate.version>
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
<!-- marshalling -->
<jackson.version>2.8.5</jackson.version>
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
<!-- various -->
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
<joda-time.version>2.9.6</joda-time.version>
<gson.version>2.8.0</gson.version>
<commons-collections4.version>4.1</commons-collections4.version>
<!-- util -->
<guava.version>20.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-io.version>2.5</commons-io.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>2.2.26</mockito.version>
<httpcore.version>4.4.1</httpcore.version>
<httpclient.version>4.5</httpclient.version>
<rest-assured.version>2.9.0</rest-assured.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven-compiler-plugin.source>1.8</maven-compiler-plugin.source>
</properties>
</project>

View File

@ -0,0 +1,31 @@
package com.baeldung.jacksonannotation.deserialization.jacksoninject;
import com.baeldung.jacksonannotation.domain.Item;
import java.util.ArrayList;
import java.util.List;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Author extends Person {
List<Item> items = new ArrayList<>();
public Author(){}
public Author(String firstName, String lastName) {
super(firstName, lastName);
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.jacksonannotation.deserialization.jacksoninject;
import com.fasterxml.jackson.annotation.JacksonInject;
import java.util.UUID;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Person {
@JacksonInject
private UUID id;
private String firstName;
private String lastName;
public Person(){
}
public Person(String firstName, String lastName) {
this.id = UUID.randomUUID();
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public UUID getId() {
return id;
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.jacksonannotation.deserialization.jsonanysetter;
import com.baeldung.jacksonannotation.domain.Author;
import com.baeldung.jacksonannotation.domain.Item;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.HashMap;
import java.util.Map;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
* @see JsonAnyGetter
*/
public class Inventory {
private Map<Author, Item> stock = new HashMap<>();
private Map<String, Float> countryDeliveryCost = new HashMap<>();
@JsonIgnore
public Map<Author, Item> getStock() {
return stock;
}
public Map<String, Float> getCountryDeliveryCost() {
return countryDeliveryCost;
}
@JsonAnySetter
public void addCountryDeliveryCost(String country, Float cost) {
countryDeliveryCost.put(country, cost);
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.jacksonannotation.deserialization.jsoncreator;
import com.baeldung.jacksonannotation.domain.Item;
import com.baeldung.jacksonannotation.domain.Person;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.List;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
* @see JsonGetter
*/
public class Author extends Person {
List<Item> items = new ArrayList<>();
@JsonCreator
public Author(
@JsonProperty("christianName") String firstName,
@JsonProperty("surname") String lastName) {
super(firstName, lastName);
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.jacksonannotation.deserialization.jsondeserialize;
import com.baeldung.jacksonannotation.domain.Item;
import com.baeldung.jacksonannotation.domain.Person;
import java.util.ArrayList;
import java.util.List;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Author extends Person {
List<Item> items = new ArrayList<>();
public Author(String firstName, String lastName) {
super(firstName, lastName);
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.jacksonannotation.deserialization.jsondeserialize;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.math.BigDecimal;
import java.util.Date;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Book extends Item {
private String ISBN;
@JsonDeserialize(using = CustomDateDeserializer.class)
private Date published;
private BigDecimal pages;
public Book() {}
public Book(String title, Author author) {
super(title, author);
}
public String getISBN() {
return ISBN;
}
public void setISBN(String ISBN) {
this.ISBN = ISBN;
}
public Date getPublished() {
return published;
}
public void setPublished(Date published) {
this.published = published;
}
public BigDecimal getPages() {
return pages;
}
public void setPages(BigDecimal pages) {
this.pages = pages;
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.jacksonannotation.deserialization.jsondeserialize;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class CustomDateDeserializer extends StdDeserializer<Date> {
private static SimpleDateFormat formatter =
new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
public CustomDateDeserializer() {
this(null);
}
public CustomDateDeserializer(Class<?> vc) {
super(vc);
}
@Override
public Date deserialize(JsonParser jsonparser, DeserializationContext context)
throws IOException, JsonProcessingException {
String date = jsonparser.getText();
try {
return formatter.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -0,0 +1,61 @@
package com.baeldung.jacksonannotation.deserialization.jsondeserialize;
import com.baeldung.jacksonannotation.domain.Person;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Item {
private UUID id;
private String title;
private List<Person> authors = new ArrayList<>();
private float price;
public Item(){}
public Item(String title, Author author) {
this.id = UUID.randomUUID();
this.title = title;
this.authors.add(author);
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Person> getAuthors() {
return authors;
}
public void setAuthors(List<Person> authors) {
this.authors = authors;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.jacksonannotation.deserialization.jsonsetter;
import com.baeldung.jacksonannotation.domain.Item;
import com.baeldung.jacksonannotation.domain.Person;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonSetter;
import java.util.ArrayList;
import java.util.List;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Author extends Person {
private List<Item> items = new ArrayList<>();
public Author(){}
public Author(String firstName, String lastName) {
super(firstName, lastName);
}
@JsonIgnore
public List<Item> getItems() {
return items;
}
@JsonSetter("publications")
public void setItems(List<Item> items) {
this.items = items;
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.jacksonannotation.domain;
import java.util.ArrayList;
import java.util.List;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Author extends Person {
private List<Item> items = new ArrayList<>();
public Author(String firstName, String lastName) {
super(firstName, lastName);
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.jacksonannotation.domain;
import java.math.BigDecimal;
import java.util.Date;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Book extends Item {
private String ISBN;
private Date published;
private BigDecimal pages;
public Book(){
}
public Book(String title, Author author) {
super(title, author);
}
public String getISBN() {
return ISBN;
}
public void setISBN(String ISBN) {
this.ISBN = ISBN;
}
public Date getPublished() {
return published;
}
public void setPublished(Date published) {
this.published = published;
}
public BigDecimal getPages() {
return pages;
}
public void setPages(BigDecimal pages) {
this.pages = pages;
}
}

View File

@ -0,0 +1,71 @@
package com.baeldung.jacksonannotation.domain;
import java.util.List;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Course extends Item {
public enum Medium {CLASSROOM, ONLINE}
public enum Level {
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);
private String name;
private int number;
Level(String name, int number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
}
private float duration;
private Medium medium;
private Level level;
private List<Course> prerequisite;
public Course(String title, Author author) {
super(title, author);
}
public float getDuration() {
return duration;
}
public void setDuration(float duration) {
this.duration = duration;
}
public Medium getMedium() {
return medium;
}
public void setMedium(Medium medium) {
this.medium = medium;
}
public Level getLevel() {
return level;
}
public void setLevel(Level level) {
this.level = level;
}
public List<Course> getPrerequisite() {
return prerequisite;
}
public void setPrerequisite(List<Course> prerequisite) {
this.prerequisite = prerequisite;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.jacksonannotation.domain;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Customer extends Person {
private String configuration;
public Customer(String firstName, String lastName) {
super(firstName, lastName);
}
public String getConfiguration() {
return configuration;
}
public void setConfiguration(String configuration) {
this.configuration = configuration;
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.jacksonannotation.domain;
import java.util.HashMap;
import java.util.Map;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Inventory {
private Map<Author, Item> stock;
private Map<String, Float> countryDeliveryCost = new HashMap<>();
public Map<Author, Item> getStock() {
return stock;
}
public void setStock(Map<Author, Item> stock) {
this.stock = stock;
}
public Map<String, Float> getCountryDeliveryCost() {
return countryDeliveryCost;
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.jacksonannotation.domain;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Item {
private UUID id;
private String title;
private List<Person> authors = new ArrayList<>();
private float price;
public Item(){}
public Item(String title, Author author) {
this.id = UUID.randomUUID();
this.title = title;
this.authors.add(author);
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Person> getAuthors() {
return authors;
}
public void setAuthors(List<Person> authors) {
this.authors = authors;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.jacksonannotation.domain;
import java.util.UUID;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Order {
private UUID id;
private Type type;
private int internalAudit;
public static class Type {
public long id;
public String name;
}
public Order() {
this.id = UUID.randomUUID();
}
public Order(Type type) {
this();
this.type = type;
}
public Order(int internalAudit) {
this();
this.type = new Type();
this.type.id = 20;
this.type.name = "Order";
this.internalAudit = internalAudit;
}
public UUID getId() {
return id;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.jacksonannotation.domain;
import java.util.UUID;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Person {
private UUID id;
private String firstName;
private String lastName;
public Person(){}
public Person(String firstName, String lastName) {
this.id = UUID.randomUUID();
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public UUID getId() {
return id;
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.jacksonannotation.general.jsonfilter;
import com.baeldung.jacksonannotation.domain.Item;
import com.baeldung.jacksonannotation.domain.Person;
import com.fasterxml.jackson.annotation.JsonFilter;
import java.util.ArrayList;
import java.util.List;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
@JsonFilter("authorFilter")
public class Author extends Person {
private List<Item> items = new ArrayList<>();
public Author(String firstName, String lastName) {
super(firstName, lastName);
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.jacksonannotation.general.jsonformat;
import com.baeldung.jacksonannotation.domain.Author;
import com.baeldung.jacksonannotation.domain.Item;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.math.BigDecimal;
import java.util.Date;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Book extends Item {
private String ISBN;
@JsonFormat(
shape = JsonFormat.Shape.STRING,
pattern = "dd-MM-yyyy HH:mm:ss")
private Date published;
private BigDecimal pages;
public Book() {
}
public Book(String title, Author author) {
super(title, author);
}
public String getISBN() {
return ISBN;
}
public void setISBN(String ISBN) {
this.ISBN = ISBN;
}
public Date getPublished() {
return published;
}
public void setPublished(Date published) {
this.published = published;
}
public BigDecimal getPages() {
return pages;
}
public void setPages(BigDecimal pages) {
this.pages = pages;
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.jacksonannotation.general.jsonidentityinfo;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import java.util.ArrayList;
import java.util.List;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
public class Author extends Person {
private List<Item> items = new ArrayList<>();
public Author(String firstName, String lastName) {
super(firstName, lastName);
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}

View File

@ -0,0 +1,72 @@
package com.baeldung.jacksonannotation.general.jsonidentityinfo;
import java.util.List;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Course extends Item {
public enum Medium {CLASSROOM, ONLINE}
public enum Level {
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);
private String name;
private int number;
Level(String name, int number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
}
private float duration;
private Medium medium;
private Level level;
private List<Course> prerequisite;
public Course(String title, Author author) {
super(title, author);
}
public float getDuration() {
return duration;
}
public void setDuration(float duration) {
this.duration = duration;
}
public Medium getMedium() {
return medium;
}
public void setMedium(Medium medium) {
this.medium = medium;
}
public Level getLevel() {
return level;
}
public void setLevel(Level level) {
this.level = level;
}
public List<Course> getPrerequisite() {
return prerequisite;
}
public void setPrerequisite(List<Course> prerequisite) {
this.prerequisite = prerequisite;
}
}

View File

@ -0,0 +1,65 @@
package com.baeldung.jacksonannotation.general.jsonidentityinfo;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
public class Item {
private UUID id;
private String title;
private List<Person> authors = new ArrayList<>();
private float price;
public Item(){}
public Item(String title, Author author) {
this.id = UUID.randomUUID();
this.title = title;
this.authors.add(author);
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Person> getAuthors() {
return authors;
}
public void setAuthors(List<Person> authors) {
this.authors = authors;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.jacksonannotation.general.jsonidentityinfo;
import java.util.UUID;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Person {
private UUID id;
private String firstName;
private String lastName;
public Person(){}
public Person(String firstName, String lastName) {
this.id = UUID.randomUUID();
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public UUID getId() {
return id;
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.jacksonannotation.general.jsonproperty;
import com.baeldung.jacksonannotation.domain.Person;
import java.util.ArrayList;
import java.util.List;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Author extends Person {
private List<Item> items = new ArrayList<>();
public Author(String firstName, String lastName) {
super(firstName, lastName);
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}

View File

@ -0,0 +1,61 @@
package com.baeldung.jacksonannotation.general.jsonproperty;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
import java.util.Date;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Book extends Item {
private String ISBN;
private Date published;
private BigDecimal pages;
private String binding;
public Book() {
}
public Book(String title, Author author) {
super(title, author);
}
public String getISBN() {
return ISBN;
}
public void setISBN(String ISBN) {
this.ISBN = ISBN;
}
public Date getPublished() {
return published;
}
public void setPublished(Date published) {
this.published = published;
}
public BigDecimal getPages() {
return pages;
}
public void setPages(BigDecimal pages) {
this.pages = pages;
}
@JsonProperty("binding")
public String coverBinding() {
return binding;
}
@JsonProperty("binding")
public void configureBinding(String binding) {
this.binding = binding;
}
}

View File

@ -0,0 +1,61 @@
package com.baeldung.jacksonannotation.general.jsonproperty;
import com.baeldung.jacksonannotation.domain.Person;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Item {
private UUID id;
private String title;
private List<Person> authors = new ArrayList<>();
private float price;
public Item(){}
public Item(String title, Author author) {
this.id = UUID.randomUUID();
this.title = title;
this.authors.add(author);
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Person> getAuthors() {
return authors;
}
public void setAuthors(List<Person> authors) {
this.authors = authors;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.jacksonannotation.general.jsonunwrapped;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import java.util.UUID;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Order {
private UUID id;
@JsonUnwrapped
private Type type;
private int internalAudit;
public static class Type {
public long id;
public String name;
}
public Order() {
this.id = UUID.randomUUID();
}
public Order(Type type) {
this();
this.type = type;
}
public Order(int internalAudit) {
this();
this.type = new Type();
this.type.id = 20;
this.type.name = "Order";
this.internalAudit = internalAudit;
}
public UUID getId() {
return id;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
}

View File

@ -0,0 +1,57 @@
package com.baeldung.jacksonannotation.general.jsonview;
import com.fasterxml.jackson.annotation.JsonView;
import java.util.UUID;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Order {
@JsonView(Views.Public.class)
private UUID id;
@JsonView(Views.Public.class)
private Type type;
@JsonView(Views.Internal.class)
private int internalAudit;
public static class Type {
public long id;
public String name;
}
public Order() {
this.id = UUID.randomUUID();
}
public Order(Type type) {
this();
this.type = type;
}
public Order(int internalAudit) {
this();
this.type = new Type();
this.type.id = 20;
this.type.name = "Order";
this.internalAudit = internalAudit;
}
public UUID getId() {
return id;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.jacksonannotation.general.jsonview;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Views {
public static class Public {
}
public static class Internal extends Public {
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.jacksonannotation.general.reference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import java.util.ArrayList;
import java.util.List;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Author extends Person {
private List<Item> items = new ArrayList<>();
public Author(String firstName, String lastName) {
super(firstName, lastName);
}
@JsonManagedReference
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}

View File

@ -0,0 +1,72 @@
package com.baeldung.jacksonannotation.general.reference;
import java.util.List;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Course extends Item {
public enum Medium {CLASSROOM, ONLINE}
public enum Level {
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);
private String name;
private int number;
Level(String name, int number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
}
private float duration;
private Medium medium;
private Level level;
private List<Course> prerequisite;
public Course(String title, Author author) {
super(title, author);
}
public float getDuration() {
return duration;
}
public void setDuration(float duration) {
this.duration = duration;
}
public Medium getMedium() {
return medium;
}
public void setMedium(Medium medium) {
this.medium = medium;
}
public Level getLevel() {
return level;
}
public void setLevel(Level level) {
this.level = level;
}
public List<Course> getPrerequisite() {
return prerequisite;
}
public void setPrerequisite(List<Course> prerequisite) {
this.prerequisite = prerequisite;
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.jacksonannotation.general.reference;
import com.fasterxml.jackson.annotation.JsonBackReference;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Item {
private UUID id;
private String title;
@JsonBackReference
private List<Person> authors = new ArrayList<>();
private float price;
public Item(){}
public Item(String title, Author author) {
this.id = UUID.randomUUID();
this.title = title;
this.authors.add(author);
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Person> getAuthors() {
return authors;
}
public void setAuthors(List<Person> authors) {
this.authors = authors;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.jacksonannotation.general.reference;
import java.util.UUID;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Person {
private UUID id;
private String firstName;
private String lastName;
public Person(){}
public Person(String firstName, String lastName) {
this.id = UUID.randomUUID();
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public UUID getId() {
return id;
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.jacksonannotation.inclusion.jsonautodetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import java.util.UUID;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
public class Order {
private UUID id;
private Type type;
private int internalAudit;
public static class Type {
public long id;
public String name;
}
public Order() {
this.id = UUID.randomUUID();
}
public Order(Type type) {
this();
this.type = type;
}
public Order(int internalAudit) {
this();
this.type = new Type();
this.type.id = 20;
this.type.name = "Order";
this.internalAudit = internalAudit;
}
public UUID getId() {
return id;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.jacksonannotation.inclusion.jsonignore;
import com.baeldung.jacksonannotation.domain.Item;
import java.util.ArrayList;
import java.util.List;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Author extends Person {
private List<Item> items = new ArrayList<>();
public Author(String firstName, String lastName) {
super(firstName, lastName);
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.jacksonannotation.inclusion.jsonignore;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.UUID;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Person {
@JsonIgnore
private UUID id;
private String firstName;
private String lastName;
public Person(){}
public Person(String firstName, String lastName) {
this.id = UUID.randomUUID();
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public UUID getId() {
return id;
}
}

View File

@ -0,0 +1,76 @@
package com.baeldung.jacksonannotation.inclusion.jsonignoreproperties;
import com.baeldung.jacksonannotation.domain.Author;
import com.baeldung.jacksonannotation.domain.Item;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
@JsonIgnoreProperties({"medium"})
public class Course extends Item {
public enum Medium {CLASSROOM, ONLINE}
public enum Level {
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);
private String name;
private int number;
Level(String name, int number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
}
private float duration;
private Medium medium;
private Level level;
private List<Course> prerequisite;
public Course(String title, Author author) {
super(title, author);
}
public float getDuration() {
return duration;
}
public void setDuration(float duration) {
this.duration = duration;
}
public Medium getMedium() {
return medium;
}
public void setMedium(Medium medium) {
this.medium = medium;
}
public Level getLevel() {
return level;
}
public void setLevel(Level level) {
this.level = level;
}
public List<Course> getPrerequisite() {
return prerequisite;
}
public void setPrerequisite(List<Course> prerequisite) {
this.prerequisite = prerequisite;
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.jacksonannotation.inclusion.jsonignoretype;
import com.fasterxml.jackson.annotation.JsonIgnoreType;
import java.util.UUID;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Order {
private UUID id;
private Type type;
@JsonIgnoreType
public static class Type {
public long id;
public String name;
}
public Order() {
this.id = UUID.randomUUID();
}
public Order(Type type) {
this();
this.type = type;
}
public UUID getId() {
return id;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.jacksonannotation.inclusion.jsoninclude;
import com.baeldung.jacksonannotation.domain.Item;
import com.baeldung.jacksonannotation.domain.Person;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.util.ArrayList;
import java.util.List;
import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
@JsonInclude(NON_NULL)
public class Author extends Person {
private List<Item> items = new ArrayList<>();
public Author(String firstName, String lastName) {
super(firstName, lastName);
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}

View File

@ -0,0 +1,74 @@
package com.baeldung.jacksonannotation.miscellaneous.custom;
import com.baeldung.jacksonannotation.domain.Author;
import java.util.List;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
@CustomCourseAnnotation
public class Course extends Item {
public enum Medium {CLASSROOM, ONLINE}
public enum Level {
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);
private String name;
private int number;
Level(String name, int number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
}
private float duration;
private Medium medium;
private Level level;
private List<Course> prerequisite;
public Course(String title, Author author) {
super(title, author);
}
public float getDuration() {
return duration;
}
public void setDuration(float duration) {
this.duration = duration;
}
public Medium getMedium() {
return medium;
}
public void setMedium(Medium medium) {
this.medium = medium;
}
public Level getLevel() {
return level;
}
public void setLevel(Level level) {
this.level = level;
}
public List<Course> getPrerequisite() {
return prerequisite;
}
public void setPrerequisite(List<Course> prerequisite) {
this.prerequisite = prerequisite;
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.jacksonannotation.miscellaneous.custom;
import com.fasterxml.jackson.annotation.*;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"title", "price", "id", "duration", "authors", "level"})
@JsonIgnoreProperties({"prerequisite"})
public @interface CustomCourseAnnotation {
}

View File

@ -0,0 +1,62 @@
package com.baeldung.jacksonannotation.miscellaneous.custom;
import com.baeldung.jacksonannotation.domain.Author;
import com.baeldung.jacksonannotation.domain.Person;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Item {
private UUID id;
private String title;
private List<Person> authors = new ArrayList<>();
private float price;
public Item(){}
public Item(String title, Author author) {
this.id = UUID.randomUUID();
this.title = title;
this.authors.add(author);
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Person> getAuthors() {
return authors;
}
public void setAuthors(List<Person> authors) {
this.authors = authors;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.jacksonannotation.miscellaneous.disable;
import com.baeldung.jacksonannotation.domain.Item;
import com.baeldung.jacksonannotation.domain.Person;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import java.util.ArrayList;
import java.util.List;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"lastName", "items", "firstName", "id"})
public class Author extends Person {
@JsonIgnore
private List<Item> items = new ArrayList<>();
public Author(String firstName, String lastName) {
super(firstName, lastName);
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.jacksonannotation.miscellaneous.mixin;
import com.baeldung.jacksonannotation.domain.Item;
import com.baeldung.jacksonannotation.domain.Person;
import java.util.ArrayList;
import java.util.List;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Author extends Person {
private List<Item> items = new ArrayList<>();
public Author(String firstName, String lastName) {
super(firstName, lastName);
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.jacksonannotation.miscellaneous.mixin;
import com.fasterxml.jackson.annotation.JsonIgnoreType;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
@JsonIgnoreType
public class IgnoreListMixIn {
}

View File

@ -0,0 +1,66 @@
package com.baeldung.jacksonannotation.polymorphism;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import java.util.UUID;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Order {
private UUID id;
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")
})
public static class Type {
public long id;
public String name;
}
@JsonTypeName("internal")
public static class InternalType extends Type {
public long id;
public String name;
}
public Order() {
this.id = UUID.randomUUID();
}
public Order(Type type) {
this();
this.type = type;
}
public Order(int internalAudit) {
this();
this.type = new Type();
this.type.id = 20;
this.type.name = "Order";
this.internalAudit = internalAudit;
}
public UUID getId() {
return id;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.jacksonannotation.serialization.jsonanygetter;
import com.baeldung.jacksonannotation.domain.Author;
import com.baeldung.jacksonannotation.domain.Item;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.HashMap;
import java.util.Map;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Inventory {
private String location;
private Map<Author, Item> stock = new HashMap<>();
private Map<String, Float> countryDeliveryCost = new HashMap<>();
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
@JsonIgnore
public Map<Author, Item> getStock() {
return stock;
}
@JsonAnyGetter
public Map<String, Float> getCountryDeliveryCost() {
return countryDeliveryCost;
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.jacksonannotation.serialization.jsongetter;
import com.baeldung.jacksonannotation.domain.Item;
import com.baeldung.jacksonannotation.domain.Person;
import com.fasterxml.jackson.annotation.JsonGetter;
import java.util.ArrayList;
import java.util.List;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Author extends Person {
List<Item> items = new ArrayList<>();
public Author(String firstName, String lastName) {
super(firstName, lastName);
}
@JsonGetter("publications")
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.jacksonannotation.serialization.jsonpropertyorder;
import com.baeldung.jacksonannotation.domain.Item;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import java.util.ArrayList;
import java.util.List;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
@JsonPropertyOrder({"items", "firstName", "lastName", "id"})
public class Author extends Person {
List<Item> items = new ArrayList<>();
public Author(String firstName, String lastName) {
super(firstName, lastName);
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.jacksonannotation.serialization.jsonpropertyorder;
import java.util.UUID;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Person {
private UUID id;
private String firstName;
private String lastName;
public Person(String firstName, String lastName) {
this.id = UUID.randomUUID();
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public UUID getId() {
return id;
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.jacksonannotation.serialization.jsonrawvalue;
import com.baeldung.jacksonannotation.domain.Person;
import com.fasterxml.jackson.annotation.JsonRawValue;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Customer extends Person {
@JsonRawValue
private String configuration;
public Customer(String firstName, String lastName) {
super(firstName, lastName);
}
public String getConfiguration() {
return configuration;
}
public void setConfiguration(String configuration) {
this.configuration = configuration;
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.jacksonannotation.serialization.jsonrootname;
import com.baeldung.jacksonannotation.domain.Item;
import com.baeldung.jacksonannotation.domain.Person;
import com.fasterxml.jackson.annotation.JsonRootName;
import java.util.ArrayList;
import java.util.List;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
@JsonRootName("writer")
public class Author extends Person {
List<Item> items = new ArrayList<>();
public Author(String firstName, String lastName) {
super(firstName, lastName);
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.jacksonannotation.serialization.jsonserialize;
import com.baeldung.jacksonannotation.domain.Item;
import com.baeldung.jacksonannotation.domain.Person;
import java.util.ArrayList;
import java.util.List;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Author extends Person {
List<Item> items = new ArrayList<>();
public Author(String firstName, String lastName) {
super(firstName, lastName);
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.jacksonannotation.serialization.jsonserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.math.BigDecimal;
import java.util.Date;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Book extends Item {
private String ISBN;
@JsonSerialize(using = CustomDateSerializer.class)
private Date published;
private BigDecimal pages;
public Book(){}
public Book(String title, Author author) {
super(title, author);
}
public String getISBN() {
return ISBN;
}
public void setISBN(String ISBN) {
this.ISBN = ISBN;
}
public Date getPublished() {
return published;
}
public void setPublished(Date published) {
this.published = published;
}
public BigDecimal getPages() {
return pages;
}
public void setPages(BigDecimal pages) {
this.pages = pages;
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.jacksonannotation.serialization.jsonserialize;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class CustomDateSerializer extends StdSerializer<Date> {
private static SimpleDateFormat formatter =
new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
public CustomDateSerializer() {
this(null);
}
public CustomDateSerializer(Class<Date> t) {
super(t);
}
@Override
public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2)
throws IOException, JsonProcessingException {
gen.writeString(formatter.format(value));
}
}

View File

@ -0,0 +1,61 @@
package com.baeldung.jacksonannotation.serialization.jsonserialize;
import com.baeldung.jacksonannotation.domain.Person;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Item {
private UUID id;
private String title;
private List<Person> authors = new ArrayList<>();
private float price;
public Item(){}
public Item(String title, Author author) {
this.id = UUID.randomUUID();
this.title = title;
this.authors.add(author);
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Person> getAuthors() {
return authors;
}
public void setAuthors(List<Person> authors) {
this.authors = authors;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}

View File

@ -0,0 +1,76 @@
package com.baeldung.jacksonannotation.serialization.jsonvalue;
import com.baeldung.jacksonannotation.domain.Author;
import com.baeldung.jacksonannotation.domain.Item;
import com.fasterxml.jackson.annotation.JsonValue;
import java.util.List;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Course extends Item {
public enum Medium {CLASSROOM, ONLINE}
public enum Level {
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);
private String name;
private int number;
Level(String name, int number) {
this.name = name;
this.number = number;
}
@JsonValue
public String getName() {
return name;
}
}
private float duration;
private Medium medium;
private Level level;
private List<Course> prerequisite;
public Course(String title, Author author) {
super(title, author);
}
public float getDuration() {
return duration;
}
public void setDuration(float duration) {
this.duration = duration;
}
public Medium getMedium() {
return medium;
}
public void setMedium(Medium medium) {
this.medium = medium;
}
public Level getLevel() {
return level;
}
public void setLevel(Level level) {
this.level = level;
}
public List<Course> getPrerequisite() {
return prerequisite;
}
public void setPrerequisite(List<Course> prerequisite) {
this.prerequisite = prerequisite;
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.jacksonannotation.deserialization.jacksoninject;
import com.fasterxml.jackson.databind.InjectableValues;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.io.IOException;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class JacksonInjectTest {
@Test
public void whenDeserializingUsingJacksonInject_thenCorrect() throws IOException {
UUID id = UUID.fromString("9616dc8c-bad3-11e6-a4a6-cec0c932ce01");
// arrange
String authorJson = "{\"firstName\": \"Alex\", \"lastName\": \"Theedom\"}";
// act
InjectableValues inject = new InjectableValues.Std().addValue(UUID.class, id);
Author author = new ObjectMapper().reader(inject).forType(Author.class).readValue(authorJson);
// assert
assertThat(author.getId()).isEqualTo(id);
/*
{
"firstName": "Alex",
"lastName": "Theedom",
"publications": []
}
*/
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.jacksonannotation.deserialization.jsonanysetter;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.io.IOException;
import static io.restassured.path.json.JsonPath.from;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class JsonAnySetterTest {
@Test
public void whenDeserializingUsingJsonAnySetter_thenCorrect() throws IOException {
// arrange
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);
// 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"));
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.jacksonannotation.deserialization.jsoncreator;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.io.IOException;
import static io.restassured.path.json.JsonPath.from;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class JsonCreatorTest {
@Test
public void whenDeserializingUsingJsonCreator_thenCorrect() throws IOException {
// arrange
String authorJson =
"{" +
" \"christianName\": \"Alex\"," +
" \"surname\": \"Theedom\"" +
"}";
// act
final Author author = new ObjectMapper().readerFor(Author.class).readValue(authorJson);
// assert
assertThat(from(authorJson).getString("christianName")).isEqualTo(author.getFirstName());
assertThat(from(authorJson).getString("surname")).isEqualTo(author.getLastName());
/*
{
"christianName": "Alex",
"surname": "Theedom"
}
*/
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.jacksonannotation.deserialization.jsondeserialize;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.io.IOException;
import java.text.SimpleDateFormat;
import static io.restassured.path.json.JsonPath.from;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class JsonDeserializeTest {
@Test
public void whenDeserializingUsingJsonDeserialize_thenCorrect() throws IOException {
// arrange
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);
// assert
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
assertThat(from(bookJson).getString("published")).isEqualTo(df.format(book.getPublished()));
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.jacksonannotation.deserialization.jsonsetter;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.io.IOException;
import static io.restassured.path.json.JsonPath.from;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class JsonSetterTest {
@Test
public void whenDeserializingUsingJsonSetter_thenCorrect() throws IOException {
// arrange
String json = "{\"firstName\":\"Alex\",\"lastName\":\"Theedom\",\"publications\":[{\"title\":\"Professional Java EE Design Patterns\"}]}";
// act
Author author = new ObjectMapper().readerFor(Author.class).readValue(json);
// assert
assertThat(from(json).getList("publications").size()).isEqualTo(author.getItems().size());
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.jacksonannotation.general.jsonfilter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import org.junit.Test;
import static io.restassured.path.json.JsonPath.from;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class JsonFilterTest {
@Test
public void whenSerializingUsingJsonFilter_thenCorrect() throws JsonProcessingException {
// arrange
Author author = new Author("Alex", "Theedom");
FilterProvider filters = new SimpleFilterProvider()
.addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName"));
// act
String result = new ObjectMapper().writer(filters).writeValueAsString(author);
// assert
assertThat(from(result).getList("items")).isNull();
/*
{
"lastName": "Theedom"
}
*/
}
}

View File

@ -0,0 +1,66 @@
package com.baeldung.jacksonannotation.general.jsonformat;
import com.baeldung.jacksonannotation.domain.Author;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import static io.restassured.path.json.JsonPath.from;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class JsonFormatTest {
@Test
public void whenSerializingUsingJsonFormat_thenCorrect() throws JsonProcessingException, ParseException {
// arrange
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
String toParse = "20-12-2014 14:30:00";
Date date = df.parse(toParse);
Book book = new Book(
"Design Patterns: Elements of Reusable Object-oriented Software",
new Author("The", "GoF")
);
book.setPublished(date);
// act
String result = new ObjectMapper().writeValueAsString(book);
// assert
assertThat(from(result).getString("published")).isEqualTo(toParse);
/*
{
"id": "762b39be-fd5b-489e-8688-aeb3b9bbf019",
"title": "Design Patterns: Elements of Reusable Object-oriented Software",
"authors": [
{
"id": "6941b780-0f54-4259-adcb-85523c8f25f4",
"firstName": "The",
"lastName": "GoF",
"items": []
}
],
"price": 0,
"published": "20-12-2014 02:30:00",
"pages": null,
"isbn": null
}
*/
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.jacksonannotation.general.jsonidentityinfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.util.Collections;
import static io.restassured.path.json.JsonPath.from;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class JsonIdentityInfoTest {
@Test
public void whenSerializingUsingJsonIdentityInfo_thenCorrect() throws JsonProcessingException {
// arrange
Author author = new Author("Alex", "Theedom");
Course course = new Course("Java EE Introduction", author);
author.setItems(Collections.singletonList(course));
course.setAuthors(Collections.singletonList(author));
// act
String result = new ObjectMapper().writeValueAsString(author);
// assert
assertThat(from(result).getString("items[0].authors")).isNotNull();
/*
Authors are included.
{
"id": "1b408bf9-5946-4a14-a112-fde2953a7fe7",
"firstName": "Alex",
"lastName": "Theedom",
"items": [
{
"id": "5ed30530-f0a5-42eb-b786-be2c655da968",
"title": "Java EE Introduction",
"authors": [
"1b408bf9-5946-4a14-a112-fde2953a7fe7"
],
"price": 0,
"duration": 0,
"medium": null,
"level": null,
"prerequisite": null
}
]
}
*/
}
}

View File

@ -0,0 +1,73 @@
package com.baeldung.jacksonannotation.general.jsonproperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.io.IOException;
import static io.restassured.path.json.JsonPath.from;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class JsonPropertyTest {
@Test
public void whenSerializingUsingJsonProperty_thenCorrect() throws JsonProcessingException {
// arrange
Book book = new Book(
"Design Patterns: Elements of Reusable Object-oriented Software",
new Author("The", "GoF")
);
book.configureBinding("Hardback");
// act
String result = new ObjectMapper().writeValueAsString(book);
// assert
assertThat(from(result).getString("binding")).isEqualTo("Hardback");
/*
{
"id": "cd941587-d1ae-4c2a-9a36-29533bf50411",
"title": "Design Patterns: Elements of Reusable Object-oriented Software",
"authors": [
{
"id": "c8e26318-2f5b-4fa2-9fdc-6e99be021fca",
"firstName": "The",
"lastName": "GoF",
"items": []
}
],
"price": 0,
"published": null,
"pages": null,
"isbn": null,
"binding": "Hardback"
}
*/
}
@Test
public void whenDeserializingUsingJsonProperty_thenCorrect() throws IOException {
// arrange
String result = "{\"id\":\"cd941587-d1ae-4c2a-9a36-29533bf50411\",\"title\":\"Design Patterns: Elements of Reusable Object-oriented Software\",\"authors\":[{\"id\":\"c8e26318-2f5b-4fa2-9fdc-6e99be021fca\",\"firstName\":\"The\",\"lastName\":\"GoF\"}],\"binding\":\"Hardback\"}";
// act
Book book = new ObjectMapper().readerFor(Book.class).readValue(result);
// assert
assertThat(book.coverBinding()).isEqualTo("Hardback");
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.jacksonannotation.general.jsonunwrapped;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import static io.restassured.path.json.JsonPath.from;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class JsonUnwrappedTest {
@Test
public void whenSerializingUsingJsonUnwrapped_thenCorrect() throws JsonProcessingException {
// arrange
Order.Type preorderType = new Order.Type();
preorderType.id = 10;
preorderType.name = "pre-order";
Order order = new Order(preorderType);
// act
String result = new ObjectMapper().writeValueAsString(order);
// assert
assertThat(from(result).getInt("id")).isEqualTo(10);
assertThat(from(result).getString("name")).isEqualTo("pre-order");
/*
{
"id": 10,
"name": "pre-order"
}
*/
}
}

View File

@ -0,0 +1,72 @@
package com.baeldung.jacksonannotation.general.jsonview;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import static io.restassured.path.json.JsonPath.from;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class JsonViewTest {
@Test
public void whenSerializingUsingJsonView_andInternalView_thenCorrect() throws JsonProcessingException {
// arrange
Order order = new Order(120);
// act
String result = new ObjectMapper().writerWithView(Views.Internal.class).writeValueAsString(order);
// assert
assertThat(from(result).getUUID("id")).isNotNull();
assertThat(from(result).getObject("type", Order.Type.class)).isNotNull();
assertThat(from(result).getInt("internalAudit")).isEqualTo(120);
/*
{
"id": "33806388-795b-4812-b90a-60292111bc5c",
"type": {
"id": 20,
"name": "Order"
},
"internalAudit": 120
}
*/
}
@Test
public void whenSerializingUsingJsonView_andPublicView_thenCorrect() throws JsonProcessingException {
// arrange
Order order = new Order(120);
// act
String result = new ObjectMapper().writerWithView(Views.Public.class).writeValueAsString(order);
// assert
assertThat(from(result).getUUID("id")).isNotNull();
assertThat(from(result).getObject("type", Order.Type.class)).isNotNull();
assertThat(result).doesNotContain("internalAudit");
/*
{
"id": "5184d5fc-e359-4cdf-93fa-4054025bef4e",
"type": {
"id": 20,
"name": "Order"
}
}
*/
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.jacksonannotation.general.reference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.util.Collections;
import static io.restassured.path.json.JsonPath.from;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class ReferenceTest {
@Test
public void whenSerializingUsingReference_thenCorrect() throws JsonProcessingException {
// arrange
Author author = new Author("Alex", "Theedom");
Course course = new Course("Java EE Introduction", author);
author.setItems(Collections.singletonList(course));
course.setAuthors(Collections.singletonList(author));
// act
String result = new ObjectMapper().writeValueAsString(author);
// assert
assertThat(from(result).getString("items[0].authors")).isNull();
/*
Without references defined it throws StackOverflowError.
Authors excluded.
{
"id": "9c45d9b3-4888-4c24-8b74-65ef35627cd7",
"firstName": "Alex",
"lastName": "Theedom",
"items": [
{
"id": "f8309629-d178-4d67-93a4-b513ec4a7f47",
"title": "Java EE Introduction",
"price": 0,
"duration": 0,
"medium": null,
"level": null,
"prerequisite": null
}
]
}
*/
}
}

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