Split or move libraries-data module

This commit is contained in:
catalin-burcea
2019-10-13 16:35:46 +03:00
parent 6a22b9162b
commit 7b2920f109
171 changed files with 678 additions and 690 deletions

View File

@@ -0,0 +1,95 @@
package com.baeldung.libraries.docx;
import org.docx4j.dml.wordprocessingDrawing.Inline;
import org.docx4j.jaxb.Context;
import org.docx4j.model.table.TblFactory;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.*;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import java.io.File;
import java.nio.file.Files;
import java.util.List;
class Docx4jExample {
void createDocumentPackage(String outputPath, String imagePath) throws Exception {
WordprocessingMLPackage wordPackage = WordprocessingMLPackage.createPackage();
MainDocumentPart mainDocumentPart = wordPackage.getMainDocumentPart();
mainDocumentPart.addStyledParagraphOfText("Title", "Hello World!");
mainDocumentPart.addParagraphOfText("Welcome To Baeldung!");
ObjectFactory factory = Context.getWmlObjectFactory();
P p = factory.createP();
R r = factory.createR();
Text t = factory.createText();
t.setValue("Welcome To Baeldung");
r.getContent().add(t);
p.getContent().add(r);
RPr rpr = factory.createRPr();
BooleanDefaultTrue b = new BooleanDefaultTrue();
rpr.setB(b);
rpr.setI(b);
rpr.setCaps(b);
Color red = factory.createColor();
red.setVal("green");
rpr.setColor(red);
r.setRPr(rpr);
mainDocumentPart.getContent().add(p);
File image = new File(imagePath);
byte[] fileContent = Files.readAllBytes(image.toPath());
BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordPackage, fileContent);
Inline inline = imagePart.createImageInline("Baeldung Image", "Alt Text", 1, 2, false);
P Imageparagraph = addImageToParagraph(inline);
mainDocumentPart.getContent().add(Imageparagraph);
int writableWidthTwips = wordPackage.getDocumentModel().getSections().get(0).getPageDimensions().getWritableWidthTwips();
int columnNumber = 3;
Tbl tbl = TblFactory.createTable(3, 3, writableWidthTwips / columnNumber);
List<Object> rows = tbl.getContent();
for (Object row : rows) {
Tr tr = (Tr) row;
List<Object> cells = tr.getContent();
for (Object cell : cells) {
Tc td = (Tc) cell;
td.getContent().add(p);
}
}
mainDocumentPart.getContent().add(tbl);
File exportFile = new File(outputPath);
wordPackage.save(exportFile);
}
boolean isTextExist(String testText) throws Docx4JException, JAXBException {
File doc = new File("helloWorld.docx");
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(doc);
MainDocumentPart mainDocumentPart = wordMLPackage.getMainDocumentPart();
String textNodesXPath = "//w:t";
List<Object> paragraphs = mainDocumentPart.getJAXBNodesViaXPath(textNodesXPath, true);
for (Object obj : paragraphs) {
Text text = (Text) ((JAXBElement) obj).getValue();
String textValue = text.getValue();
if (textValue != null && textValue.contains(testText)) {
return true;
}
}
return false;
}
private static P addImageToParagraph(Inline inline) {
ObjectFactory factory = new ObjectFactory();
P p = factory.createP();
R r = factory.createR();
p.getContent().add(r);
Drawing drawing = factory.createDrawing();
r.getContent().add(drawing);
drawing.getAnchorOrInline().add(inline);
return p;
}
}

View File

@@ -0,0 +1,16 @@
package com.baeldung.libraries.kryo;
import java.io.Serializable;
public class ComplexClass implements Serializable{
private static final long serialVersionUID = 123456L;
private String name = "Bael";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,55 @@
package com.baeldung.libraries.kryo;
import com.esotericsoftware.kryo.DefaultSerializer;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.KryoSerializable;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import java.util.Date;
@DefaultSerializer(PersonSerializer.class)
public class Person implements KryoSerializable {
private String name = "John Doe";
private int age = 18;
private Date birthDate = new Date(933191282821L);
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 Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
@Override
public void write(Kryo kryo, Output output) {
output.writeString(name);
output.writeLong(birthDate.getTime());
output.writeInt(age);
}
@Override
public void read(Kryo kryo, Input input) {
name = input.readString();
birthDate = new Date(input.readLong());
age = input.readInt();
}
}

View File

@@ -0,0 +1,34 @@
package com.baeldung.libraries.kryo;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import java.util.Date;
public class PersonSerializer extends Serializer<Person> {
@Override
public void write(Kryo kryo, Output output, Person object) {
output.writeString(object.getName());
output.writeLong(object.getBirthDate()
.getTime());
}
@Override
public Person read(Kryo kryo, Input input, Class<Person> type) {
Person person = new Person();
person.setName(input.readString());
long birthDate = input.readLong();
person.setBirthDate(new Date(birthDate));
person.setAge(calculateAge(birthDate));
return person;
}
private int calculateAge(long birthDate) {
// Some custom logic
return 18;
}
}

View File

@@ -0,0 +1,108 @@
package com.baeldung.libraries.opencsv;
import com.baeldung.libraries.opencsv.beans.NamedColumnBean;
import com.baeldung.libraries.opencsv.beans.SimplePositionBean;
import com.baeldung.libraries.opencsv.examples.sync.BeanExamples;
import com.baeldung.libraries.opencsv.examples.sync.CsvReaderExamples;
import com.baeldung.libraries.opencsv.examples.sync.CsvWriterExamples;
import com.baeldung.libraries.opencsv.helpers.Helpers;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
public class Application {
/*
* Bean Examples.
*/
public static String simpleSyncPositionBeanExample() {
Path path = null;
try {
path = Helpers.twoColumnCsvPath();
} catch (Exception ex) {
Helpers.err(ex);
}
return BeanExamples.beanBuilderExample(path, SimplePositionBean.class).toString();
}
public static String namedSyncColumnBeanExample() {
Path path = null;
try {
path = Helpers.namedColumnCsvPath();
} catch (Exception ex) {
Helpers.err(ex);
}
return BeanExamples.beanBuilderExample(path, NamedColumnBean.class).toString();
}
public static String writeSyncCsvFromBeanExample() {
Path path = null;
try {
path = Helpers.fileOutBeanPath();
} catch (Exception ex) {
Helpers.err(ex);
}
return BeanExamples.writeCsvFromBean(path);
}
/*
* CSV Reader Examples.
*/
public static String oneByOneSyncExample() {
Reader reader = null;
try {
reader = Files.newBufferedReader(Helpers.twoColumnCsvPath());
} catch (Exception ex) {
Helpers.err(ex);
}
return CsvReaderExamples.oneByOne(reader).toString();
}
public static String readAllSyncExample() {
Reader reader = null;
try {
reader = Files.newBufferedReader(Helpers.twoColumnCsvPath());
} catch (Exception ex) {
Helpers.err(ex);
}
return CsvReaderExamples.readAll(reader).toString();
}
/*
* CSV Writer Examples.
*/
public static String csvWriterSyncOneByOne() {
Path path = null;
try {
path = Helpers.fileOutOnePath();
} catch (Exception ex) {
Helpers.err(ex);
}
return CsvWriterExamples.csvWriterOneByOne(Helpers.fourColumnCsvString(), path);
}
public static String csvWriterSyncAll() {
Path path = null;
try {
path = Helpers.fileOutAllPath();
} catch (Exception ex) {
Helpers.err(ex);
}
return CsvWriterExamples.csvWriterAll(Helpers.fourColumnCsvString(), path);
}
public static void main(String[] args) {
simpleSyncPositionBeanExample();
namedSyncColumnBeanExample();
writeSyncCsvFromBeanExample();
oneByOneSyncExample();
readAllSyncExample();
csvWriterSyncOneByOne();
csvWriterSyncAll();
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.libraries.opencsv;
public class Constants {
public static final String GENERIC_EXCEPTION = "EXCEPTION ENCOUNTERED: ";
public static final String GENERIC_SUCCESS = "SUCCESS";
public static final String TWO_COLUMN_CSV = "csv/twoColumn.csv";
public static final String FOUR_COLUMN_CSV = "csv/fourColumn.csv";
public static final String NAMED_COLUMN_CSV = "csv/namedColumn.csv";
public static final String CSV_All = "csv/writtenAll.csv";
public static final String CSV_BEAN = "csv/writtenBean.csv";
public static final String CSV_ONE = "csv/writtenOneByOne.csv";
}

View File

@@ -0,0 +1,3 @@
package com.baeldung.libraries.opencsv.beans;
public class CsvBean { }

View File

@@ -0,0 +1,31 @@
package com.baeldung.libraries.opencsv.beans;
import com.opencsv.bean.CsvBindByName;
public class NamedColumnBean extends CsvBean {
@CsvBindByName(column = "name")
private String name;
//Automatically infer column name as Age
@CsvBindByName
private int age;
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;
}
}

View File

@@ -0,0 +1,29 @@
package com.baeldung.libraries.opencsv.beans;
import com.opencsv.bean.CsvBindByPosition;
public class SimplePositionBean extends CsvBean {
@CsvBindByPosition(position = 0)
private String exampleColOne;
@CsvBindByPosition(position = 1)
private String exampleColTwo;
public String getExampleColOne() {
return exampleColOne;
}
private void setExampleColOne(String exampleColOne) {
this.exampleColOne = exampleColOne;
}
public String getExampleColTwo() {
return exampleColTwo;
}
private void setExampleCsvTwo (String exampleColTwo) {
this.exampleColTwo = exampleColTwo;
}
}

View File

@@ -0,0 +1,40 @@
package com.baeldung.libraries.opencsv.beans;
public class WriteExampleBean extends CsvBean {
private String colA;
private String colB;
private String colC;
public WriteExampleBean(String colA, String colB, String colC) {
this.colA = colA;
this.colB = colB;
this.colC = colC;
}
public String getColA() {
return colA;
}
public void setColA(String colA) {
this.colA = colA;
}
public String getColB() {
return colB;
}
public void setColB(String colB) {
this.colB = colB;
}
public String getColC() {
return colC;
}
public void setColC(String colC) {
this.colC = colC;
}
}

View File

@@ -0,0 +1,63 @@
package com.baeldung.libraries.opencsv.examples.sync;
import com.baeldung.libraries.opencsv.beans.CsvBean;
import com.baeldung.libraries.opencsv.beans.WriteExampleBean;
import com.baeldung.libraries.opencsv.helpers.Helpers;
import com.baeldung.libraries.opencsv.pojos.CsvTransfer;
import com.opencsv.CSVWriter;
import com.opencsv.bean.*;
import java.io.FileWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class BeanExamples {
public static List<CsvBean> beanBuilderExample(Path path, Class clazz) {
ColumnPositionMappingStrategy ms = new ColumnPositionMappingStrategy();
return beanBuilderExample(path, clazz, ms);
}
public static List<CsvBean> beanBuilderExample(Path path, Class clazz, MappingStrategy ms) {
CsvTransfer csvTransfer = new CsvTransfer();
try {
ms.setType(clazz);
Reader reader = Files.newBufferedReader(path);
CsvToBean cb = new CsvToBeanBuilder(reader).withType(clazz)
.withMappingStrategy(ms)
.build();
csvTransfer.setCsvList(cb.parse());
reader.close();
} catch (Exception ex) {
Helpers.err(ex);
}
return csvTransfer.getCsvList();
}
public static String writeCsvFromBean(Path path) {
try {
Writer writer = new FileWriter(path.toString());
StatefulBeanToCsv sbc = new StatefulBeanToCsvBuilder(writer).withSeparator(CSVWriter.DEFAULT_SEPARATOR)
.build();
List<CsvBean> list = new ArrayList<>();
list.add(new WriteExampleBean("Test1", "sfdsf", "fdfd"));
list.add(new WriteExampleBean("Test2", "ipso", "facto"));
sbc.write(list);
writer.close();
} catch (Exception ex) {
Helpers.err(ex);
}
return Helpers.readFile(path);
}
}

View File

@@ -0,0 +1,63 @@
package com.baeldung.libraries.opencsv.examples.sync;
import com.baeldung.libraries.opencsv.helpers.Helpers;
import com.opencsv.CSVParser;
import com.opencsv.CSVParserBuilder;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
public class CsvReaderExamples {
public static List<String[]> readAll(Reader reader) {
CSVParser parser = new CSVParserBuilder()
.withSeparator(',')
.withIgnoreQuotations(true)
.build();
CSVReader csvReader = new CSVReaderBuilder(reader)
.withSkipLines(0)
.withCSVParser(parser)
.build();
List<String[]> list = new ArrayList<>();
try {
list = csvReader.readAll();
reader.close();
csvReader.close();
} catch (Exception ex) {
Helpers.err(ex);
}
return list;
}
public static List<String[]> oneByOne(Reader reader) {
List<String[]> list = new ArrayList<>();
try {
CSVParser parser = new CSVParserBuilder()
.withSeparator(',')
.withIgnoreQuotations(true)
.build();
CSVReader csvReader = new CSVReaderBuilder(reader)
.withSkipLines(0)
.withCSVParser(parser)
.build();
String[] line;
while ((line = csvReader.readNext()) != null) {
list.add(line);
}
reader.close();
csvReader.close();
} catch (Exception ex) {
Helpers.err(ex);
}
return list;
}
}

View File

@@ -0,0 +1,35 @@
package com.baeldung.libraries.opencsv.examples.sync;
import com.baeldung.libraries.opencsv.helpers.Helpers;
import com.opencsv.CSVWriter;
import java.io.FileWriter;
import java.nio.file.Path;
import java.util.List;
public class CsvWriterExamples {
public static String csvWriterOneByOne(List<String[]> stringArray, Path path) {
try {
CSVWriter writer = new CSVWriter(new FileWriter(path.toString()));
for (String[] array : stringArray) {
writer.writeNext(array);
}
writer.close();
} catch (Exception ex) {
Helpers.err(ex);
}
return Helpers.readFile(path);
}
public static String csvWriterAll(List<String[]> stringArray, Path path) {
try {
CSVWriter writer = new CSVWriter(new FileWriter(path.toString()));
writer.writeAll(stringArray);
writer.close();
} catch (Exception ex) {
Helpers.err(ex);
}
return Helpers.readFile(path);
}
}

View File

@@ -0,0 +1,108 @@
package com.baeldung.libraries.opencsv.helpers;
import com.baeldung.libraries.opencsv.Constants;
import java.io.BufferedReader;
import java.io.FileReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class Helpers {
/**
* Write Files
*/
public static Path fileOutAllPath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.CSV_All).toURI();
return Paths.get(uri);
}
public static Path fileOutBeanPath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.CSV_BEAN).toURI();
return Paths.get(uri);
}
public static Path fileOutOnePath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.CSV_ONE).toURI();
return Paths.get(uri);
}
/**
* Read Files
*/
public static Path twoColumnCsvPath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.TWO_COLUMN_CSV).toURI();
return Paths.get(uri);
}
public static Path fourColumnCsvPath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.FOUR_COLUMN_CSV).toURI();
return Paths.get(uri);
}
public static Path namedColumnCsvPath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.NAMED_COLUMN_CSV).toURI();
return Paths.get(uri);
}
/**
* Simple File Reader
*/
public static String readFile(Path path) {
String response = "";
try {
FileReader fr = new FileReader(path.toString());
BufferedReader br = new BufferedReader(fr);
String strLine;
StringBuffer sb = new StringBuffer();
while ((strLine = br.readLine()) != null) {
sb.append(strLine);
}
response = sb.toString();
System.out.println(response);
fr.close();
br.close();
} catch (Exception ex) {
Helpers.err(ex);
}
return response;
}
/**
* Dummy Data for Writing.
*/
public static List<String[]> twoColumnCsvString() {
List<String[]> list = new ArrayList<>();
list.add(new String[]{"ColA", "ColB"});
list.add(new String[]{"A", "B"});
return list;
}
public static List<String[]> fourColumnCsvString() {
List<String[]> list = new ArrayList<>();
list.add(new String[]{"ColA", "ColB", "ColC", "ColD"});
list.add(new String[]{"A", "B", "A", "B"});
list.add(new String[]{"BB", "AB", "AA", "B"});
return list;
}
/**
* Message Helpers
*/
public static void print(String msg) {
System.out.println(msg);
}
public static void err(Exception ex) {
System.out.println(Constants.GENERIC_EXCEPTION + " " + ex);
}
}

View File

@@ -0,0 +1,38 @@
package com.baeldung.libraries.opencsv.pojos;
import com.baeldung.libraries.opencsv.beans.CsvBean;
import java.util.ArrayList;
import java.util.List;
public class CsvTransfer {
private List<String[]> csvStringList;
private List<CsvBean> csvList;
public CsvTransfer() {}
public List<String[]> getCsvStringList() {
if (csvStringList != null) return csvStringList;
return new ArrayList<String[]>();
}
public void addLine(String[] line) {
if (this.csvList == null) this.csvStringList = new ArrayList<>();
this.csvStringList.add(line);
}
public void setCsvStringList(List<String[]> csvStringList) {
this.csvStringList = csvStringList;
}
public void setCsvList(List<CsvBean> csvList) {
this.csvList = csvList;
}
public List<CsvBean> getCsvList() {
if (csvList != null) return csvList;
return new ArrayList<CsvBean>();
}
}

View File

@@ -0,0 +1,34 @@
package com.baeldung.libraries.sheets;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.MemoryDataStoreFactory;
import com.google.api.services.sheets.v4.SheetsScopes;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
public class GoogleAuthorizeUtil {
public static Credential authorize() throws IOException, GeneralSecurityException {
InputStream in = GoogleAuthorizeUtil.class.getResourceAsStream("/google-sheets-client-secret.json");
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(), new InputStreamReader(in));
List<String> scopes = Arrays.asList(SheetsScopes.SPREADSHEETS);
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), clientSecrets, scopes).setDataStoreFactory(new MemoryDataStoreFactory())
.setAccessType("offline").build();
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
return credential;
}
}

View File

@@ -0,0 +1,20 @@
package com.baeldung.libraries.sheets;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.sheets.v4.Sheets;
import java.io.IOException;
import java.security.GeneralSecurityException;
public class SheetsServiceUtil {
private static final String APPLICATION_NAME = "Google Sheets Example";
public static Sheets getSheetsService() throws IOException, GeneralSecurityException {
Credential credential = GoogleAuthorizeUtil.authorize();
return new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), credential).setApplicationName(APPLICATION_NAME).build();
}
}

View File

@@ -0,0 +1,44 @@
package com.baeldung.libraries.smooks.converter;
import com.baeldung.libraries.smooks.model.Order;
import org.milyn.Smooks;
import org.milyn.payload.JavaResult;
import org.milyn.payload.StringResult;
import org.xml.sax.SAXException;
import javax.xml.transform.stream.StreamSource;
import java.io.IOException;
public class OrderConverter {
public Order convertOrderXMLToOrderObject(String path) throws IOException, SAXException {
Smooks smooks = new Smooks(OrderConverter.class.getResourceAsStream("/smooks/smooks-mapping.xml"));
try {
JavaResult javaResult = new JavaResult();
smooks.filterSource(new StreamSource(OrderConverter.class.getResourceAsStream(path)), javaResult);
return (Order) javaResult.getBean("order");
} finally {
smooks.close();
}
}
public String convertOrderXMLtoEDIFACT(String path) throws IOException, SAXException {
return convertDocumentWithTempalte(path, "/smooks/smooks-transform-edi.xml");
}
public String convertOrderXMLtoEmailMessage(String path) throws IOException, SAXException {
return convertDocumentWithTempalte(path, "/smooks/smooks-transform-email.xml");
}
private String convertDocumentWithTempalte(String path, String config) throws IOException, SAXException {
Smooks smooks = new Smooks(config);
try {
StringResult stringResult = new StringResult();
smooks.filterSource(new StreamSource(OrderConverter.class.getResourceAsStream(path)), stringResult);
return stringResult.toString();
} finally {
smooks.close();
}
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.libraries.smooks.converter;
import org.milyn.Smooks;
import org.milyn.payload.JavaResult;
import org.milyn.payload.StringResult;
import org.milyn.validation.ValidationResult;
import org.xml.sax.SAXException;
import javax.xml.transform.stream.StreamSource;
import java.io.IOException;
public class OrderValidator {
public ValidationResult validate(String path) throws IOException, SAXException {
Smooks smooks = new Smooks(OrderValidator.class.getResourceAsStream("/smooks/smooks-validation.xml"));
try {
StringResult xmlResult = new StringResult();
JavaResult javaResult = new JavaResult();
ValidationResult validationResult = new ValidationResult();
smooks.filterSource(new StreamSource(OrderValidator.class.getResourceAsStream(path)), xmlResult, javaResult, validationResult);
return validationResult;
} finally {
smooks.close();
}
}
}

View File

@@ -0,0 +1,70 @@
package com.baeldung.libraries.smooks.model;
public class Item {
public Item() {
}
public Item(String code, Double price, Integer quantity) {
this.code = code;
this.price = price;
this.quantity = quantity;
}
private String code;
private Double price;
private Integer quantity;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Item item = (Item) o;
if (code != null ? !code.equals(item.code) : item.code != null)
return false;
if (price != null ? !price.equals(item.price) : item.price != null)
return false;
return quantity != null ? quantity.equals(item.quantity) : item.quantity == null;
}
@Override
public int hashCode() {
int result = code != null ? code.hashCode() : 0;
result = 31 * result + (price != null ? price.hashCode() : 0);
result = 31 * result + (quantity != null ? quantity.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Item{" + "code='" + code + '\'' + ", price=" + price + ", quantity=" + quantity + '}';
}
}

View File

@@ -0,0 +1,52 @@
package com.baeldung.libraries.smooks.model;
import java.util.Date;
import java.util.List;
public class Order {
private Date creationDate;
private Long number;
private Status status;
private Supplier supplier;
private List<Item> items;
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Long getNumber() {
return number;
}
public void setNumber(Long number) {
this.number = number;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public Supplier getSupplier() {
return supplier;
}
public void setSupplier(Supplier supplier) {
this.supplier = supplier;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.libraries.smooks.model;
public enum Status {
NEW, IN_PROGRESS, FINISHED
}

View File

@@ -0,0 +1,52 @@
package com.baeldung.libraries.smooks.model;
public class Supplier {
private String name;
private String phoneNumber;
public Supplier() {
}
public Supplier(String name, String phoneNumber) {
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Supplier supplier = (Supplier) o;
if (name != null ? !name.equals(supplier.name) : supplier.name != null)
return false;
return phoneNumber != null ? phoneNumber.equals(supplier.phoneNumber) : supplier.phoneNumber == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0);
return result;
}
}

View File

@@ -0,0 +1,41 @@
package com.baeldung.libraries.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;
}
}

View File

@@ -0,0 +1,26 @@
package com.baeldung.libraries.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;
}
}

View File

@@ -0,0 +1,53 @@
package com.baeldung.libraries.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;
}
}

View File

@@ -0,0 +1 @@
{"installed":{"client_id":"394827218507-2ev02b2ha8plt7g2lh5nqse02ee737cf.apps.googleusercontent.com","project_id":"decisive-octane-187810","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://accounts.google.com/o/oauth2/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"2MnN1DfenoCGWMay3v8Bf7eI","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]}}

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

View File

@@ -0,0 +1,8 @@
<#setting locale="en_US">
Hi,
Order number #${order.number} created on ${order.creationDate?string["yyyy-MM-dd"]} is currently in ${order.status} status.
Consider contact supplier "${supplier.name}" with phone number: "${supplier.phoneNumber}".
Order items:
<#list items as item>
${item.quantity} X ${item.code} (total price ${item.price * item.quantity})
</#list>

View File

@@ -0,0 +1 @@
"max_total","item.quantity * item.price < 300.00"
1 max_total item.quantity * item.price < 300.00

View File

@@ -0,0 +1,7 @@
<#setting locale="en_US">
UNA:+.? '
UNH+${order.number}+${order.status}+${order.creationDate?string["yyyy-MM-dd"]}'
CTA+${supplier.name}+${supplier.phoneNumber}'
<#list items as item>
LIN+${item.quantity}+${item.code}+${item.price}'
</#list>

View File

@@ -0,0 +1,21 @@
{
"creationDate":"2018-01-14",
"orderNumber":771,
"orderStatus":"IN_PROGRESS",
"supplier":{
"name":"CompanyX",
"phone":"1234567"
},
"orderItems":[
{
"quantity":1,
"code":"PX1234",
"price":9.99
},
{
"quantity":2,
"code":"RX1990",
"price":120.32
}
]
}

View File

@@ -0,0 +1,20 @@
<order creation-date="2018-01-14">
<order-number>771</order-number>
<order-status>IN_PROGRESS</order-status>
<supplier>
<name>CompanyX</name>
<phone>1234567</phone>
</supplier>
<order-items>
<item>
<quantity>1</quantity>
<code>PX1234</code>
<price>9.99</price>
</item>
<item>
<quantity>2</quantity>
<code>RX990</code>
<price>120.32</price>
</item>
</order-items>
</order>

View File

@@ -0,0 +1,29 @@
<?xml version="1.0"?>
<smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd"
xmlns:jb="http://www.milyn.org/xsd/smooks/javabean-1.2.xsd">
<jb:bean beanId="order" class="com.baeldung.libraries.smooks.model.Order" createOnElement="order">
<jb:value property="number" data="order/order-number" />
<jb:value property="status" data="order/order-status" />
<jb:value property="creationDate" data="order/@creation-date" decoder="Date">
<jb:decodeParam name="format">yyyy-MM-dd</jb:decodeParam>
</jb:value>
<jb:wiring property="supplier" beanIdRef="supplier" />
<jb:wiring property="items" beanIdRef="items" />
</jb:bean>
<jb:bean beanId="supplier" class="com.baeldung.libraries.smooks.model.Supplier" createOnElement="supplier">
<jb:value property="name" data="name" />
<jb:value property="phoneNumber" data="phone" />
</jb:bean>
<jb:bean beanId="items" class="java.util.ArrayList" createOnElement="order">
<jb:wiring beanIdRef="item" />
</jb:bean>
<jb:bean beanId="item" class="com.baeldung.libraries.smooks.model.Item" createOnElement="item">
<jb:value property="code" data="item/code" />
<jb:value property="price" decoder="Double" data="item/price" />
<jb:value property="quantity" decoder="Integer" data="item/quantity" />
</jb:bean>
</smooks-resource-list>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0"?>
<smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd"
xmlns:ftl="http://www.milyn.org/xsd/smooks/freemarker-1.1.xsd">
<import file="smooks-validation.xml" />
<ftl:freemarker applyOnElement="#document">
<ftl:template>/smooks/order.ftl</ftl:template>
</ftl:freemarker>
</smooks-resource-list>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0"?>
<smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd"
xmlns:ftl="http://www.milyn.org/xsd/smooks/freemarker-1.1.xsd">
<import file="smooks-validation.xml" />
<ftl:freemarker applyOnElement="#document">
<ftl:template>/smooks/email.ftl</ftl:template>
</ftl:freemarker>
</smooks-resource-list>

View File

@@ -0,0 +1,17 @@
<?xml version="1.0"?>
<smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd"
xmlns:rules="http://www.milyn.org/xsd/smooks/rules-1.0.xsd"
xmlns:validation="http://www.milyn.org/xsd/smooks/validation-1.0.xsd">
<import file="/smooks/smooks-mapping.xml" />
<rules:ruleBases>
<rules:ruleBase name="supplierValidation" src="/smooks/supplier.properties" provider="org.milyn.rules.regex.RegexProvider"/>
<rules:ruleBase name="itemsValidation" src="/smooks/item-rules.csv" provider="org.milyn.rules.mvel.MVELProvider"/>
</rules:ruleBases>
<validation:rule executeOn="supplier/name" name="supplierValidation.supplierName" onFail="ERROR"/>
<validation:rule executeOn="supplier/phone" name="supplierValidation.supplierPhone" onFail="ERROR"/>
<validation:rule executeOn="order-items/item" name="itemsValidation.max_total" onFail="ERROR"/>
</smooks-resource-list>

View File

@@ -0,0 +1,2 @@
supplierName=[A-Za-z0-9]*
supplierPhone=^[0-9\\-\\+]{9,15}$

View File

@@ -0,0 +1,19 @@
package com.baeldung.libraries.docx;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class Docx4jReadAndWriteIntegrationTest {
private static final String imagePath = "src/main/resources/image.jpg";
private static final String outputPath = "helloWorld.docx";
@Test
public void givenWordPackage_whenTextExist_thenReturnTrue() throws Exception {
Docx4jExample docx4j = new Docx4jExample();
docx4j.createDocumentPackage(outputPath, imagePath);
assertTrue(docx4j.isTextExist("Hello World!"));
assertTrue(!docx4j.isTextExist("InexistantText"));
}
}

View File

@@ -0,0 +1,124 @@
package com.baeldung.libraries.kryo;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.serializers.JavaSerializer;
import org.junit.Before;
import org.junit.Test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.junit.Assert.assertEquals;
public class KryoUnitTest {
private Kryo kryo;
private Output output;
private Input input;
@Before
public void init() {
kryo = new Kryo();
try {
output = new Output(new FileOutputStream("src/test/resources/file.dat"));
input = new Input(new FileInputStream("src/test/resources/file.dat"));
} catch (FileNotFoundException ex) {
Logger.getLogger(KryoUnitTest.class.getName())
.log(Level.SEVERE, null, ex);
}
}
@Test
public void givenObject_whenSerializing_thenReadCorrectly() {
Object someObject = "Some string";
kryo.writeClassAndObject(output, someObject);
output.close();
Object theObject = kryo.readClassAndObject(input);
input.close();
assertEquals(theObject, "Some string");
}
@Test
public void givenObjects_whenSerializing_thenReadCorrectly() {
String someString = "Multiple Objects";
Date someDate = new Date(915170400000L);
kryo.writeObject(output, someString);
kryo.writeObject(output, someDate);
output.close();
String readString = kryo.readObject(input, String.class);
Date readDate = kryo.readObject(input, Date.class);
input.close();
assertEquals(readString, "Multiple Objects");
assertEquals(readDate.getTime(), 915170400000L);
}
@Test
public void givenPerson_whenSerializing_thenReadCorrectly() {
Person person = new Person();
kryo.writeObject(output, person);
output.close();
Person readPerson = kryo.readObject(input, Person.class);
input.close();
assertEquals(readPerson.getName(), "John Doe");
}
@Test
public void givenPerson_whenUsingCustomSerializer_thenReadCorrectly() {
Person person = new Person();
person.setAge(0);
kryo.register(Person.class, new PersonSerializer());
kryo.writeObject(output, person);
output.close();
Person readPerson = kryo.readObject(input, Person.class);
input.close();
assertEquals(readPerson.getName(), "John Doe");
assertEquals(readPerson.getAge(), 18);
}
@Test
public void givenPerson_whenCustomSerialization_thenReadCorrectly() {
Person person = new Person();
kryo.writeObject(output, person);
output.close();
Person readPerson = kryo.readObject(input, Person.class);
input.close();
assertEquals(readPerson.getName(), "John Doe");
assertEquals(readPerson.getAge(), 18);
}
@Test
public void givenJavaSerializable_whenSerializing_thenReadCorrectly() {
ComplexClass complexClass = new ComplexClass();
kryo.register(ComplexClass.class, new JavaSerializer());
kryo.writeObject(output, complexClass);
output.close();
ComplexClass readComplexObject = kryo.readObject(input, ComplexClass.class);
input.close();
assertEquals(readComplexObject.getName(), "Bael");
}
}

View File

@@ -0,0 +1,66 @@
package com.baeldung.libraries.opencsv;
import com.baeldung.libraries.opencsv.helpers.Helpers;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class OpenCsvIntegrationTest {
private Object testReadCsv(Object result) {
assert (result != null);
assert (result instanceof String);
assert (!((String) result).isEmpty());
System.out.println(result);
return result;
}
private Object testWriteCsv(Object result) {
assert (result instanceof String);
assert (!((String) result).isEmpty());
return result;
}
@Before
public void setup() {
}
@Test
public void positionExampleTest() {
testReadCsv(Application.simpleSyncPositionBeanExample());
}
@Test
public void namedColumnExampleTest() {
testReadCsv(Application.namedSyncColumnBeanExample());
}
@Test
public void writeCsvUsingBeanBuilderTest() {
testWriteCsv(Application.writeSyncCsvFromBeanExample());
}
@Test
public void oneByOneExampleTest() {
testReadCsv(Application.oneByOneSyncExample());
}
@Test
public void readAllExampleTest() {
testReadCsv(Application.readAllSyncExample());
}
@Test
public void csvWriterOneByOneTest() {
testWriteCsv(Application.csvWriterSyncOneByOne());
}
@Test
public void csvWriterAllTest() {
testWriteCsv(Application.csvWriterSyncAll());
}
@After
public void close() {
}
}

View File

@@ -0,0 +1,96 @@
package com.baeldung.libraries.sheets;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.model.AppendValuesResponse;
import com.google.api.services.sheets.v4.model.BatchGetValuesResponse;
import com.google.api.services.sheets.v4.model.BatchUpdateSpreadsheetRequest;
import com.google.api.services.sheets.v4.model.BatchUpdateValuesRequest;
import com.google.api.services.sheets.v4.model.BatchUpdateValuesResponse;
import com.google.api.services.sheets.v4.model.CopyPasteRequest;
import com.google.api.services.sheets.v4.model.GridRange;
import com.google.api.services.sheets.v4.model.Request;
import com.google.api.services.sheets.v4.model.Spreadsheet;
import com.google.api.services.sheets.v4.model.SpreadsheetProperties;
import com.google.api.services.sheets.v4.model.UpdateSpreadsheetPropertiesRequest;
import com.google.api.services.sheets.v4.model.UpdateValuesResponse;
import com.google.api.services.sheets.v4.model.ValueRange;
import static org.assertj.core.api.Assertions.*;
public class GoogleSheetsLiveTest {
private static Sheets sheetsService;
// this id can be replaced with your spreadsheet id
// otherwise be advised that multiple people may run this test and update the public spreadsheet
private static final String SPREADSHEET_ID = "1sILuxZUnyl_7-MlNThjt765oWshN3Xs-PPLfqYe4DhI";
@BeforeClass
public static void setup() throws GeneralSecurityException, IOException {
sheetsService = SheetsServiceUtil.getSheetsService();
}
@Test
public void whenWriteSheet_thenReadSheetOk() throws IOException {
ValueRange body = new ValueRange().setValues(Arrays.asList(Arrays.asList("Expenses January"), Arrays.asList("books", "30"), Arrays.asList("pens", "10"), Arrays.asList("Expenses February"), Arrays.asList("clothes", "20"), Arrays.asList("shoes", "5")));
UpdateValuesResponse result = sheetsService.spreadsheets().values().update(SPREADSHEET_ID, "A1", body).setValueInputOption("RAW").execute();
List<ValueRange> data = new ArrayList<>();
data.add(new ValueRange().setRange("D1").setValues(Arrays.asList(Arrays.asList("January Total", "=B2+B3"))));
data.add(new ValueRange().setRange("D4").setValues(Arrays.asList(Arrays.asList("February Total", "=B5+B6"))));
BatchUpdateValuesRequest batchBody = new BatchUpdateValuesRequest().setValueInputOption("USER_ENTERED").setData(data);
BatchUpdateValuesResponse batchResult = sheetsService.spreadsheets().values().batchUpdate(SPREADSHEET_ID, batchBody).execute();
List<String> ranges = Arrays.asList("E1", "E4");
BatchGetValuesResponse readResult = sheetsService.spreadsheets().values().batchGet(SPREADSHEET_ID).setRanges(ranges).execute();
ValueRange januaryTotal = readResult.getValueRanges().get(0);
assertThat(januaryTotal.getValues().get(0).get(0)).isEqualTo("40");
ValueRange febTotal = readResult.getValueRanges().get(1);
assertThat(febTotal.getValues().get(0).get(0)).isEqualTo("25");
ValueRange appendBody = new ValueRange().setValues(Arrays.asList(Arrays.asList("Total", "=E1+E4")));
AppendValuesResponse appendResult = sheetsService.spreadsheets().values().append(SPREADSHEET_ID, "A1", appendBody).setValueInputOption("USER_ENTERED").setInsertDataOption("INSERT_ROWS").setIncludeValuesInResponse(true).execute();
ValueRange total = appendResult.getUpdates().getUpdatedData();
assertThat(total.getValues().get(0).get(1)).isEqualTo("65");
}
@Test
public void whenUpdateSpreadSheetTitle_thenOk() throws IOException {
UpdateSpreadsheetPropertiesRequest updateRequest = new UpdateSpreadsheetPropertiesRequest().setFields("*").setProperties(new SpreadsheetProperties().setTitle("Expenses"));
CopyPasteRequest copyRequest = new CopyPasteRequest().setSource(new GridRange().setSheetId(0).setStartColumnIndex(0).setEndColumnIndex(2).setStartRowIndex(0).setEndRowIndex(1))
.setDestination(new GridRange().setSheetId(1).setStartColumnIndex(0).setEndColumnIndex(2).setStartRowIndex(0).setEndRowIndex(1)).setPasteType("PASTE_VALUES");
List<Request> requests = new ArrayList<>();
requests.add(new Request().setCopyPaste(copyRequest));
requests.add(new Request().setUpdateSpreadsheetProperties(updateRequest));
BatchUpdateSpreadsheetRequest body = new BatchUpdateSpreadsheetRequest().setRequests(requests);
sheetsService.spreadsheets().batchUpdate(SPREADSHEET_ID, body).execute();
}
@Test
public void whenCreateSpreadSheet_thenIdOk() throws IOException {
Spreadsheet spreadSheet = new Spreadsheet().setProperties(new SpreadsheetProperties().setTitle("My Spreadsheet"));
Spreadsheet result = sheetsService.spreadsheets().create(spreadSheet).execute();
assertThat(result.getSpreadsheetId()).isNotNull();
}
}

View File

@@ -0,0 +1,62 @@
package com.baeldung.libraries.smooks;
import com.baeldung.libraries.smooks.converter.OrderConverter;
import com.baeldung.libraries.smooks.converter.OrderValidator;
import com.baeldung.libraries.smooks.model.Item;
import com.baeldung.libraries.smooks.model.Order;
import com.baeldung.libraries.smooks.model.Status;
import com.baeldung.libraries.smooks.model.Supplier;
import org.junit.Test;
import org.milyn.validation.ValidationResult;
import java.text.SimpleDateFormat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
public class SmooksIntegrationTest {
private static final String EDIFACT_MESSAGE = "UNA:+.? '" + System.lineSeparator() + "UNH+771+IN_PROGRESS+2018-01-14'" + System.lineSeparator() + "CTA+CompanyX+1234567'" + System.lineSeparator() + "LIN+1+PX1234+9.99'" + System.lineSeparator()
+ "LIN+2+RX990+120.32'" + System.lineSeparator();
private static final String EMAIL_MESSAGE = "Hi," + System.lineSeparator() + "Order number #771 created on 2018-01-14 is currently in IN_PROGRESS status." + System.lineSeparator() + "Consider contact supplier \"CompanyX\" with phone number: \"1234567\"."
+ System.lineSeparator() + "Order items:" + System.lineSeparator() + "1 X PX1234 (total price 9.99)" + System.lineSeparator() + "2 X RX990 (total price 240.64)" + System.lineSeparator();
@Test
public void givenOrderXML_whenConvert_thenPOJOsConstructedCorrectly() throws Exception {
OrderConverter xmlToJavaOrderConverter = new OrderConverter();
Order order = xmlToJavaOrderConverter.convertOrderXMLToOrderObject("/smooks/order.xml");
assertThat(order.getNumber(), is(771L));
assertThat(order.getStatus(), is(Status.IN_PROGRESS));
assertThat(order.getCreationDate(), is(new SimpleDateFormat("yyyy-MM-dd").parse("2018-01-14")));
assertThat(order.getSupplier(), is(new Supplier("CompanyX", "1234567")));
assertThat(order.getItems(), containsInAnyOrder(new Item("PX1234", 9.99, 1), new Item("RX990", 120.32, 2)));
}
@Test
public void givenIncorrectOrderXML_whenValidate_thenExpectValidationErrors() throws Exception {
OrderValidator orderValidator = new OrderValidator();
ValidationResult validationResult = orderValidator.validate("/smooks/order.xml");
assertThat(validationResult.getErrors(), hasSize(1));
// 1234567 didn't match ^[0-9\\-\\+]{9,15}$
assertThat(validationResult.getErrors()
.get(0)
.getFailRuleResult()
.getRuleName(), is("supplierPhone"));
}
@Test
public void givenOrderXML_whenApplyEDITemplate_thenConvertedToEDIFACT() throws Exception {
OrderConverter orderConverter = new OrderConverter();
String edifact = orderConverter.convertOrderXMLtoEDIFACT("/smooks/order.xml");
assertThat(edifact, is(EDIFACT_MESSAGE));
}
@Test
public void givenOrderXML_whenApplyEmailTemplate_thenConvertedToEmailMessage() throws Exception {
OrderConverter orderConverter = new OrderConverter();
String emailMessage = orderConverter.convertOrderXMLtoEmailMessage("/smooks/order.xml");
assertThat(emailMessage, is(EMAIL_MESSAGE));
}
}

View File

@@ -0,0 +1,52 @@
package com.baeldung.libraries.snakeyaml;
import org.junit.Test;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.nodes.Tag;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
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.libraries.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));
}
}

View File

@@ -0,0 +1,131 @@
package com.baeldung.libraries.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);
}
}

Binary file not shown.

View File

@@ -0,0 +1,3 @@
firstName: "John"
lastName: "Doe"
age: 20

View File

@@ -0,0 +1,7 @@
firstName: "John"
lastName: "Doe"
age: 31
contactDetails:
- { type: "mobile", number: 123456789}
- { type: "landline", number: 456786868}

View File

@@ -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

View File

@@ -0,0 +1,6 @@
firstName: "John"
lastName: "Doe"
age: 31
contactDetails:
- !contact { type: "mobile", number: 123456789}
- !contact { type: "landline", number: 456786868}

View File

@@ -0,0 +1,4 @@
!!com.baeldung.libraries.snakeyaml.Customer
firstName: "John"
lastName: "Doe"
age: 20

View File

@@ -0,0 +1,8 @@
---
firstName: "John"
lastName: "Doe"
age: 20
---
firstName: "Jack"
lastName: "Jones"
age: 25