Split or move libraries-data module
This commit is contained in:
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user