Split or move libraries-data module
This commit is contained in:
@@ -7,10 +7,8 @@ This module contains articles about libraries for data processing in Java.
|
||||
- [Guide to the HyperLogLog Algorithm](https://www.baeldung.com/java-hyperloglog)
|
||||
- [Introduction to Conflict-Free Replicated Data Types](https://www.baeldung.com/java-conflict-free-replicated-data-types)
|
||||
- [Introduction to javax.measure](https://www.baeldung.com/javax-measure)
|
||||
- [Introduction To Docx4J](https://www.baeldung.com/docx4j)
|
||||
- [Interact with Google Sheets from Java](https://www.baeldung.com/google-sheets-java-client)
|
||||
- [Introduction To OpenCSV](https://www.baeldung.com/opencsv)
|
||||
- [Introduction to Smooks](https://www.baeldung.com/smooks)
|
||||
- [A Guide to Infinispan in Java](https://www.baeldung.com/infinispan)
|
||||
- More articles: [[<-- prev>]](/libraries-data)
|
||||
|
||||
- [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)
|
||||
More articles: [[<-- prev]](/../libraries-data)
|
||||
@@ -67,43 +67,6 @@
|
||||
<artifactId>unit-ri</artifactId>
|
||||
<version>${unit-ri.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.xml.bind</groupId>
|
||||
<artifactId>jaxb-api</artifactId>
|
||||
<version>${jaxb-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.docx4j</groupId>
|
||||
<artifactId>docx4j</artifactId>
|
||||
<version>${docx4j.version}</version>
|
||||
</dependency>
|
||||
<!-- google api -->
|
||||
<dependency>
|
||||
<groupId>com.google.api-client</groupId>
|
||||
<artifactId>google-api-client</artifactId>
|
||||
<version>${google-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.oauth-client</groupId>
|
||||
<artifactId>google-oauth-client-jetty</artifactId>
|
||||
<version>${google-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.apis</groupId>
|
||||
<artifactId>google-api-services-sheets</artifactId>
|
||||
<version>${google-sheets.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/com.opencsv/opencsv -->
|
||||
<dependency>
|
||||
<groupId>com.opencsv</groupId>
|
||||
<artifactId>opencsv</artifactId>
|
||||
<version>${opencsv.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.milyn</groupId>
|
||||
<artifactId>milyn-smooks-all</artifactId>
|
||||
<version>${smooks.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.infinispan</groupId>
|
||||
<artifactId>infinispan-core</artifactId>
|
||||
@@ -124,22 +87,78 @@
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.api-client</groupId>
|
||||
<artifactId>google-api-client</artifactId>
|
||||
<version>${google-api.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>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-log4j12</artifactId>
|
||||
<version>${slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.awaitility</groupId>
|
||||
<artifactId>awaitility</artifactId>
|
||||
<version>${awaitility.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.awaitility</groupId>
|
||||
<artifactId>awaitility-proxy</artifactId>
|
||||
<version>${awaitility.version}</version>
|
||||
<scope>test</scope>
|
||||
</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>
|
||||
<flink.version>1.5.0</flink.version>
|
||||
<hll.version>1.6.0</hll.version>
|
||||
<crdt.version>0.1.0</crdt.version>
|
||||
<unit-ri.version>1.0.3</unit-ri.version>
|
||||
<docx4j.version>3.3.5</docx4j.version>
|
||||
<jaxb-api.version>2.1</jaxb-api.version>
|
||||
<google-api.version>1.23.0</google-api.version>
|
||||
<opencsv.version>4.1</opencsv.version>
|
||||
<smooks.version>1.7.0</smooks.version>
|
||||
<infinispan.version>9.1.5.Final</infinispan.version>
|
||||
<google-sheets.version>v4-rev493-1.21.0</google-sheets.version>
|
||||
<jackson.version>2.9.8</jackson.version>
|
||||
<spring.version>4.3.8.RELEASE</spring.version>
|
||||
<google-api.version>1.23.0</google-api.version>
|
||||
<jmapper.version>1.6.0.1</jmapper.version>
|
||||
<suanshu.version>4.0.0</suanshu.version>
|
||||
<derive4j.version>1.1.0</derive4j.version>
|
||||
<assertj.version>3.6.2</assertj.version>
|
||||
<slf4j.version>1.7.25</slf4j.version>
|
||||
<awaitility.version>3.0.0</awaitility.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(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));
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
package com.baeldung.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.BooleanDefaultTrue;
|
||||
import org.docx4j.wml.Color;
|
||||
import org.docx4j.wml.Drawing;
|
||||
import org.docx4j.wml.ObjectFactory;
|
||||
import org.docx4j.wml.P;
|
||||
import org.docx4j.wml.R;
|
||||
import org.docx4j.wml.RPr;
|
||||
import org.docx4j.wml.Tbl;
|
||||
import org.docx4j.wml.Tc;
|
||||
import org.docx4j.wml.Text;
|
||||
import org.docx4j.wml.Tr;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package com.baeldung.google.sheets;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
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;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.baeldung.google.sheets;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.GeneralSecurityException;
|
||||
|
||||
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;
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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 com.googlecode.jmapper.annotations.JMap;
|
||||
import com.googlecode.jmapper.annotations.JMapConversion;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.Period;
|
||||
|
||||
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 + "]";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
package com.baeldung.opencsv;
|
||||
|
||||
import com.baeldung.opencsv.beans.NamedColumnBean;
|
||||
import com.baeldung.opencsv.beans.SimplePositionBean;
|
||||
import com.baeldung.opencsv.examples.sync.BeanExamples;
|
||||
import com.baeldung.opencsv.examples.sync.CsvReaderExamples;
|
||||
import com.baeldung.opencsv.examples.sync.CsvWriterExamples;
|
||||
import com.baeldung.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();
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.baeldung.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";
|
||||
|
||||
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
package com.baeldung.opencsv.beans;
|
||||
|
||||
public class CsvBean { }
|
||||
@@ -1,31 +0,0 @@
|
||||
package com.baeldung.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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package com.baeldung.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;
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package com.baeldung.opencsv.examples.sync;
|
||||
|
||||
import com.baeldung.opencsv.beans.CsvBean;
|
||||
import com.baeldung.opencsv.beans.WriteExampleBean;
|
||||
import com.baeldung.opencsv.helpers.Helpers;
|
||||
import com.baeldung.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);
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package com.baeldung.opencsv.examples.sync;
|
||||
|
||||
import com.baeldung.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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package com.baeldung.opencsv.examples.sync;
|
||||
|
||||
import com.baeldung.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);
|
||||
}
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
package com.baeldung.opencsv.helpers;
|
||||
|
||||
import com.baeldung.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);
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package com.baeldung.opencsv.pojos;
|
||||
|
||||
import com.baeldung.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>();
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package com.baeldung.smooks.converter;
|
||||
|
||||
import com.baeldung.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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package com.baeldung.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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
package com.baeldung.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 + '}';
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package com.baeldung.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;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.baeldung.smooks.model;
|
||||
|
||||
public enum Status {
|
||||
NEW, IN_PROGRESS, FINISHED
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package com.baeldung.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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package com.baeldung.suanshu;
|
||||
|
||||
import com.numericalmethod.suanshu.algebra.linear.matrix.doubles.Matrix;
|
||||
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.algebra.linear.vector.doubles.Vector;
|
||||
import com.numericalmethod.suanshu.algebra.linear.vector.doubles.dense.DenseVector;
|
||||
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;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
{"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.
|
Before Width: | Height: | Size: 69 KiB |
@@ -1,8 +0,0 @@
|
||||
<#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>
|
||||
@@ -1 +0,0 @@
|
||||
"max_total","item.quantity * item.price < 300.00"
|
||||
|
@@ -1,7 +0,0 @@
|
||||
<#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>
|
||||
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"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
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
<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>
|
||||
@@ -1,29 +0,0 @@
|
||||
<?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.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.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.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>
|
||||
@@ -1,11 +0,0 @@
|
||||
<?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>
|
||||
@@ -1,12 +0,0 @@
|
||||
<?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>
|
||||
@@ -1,17 +0,0 @@
|
||||
<?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>
|
||||
@@ -1,2 +0,0 @@
|
||||
supplierName=[A-Za-z0-9]*
|
||||
supplierPhone=^[0-9\\-\\+]{9,15}$
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.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"));
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
package com.baeldung.google.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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package com.baeldung.opencsv;
|
||||
|
||||
import com.baeldung.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() {
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
package com.baeldung.smooks.converter;
|
||||
|
||||
import com.baeldung.smooks.model.Item;
|
||||
import com.baeldung.smooks.model.Order;
|
||||
import com.baeldung.smooks.model.Status;
|
||||
import com.baeldung.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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
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,99 @@
|
||||
package com.baeldung.jmapper;
|
||||
|
||||
import com.googlecode.jmapper.JMapper;
|
||||
import com.googlecode.jmapper.api.JMapperAPI;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
import static com.googlecode.jmapper.api.JMapperAPI.*;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
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,75 @@
|
||||
package com.baeldung.jmapper;
|
||||
|
||||
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;
|
||||
import org.junit.Test;
|
||||
|
||||
import static com.googlecode.jmapper.api.JMapperAPI.attribute;
|
||||
import static com.googlecode.jmapper.api.JMapperAPI.mappedClass;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
}
|
||||
10
libraries-data-2/src/test/resources/user_jmapper.xml
Normal file
10
libraries-data-2/src/test/resources/user_jmapper.xml
Normal file
@@ -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>
|
||||
5
libraries-data-2/src/test/resources/user_jmapper1.xml
Normal file
5
libraries-data-2/src/test/resources/user_jmapper1.xml
Normal file
@@ -0,0 +1,5 @@
|
||||
<jmapper>
|
||||
<class name="com.baeldung.jmapper.UserDto1">
|
||||
<global/>
|
||||
</class>
|
||||
</jmapper>
|
||||
21
libraries-data-2/src/test/resources/user_jmapper2.xml
Normal file
21
libraries-data-2/src/test/resources/user_jmapper2.xml
Normal file
@@ -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>
|
||||
Reference in New Issue
Block a user