Spark graphx moved to a new project due to a incompatibility of scala compiler

This commit is contained in:
Norberto Ritzmann Jr
2019-10-06 21:57:54 +02:00
parent db85c8f275
commit 45be61376e
20299 changed files with 1635696 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
### Relevant articles
- [Parsing YAML with SnakeYAML](https://www.baeldung.com/java-snake-yaml)
- [Guide to JMapper](https://www.baeldung.com/jmapper)
- [An Introduction to SuanShu](https://www.baeldung.com/suanshu)
- [Intro to Derive4J](https://www.baeldung.com/derive4j)
+1
View File
@@ -0,0 +1 @@
log4j.rootLogger=INFO, stdout
+55
View File
@@ -0,0 +1,55 @@
<?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>
<artifactId>libraries-data-3</artifactId>
<name>libraries-data-3</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>${snakeyaml.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.jmapper-framework</groupId>
<artifactId>jmapper-core</artifactId>
<version>${jmapper.version}</version>
</dependency>
<dependency>
<groupId>com.numericalmethod</groupId>
<artifactId>suanshu</artifactId>
<version>${suanshu.version}</version>
</dependency>
<dependency>
<groupId>org.derive4j</groupId>
<artifactId>derive4j</artifactId>
<version>${derive4j.version}</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>nm-repo</id>
<name>Numerical Method's Maven Repository</name>
<url>http://repo.numericalmethod.com/maven/</url>
<layout>default</layout>
</repository>
</repositories>
<properties>
<snakeyaml.version>1.21</snakeyaml.version>
<jmapper.version>1.6.0.1</jmapper.version>
<suanshu.version>4.0.0</suanshu.version>
<derive4j.version>1.1.0</derive4j.version>
</properties>
</project>
@@ -0,0 +1,10 @@
package com.baeldung.derive4j.adt;
import org.derive4j.Data;
import java.util.function.Function;
@Data
interface Either<A,B>{
<X> X match(Function<A, X> left, Function<B, X> right);
}
@@ -0,0 +1,21 @@
package com.baeldung.derive4j.lazy;
import org.derive4j.Data;
import org.derive4j.Derive;
import org.derive4j.Make;
@Data(value = @Derive(
inClass = "{ClassName}Impl",
make = {Make.lazyConstructor, Make.constructors, Make.getters}
))
public interface LazyRequest {
interface Cases<R>{
R GET(String path);
R POST(String path, String body);
R PUT(String path, String body);
R DELETE(String path);
}
<R> R match(LazyRequest.Cases<R> method);
}
@@ -0,0 +1,15 @@
package com.baeldung.derive4j.pattern;
import org.derive4j.Data;
@Data
interface HTTPRequest {
interface Cases<R>{
R GET(String path);
R POST(String path, String body);
R PUT(String path, String body);
R DELETE(String path);
}
<R> R match(Cases<R> method);
}
@@ -0,0 +1,19 @@
package com.baeldung.derive4j.pattern;
public class HTTPResponse {
private int statusCode;
private String responseBody;
public int getStatusCode() {
return statusCode;
}
public String getResponseBody() {
return responseBody;
}
public HTTPResponse(int statusCode, String responseBody) {
this.statusCode = statusCode;
this.responseBody = responseBody;
}
}
@@ -0,0 +1,17 @@
package com.baeldung.derive4j.pattern;
public class HTTPServer {
public static String GET_RESPONSE_BODY = "Success!";
public static String PUT_RESPONSE_BODY = "Resource Created!";
public static String POST_RESPONSE_BODY = "Resource Updated!";
public static String DELETE_RESPONSE_BODY = "Resource Deleted!";
public HTTPResponse acceptRequest(HTTPRequest request) {
return HTTPRequests.caseOf(request)
.GET((path) -> new HTTPResponse(200, GET_RESPONSE_BODY))
.POST((path,body) -> new HTTPResponse(201, POST_RESPONSE_BODY))
.PUT((path,body) -> new HTTPResponse(200, PUT_RESPONSE_BODY))
.DELETE(path -> new HTTPResponse(200, DELETE_RESPONSE_BODY));
}
}
@@ -0,0 +1,56 @@
package com.baeldung.jmapper;
import java.time.LocalDate;
public class User {
private long id;
private String email;
private LocalDate birthDate;
// constructors
public User() {
super();
}
public User(long id, String email, LocalDate birthDate) {
super();
this.id = id;
this.email = email;
this.birthDate = birthDate;
}
// getters and setters
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public LocalDate getBirthDate() {
return birthDate;
}
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
@Override
public String toString() {
return "User [id=" + id + ", email=" + email + ", birthDate=" + birthDate + "]";
}
}
@@ -0,0 +1,69 @@
package com.baeldung.jmapper;
import java.time.LocalDate;
import java.time.Period;
import com.googlecode.jmapper.annotations.JMap;
import com.googlecode.jmapper.annotations.JMapConversion;
public class UserDto {
@JMap
private long id;
@JMap("email")
private String username;
@JMap("birthDate")
private int age;
@JMapConversion(from={"birthDate"}, to={"age"})
public int conversion(LocalDate birthDate){
return Period.between(birthDate, LocalDate.now()).getYears();
}
// constructors
public UserDto() {
super();
}
public UserDto(long id, String username, int age) {
super();
this.id = id;
this.username = username;
this.age = age;
}
// getters and setters
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "UserDto [id=" + id + ", username=" + username + ", age=" + age + "]";
}
}
@@ -0,0 +1,47 @@
package com.baeldung.jmapper;
import com.googlecode.jmapper.annotations.JGlobalMap;
@JGlobalMap
public class UserDto1 {
private long id;
private String email;
// constructors
public UserDto1() {
super();
}
public UserDto1(long id, String email) {
super();
this.id = id;
this.email = email;
}
// getters and setters
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "UserDto [id=" + id + ", email=" + email + "]";
}
}
@@ -0,0 +1,49 @@
package com.baeldung.jmapper.relational;
import com.googlecode.jmapper.annotations.JMap;
public class User {
@JMap(classes = {UserDto1.class, UserDto2.class})
private long id;
@JMap(attributes = {"username", "email"}, classes = {UserDto1.class, UserDto2.class})
private String email;
// constructors
public User() {
super();
}
public User(long id, String email) {
super();
this.id = id;
this.email = email;
}
// getters and setters
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User [id=" + id + ", email=" + email + "]";
}
}
@@ -0,0 +1,44 @@
package com.baeldung.jmapper.relational;
public class UserDto1 {
private long id;
private String username;
// constructors
public UserDto1() {
super();
}
public UserDto1(long id, String username) {
super();
this.id = id;
this.username = username;
}
// getters and setters
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String toString() {
return "UserDto [id=" + id + ", username=" + username + "]";
}
}
@@ -0,0 +1,44 @@
package com.baeldung.jmapper.relational;
public class UserDto2 {
private long id;
private String email;
// constructors
public UserDto2() {
super();
}
public UserDto2(long id, String email) {
super();
this.id = id;
this.email = email;
}
// getters and setters
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "UserDto2 [id=" + id + ", email=" + email + "]";
}
}
@@ -0,0 +1,41 @@
package com.baeldung.snakeyaml;
public class Address {
private String line;
private String city;
private String state;
private Integer zip;
public String getLine() {
return line;
}
public void setLine(String line) {
this.line = line;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Integer getZip() {
return zip;
}
public void setZip(Integer zip) {
this.zip = zip;
}
}
@@ -0,0 +1,26 @@
package com.baeldung.snakeyaml;
public class Contact {
private String type;
private int number;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
@@ -0,0 +1,53 @@
package com.baeldung.snakeyaml;
import java.util.List;
public class Customer {
private String firstName;
private String lastName;
private int age;
private List<Contact> contactDetails;
private Address homeAddress;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<Contact> getContactDetails() {
return contactDetails;
}
public void setContactDetails(List<Contact> contactDetails) {
this.contactDetails = contactDetails;
}
public Address getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(Address homeAddress) {
this.homeAddress = homeAddress;
}
}
@@ -0,0 +1,142 @@
package com.baeldung.suanshu;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.numericalmethod.suanshu.algebra.linear.matrix.doubles.Matrix;
import com.numericalmethod.suanshu.algebra.linear.vector.doubles.Vector;
import com.numericalmethod.suanshu.algebra.linear.vector.doubles.dense.DenseVector;
import com.numericalmethod.suanshu.algebra.linear.matrix.doubles.matrixtype.dense.DenseMatrix;
import com.numericalmethod.suanshu.algebra.linear.matrix.doubles.operation.Inverse;
import com.numericalmethod.suanshu.analysis.function.polynomial.Polynomial;
import com.numericalmethod.suanshu.analysis.function.polynomial.root.PolyRoot;
import com.numericalmethod.suanshu.analysis.function.polynomial.root.PolyRootSolver;
import com.numericalmethod.suanshu.number.complex.Complex;
class SuanShuMath {
private static final Logger log = LoggerFactory.getLogger(SuanShuMath.class);
public static void main(String[] args) throws Exception {
SuanShuMath math = new SuanShuMath();
math.addingVectors();
math.scaleVector();
math.innerProductVectors();
math.addingIncorrectVectors();
math.addingMatrices();
math.multiplyMatrices();
math.multiplyIncorrectMatrices();
math.inverseMatrix();
Polynomial p = math.createPolynomial();
math.evaluatePolynomial(p);
math.solvePolynomial();
}
public void addingVectors() throws Exception {
Vector v1 = new DenseVector(new double[]{1, 2, 3, 4, 5});
Vector v2 = new DenseVector(new double[]{5, 4, 3, 2, 1});
Vector v3 = v1.add(v2);
log.info("Adding vectors: {}", v3);
}
public void scaleVector() throws Exception {
Vector v1 = new DenseVector(new double[]{1, 2, 3, 4, 5});
Vector v2 = v1.scaled(2.0);
log.info("Scaling a vector: {}", v2);
}
public void innerProductVectors() throws Exception {
Vector v1 = new DenseVector(new double[]{1, 2, 3, 4, 5});
Vector v2 = new DenseVector(new double[]{5, 4, 3, 2, 1});
double inner = v1.innerProduct(v2);
log.info("Vector inner product: {}", inner);
}
public void addingIncorrectVectors() throws Exception {
Vector v1 = new DenseVector(new double[]{1, 2, 3});
Vector v2 = new DenseVector(new double[]{5, 4});
Vector v3 = v1.add(v2);
log.info("Adding vectors: {}", v3);
}
public void addingMatrices() throws Exception {
Matrix m1 = new DenseMatrix(new double[][]{
{1, 2, 3},
{4, 5, 6}
});
Matrix m2 = new DenseMatrix(new double[][]{
{3, 2, 1},
{6, 5, 4}
});
Matrix m3 = m1.add(m2);
log.info("Adding matrices: {}", m3);
}
public void multiplyMatrices() throws Exception {
Matrix m1 = new DenseMatrix(new double[][]{
{1, 2, 3},
{4, 5, 6}
});
Matrix m2 = new DenseMatrix(new double[][]{
{1, 4},
{2, 5},
{3, 6}
});
Matrix m3 = m1.multiply(m2);
log.info("Multiplying matrices: {}", m3);
}
public void multiplyIncorrectMatrices() throws Exception {
Matrix m1 = new DenseMatrix(new double[][]{
{1, 2, 3},
{4, 5, 6}
});
Matrix m2 = new DenseMatrix(new double[][]{
{3, 2, 1},
{6, 5, 4}
});
Matrix m3 = m1.multiply(m2);
log.info("Multiplying matrices: {}", m3);
}
public void inverseMatrix() {
Matrix m1 = new DenseMatrix(new double[][]{
{1, 2},
{3, 4}
});
Inverse m2 = new Inverse(m1);
log.info("Inverting a matrix: {}", m2);
log.info("Verifying a matrix inverse: {}", m1.multiply(m2));
}
public Polynomial createPolynomial() {
return new Polynomial(new double[]{3, -5, 1});
}
public void evaluatePolynomial(Polynomial p) {
// Evaluate using a real number
log.info("Evaluating a polynomial using a real number: {}", p.evaluate(5));
// Evaluate using a complex number
log.info("Evaluating a polynomial using a complex number: {}", p.evaluate(new Complex(1, 2)));
}
public void solvePolynomial() {
Polynomial p = new Polynomial(new double[]{2, 2, -4});
PolyRootSolver solver = new PolyRoot();
List<? extends Number> roots = solver.solve(p);
log.info("Finding polynomial roots: {}", roots);
}
}
@@ -0,0 +1,10 @@
<jmapper>
<class name="com.baeldung.jmapper.UserDto">
<attribute name="id">
<value name="id"/>
</attribute>
<attribute name="username">
<value name="email"/>
</attribute>
</class>
</jmapper>
@@ -0,0 +1,5 @@
<jmapper>
<class name="com.baeldung.jmapper.UserDto1">
<global/>
</class>
</jmapper>
@@ -0,0 +1,21 @@
<jmapper>
<class name="com.baeldung.jmapper.relational.User">
<attribute name="id">
<value name="id"/>
<classes>
<class name="com.baeldung.jmapper.relational.UserDto1"/>
<class name="com.baeldung.jmapper.relational.UserDto2"/>
</classes>
</attribute>
<attribute name="email">
<attributes>
<attribute name="username"/>
<attribute name="email"/>
</attributes>
<classes>
<class name="com.baeldung.jmapper.relational.UserDto1"/>
<class name="com.baeldung.jmapper.relational.UserDto2"/>
</classes>
</attribute>
</class>
</jmapper>
@@ -0,0 +1,33 @@
package com.baeldung.derive4j.adt;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Optional;
import java.util.function.Function;
@RunWith(MockitoJUnitRunner.class)
public class EitherUnitTest {
@Test
public void testEitherIsCreatedFromRight() {
Either<Exception, String> either = Eithers.right("Okay");
Optional<Exception> leftOptional = Eithers.getLeft(either);
Optional<String> rightOptional = Eithers.getRight(either);
Assertions.assertThat(leftOptional).isEmpty();
Assertions.assertThat(rightOptional).hasValue("Okay");
}
@Test
public void testEitherIsMatchedWithRight() {
Either<Exception, String> either = Eithers.right("Okay");
Function<Exception, String> leftFunction = Mockito.mock(Function.class);
Function<String, String> rightFunction = Mockito.mock(Function.class);
either.match(leftFunction, rightFunction);
Mockito.verify(rightFunction, Mockito.times(1)).apply("Okay");
Mockito.verify(leftFunction, Mockito.times(0)).apply(Mockito.any(Exception.class));
}
}
@@ -0,0 +1,28 @@
package com.baeldung.derive4j.lazy;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import java.util.function.Supplier;
public class LazyRequestUnitTest {
@Test
public void givenLazyContstructedRequest_whenRequestIsReferenced_thenRequestIsLazilyContructed() {
LazyRequestSupplier mockSupplier = Mockito.spy(new LazyRequestSupplier());
LazyRequest request = LazyRequestImpl.lazy(() -> mockSupplier.get());
Mockito.verify(mockSupplier, Mockito.times(0)).get();
Assert.assertEquals(LazyRequestImpl.getPath(request), "http://test.com/get");
Mockito.verify(mockSupplier, Mockito.times(1)).get();
}
class LazyRequestSupplier implements Supplier<LazyRequest> {
@Override
public LazyRequest get() {
return LazyRequestImpl.GET("http://test.com/get");
}
}
}
@@ -0,0 +1,22 @@
package com.baeldung.derive4j.pattern;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class HTTPRequestUnitTest {
public static HTTPServer server;
@BeforeClass
public static void setUp() {
server = new HTTPServer();
}
@Test
public void givenHttpGETRequest_whenRequestReachesServer_thenProperResponseIsReturned() {
HTTPRequest postRequest = HTTPRequests.POST("http://test.com/post", "Resource");
HTTPResponse response = server.acceptRequest(postRequest);
Assert.assertEquals(201, response.getStatusCode());
Assert.assertEquals(HTTPServer.POST_RESPONSE_BODY, response.getResponseBody());
}
}
@@ -0,0 +1,102 @@
package com.baeldung.jmapper;
import static com.googlecode.jmapper.api.JMapperAPI.attribute;
import static com.googlecode.jmapper.api.JMapperAPI.global;
import static com.googlecode.jmapper.api.JMapperAPI.mappedClass;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.time.LocalDate;
import org.junit.Test;
import com.googlecode.jmapper.JMapper;
import com.googlecode.jmapper.api.JMapperAPI;
public class JMapperIntegrationTest {
@Test
public void givenUser_whenUseAnnotation_thenConverted() {
JMapper<UserDto, User> userMapper = new JMapper<>(UserDto.class, User.class);
User user = new User(1L, "john@test.com", LocalDate.of(1980, 8, 20));
UserDto result = userMapper.getDestination(user);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getUsername());
}
@Test
public void givenUser_whenUseGlobalMapAnnotation_thenConverted() {
JMapper<UserDto1, User> userMapper = new JMapper<>(UserDto1.class, User.class);
User user = new User(1L, "john@test.com", LocalDate.of(1980, 8, 20));
UserDto1 result = userMapper.getDestination(user);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getEmail());
}
@Test
public void givenUser_whenUseAnnotationExplicitConversion_thenConverted() {
JMapper<UserDto, User> userMapper = new JMapper<>(UserDto.class, User.class);
User user = new User(1L, "john@test.com", LocalDate.of(1980, 8, 20));
UserDto result = userMapper.getDestination(user);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getUsername());
assertTrue(result.getAge() > 0);
}
// ======================= XML
@Test
public void givenUser_whenUseXml_thenConverted() {
JMapper<UserDto, User> userMapper = new JMapper<>(UserDto.class, User.class, "user_jmapper.xml");
User user = new User(1L, "john@test.com", LocalDate.of(1980, 8, 20));
UserDto result = userMapper.getDestination(user);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getUsername());
}
@Test
public void givenUser_whenUseXmlGlobal_thenConverted() {
JMapper<UserDto1, User> userMapper = new JMapper<>(UserDto1.class, User.class, "user_jmapper1.xml");
User user = new User(1L, "john@test.com", LocalDate.of(1980, 8, 20));
UserDto1 result = userMapper.getDestination(user);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getEmail());
}
// ===== API
@Test
public void givenUser_whenUseApi_thenConverted() {
JMapperAPI jmapperApi = new JMapperAPI().add(mappedClass(UserDto.class).add(attribute("id").value("id")).add(attribute("username").value("email")));
JMapper<UserDto, User> userMapper = new JMapper<>(UserDto.class, User.class, jmapperApi);
User user = new User(1L, "john@test.com", LocalDate.of(1980, 8, 20));
UserDto result = userMapper.getDestination(user);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getUsername());
}
@Test
public void givenUser_whenUseApiGlobal_thenConverted() {
JMapperAPI jmapperApi = new JMapperAPI().add(mappedClass(UserDto.class).add(global()));
JMapper<UserDto1, User> userMapper1 = new JMapper<>(UserDto1.class, User.class, jmapperApi);
User user = new User(1L, "john@test.com", LocalDate.of(1980, 8, 20));
UserDto1 result = userMapper1.getDestination(user);
assertEquals(user.getId(), result.getId());
assertEquals(user.getEmail(), result.getEmail());
}
}
@@ -0,0 +1,76 @@
package com.baeldung.jmapper;
import static com.googlecode.jmapper.api.JMapperAPI.attribute;
import static com.googlecode.jmapper.api.JMapperAPI.mappedClass;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.baeldung.jmapper.relational.User;
import com.baeldung.jmapper.relational.UserDto1;
import com.baeldung.jmapper.relational.UserDto2;
import com.googlecode.jmapper.RelationalJMapper;
import com.googlecode.jmapper.api.JMapperAPI;
public class JMapperRelationalIntegrationTest {
@Test
public void givenUser_whenUseAnnotation_thenConverted(){
RelationalJMapper<User> relationalMapper = new RelationalJMapper<>(User.class);
User user = new User(1L,"john@test.com");
UserDto1 result1 = relationalMapper.oneToMany(UserDto1.class, user);
UserDto2 result2= relationalMapper.oneToMany(UserDto2.class, user);
System.out.println(result1);
System.out.println(result2);
assertEquals(user.getId(), result1.getId());
assertEquals(user.getEmail(), result1.getUsername());
assertEquals(user.getId(), result2.getId());
assertEquals(user.getEmail(), result2.getEmail());
}
//======================= XML
@Test
public void givenUser_whenUseXml_thenConverted(){
RelationalJMapper<User> relationalMapper = new RelationalJMapper<>(User.class,"user_jmapper2.xml");
User user = new User(1L,"john@test.com");
UserDto1 result1 = relationalMapper.oneToMany(UserDto1.class, user);
UserDto2 result2 = relationalMapper.oneToMany(UserDto2.class, user);
System.out.println(result1);
System.out.println(result2);
assertEquals(user.getId(), result1.getId());
assertEquals(user.getEmail(), result1.getUsername());
assertEquals(user.getId(), result2.getId());
assertEquals(user.getEmail(), result2.getEmail());
}
// ===== API
@Test
public void givenUser_whenUseApi_thenConverted(){
JMapperAPI jmapperApi = new JMapperAPI()
.add(mappedClass(User.class)
.add(attribute("id").value("id").targetClasses(UserDto1.class,UserDto2.class))
.add(attribute("email").targetAttributes("username","email").targetClasses(UserDto1.class,UserDto2.class)) )
;
RelationalJMapper<User> relationalMapper = new RelationalJMapper<>(User.class,jmapperApi);
User user = new User(1L,"john@test.com");
UserDto1 result1 = relationalMapper.oneToMany(UserDto1.class, user);
UserDto2 result2 = relationalMapper.oneToMany(UserDto2.class, user);
System.out.println(result1);
System.out.println(result2);
assertEquals(user.getId(), result1.getId());
assertEquals(user.getEmail(), result1.getUsername());
assertEquals(user.getId(), result2.getId());
assertEquals(user.getEmail(), result2.getEmail());
}
}
@@ -0,0 +1,54 @@
package com.baeldung.snakeyaml;
import static org.junit.Assert.assertEquals;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.Test;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.nodes.Tag;
import com.baeldung.snakeyaml.Customer;
public class JavaToYAMLSerializationUnitTest {
@Test
public void whenDumpMap_thenGenerateCorrectYAML() {
Map<String, Object> data = new LinkedHashMap<String, Object>();
data.put("name", "Silenthand Olleander");
data.put("race", "Human");
data.put("traits", new String[] { "ONE_HAND", "ONE_EYE" });
Yaml yaml = new Yaml();
StringWriter writer = new StringWriter();
yaml.dump(data, writer);
String expectedYaml = "name: Silenthand Olleander\nrace: Human\ntraits: [ONE_HAND, ONE_EYE]\n";
assertEquals(expectedYaml, writer.toString());
}
@Test
public void whenDumpACustomType_thenGenerateCorrectYAML() {
Customer customer = new Customer();
customer.setAge(45);
customer.setFirstName("Greg");
customer.setLastName("McDowell");
Yaml yaml = new Yaml();
StringWriter writer = new StringWriter();
yaml.dump(customer, writer);
String expectedYaml = "!!com.baeldung.snakeyaml.Customer {age: 45, contactDetails: null, firstName: Greg,\n homeAddress: null, lastName: McDowell}\n";
assertEquals(expectedYaml, writer.toString());
}
@Test
public void whenDumpAsCustomType_thenGenerateCorrectYAML() {
Customer customer = new Customer();
customer.setAge(45);
customer.setFirstName("Greg");
customer.setLastName("McDowell");
Yaml yaml = new Yaml();
String expectedYaml = "{age: 45, contactDetails: null, firstName: Greg, homeAddress: null, lastName: McDowell}\n";
assertEquals(expectedYaml, yaml.dumpAs(customer, Tag.MAP, null));
}
}
@@ -0,0 +1,131 @@
package com.baeldung.snakeyaml;
import org.junit.Test;
import org.yaml.snakeyaml.TypeDescription;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;
import static org.junit.Assert.*;
public class YAMLToJavaDeserialisationUnitTest {
@Test
public void whenLoadYAMLDocument_thenLoadCorrectMap() {
Yaml yaml = new Yaml();
InputStream inputStream = this.getClass()
.getClassLoader()
.getResourceAsStream("yaml/customer.yaml");
Map<String, Object> obj = yaml.load(inputStream);
assertEquals("John", obj.get("firstName"));
assertEquals("Doe", obj.get("lastName"));
assertEquals(20, obj.get("age"));
}
@Test
public void whenLoadYAMLDocumentWithTopLevelClass_thenLoadCorrectJavaObject() {
Yaml yaml = new Yaml(new Constructor(Customer.class));
InputStream inputStream = this.getClass()
.getClassLoader()
.getResourceAsStream("yaml/customer.yaml");
Customer customer = yaml.load(inputStream);
assertEquals("John", customer.getFirstName());
assertEquals("Doe", customer.getLastName());
assertEquals(20, customer.getAge());
}
@Test
public void whenLoadYAMLDocumentWithAssumedClass_thenLoadCorrectJavaObject() {
Yaml yaml = new Yaml();
InputStream inputStream = this.getClass()
.getClassLoader()
.getResourceAsStream("yaml/customer_with_type.yaml");
Customer customer = yaml.load(inputStream);
assertEquals("John", customer.getFirstName());
assertEquals("Doe", customer.getLastName());
assertEquals(20, customer.getAge());
}
@Test
public void whenLoadYAML_thenLoadCorrectImplicitTypes() {
Yaml yaml = new Yaml();
Map<Object, Object> document = yaml.load("3.0: 2018-07-22");
assertNotNull(document);
assertEquals(1, document.size());
assertTrue(document.containsKey(3.0d));
assertTrue(document.get(3.0d) instanceof Date);
}
@Test
public void whenLoadYAMLDocumentWithTopLevelClass_thenLoadCorrectJavaObjectWithNestedObjects() {
Yaml yaml = new Yaml(new Constructor(Customer.class));
InputStream inputStream = this.getClass()
.getClassLoader()
.getResourceAsStream("yaml/customer_with_contact_details_and_address.yaml");
Customer customer = yaml.load(inputStream);
assertNotNull(customer);
assertEquals("John", customer.getFirstName());
assertEquals("Doe", customer.getLastName());
assertEquals(31, customer.getAge());
assertNotNull(customer.getContactDetails());
assertEquals(2, customer.getContactDetails().size());
assertEquals("mobile", customer.getContactDetails()
.get(0)
.getType());
assertEquals(123456789,customer.getContactDetails()
.get(0)
.getNumber());
assertEquals("landline", customer.getContactDetails()
.get(1)
.getType());
assertEquals(456786868, customer.getContactDetails()
.get(1)
.getNumber());
assertNotNull(customer.getHomeAddress());
assertEquals("Xyz, DEF Street", customer.getHomeAddress()
.getLine());
}
@Test
public void whenLoadYAMLDocumentWithTypeDescription_thenLoadCorrectJavaObjectWithCorrectGenericType() {
Constructor constructor = new Constructor(Customer.class);
TypeDescription customTypeDescription = new TypeDescription(Customer.class);
customTypeDescription.addPropertyParameters("contactDetails", Contact.class);
constructor.addTypeDescription(customTypeDescription);
Yaml yaml = new Yaml(constructor);
InputStream inputStream = this.getClass()
.getClassLoader()
.getResourceAsStream("yaml/customer_with_contact_details.yaml");
Customer customer = yaml.load(inputStream);
assertNotNull(customer);
assertEquals("John", customer.getFirstName());
assertEquals("Doe", customer.getLastName());
assertEquals(31, customer.getAge());
assertNotNull(customer.getContactDetails());
assertEquals(2, customer.getContactDetails().size());
assertEquals("mobile", customer.getContactDetails()
.get(0)
.getType());
assertEquals("landline", customer.getContactDetails()
.get(1)
.getType());
}
@Test
public void whenLoadMultipleYAMLDocuments_thenLoadCorrectJavaObjects() {
Yaml yaml = new Yaml(new Constructor(Customer.class));
InputStream inputStream = this.getClass()
.getClassLoader()
.getResourceAsStream("yaml/customers.yaml");
int count = 0;
for (Object object : yaml.loadAll(inputStream)) {
count++;
assertTrue(object instanceof Customer);
}
assertEquals(2, count);
}
}
@@ -0,0 +1,3 @@
firstName: "John"
lastName: "Doe"
age: 20
@@ -0,0 +1,7 @@
firstName: "John"
lastName: "Doe"
age: 31
contactDetails:
- { type: "mobile", number: 123456789}
- { type: "landline", number: 456786868}
@@ -0,0 +1,13 @@
firstName: "John"
lastName: "Doe"
age: 31
contactDetails:
- type: "mobile"
number: 123456789
- type: "landline"
number: 456786868
homeAddress:
line: "Xyz, DEF Street"
city: "City Y"
state: "State Y"
zip: 345657
@@ -0,0 +1,6 @@
firstName: "John"
lastName: "Doe"
age: 31
contactDetails:
- !contact { type: "mobile", number: 123456789}
- !contact { type: "landline", number: 456786868}
@@ -0,0 +1,4 @@
!!com.baeldung.snakeyaml.Customer
firstName: "John"
lastName: "Doe"
age: 20
@@ -0,0 +1,8 @@
---
firstName: "John"
lastName: "Doe"
age: 20
---
firstName: "Jack"
lastName: "Jones"
age: 25