Merge branch 'master' into pr/837-sunil
This commit is contained in:
commit
9ae3a640a2
@ -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>
|
||||
|
||||
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
@ -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) {
|
||||
|
@ -49,7 +49,7 @@
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk15on</artifactId>
|
||||
<version>1.55</version>
|
||||
<version>${bouncycastle.version}</version>
|
||||
</dependency>
|
||||
<!-- web -->
|
||||
|
||||
@ -134,7 +134,7 @@
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>1.10</version>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
@ -338,6 +338,8 @@
|
||||
<!-- util -->
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.4</commons-lang3.version>
|
||||
<bouncycastle.version>1.55</bouncycastle.version>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
|
12
core-java/src/main/java/com/baeldung/generics/Building.java
Normal file
12
core-java/src/main/java/com/baeldung/generics/Building.java
Normal 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");
|
||||
}
|
||||
}
|
31
core-java/src/main/java/com/baeldung/generics/Generics.java
Normal file
31
core-java/src/main/java/com/baeldung/generics/Generics.java
Normal file
@ -0,0 +1,31 @@
|
||||
package com.baeldung.generics;
|
||||
|
||||
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) {
|
||||
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) {
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
12
core-java/src/main/java/com/baeldung/generics/House.java
Normal file
12
core-java/src/main/java/com/baeldung/generics/House.java
Normal 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");
|
||||
}
|
||||
}
|
@ -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();
|
||||
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
@ -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();
|
||||
|
||||
|
@ -0,0 +1,69 @@
|
||||
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 };
|
||||
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" };
|
||||
List<String> list = Generics.fromArrayToList(stringArray);
|
||||
|
||||
assertThat(list, hasItems(stringArray));
|
||||
}
|
||||
|
||||
// testing the generic method with Number as upper bound with Integer
|
||||
// if we test fromArrayToListWithUpperBound with any type that doesn't
|
||||
// extend Number it will fail to compile
|
||||
@Test
|
||||
public void givenArrayOfIntegersAndNumberUpperBound_thanListOfIntegersReturnedOK() {
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -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 {
|
||||
|
@ -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);
|
||||
|
@ -1,122 +0,0 @@
|
||||
package com.baeldung.java.networking.interfaces;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.InterfaceAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.net.SocketException;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class NetworkInterfaceTest {
|
||||
@Test
|
||||
public void givenName_whenReturnsNetworkInterface_thenCorrect() throws SocketException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInExistentName_whenReturnsNull_thenCorrect() throws SocketException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("inexistent_name");
|
||||
assertNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIP_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||
byte[] ip = new byte[] { 127, 0, 0, 1 };
|
||||
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getByAddress(ip));
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHostName_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getByName("localhost"));
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalHost_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoopBack_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getLoopbackAddress());
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIndex_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByIndex(0);
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenReturnsInetAddresses_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
Enumeration<InetAddress> addressEnum = nif.getInetAddresses();
|
||||
InetAddress address = addressEnum.nextElement();
|
||||
assertEquals("127.0.0.1", address.getHostAddress());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenReturnsInterfaceAddresses_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
|
||||
List<InterfaceAddress> addressEnum = nif.getInterfaceAddresses();
|
||||
InterfaceAddress address = addressEnum.get(0);
|
||||
InetAddress localAddress = address.getAddress();
|
||||
InetAddress broadCastAddress = address.getBroadcast();
|
||||
assertEquals("127.0.0.1", localAddress.getHostAddress());
|
||||
assertEquals("127.255.255.255", broadCastAddress.getHostAddress());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenChecksIfLoopback_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertTrue(nif.isLoopback());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenChecksIfUp_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertTrue(nif.isUp());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenChecksIfPointToPoint_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertFalse(nif.isPointToPoint());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenChecksIfVirtual_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertFalse(nif.isVirtual());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenChecksMulticastSupport_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertTrue(nif.supportsMulticast());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenGetsMacAddress_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
byte[] bytes = nif.getHardwareAddress();
|
||||
assertNotNull(bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenGetsMTU_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("net0");
|
||||
int mtu = nif.getMTU();
|
||||
assertEquals(1500, mtu);
|
||||
}
|
||||
}
|
@ -1,64 +1,72 @@
|
||||
package com.baeldung.java.nio2;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.DirectoryNotEmptyException;
|
||||
import java.nio.file.FileAlreadyExistsException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.NoSuchFileException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FileTest {
|
||||
private static final String HOME = System.getProperty("user.home");
|
||||
private static final String TEMP_DIR = String.format("%s/temp%s", System.getProperty("user.home"), UUID.randomUUID().toString());
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() throws IOException {
|
||||
Files.createDirectory(Paths.get(TEMP_DIR));
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void cleanup() throws IOException {
|
||||
FileUtils.deleteDirectory(new File(TEMP_DIR));
|
||||
}
|
||||
|
||||
// checking file or dir
|
||||
@Test
|
||||
public void givenExistentPath_whenConfirmsFileExists_thenCorrect() {
|
||||
Path p = Paths.get(HOME);
|
||||
Path p = Paths.get(TEMP_DIR);
|
||||
assertTrue(Files.exists(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonexistentPath_whenConfirmsFileNotExists_thenCorrect() {
|
||||
Path p = Paths.get(HOME + "/inexistent_file.txt");
|
||||
Path p = Paths.get(TEMP_DIR + "/inexistent_file.txt");
|
||||
assertTrue(Files.notExists(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDirPath_whenConfirmsNotRegularFile_thenCorrect() {
|
||||
Path p = Paths.get(HOME);
|
||||
Path p = Paths.get(TEMP_DIR);
|
||||
assertFalse(Files.isRegularFile(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistentDirPath_whenConfirmsReadable_thenCorrect() {
|
||||
Path p = Paths.get(HOME);
|
||||
Path p = Paths.get(TEMP_DIR);
|
||||
assertTrue(Files.isReadable(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistentDirPath_whenConfirmsWritable_thenCorrect() {
|
||||
Path p = Paths.get(HOME);
|
||||
Path p = Paths.get(System.getProperty("user.home"));
|
||||
assertTrue(Files.isWritable(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistentDirPath_whenConfirmsExecutable_thenCorrect() {
|
||||
Path p = Paths.get(HOME);
|
||||
Path p = Paths.get(System.getProperty("user.home"));
|
||||
assertTrue(Files.isExecutable(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSameFilePaths_whenConfirmsIsSame_thenCorrect() throws IOException {
|
||||
Path p1 = Paths.get(HOME);
|
||||
Path p2 = Paths.get(HOME);
|
||||
Path p1 = Paths.get(TEMP_DIR);
|
||||
Path p2 = Paths.get(TEMP_DIR);
|
||||
assertTrue(Files.isSameFile(p1, p2));
|
||||
}
|
||||
|
||||
@ -67,7 +75,7 @@ public class FileTest {
|
||||
@Test
|
||||
public void givenFilePath_whenCreatesNewFile_thenCorrect() throws IOException {
|
||||
String fileName = "myfile_" + UUID.randomUUID().toString() + ".txt";
|
||||
Path p = Paths.get(HOME + "/" + fileName);
|
||||
Path p = Paths.get(TEMP_DIR + "/" + fileName);
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createFile(p);
|
||||
assertTrue(Files.exists(p));
|
||||
@ -77,7 +85,7 @@ public class FileTest {
|
||||
@Test
|
||||
public void givenDirPath_whenCreatesNewDir_thenCorrect() throws IOException {
|
||||
String dirName = "myDir_" + UUID.randomUUID().toString();
|
||||
Path p = Paths.get(HOME + "/" + dirName);
|
||||
Path p = Paths.get(TEMP_DIR + "/" + dirName);
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createDirectory(p);
|
||||
assertTrue(Files.exists(p));
|
||||
@ -89,7 +97,7 @@ public class FileTest {
|
||||
@Test(expected = NoSuchFileException.class)
|
||||
public void givenDirPath_whenFailsToCreateRecursively_thenCorrect() throws IOException {
|
||||
String dirName = "myDir_" + UUID.randomUUID().toString() + "/subdir";
|
||||
Path p = Paths.get(HOME + "/" + dirName);
|
||||
Path p = Paths.get(TEMP_DIR + "/" + dirName);
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createDirectory(p);
|
||||
|
||||
@ -97,7 +105,7 @@ public class FileTest {
|
||||
|
||||
@Test
|
||||
public void givenDirPath_whenCreatesRecursively_thenCorrect() throws IOException {
|
||||
Path dir = Paths.get(HOME + "/myDir_" + UUID.randomUUID().toString());
|
||||
Path dir = Paths.get(TEMP_DIR + "/myDir_" + UUID.randomUUID().toString());
|
||||
Path subdir = dir.resolve("subdir");
|
||||
assertFalse(Files.exists(dir));
|
||||
assertFalse(Files.exists(subdir));
|
||||
@ -110,7 +118,7 @@ public class FileTest {
|
||||
public void givenFilePath_whenCreatesTempFile_thenCorrect() throws IOException {
|
||||
String prefix = "log_";
|
||||
String suffix = ".txt";
|
||||
Path p = Paths.get(HOME + "/");
|
||||
Path p = Paths.get(TEMP_DIR + "/");
|
||||
p = Files.createTempFile(p, prefix, suffix);
|
||||
// like log_8821081429012075286.txt
|
||||
assertTrue(Files.exists(p));
|
||||
@ -119,7 +127,7 @@ public class FileTest {
|
||||
|
||||
@Test
|
||||
public void givenPath_whenCreatesTempFileWithDefaults_thenCorrect() throws IOException {
|
||||
Path p = Paths.get(HOME + "/");
|
||||
Path p = Paths.get(TEMP_DIR + "/");
|
||||
p = Files.createTempFile(p, null, null);
|
||||
// like 8600179353689423985.tmp
|
||||
assertTrue(Files.exists(p));
|
||||
@ -136,7 +144,7 @@ public class FileTest {
|
||||
// delete file
|
||||
@Test
|
||||
public void givenPath_whenDeletes_thenCorrect() throws IOException {
|
||||
Path p = Paths.get(HOME + "/fileToDelete.txt");
|
||||
Path p = Paths.get(TEMP_DIR + "/fileToDelete.txt");
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createFile(p);
|
||||
assertTrue(Files.exists(p));
|
||||
@ -147,7 +155,7 @@ public class FileTest {
|
||||
|
||||
@Test(expected = DirectoryNotEmptyException.class)
|
||||
public void givenPath_whenFailsToDeleteNonEmptyDir_thenCorrect() throws IOException {
|
||||
Path dir = Paths.get(HOME + "/emptyDir" + UUID.randomUUID().toString());
|
||||
Path dir = Paths.get(TEMP_DIR + "/emptyDir" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir);
|
||||
assertTrue(Files.exists(dir));
|
||||
Path file = dir.resolve("file.txt");
|
||||
@ -160,7 +168,7 @@ public class FileTest {
|
||||
|
||||
@Test(expected = NoSuchFileException.class)
|
||||
public void givenInexistentFile_whenDeleteFails_thenCorrect() throws IOException {
|
||||
Path p = Paths.get(HOME + "/inexistentFile.txt");
|
||||
Path p = Paths.get(TEMP_DIR + "/inexistentFile.txt");
|
||||
assertFalse(Files.exists(p));
|
||||
Files.delete(p);
|
||||
|
||||
@ -168,7 +176,7 @@ public class FileTest {
|
||||
|
||||
@Test
|
||||
public void givenInexistentFile_whenDeleteIfExistsWorks_thenCorrect() throws IOException {
|
||||
Path p = Paths.get(HOME + "/inexistentFile.txt");
|
||||
Path p = Paths.get(TEMP_DIR + "/inexistentFile.txt");
|
||||
assertFalse(Files.exists(p));
|
||||
Files.deleteIfExists(p);
|
||||
|
||||
@ -177,8 +185,8 @@ public class FileTest {
|
||||
// copy file
|
||||
@Test
|
||||
public void givenFilePath_whenCopiesToNewLocation_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
@ -193,8 +201,8 @@ public class FileTest {
|
||||
|
||||
@Test(expected = FileAlreadyExistsException.class)
|
||||
public void givenPath_whenCopyFailsDueToExistingFile_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
@ -210,8 +218,8 @@ public class FileTest {
|
||||
// moving files
|
||||
@Test
|
||||
public void givenFilePath_whenMovesToNewLocation_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
@ -227,8 +235,8 @@ public class FileTest {
|
||||
|
||||
@Test(expected = FileAlreadyExistsException.class)
|
||||
public void givenFilePath_whenMoveFailsDueToExistingFile_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
|
@ -1,195 +0,0 @@
|
||||
package com.baeldung.java.nio2;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.file.NoSuchFileException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class PathTest {
|
||||
|
||||
private static final String HOME = System.getProperty("user.home");
|
||||
|
||||
// creating a path
|
||||
@Test
|
||||
public void givenPathString_whenCreatesPathObject_thenCorrect() {
|
||||
Path p = Paths.get("/articles/baeldung");
|
||||
assertEquals("\\articles\\baeldung", p.toString());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPathParts_whenCreatesPathObject_thenCorrect() {
|
||||
Path p = Paths.get("/articles", "baeldung");
|
||||
assertEquals("\\articles\\baeldung", p.toString());
|
||||
|
||||
}
|
||||
|
||||
// retrieving path info
|
||||
@Test
|
||||
public void givenPath_whenRetrievesFileName_thenCorrect() {
|
||||
Path p = Paths.get("/articles/baeldung/logs");
|
||||
assertEquals("logs", p.getFileName().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenRetrievesNameByIndex_thenCorrect() {
|
||||
Path p = Paths.get("/articles/baeldung/logs");
|
||||
assertEquals("articles", p.getName(0).toString());
|
||||
assertEquals("baeldung", p.getName(1).toString());
|
||||
assertEquals("logs", p.getName(2).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenCountsParts_thenCorrect() {
|
||||
Path p = Paths.get("/articles/baeldung/logs");
|
||||
assertEquals(3, p.getNameCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenCanRetrieveSubsequenceByIndex_thenCorrect() {
|
||||
Path p = Paths.get("/articles/baeldung/logs");
|
||||
assertEquals("articles", p.subpath(0, 1).toString());
|
||||
assertEquals("articles\\baeldung", p.subpath(0, 2).toString());
|
||||
assertEquals("articles\\baeldung\\logs", p.subpath(0, 3).toString());
|
||||
assertEquals("baeldung", p.subpath(1, 2).toString());
|
||||
assertEquals("baeldung\\logs", p.subpath(1, 3).toString());
|
||||
assertEquals("logs", p.subpath(2, 3).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenRetrievesParent_thenCorrect() {
|
||||
Path p1 = Paths.get("/articles/baeldung/logs");
|
||||
Path p2 = Paths.get("/articles/baeldung");
|
||||
Path p3 = Paths.get("/articles");
|
||||
Path p4 = Paths.get("/");
|
||||
|
||||
assertEquals("\\articles\\baeldung", p1.getParent().toString());
|
||||
assertEquals("\\articles", p2.getParent().toString());
|
||||
assertEquals("\\", p3.getParent().toString());
|
||||
assertEquals(null, p4.getParent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenRetrievesRoot_thenCorrect() {
|
||||
Path p1 = Paths.get("/articles/baeldung/logs");
|
||||
Path p2 = Paths.get("c:/articles/baeldung/logs");
|
||||
|
||||
assertEquals("\\", p1.getRoot().toString());
|
||||
assertEquals("c:\\", p2.getRoot().toString());
|
||||
}
|
||||
|
||||
// removing redundancies from path
|
||||
@Test
|
||||
public void givenPath_whenRemovesRedundancies_thenCorrect1() {
|
||||
Path p = Paths.get("/home/./baeldung/articles");
|
||||
p = p.normalize();
|
||||
assertEquals("\\home\\baeldung\\articles", p.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenRemovesRedundancies_thenCorrect2() {
|
||||
Path p = Paths.get("/home/baeldung/../articles");
|
||||
p = p.normalize();
|
||||
assertEquals("\\home\\articles", p.toString());
|
||||
}
|
||||
|
||||
// converting a path
|
||||
@Test
|
||||
public void givenPath_whenConvertsToBrowseablePath_thenCorrect() {
|
||||
Path p = Paths.get("/home/baeldung/articles.html");
|
||||
URI uri = p.toUri();
|
||||
assertEquals("file:///E:/home/baeldung/articles.html", uri.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenConvertsToAbsolutePath_thenCorrect() {
|
||||
Path p = Paths.get("/home/baeldung/articles.html");
|
||||
assertEquals("E:\\home\\baeldung\\articles.html", p.toAbsolutePath().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePath_whenRetainsAsAbsolute_thenCorrect() {
|
||||
Path p = Paths.get("E:\\home\\baeldung\\articles.html");
|
||||
assertEquals("E:\\home\\baeldung\\articles.html", p.toAbsolutePath().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingPath_whenGetsRealPathToFile_thenCorrect() throws IOException {
|
||||
Path p = Paths.get(HOME);
|
||||
assertEquals(HOME, p.toRealPath().toString());
|
||||
}
|
||||
|
||||
@Test(expected = NoSuchFileException.class)
|
||||
public void givenInExistentPath_whenFailsToConvert_thenCorrect() throws IOException {
|
||||
Path p = Paths.get("E:\\home\\baeldung\\articles.html");
|
||||
|
||||
p.toRealPath();
|
||||
}
|
||||
|
||||
// joining paths
|
||||
@Test
|
||||
public void givenTwoPaths_whenJoinsAndResolves_thenCorrect() throws IOException {
|
||||
Path p = Paths.get("/baeldung/articles");
|
||||
assertEquals("\\baeldung\\articles\\java", p.resolve("java").toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePath_whenResolutionRetainsIt_thenCorrect() throws IOException {
|
||||
Path p = Paths.get("/baeldung/articles");
|
||||
assertEquals("C:\\baeldung\\articles\\java", p.resolve("C:\\baeldung\\articles\\java").toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPathWithRoot_whenResolutionRetainsIt_thenCorrect2() throws IOException {
|
||||
Path p = Paths.get("/baeldung/articles");
|
||||
assertEquals("\\java", p.resolve("/java").toString());
|
||||
}
|
||||
|
||||
// creating a path between 2 paths
|
||||
@Test
|
||||
public void givenSiblingPaths_whenCreatesPathToOther_thenCorrect() throws IOException {
|
||||
Path p1 = Paths.get("articles");
|
||||
Path p2 = Paths.get("authors");
|
||||
assertEquals("..\\authors", p1.relativize(p2).toString());
|
||||
assertEquals("..\\articles", p2.relativize(p1).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonSiblingPaths_whenCreatesPathToOther_thenCorrect() throws IOException {
|
||||
Path p1 = Paths.get("/baeldung");
|
||||
Path p2 = Paths.get("/baeldung/authors/articles");
|
||||
assertEquals("authors\\articles", p1.relativize(p2).toString());
|
||||
assertEquals("..\\..", p2.relativize(p1).toString());
|
||||
}
|
||||
|
||||
// comparing 2 paths
|
||||
@Test
|
||||
public void givenTwoPaths_whenTestsEquality_thenCorrect() throws IOException {
|
||||
Path p1 = Paths.get("/baeldung/articles");
|
||||
Path p2 = Paths.get("/baeldung/articles");
|
||||
Path p3 = Paths.get("/baeldung/authors");
|
||||
|
||||
assertTrue(p1.equals(p2));
|
||||
assertFalse(p1.equals(p3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenInspectsStart_thenCorrect() {
|
||||
Path p1 = Paths.get("/baeldung/articles");
|
||||
assertTrue(p1.startsWith("/baeldung"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenInspectsEnd_thenCorrect() {
|
||||
Path p1 = Paths.get("/baeldung/articles");
|
||||
assertTrue(p1.endsWith("articles"));
|
||||
}
|
||||
}
|
@ -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:");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -0,0 +1,206 @@
|
||||
package com.baeldung.java8.optional;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.java_8_features.Person;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
// 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";
|
||||
}
|
||||
}
|
@ -0,0 +1,110 @@
|
||||
package org.baeldung.java.collections;
|
||||
|
||||
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 {
|
||||
|
||||
@Test
|
||||
public void givenUsingJava8_whenConcatenatingUsingConcat_thenCorrect() {
|
||||
Collection<String> collectionA = asList("S", "T");
|
||||
Collection<String> collectionB = asList("U", "V");
|
||||
Collection<String> collectionC = asList("W", "X");
|
||||
|
||||
Stream<String> combinedStream = Stream.concat(Stream.concat(collectionA.stream(), collectionB.stream()), collectionC.stream());
|
||||
Collection<String> collectionCombined = combinedStream.collect(Collectors.toList());
|
||||
|
||||
Assert.assertEquals(asList("S", "T", "U", "V", "W", "X"), collectionCombined);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingJava8_whenConcatenatingUsingflatMap_thenCorrect() {
|
||||
Collection<String> collectionA = asList("S", "T");
|
||||
Collection<String> collectionB = asList("U", "V");
|
||||
|
||||
Stream<String> combinedStream = Stream.of(collectionA, collectionB).flatMap(Collection::stream);
|
||||
Collection<String> collectionCombined = combinedStream.collect(Collectors.toList());
|
||||
|
||||
Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConcatenatingUsingIterables_thenCorrect() {
|
||||
Collection<String> collectionA = asList("S", "T");
|
||||
Collection<String> collectionB = asList("U", "V");
|
||||
|
||||
Iterable<String> combinedIterables = Iterables.unmodifiableIterable(Iterables.concat(collectionA, collectionB));
|
||||
Collection<String> collectionCombined = Lists.newArrayList(combinedIterables);
|
||||
|
||||
Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingJava7_whenConcatenatingUsingIterables_thenCorrect() {
|
||||
Collection<String> collectionA = asList("S", "T");
|
||||
Collection<String> collectionB = asList("U", "V");
|
||||
|
||||
Iterable<String> combinedIterables = concat(collectionA, collectionB);
|
||||
Collection<String> collectionCombined = makeListFromIterable(combinedIterables);
|
||||
Assert.assertEquals(Arrays.asList("S", "T", "U", "V"), collectionCombined);
|
||||
}
|
||||
|
||||
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>() {
|
||||
Iterator<? extends E> listIterator = i1.iterator();
|
||||
Boolean checkedHasNext;
|
||||
E nextValue;
|
||||
private boolean startTheSecond;
|
||||
|
||||
void theNext() {
|
||||
if (listIterator.hasNext()) {
|
||||
checkedHasNext = true;
|
||||
nextValue = listIterator.next();
|
||||
} else if (startTheSecond)
|
||||
checkedHasNext = false;
|
||||
else {
|
||||
startTheSecond = true;
|
||||
listIterator = i2.iterator();
|
||||
theNext();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasNext() {
|
||||
if (checkedHasNext == null)
|
||||
theNext();
|
||||
return checkedHasNext;
|
||||
}
|
||||
|
||||
public E next() {
|
||||
if (!hasNext())
|
||||
throw new NoSuchElementException();
|
||||
checkedHasNext = null;
|
||||
return nextValue;
|
||||
}
|
||||
|
||||
public void remove() {
|
||||
listIterator.remove();
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public static <E> List<E> makeListFromIterable(Iterable<E> iter) {
|
||||
List<E> list = new ArrayList<>();
|
||||
for (E item : iter) {
|
||||
list.add(item);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
@ -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")));
|
||||
}
|
||||
}
|
@ -1,7 +1,9 @@
|
||||
package org.baeldung.java.io;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
@ -9,17 +11,28 @@ import java.nio.file.FileSystemException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.Test;
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class JavaFileUnitTest {
|
||||
|
||||
// create a file
|
||||
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));
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void cleanup() throws IOException {
|
||||
FileUtils.deleteDirectory(new File(TEMP_DIR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingJDK6_whenCreatingFile_thenCorrect() throws IOException {
|
||||
final File newFile = new File("src/test/resources/newFile_jdk6.txt");
|
||||
final File newFile = new File(TEMP_DIR + "/newFile_jdk6.txt");
|
||||
final boolean success = newFile.createNewFile();
|
||||
|
||||
assertTrue(success);
|
||||
@ -27,48 +40,48 @@ public class JavaFileUnitTest {
|
||||
|
||||
@Test
|
||||
public final void givenUsingJDK7nio2_whenCreatingFile_thenCorrect() throws IOException {
|
||||
final Path newFilePath = Paths.get("src/test/resources/newFile_jdk7.txt");
|
||||
final Path newFilePath = Paths.get(TEMP_DIR + "/newFile_jdk7.txt");
|
||||
Files.createFile(newFilePath);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCommonsIo_whenCreatingFile_thenCorrect() throws IOException {
|
||||
FileUtils.touch(new File("src/test/resources/newFile_commonsio.txt"));
|
||||
FileUtils.touch(new File(TEMP_DIR + "/newFile_commonsio.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException {
|
||||
com.google.common.io.Files.touch(new File("src/test/resources/newFile_guava.txt"));
|
||||
com.google.common.io.Files.touch(new File(TEMP_DIR + "/newFile_guava.txt"));
|
||||
}
|
||||
|
||||
// move a file
|
||||
|
||||
@Test
|
||||
public final void givenUsingJDK6_whenMovingFile_thenCorrect() throws IOException {
|
||||
final File fileToMove = new File("src/test/resources/toMoveFile_jdk6.txt");
|
||||
final File fileToMove = new File(TEMP_DIR + "/toMoveFile_jdk6.txt");
|
||||
fileToMove.createNewFile();// .exists();
|
||||
final File destDir = new File("src/test/resources/");
|
||||
final File destDir = new File(TEMP_DIR + "/");
|
||||
destDir.mkdir();
|
||||
|
||||
final boolean isMoved = fileToMove.renameTo(new File("src/test/resources/movedFile_jdk6.txt"));
|
||||
final boolean isMoved = fileToMove.renameTo(new File(TEMP_DIR + "/movedFile_jdk6.txt"));
|
||||
if (!isMoved) {
|
||||
throw new FileSystemException("src/test/resources/movedFile_jdk6.txt");
|
||||
throw new FileSystemException(TEMP_DIR + "/movedFile_jdk6.txt");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingJDK7Nio2_whenMovingFile_thenCorrect() throws IOException {
|
||||
final Path fileToMovePath = Files.createFile(Paths.get("src/test/resources/" + randomAlphabetic(5) + ".txt"));
|
||||
final Path targetPath = Paths.get("src/main/resources/");
|
||||
final Path fileToMovePath = Files.createFile(Paths.get(TEMP_DIR + "/" + randomAlphabetic(5) + ".txt"));
|
||||
final Path targetPath = Paths.get(TEMP_DIR + "/");
|
||||
|
||||
Files.move(fileToMovePath, targetPath.resolve(fileToMovePath.getFileName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenMovingFile_thenCorrect() throws IOException {
|
||||
final File fileToMove = new File("src/test/resources/fileToMove.txt");
|
||||
final File fileToMove = new File(TEMP_DIR + "/fileToMove.txt");
|
||||
fileToMove.createNewFile();
|
||||
final File destDir = new File("src/main/resources/");
|
||||
final File destDir = new File(TEMP_DIR + "/temp");
|
||||
final File targetFile = new File(destDir, fileToMove.getName());
|
||||
com.google.common.io.Files.createParentDirs(targetFile);
|
||||
com.google.common.io.Files.move(fileToMove, targetFile);
|
||||
@ -76,23 +89,24 @@ public class JavaFileUnitTest {
|
||||
|
||||
@Test
|
||||
public final void givenUsingApache_whenMovingFile_thenCorrect() throws IOException {
|
||||
FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt"));
|
||||
FileUtils.moveFile(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/test/resources/fileMoved_apache2.txt"));
|
||||
FileUtils.touch(new File(TEMP_DIR + "/fileToMove_apache.txt"));
|
||||
FileUtils.moveFile(FileUtils.getFile(TEMP_DIR + "/fileToMove_apache.txt"), FileUtils.getFile(TEMP_DIR + "/fileMoved_apache2.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingApache_whenMovingFileApproach2_thenCorrect() throws IOException {
|
||||
FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt"));
|
||||
FileUtils.moveFileToDirectory(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/main/resources/"), true);
|
||||
FileUtils.touch(new File(TEMP_DIR + "/fileToMove_apache.txt"));
|
||||
Files.createDirectory(Paths.get(TEMP_DIR + "/temp"));
|
||||
FileUtils.moveFileToDirectory(FileUtils.getFile(TEMP_DIR + "/fileToMove_apache.txt"), FileUtils.getFile(TEMP_DIR + "/temp"), true);
|
||||
}
|
||||
|
||||
// delete a file
|
||||
|
||||
@Test
|
||||
public final void givenUsingJDK6_whenDeletingAFile_thenCorrect() throws IOException {
|
||||
new File("src/test/resources/fileToDelete_jdk6.txt").createNewFile();
|
||||
new File(TEMP_DIR + "/fileToDelete_jdk6.txt").createNewFile();
|
||||
|
||||
final File fileToDelete = new File("src/test/resources/fileToDelete_jdk6.txt");
|
||||
final File fileToDelete = new File(TEMP_DIR + "/fileToDelete_jdk6.txt");
|
||||
final boolean success = fileToDelete.delete();
|
||||
|
||||
assertTrue(success);
|
||||
@ -100,17 +114,17 @@ public class JavaFileUnitTest {
|
||||
|
||||
@Test
|
||||
public final void givenUsingJDK7nio2_whenDeletingAFile_thenCorrect() throws IOException {
|
||||
Files.createFile(Paths.get("src/test/resources/fileToDelete_jdk7.txt"));
|
||||
Files.createFile(Paths.get(TEMP_DIR + "/fileToDelete_jdk7.txt"));
|
||||
|
||||
final Path fileToDeletePath = Paths.get("src/test/resources/fileToDelete_jdk7.txt");
|
||||
final Path fileToDeletePath = Paths.get(TEMP_DIR + "/fileToDelete_jdk7.txt");
|
||||
Files.delete(fileToDeletePath);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCommonsIo_whenDeletingAFileV1_thenCorrect() throws IOException {
|
||||
FileUtils.touch(new File("src/test/resources/fileToDelete_commonsIo.txt"));
|
||||
FileUtils.touch(new File(TEMP_DIR + "/fileToDelete_commonsIo.txt"));
|
||||
|
||||
final File fileToDelete = FileUtils.getFile("src/test/resources/fileToDelete_commonsIo.txt");
|
||||
final File fileToDelete = FileUtils.getFile(TEMP_DIR + "/fileToDelete_commonsIo.txt");
|
||||
final boolean success = FileUtils.deleteQuietly(fileToDelete);
|
||||
|
||||
assertTrue(success);
|
||||
@ -118,9 +132,9 @@ public class JavaFileUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIo_whenDeletingAFileV2_thenCorrect() throws IOException {
|
||||
FileUtils.touch(new File("src/test/resources/fileToDelete.txt"));
|
||||
FileUtils.touch(new File(TEMP_DIR + "/fileToDelete.txt"));
|
||||
|
||||
FileUtils.forceDelete(FileUtils.getFile("src/test/resources/fileToDelete.txt"));
|
||||
FileUtils.forceDelete(FileUtils.getFile(TEMP_DIR + "/fileToDelete.txt"));
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
@ -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()));
|
||||
}
|
||||
|
||||
}
|
1
core-java/src/test/resources/file.txt
Normal file
1
core-java/src/test/resources/file.txt
Normal file
@ -0,0 +1 @@
|
||||
baeldung.com
|
47
ejb/ejb-client/pom.xml
Executable file
47
ejb/ejb-client/pom.xml
Executable file
@ -0,0 +1,47 @@
|
||||
<?xml version="1.0"?>
|
||||
<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/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.baeldung.ejb</groupId>
|
||||
<artifactId>ejb</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>ejb-client</artifactId>
|
||||
<name>EJB3 Client Maven</name>
|
||||
<description>EJB3 Client Maven</description>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.wildfly</groupId>
|
||||
<artifactId>wildfly-ejb-client-bom</artifactId>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baeldung.ejb</groupId>
|
||||
<artifactId>ejb-remote</artifactId>
|
||||
<type>ejb</type>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*EJBSetupTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
71
ejb/ejb-client/src/main/java/com/baeldung/ejb/client/EJBClient.java
Executable file
71
ejb/ejb-client/src/main/java/com/baeldung/ejb/client/EJBClient.java
Executable file
@ -0,0 +1,71 @@
|
||||
package com.baeldung.ejb.client;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.naming.Context;
|
||||
import javax.naming.InitialContext;
|
||||
import javax.naming.NamingException;
|
||||
|
||||
import com.baeldung.ejb.tutorial.HelloWorld;
|
||||
|
||||
public class EJBClient {
|
||||
|
||||
public EJBClient() {
|
||||
}
|
||||
|
||||
private Context context = null;
|
||||
|
||||
public String getEJBRemoteMessage() {
|
||||
EJBClient main = new EJBClient();
|
||||
try {
|
||||
// 1. Obtaining Context
|
||||
main.createInitialContext();
|
||||
// 2. Generate JNDI Lookup name and caste
|
||||
HelloWorld helloWorld = main.lookup();
|
||||
return helloWorld.getHelloWorld();
|
||||
} catch (NamingException e) {
|
||||
e.printStackTrace();
|
||||
return "";
|
||||
} finally {
|
||||
try {
|
||||
main.closeContext();
|
||||
} catch (NamingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public HelloWorld lookup() throws NamingException {
|
||||
|
||||
// The app name is the EAR name of the deployed EJB without .ear suffix.
|
||||
// Since we haven't deployed the application as a .ear, the app name for
|
||||
// us will be an empty string
|
||||
final String appName = "";
|
||||
final String moduleName = "remote";
|
||||
final String distinctName = "";
|
||||
final String beanName = "HelloWorld";
|
||||
final String viewClassName = HelloWorld.class.getName();
|
||||
final String toLookup = "ejb:" + appName + "/" + moduleName
|
||||
+ "/" + distinctName + "/" + beanName + "!" + viewClassName;
|
||||
return (HelloWorld) context.lookup(toLookup);
|
||||
}
|
||||
|
||||
public void createInitialContext() throws NamingException {
|
||||
Properties prop = new Properties();
|
||||
prop.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
|
||||
prop.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
|
||||
prop.put(Context.PROVIDER_URL, "http-remoting://127.0.0.1:8080");
|
||||
prop.put(Context.SECURITY_PRINCIPAL, "testUser");
|
||||
prop.put(Context.SECURITY_CREDENTIALS, "admin1234!");
|
||||
prop.put("jboss.naming.client.ejb.context", false);
|
||||
|
||||
context = new InitialContext(prop);
|
||||
}
|
||||
|
||||
public void closeContext() throws NamingException {
|
||||
if (context != null) {
|
||||
context.close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
8
ejb/ejb-client/src/main/resources/jboss-ejb-client.properties
Executable file
8
ejb/ejb-client/src/main/resources/jboss-ejb-client.properties
Executable file
@ -0,0 +1,8 @@
|
||||
remote.connections=default
|
||||
remote.connection.default.host=127.0.0.1
|
||||
remote.connection.default.port=8080
|
||||
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false
|
||||
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT=false
|
||||
remote.connection.default.connect.options.org.xnio.Options.SASL_DISALLOWED_MECHANISMS=${host.auth:JBOSS-LOCAL-USER}
|
||||
remote.connection.default.username=testUser
|
||||
remote.connection.default.password=admin1234!
|
16
ejb/ejb-client/src/test/java/com/baeldung/ejb/setup/test/EJBSetupTest.java
Executable file
16
ejb/ejb-client/src/test/java/com/baeldung/ejb/setup/test/EJBSetupTest.java
Executable file
@ -0,0 +1,16 @@
|
||||
package com.baeldung.ejb.setup.test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Test;
|
||||
import com.baeldung.ejb.client.EJBClient;
|
||||
import com.baeldung.ejb.tutorial.HelloWorldBean;
|
||||
|
||||
public class EJBSetupTest {
|
||||
|
||||
@Test
|
||||
public void testEJBClient() {
|
||||
EJBClient ejbClient = new EJBClient();
|
||||
HelloWorldBean bean = new HelloWorldBean();
|
||||
assertEquals(bean.getHelloWorld(), ejbClient.getEJBRemoteMessage());
|
||||
}
|
||||
}
|
40
ejb/ejb-remote/pom.xml
Executable file
40
ejb/ejb-remote/pom.xml
Executable file
@ -0,0 +1,40 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.baeldung.ejb</groupId>
|
||||
<artifactId>ejb</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>ejb-remote</artifactId>
|
||||
<packaging>ejb</packaging>
|
||||
|
||||
<!-- <name>ejb-remote</name> -->
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>javax</groupId>
|
||||
<artifactId>javaee-api</artifactId>
|
||||
<version>7.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.wildfly.plugins</groupId>
|
||||
<artifactId>wildfly-maven-plugin</artifactId>
|
||||
<version>1.1.0.Alpha5</version>
|
||||
<configuration>
|
||||
<hostname>127.0.0.1</hostname>
|
||||
<port>9990</port>
|
||||
<username>testUser</username>
|
||||
<password>admin1234!</password>
|
||||
<filename>${build.finalName}.jar</filename>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
<!-- <finalName>ejb-remote</finalName> -->
|
||||
</build>
|
||||
</project>
|
8
ejb/ejb-remote/src/main/java/com/baeldung/ejb/tutorial/HelloWorld.java
Executable file
8
ejb/ejb-remote/src/main/java/com/baeldung/ejb/tutorial/HelloWorld.java
Executable file
@ -0,0 +1,8 @@
|
||||
package com.baeldung.ejb.tutorial;
|
||||
|
||||
import javax.ejb.Remote;
|
||||
|
||||
@Remote
|
||||
public interface HelloWorld {
|
||||
String getHelloWorld();
|
||||
}
|
19
ejb/ejb-remote/src/main/java/com/baeldung/ejb/tutorial/HelloWorldBean.java
Executable file
19
ejb/ejb-remote/src/main/java/com/baeldung/ejb/tutorial/HelloWorldBean.java
Executable file
@ -0,0 +1,19 @@
|
||||
package com.baeldung.ejb.tutorial;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.ejb.SessionContext;
|
||||
import javax.ejb.Stateless;
|
||||
|
||||
@Stateless(name = "HelloWorld")
|
||||
public class HelloWorldBean implements HelloWorld {
|
||||
|
||||
@Resource
|
||||
private SessionContext context;
|
||||
|
||||
@Override
|
||||
public String getHelloWorld() {
|
||||
return "Welcome to EJB Tutorial!";
|
||||
}
|
||||
|
||||
|
||||
}
|
7
ejb/ejb-remote/src/main/resources/META-INF/ejb-jar.xml
Executable file
7
ejb/ejb-remote/src/main/resources/META-INF/ejb-jar.xml
Executable file
@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ejb-jar xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/ejb-jar_3_2.xsd"
|
||||
version="3.2">
|
||||
<module-name>remote</module-name>
|
||||
</ejb-jar>
|
||||
|
82
ejb/pom.xml
Executable file
82
ejb/pom.xml
Executable file
@ -0,0 +1,82 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.ejb</groupId>
|
||||
<artifactId>ejb</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
<name>ejb</name>
|
||||
<description>EJB Tutorial</description>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>jboss-public-repository-group</id>
|
||||
<name>JBoss Public Maven Repository Group</name>
|
||||
<url>http://repository.jboss.org/nexus/content/groups/public/</url>
|
||||
<layout>default</layout>
|
||||
<releases>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>never</updatePolicy>
|
||||
</releases>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>never</updatePolicy>
|
||||
</snapshots>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.baeldung.ejb</groupId>
|
||||
<artifactId>ejb-remote</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<type>ejb</type>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax</groupId>
|
||||
<artifactId>javaee-api</artifactId>
|
||||
<version>7.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.wildfly</groupId>
|
||||
<artifactId>wildfly-ejb-client-bom</artifactId>
|
||||
<version>10.1.0.Final</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<artifactId>maven-ejb-plugin</artifactId>
|
||||
<version>2.4</version>
|
||||
<configuration>
|
||||
<ejbVersion>3.2</ejbVersion>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
|
||||
<modules>
|
||||
<module>ejb-remote</module>
|
||||
<module>ejb-client</module>
|
||||
</modules>
|
||||
</project>
|
235
jackson-annotations/pom.xml
Normal file
235
jackson-annotations/pom.xml
Normal 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>
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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 {
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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 {
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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 {
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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));
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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": []
|
||||
}
|
||||
*/
|
||||
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user