repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/Data2D_Filter.java | alpha/MyBox/src/main/java/mara/mybox/data2d/Data2D_Filter.java | package mara.mybox.data2d;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import mara.mybox.calculation.DescriptiveStatistic;
import mara.mybox.calculation.DescriptiveStatistic.StatisticType;
import mara.mybox.calculation.DoubleStatistic;
import mara.mybox.calculation.ExpressionCalculator;
import mara.mybox.data.FindReplaceString;
import mara.mybox.db.data.ColumnDefinition.InvalidAs;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.db.data.Data2DStyle;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.tools.DoubleTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-7-31
* @License Apache License Version 2.0
*/
public abstract class Data2D_Filter extends Data2D_Data {
public void startTask(FxTask task, DataFilter filter) {
this.task = task;
this.filter = filter;
startFilter();
}
public void startFilter(DataFilter filter) {
this.filter = filter;
startFilter();
}
public void stopTask() {
task = null;
stopFilter();
}
public String filterScipt() {
return filter == null ? null : filter.getFilledScript();
}
public boolean filterEmpty() {
return filter == null || filter.scriptEmpty();
}
public boolean needFilter() {
return filter != null && filter.needFilter();
}
public void startFilter() {
if (filter == null) {
return;
}
filter.start(task, (Data2D) this);
}
public void stopFilter() {
if (filter == null) {
return;
}
filter.stop();
}
public void resetFilterNumber() {
if (filter == null) {
return;
}
filter.resetNumber();
}
public boolean filterTableRow(List<String> tableRow, long tableRowIndex) {
error = null;
if (filter == null) {
return true;
}
if (filter.filterTableRow((Data2D) this, tableRow, tableRowIndex)) {
return true;
} else {
error = filter.getError();
return false;
}
}
public boolean filterDataRow(List<String> dataRow, long dataRowIndex) {
error = null;
if (filter == null) {
return true;
}
if (filter.filterDataRow((Data2D) this, dataRow, dataRowIndex)) {
return true;
} else {
error = filter.getError();
return false;
}
}
public boolean filterPassed() {
return filter == null || filter.passed;
}
public boolean filterReachMaxPassed() {
return filter != null && filter.reachMaxPassed();
}
public boolean calculateDataRowExpression(String script, List<String> dataRow, long dataRowNumber) {
error = null;
if (filter == null) {
return true;
}
if (filter.calculator == null) {
return false;
}
return filter.calculator.calculateDataRowExpression((Data2D) this, script, dataRow, dataRowNumber);
}
public boolean calculateTableRowExpression(String script, List<String> tableRow, long tableRowNumber) {
error = null;
if (filter == null) {
return true;
}
if (filter.calculator == null) {
return false;
}
return filter.calculator.calculateTableRowExpression((Data2D) this, script, tableRow, tableRowNumber);
}
public String expressionError() {
if (filter == null) {
return null;
}
return filter.getError();
}
public String expressionResult() {
if (filter == null) {
return null;
}
return filter.getResult();
}
public boolean fillFilterStatistic() {
if (filter == null || filter.scriptEmpty()) {
return true;
}
String filled = calculateScriptStatistic(filter.getSourceScript());
if (filled == null || filled.isBlank()) {
return false;
}
filter.setFilledScript(filled);
return true;
}
public String calculateScriptStatistic(String script) {
if (script == null || script.isBlank()) {
return script;
}
List<String> scripts = new ArrayList<>();
scripts.add(script);
scripts = calculateScriptsStatistic(scripts);
if (scripts == null || scripts.isEmpty()) {
return null;
}
return scripts.get(0);
}
public List<String> calculateScriptsStatistic(List<String> scripts) {
try {
if (scripts == null || scripts.isEmpty()) {
return scripts;
}
DescriptiveStatistic calculation = new DescriptiveStatistic()
.setStatisticObject(DescriptiveStatistic.StatisticObject.Columns)
.setInvalidAs(InvalidAs.Empty);
List<Integer> colIndices = new ArrayList<>();
for (String script : scripts) {
checkFilterStatistic(script, calculation, colIndices);
}
if (!calculation.need()) {
return scripts;
}
DoubleStatistic[] sData = null;
if (isTmpData()) {
sData = ((Data2D) this).statisticByColumnsForCurrentPage(colIndices, calculation);
} else {
Data2D filter2D = ((Data2D) this).cloneTo();
filter2D.resetStatistic();
filter2D.startTask(task, null);
if (calculation.needNonStored()) {
sData = filter2D.statisticByColumnsWithoutStored(colIndices, calculation);
}
if (calculation.needStored()) {
sData = filter2D.statisticByColumnsForStored(colIndices, calculation);
}
filter2D.stopTask();
}
if (sData == null) {
return null;
}
for (int c = 0; c < colIndices.size(); c++) {
column(colIndices.get(c)).setStatistic(sData[c]);
}
List<String> filled = new ArrayList<>();
FindReplaceString findReplace = ExpressionCalculator.createReplaceAll();
for (String script : scripts) {
if (task == null || !task.isWorking()) {
return null;
}
filled.add(replaceFilterStatistic(findReplace, script));
}
return filled;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
return null;
}
}
public void checkFilterStatistic(String script, DescriptiveStatistic calculation, List<Integer> colIndices) {
try {
if (script == null || script.isBlank() || calculation == null || colIndices == null) {
return;
}
for (int i = 0; i < columnsNumber(); i++) {
Data2DColumn column = columns.get(i);
String name = column.getColumnName();
for (StatisticType stype : StatisticType.values()) {
if (script.contains("#{" + name + "-" + message(stype.name()) + "}")) {
calculation.add(stype);
}
}
if (!calculation.need()) {
continue;
}
int col = colOrder(name);
if (!colIndices.contains(col)) {
colIndices.add(col);
}
}
} catch (Exception e) {
MyBoxLog.error(e);
if (task != null) {
task.setError(e.toString());
}
}
}
public String replaceFilterStatistic(FindReplaceString findReplace, String script) {
try {
if (!hasColumns() || script == null || script.isBlank()) {
return script;
}
String filledScript = script;
for (int i = 0; i < columnsNumber(); i++) {
if (task == null || !task.isWorking()) {
return message("Canceled");
}
Data2DColumn column = columns.get(i);
String name = column.getColumnName();
if (filledScript.contains("#{" + name + "-" + message("Mean") + "}")) {
if (column.getStatistic() == null || DoubleTools.invalidDouble(column.getStatistic().mean)) {
return null;
}
filledScript = findReplace.replace(task, filledScript, "#{" + name + "-" + message("Mean") + "}",
column.getStatistic().mean + "");
if (task == null || !task.isWorking()) {
return message("Canceled");
}
}
if (filledScript.contains("#{" + name + "-" + message("Median") + "}")) {
if (column.getStatistic() == null || DoubleTools.invalidDouble(column.getStatistic().median)) {
return null;
}
filledScript = findReplace.replace(task, filledScript, "#{" + name + "-" + message("Median") + "}",
column.getStatistic().median + "");
if (task == null || !task.isWorking()) {
return message("Canceled");
}
}
if (filledScript.contains("#{" + name + "-" + message("Mode") + "}")) {
if (column.getStatistic() == null || column.getStatistic().modeValue == null) {
return null;
}
filledScript = findReplace.replace(task, filledScript, "#{" + name + "-" + message("Mode") + "}",
column.getStatistic().modeValue.toString());
if (task == null || !task.isWorking()) {
return message("Canceled");
}
}
if (filledScript.contains("#{" + name + "-" + message("MinimumQ0") + "}")) {
if (column.getStatistic() == null || DoubleTools.invalidDouble(column.getStatistic().minimum)) {
return null;
}
filledScript = findReplace.replace(task, filledScript, "#{" + name + "-" + message("MinimumQ0") + "}",
column.getStatistic().minimum + "");
if (task == null || !task.isWorking()) {
return message("Canceled");
}
}
if (filledScript.contains("#{" + name + "-" + message("LowerQuartile") + "}")) {
if (column.getStatistic() == null || DoubleTools.invalidDouble(column.getStatistic().lowerQuartile)) {
return null;
}
filledScript = findReplace.replace(task, filledScript, "#{" + name + "-" + message("LowerQuartile") + "}",
column.getStatistic().lowerQuartile + "");
if (task == null || !task.isWorking()) {
return message("Canceled");
}
}
if (filledScript.contains("#{" + name + "-" + message("UpperQuartile") + "}")) {
if (column.getStatistic() == null || DoubleTools.invalidDouble(column.getStatistic().upperQuartile)) {
return null;
}
filledScript = findReplace.replace(task, filledScript, "#{" + name + "-" + message("UpperQuartile") + "}",
column.getStatistic().upperQuartile + "");
if (task == null || !task.isWorking()) {
return message("Canceled");
}
}
if (filledScript.contains("#{" + name + "-" + message("MaximumQ4") + "}")) {
if (column.getStatistic() == null || DoubleTools.invalidDouble(column.getStatistic().maximum)) {
return null;
}
filledScript = findReplace.replace(task, filledScript, "#{" + name + "-" + message("MaximumQ4") + "}",
column.getStatistic().maximum + "");
if (task == null || !task.isWorking()) {
return message("Canceled");
}
}
if (filledScript.contains("#{" + name + "-" + message("LowerExtremeOutlierLine") + "}")) {
if (column.getStatistic() == null || DoubleTools.invalidDouble(column.getStatistic().lowerExtremeOutlierLine)) {
return null;
}
filledScript = findReplace.replace(task, filledScript, "#{" + name + "-" + message("LowerExtremeOutlierLine") + "}",
column.getStatistic().lowerExtremeOutlierLine + "");
if (task == null || !task.isWorking()) {
return message("Canceled");
}
}
if (filledScript.contains("#{" + name + "-" + message("LowerMildOutlierLine") + "}")) {
if (column.getStatistic() == null || DoubleTools.invalidDouble(column.getStatistic().lowerMildOutlierLine)) {
return null;
}
filledScript = findReplace.replace(task, filledScript, "#{" + name + "-" + message("LowerMildOutlierLine") + "}",
column.getStatistic().lowerMildOutlierLine + "");
if (task == null || !task.isWorking()) {
return message("Canceled");
}
}
if (filledScript.contains("#{" + name + "-" + message("UpperMildOutlierLine") + "}")) {
if (column.getStatistic() == null || DoubleTools.invalidDouble(column.getStatistic().upperMildOutlierLine)) {
return null;
}
filledScript = findReplace.replace(task, filledScript, "#{" + name + "-" + message("UpperMildOutlierLine") + "}",
column.getStatistic().upperMildOutlierLine + "");
if (task == null || !task.isWorking()) {
return message("Canceled");
}
}
if (filledScript.contains("#{" + name + "-" + message("UpperExtremeOutlierLine") + "}")) {
if (column.getStatistic() == null || DoubleTools.invalidDouble(column.getStatistic().upperExtremeOutlierLine)) {
return null;
}
filledScript = findReplace.replace(task, filledScript, "#{" + name + "-" + message("UpperExtremeOutlierLine") + "}",
column.getStatistic().upperExtremeOutlierLine + "");
if (task == null || !task.isWorking()) {
return message("Canceled");
}
}
}
return filledScript;
} catch (Exception e) {
MyBoxLog.error(e);
if (task != null) {
task.setError(e.toString());
}
return null;
}
}
public String cellStyle(DataFilter styleFilter, int tableRowIndex, String colName) {
try {
if (styleFilter == null || styles == null || styles.isEmpty() || colName == null || colName.isBlank()) {
return null;
}
List<String> tableRow = pageRow(tableRowIndex, false);
if (tableRow == null || tableRow.size() < 1) {
return null;
}
int colIndex = colOrder(colName);
if (colIndex < 0) {
return null;
}
String cellStyle = null;
long dataRowIndex;
try {
dataRowIndex = Long.parseLong(tableRow.get(0)) - 1;
} catch (Exception e) {
dataRowIndex = -1;
}
for (Data2DStyle style : styles) {
String names = style.getColumns();
if (names != null && !names.isBlank()) {
String[] cols = names.split(Data2DStyle.ColumnSeparator);
if (cols != null && cols.length > 0) {
if (!(Arrays.asList(cols).contains(colName))) {
continue;
}
}
}
long rowStart = style.getRowStart();
if (rowStart >= 0) {
if (dataRowIndex <= 0 || dataRowIndex < rowStart) {
continue;
}
long rowEnd = style.getRowEnd();
if (rowEnd >= 0 && dataRowIndex >= rowEnd) {
continue;
}
}
styleFilter.setSourceScript(style.getFilter()).setMatchFalse(style.isMatchFalse());
if (!styleFilter.filterTableRow((Data2D) this, tableRow, tableRowIndex)) {
continue;
}
String styleValue = style.finalStyle();
if (styleValue == null || styleValue.isBlank()) {
cellStyle = null;
} else if (cellStyle == null) {
cellStyle = style.finalStyle();
} else {
if (!cellStyle.trim().endsWith(";")) {
cellStyle += ";";
}
cellStyle += style.finalStyle();
}
}
return cellStyle;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public List<String> namesInScript(String script) {
if (script == null || script.isEmpty()) {
return null;
}
List<String> names = new ArrayList<>();
for (String name : columnNames()) {
if (script.contains("#{" + name + "}")
|| script.contains("#{" + name + "}-" + message("Mean"))
|| script.contains("#{" + name + "}-" + message("Median"))
|| script.contains("#{" + name + "}-" + message("Mode"))
|| script.contains("#{" + name + "}-" + message("MinimumQ0"))
|| script.contains("#{" + name + "}-" + message("LowerQuartile"))
|| script.contains("#{" + name + "}-" + message("UpperQuartile"))
|| script.contains("#{" + name + "}-" + message("MaximumQ4"))
|| script.contains("#{" + name + "}-" + message("LowerExtremeOutlierLine"))
|| script.contains("#{" + name + "}-" + message("LowerMildOutlierLine"))
|| script.contains("#{" + name + "}-" + message("UpperMildOutlierLine"))
|| script.contains("#{" + name + "}-" + message("UpperExtremeOutlierLine"))) {
names.add(name);
}
}
return names;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/Data2D.java | alpha/MyBox/src/main/java/mara/mybox/data2d/Data2D.java | package mara.mybox.data2d;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import mara.mybox.data.StringTable;
import mara.mybox.data2d.tools.Data2DDefinitionTools;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.DateTools;
import mara.mybox.tools.FileDeleteTools;
import mara.mybox.tools.FileTools;
import mara.mybox.tools.StringTools;
import mara.mybox.tools.TextTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2021-10-18
* @License Apache License Version 2.0
*/
public abstract class Data2D extends Data2D_Operations {
@Override
public Data2D cloneTo() {
try {
Data2D newData = (Data2D) super.clone();
newData.cloneAttributesFrom(this);
return newData;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
@Override
public String info() {
return Data2DDefinitionTools.dataInfo(this);
}
public String pageInfo() {
StringTable infoTable = new StringTable();
List<String> row = new ArrayList<>();
row.addAll(Arrays.asList(message("Type"), getTypeName()));
infoTable.add(row);
if (file != null) {
row = new ArrayList<>();
row.addAll(Arrays.asList(message("File"), file.getAbsolutePath()));
infoTable.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList(message("FileSize"), FileTools.showFileSize(file.length()) + ""));
infoTable.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList(message("FileModifyTime"), DateTools.datetimeToString(file.lastModified())));
infoTable.add(row);
if (isExcel()) {
DataFileExcel e = (DataFileExcel) this;
row = new ArrayList<>();
row.addAll(Arrays.asList(message("CurrentSheet"), (sheet == null ? "" : sheet)
+ (e.getSheetNames() == null ? "" : " / " + e.getSheetNames().size())));
infoTable.add(row);
} else {
row = new ArrayList<>();
row.addAll(Arrays.asList(message("Charset"), charset != null ? charset.name() : message("Unknown")));
infoTable.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList(message("Delimiter"), TextTools.delimiterMessage(delimiter)));
infoTable.add(row);
}
row = new ArrayList<>();
row.addAll(Arrays.asList(message("FirstLineAsNames"), (hasHeader ? message("Yes") : message("No"))));
infoTable.add(row);
}
int tableRowsNumber = tableRowsNumber();
if (isMutiplePages()) {
row = new ArrayList<>();
row.addAll(Arrays.asList(message("RowsNumberInFile"), pagination.rowsNumber + ""));
infoTable.add(row);
} else {
row = new ArrayList<>();
row.addAll(Arrays.asList(message("RowsNumber"), tableRowsNumber + ""));
infoTable.add(row);
}
row = new ArrayList<>();
row.addAll(Arrays.asList(message("ColumnsNumber"), columnsNumber() + ""));
infoTable.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList(message("CurrentPage"),
StringTools.format(pagination.currentPage + 1)
+ " / " + StringTools.format(pagination.pagesNumber)));
infoTable.add(row);
if (isMutiplePages()) {
row = new ArrayList<>();
row.addAll(Arrays.asList(message("RowsRangeInPage"),
StringTools.format(pagination.startRowOfCurrentPage + 1) + " - "
+ StringTools.format(pagination.startRowOfCurrentPage + tableRowsNumber)
+ " ( " + StringTools.format(tableRowsNumber) + " )"));
infoTable.add(row);
}
row = new ArrayList<>();
row.addAll(Arrays.asList(message("PageModifyTime"), DateTools.nowString()));
infoTable.add(row);
return infoTable.div();
}
public String dataInfo() {
return pageInfo() + "<BR>" + Data2DDefinitionTools.toHtml(this);
}
/*
static
*/
public static Data2D create(DataType type) {
if (type == null) {
return null;
}
Data2D data;
switch (type) {
case CSV:
data = new DataFileCSV();
break;
case Excel:
data = new DataFileExcel();
break;
case Texts:
data = new DataFileText();
break;
case Matrix:
data = new DataMatrix();
break;
case MyBoxClipboard:
data = new DataClipboard();
break;
case DatabaseTable:
data = new DataTable();
break;
case InternalTable:
data = new DataInternalTable();
break;
default:
return null;
}
data.setType(type);
return data;
}
public int drop() {
if (!FileDeleteTools.delete(file)) {
return -1;
}
return tableData2DDefinition.deleteData(this);
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/DataClipboard.java | alpha/MyBox/src/main/java/mara/mybox/data2d/DataClipboard.java | package mara.mybox.data2d;
import java.io.File;
import java.nio.charset.Charset;
import java.util.List;
import mara.mybox.controller.DataInMyBoxClipboardController;
import mara.mybox.data2d.writer.Data2DWriter;
import mara.mybox.data2d.writer.DataFileCSVWriter;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.tools.DateTools;
import mara.mybox.tools.FileTools;
import mara.mybox.value.AppPaths;
/**
* @Author Mara
* @CreateDate 2021-8-25
* @License Apache License Version 2.0
*/
public class DataClipboard extends DataFileCSV {
public DataClipboard() {
dataType = DataType.MyBoxClipboard;
}
public int type() {
return type(DataType.MyBoxClipboard);
}
@Override
public boolean checkForSave() {
if (dataName == null || dataName.isBlank()) {
dataName = pagination.rowsNumber + "x" + colsNumber;
}
return true;
}
@Override
public Data2DWriter selfWriter() {
DataFileCSVWriter writer = new DataFileCSVWriter();
initSelfWriter(writer);
writer.setCharset(charset)
.setDelimiter(delimiter)
.setTargetData(this)
.setRecordTargetFile(false);
return writer;
}
public static File newFile() {
return new File(AppPaths.getDataClipboardPath() + File.separator + DateTools.nowFileString() + ".csv");
}
public static DataClipboard create(FxTask task, String clipName,
List<Data2DColumn> cols, List<List<String>> data) {
if (cols == null || data == null || data.isEmpty()) {
return null;
}
DataFileCSV csvData = DataFileCSV.save(task, null, clipName, ",", cols, data);
if (csvData == null) {
return null;
}
File dFile = newFile();
if (FileTools.override(csvData.getFile(), dFile, true)) {
return create(task, csvData, clipName, dFile);
} else {
MyBoxLog.error("Failed");
return null;
}
}
public static DataClipboard create(FxTask task, Data2D sourceData,
String clipName, File dFile) {
if (dFile == null || sourceData == null) {
return null;
}
try {
DataClipboard d = new DataClipboard();
d.setTask(task);
d.setFile(dFile);
d.setCharset(Charset.forName("UTF-8"));
d.setDelimiter(",");
List<Data2DColumn> cols = sourceData.getColumns();
long rowsNumber = sourceData.getRowsNumber();
long colsNumber = sourceData.getColsNumber();
d.setHasHeader(cols != null && !cols.isEmpty());
if (rowsNumber > 0 && colsNumber > 0) {
d.setColsNumber(colsNumber);
d.setRowsNumber(rowsNumber);
}
String srcName = sourceData.getName();
if (clipName != null && !clipName.isBlank()) {
d.setDataName(clipName);
} else if (srcName != null && !srcName.isBlank()) {
d.setDataName(srcName);
} else if (rowsNumber > 0 && colsNumber > 0) {
d.setDataName(rowsNumber + "x" + colsNumber);
} else {
d.setDataName(dFile.getName());
}
d.setComments(sourceData.getComments());
if (Data2D.saveAttributes(d, cols)) {
DataInMyBoxClipboardController.update();
return d;
} else {
return null;
}
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
MyBoxLog.error(e);
return null;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/Data2D_Operations.java | alpha/MyBox/src/main/java/mara/mybox/data2d/Data2D_Operations.java | package mara.mybox.data2d;
import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.calculation.DescriptiveStatistic;
import mara.mybox.calculation.DescriptiveStatistic.StatisticType;
import mara.mybox.calculation.DoubleStatistic;
import mara.mybox.calculation.Normalization;
import mara.mybox.calculation.SimpleLinearRegression;
import mara.mybox.data2d.operate.Data2DCopy;
import mara.mybox.data2d.operate.Data2DExport;
import mara.mybox.data2d.operate.Data2DFrequency;
import mara.mybox.data2d.operate.Data2DNormalize;
import mara.mybox.data2d.operate.Data2DOperate;
import mara.mybox.data2d.operate.Data2DPrecentage;
import mara.mybox.data2d.operate.Data2DRange;
import mara.mybox.data2d.operate.Data2DReadColumns;
import mara.mybox.data2d.operate.Data2DReadRows;
import mara.mybox.data2d.operate.Data2DRowExpression;
import mara.mybox.data2d.operate.Data2DSimpleLinearRegression;
import mara.mybox.data2d.operate.Data2DSplit;
import mara.mybox.data2d.operate.Data2DStatistic;
import mara.mybox.data2d.tools.Data2DColumnTools;
import mara.mybox.data2d.writer.Data2DWriter;
import mara.mybox.data2d.writer.DataFileCSVWriter;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.ColumnDefinition.InvalidAs;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.tools.CsvTools;
import mara.mybox.tools.DoubleTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.NumberTools;
import mara.mybox.value.AppValues;
import static mara.mybox.value.Languages.message;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.math3.stat.Frequency;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public abstract class Data2D_Operations extends Data2D_Edit {
public static enum ObjectType {
Columns, Rows, All
}
public boolean export(Data2DExport export, List<Integer> cols) {
if (export == null || cols == null || cols.isEmpty()) {
return false;
}
export.setCols(cols).setTask(task).start();
return !export.isFailed();
}
public List<List<String>> allRows(List<Integer> cols, boolean rowNumber) {
Data2DReadColumns reader = Data2DReadColumns.create(this);
reader.setIncludeRowNumber(rowNumber)
.setCols(cols).setTask(task).start();
return reader.isFailed() ? null : reader.getRows();
}
public List<List<String>> allRows(boolean rowNumber) {
Data2DReadRows operate = Data2DReadRows.create(this);
operate.setIncludeRowNumber(rowNumber)
.setWriteHeader(false)
.setTask(task).start();
return operate.isFailed() ? null : operate.getRows();
}
public DoubleStatistic[] statisticByColumnsForCurrentPage(List<Integer> cols, DescriptiveStatistic selections) {
try {
if (cols == null || cols.isEmpty() || selections == null) {
return null;
}
int colLen = cols.size();
DoubleStatistic[] sData = new DoubleStatistic[colLen];
int rNumber = pageData.size();
for (int c = 0; c < colLen; c++) {
int colIndex = cols.get(c);
String[] colData = new String[rNumber];
for (int r = 0; r < rNumber; r++) {
colData[r] = pageData.get(r).get(colIndex + 1);
}
DoubleStatistic colStatistic = new DoubleStatistic();
colStatistic.invalidAs = selections.invalidAs;
colStatistic.calculate(colData, selections);
columns.get(colIndex).setStatistic(colStatistic);
sData[c] = colStatistic;
}
return sData;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return null;
}
}
// No percentile nor mode
public DoubleStatistic[] statisticByColumnsWithoutStored(List<Integer> cols, DescriptiveStatistic selections) {
try {
if (cols == null || cols.isEmpty() || selections == null) {
return null;
}
int colLen = cols.size();
DoubleStatistic[] sData = new DoubleStatistic[colLen];
for (int c = 0; c < colLen; c++) {
Data2DColumn column = columns.get(cols.get(c));
DoubleStatistic colStatistic = column.getStatistic();
if (colStatistic == null) {
colStatistic = new DoubleStatistic();
column.setStatistic(colStatistic);
}
colStatistic.invalidAs = selections.invalidAs;
colStatistic.options = selections;
sData[c] = colStatistic;
}
Data2DOperate reader = Data2DStatistic.create(this)
.setStatisticData(sData)
.setStatisticCalculation(selections)
.setType(Data2DStatistic.Type.ColumnsPass1)
.setCols(cols).setTask(task).start();
if (reader == null || reader.isFailed()) {
return null;
}
if (selections.needVariance()) {
reader = Data2DStatistic.create(this)
.setStatisticData(sData)
.setStatisticCalculation(selections)
.setType(Data2DStatistic.Type.ColumnsPass2)
.setCols(cols).setTask(task).start();
if (reader == null || reader.isFailed()) {
return null;
}
}
return sData;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return null;
}
}
// percentile or mode
public DoubleStatistic[] statisticByColumnsForStored(List<Integer> cols, DescriptiveStatistic selections) {
try {
if (cols == null || cols.isEmpty() || selections == null) {
return null;
}
TmpTable tmpTable = TmpTable.toStatisticTable((Data2D) this, task, cols, selections.invalidAs);
if (tmpTable == null) {
return null;
}
List<Integer> tmpColIndices = tmpTable.columnIndices().subList(1, tmpTable.columnsNumber());
DoubleStatistic[] statisticData = tmpTable.statisticByColumnsForStored(tmpColIndices, selections);
if (statisticData == null) {
return null;
}
for (int i = 0; i < cols.size(); i++) {
Data2DColumn column = column(cols.get(i));
column.setStatistic(statisticData[i]);
}
tmpTable.drop();
return statisticData;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return null;
}
}
public boolean statisticByRows(FxTask task, Data2DWriter writer,
List<String> names, List<Integer> cols, DescriptiveStatistic selections) {
if (writer == null || names == null || names.isEmpty() || cols == null || cols.isEmpty()) {
return false;
}
try {
writer.setColumns(Data2DColumnTools.toColumns(names))
.setHeaderNames(names);
Data2DOperate operate = Data2DStatistic.create(this)
.setStatisticCalculation(selections)
.setType(Data2DStatistic.Type.Rows)
.addWriter(writer)
.setCols(cols).setTask(task).start();
return !operate.isFailed() && writer.isCompleted();
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
}
// No percentile nor mode
public DoubleStatistic statisticByAllWithoutStored(List<Integer> cols, DescriptiveStatistic selections) {
if (cols == null || cols.isEmpty()) {
return null;
}
DoubleStatistic sData = new DoubleStatistic();
sData.invalidAs = selections.invalidAs;
Data2DOperate reader = Data2DStatistic.create(this)
.setStatisticAll(sData)
.setStatisticCalculation(selections)
.setType(Data2DStatistic.Type.AllPass1)
.setCols(cols).setTask(task).start();
if (reader == null || reader.isFailed()) {
return null;
}
if (selections.needVariance()) {
reader = Data2DStatistic.create(this)
.setStatisticAll(sData)
.setStatisticCalculation(selections)
.setType(Data2DStatistic.Type.AllPass2)
.setCols(cols).setTask(task).start();
if (reader == null || reader.isFailed()) {
return null;
}
}
return sData;
}
public List<Data2DColumn> targetColumns(List<Integer> cols, boolean rowNumber) {
return targetColumns(cols, null, rowNumber, null);
}
public List<Data2DColumn> targetColumns(List<Integer> cols, List<Integer> otherCols, boolean rowNumber, String suffix) {
List<Data2DColumn> targetColumns = new ArrayList<>();
if (rowNumber) {
targetColumns.add(0, new Data2DColumn(message("SourceRowNumber"), ColumnDefinition.ColumnType.Long));
}
for (int c : cols) {
Data2DColumn column = columns.get(c).copy();
if (suffix != null) {
column.setColumnName(column.getColumnName() + "_" + suffix).setWidth(200);
}
targetColumns.add(column);
}
if (otherCols != null && !otherCols.isEmpty()) {
for (int c : otherCols) {
Data2DColumn column = columns.get(c).copy();
targetColumns.add(column);
}
}
return fixColumnNames(targetColumns);
}
public DataFileCSV copyTmp(FxTask task, List<Integer> cols,
boolean includeRowNumber, boolean includeColName, boolean formatValues) {
if (cols == null || cols.isEmpty()) {
return null;
}
try {
DataFileCSVWriter writer = new DataFileCSVWriter();
List<Data2DColumn> targetColumns = targetColumns(cols, includeRowNumber);
writer.setPrintFile(FileTmpTools.getTempFile(".csv"))
.setColumns(targetColumns)
.setHeaderNames(Data2DColumnTools.toNames(targetColumns))
.setWriteHeader(includeColName)
.setFormatValues(formatValues);
if (copy(task, writer, cols, includeRowNumber, InvalidAs.Empty) < 0) {
return null;
}
return (DataFileCSV) writer.getTargetData();
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return null;
}
}
public long copy(FxTask task, Data2DWriter writer, List<Integer> cols,
boolean includeRowNumber, InvalidAs invalidAs) {
try {
if (writer == null || cols == null || cols.isEmpty()) {
return -1;
}
Data2DOperate operate = Data2DCopy.create(this)
.setIncludeRowNumber(includeRowNumber)
.setCols(cols)
.setInvalidAs(invalidAs)
.addWriter(writer)
.setTask(task).start();
if (operate.isFailed() || !writer.isCompleted()) {
return -2;
}
return operate.getHandledCount();
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return -3;
}
}
public List<DataFileCSV> splitBySize(List<Integer> cols, boolean includeRowNumber, int splitSize) {
if (cols == null || cols.isEmpty()) {
return null;
}
Data2DSplit reader = Data2DSplit.create(this).setSplitSize(splitSize);
reader.setIncludeRowNumber(includeRowNumber)
.setCols(cols).setTask(task).start();
return reader.getFiles();
}
public List<DataFileCSV> splitByList(List<Integer> cols, boolean includeRowNumber, List<Integer> list) {
if (cols == null || cols.isEmpty() || list == null || list.isEmpty()) {
return null;
}
try {
String prefix = getName();
List<Data2DColumn> targetColumns = targetColumns(cols, null, includeRowNumber, null);
List<String> names = new ArrayList<>();
if (includeRowNumber) {
targetColumns.add(0, new Data2DColumn(message("SourceRowNumber"), ColumnDefinition.ColumnType.Long));
}
for (int c : cols) {
Data2DColumn column = column(c);
names.add(column.getColumnName());
targetColumns.add(column.copy());
}
List<DataFileCSV> files = new ArrayList<>();
for (int i = 0; i < list.size();) {
long start = Math.round(list.get(i++));
long end = Math.round(list.get(i++));
if (start <= 0) {
start = 1;
}
if (end > pagination.rowsNumber) {
end = pagination.rowsNumber;
}
if (start > end) {
continue;
}
File csvfile = tmpFile(prefix + "_" + start + "-" + end, null, "csv");
try (CSVPrinter csvPrinter = CsvTools.csvPrinter(csvfile)) {
csvPrinter.printRecord(names);
Data2DRange reader = Data2DRange.create(this).setStart(start).setEnd(end);
reader.setIncludeRowNumber(includeRowNumber)
// .setCsvPrinter(csvPrinter)
.setCols(cols).setTask(task).start();
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return null;
}
DataFileCSV dataFileCSV = new DataFileCSV();
dataFileCSV.setTask(task);
dataFileCSV.setColumns(targetColumns)
.setFile(csvfile)
.setCharset(Charset.forName("UTF-8"))
.setDelimiter(",")
.setHasHeader(true)
.setColsNumber(targetColumns.size())
.setRowsNumber(end - start + 1);
dataFileCSV.saveAttributes();
dataFileCSV.stopTask();
files.add(dataFileCSV);
}
return files;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return null;
}
}
public boolean rowExpression(FxTask task, Data2DWriter writer,
String script, String name,
List<Integer> cols, boolean includeRowNumber, boolean includeColName) {
try {
if (writer == null || cols == null || cols.isEmpty()) {
return false;
}
List<Data2DColumn> targetColumns = targetColumns(cols, null, includeRowNumber, null);
targetColumns.add(new Data2DColumn(name, ColumnDefinition.ColumnType.String));
writer.setColumns(targetColumns)
.setHeaderNames(Data2DColumnTools.toNames(targetColumns))
.setWriteHeader(includeColName);
Data2DOperate operate = Data2DRowExpression.create(this)
.setScript(script).setName(name)
.addWriter(writer)
.setIncludeRowNumber(includeRowNumber)
.setCols(cols).setTask(task).start();
return !operate.isFailed() && writer.isCompleted();
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
}
public List<Data2DColumn> makePercentageColumns(List<Integer> cols, List<Integer> otherCols, ObjectType objectType) {
if (objectType == null) {
objectType = ObjectType.Columns;
}
List<Data2DColumn> targetColumns;
switch (objectType) {
case Rows:
targetColumns = targetColumns(cols, otherCols, true, message("PercentageInRow"));
targetColumns.add(1, new Data2DColumn(message("Row") + "-" + message("Summation"),
ColumnDefinition.ColumnType.Double, 200));
break;
case All:
targetColumns = targetColumns(cols, otherCols, true, message("PercentageInAll"));
break;
default:
targetColumns = targetColumns(cols, otherCols, true, message("PercentageInColumn"));
}
targetColumns.get(0).setType(ColumnDefinition.ColumnType.String);
for (int i = 0; i < cols.size(); i++) {
targetColumns.get(i + 1).setType(ColumnDefinition.ColumnType.Double);
}
return fixColumnNames(targetColumns);
}
public boolean percentageColumns(FxTask task, Data2DWriter writer,
List<Integer> cols, List<Integer> otherCols,
int scale, String toNegative, InvalidAs invalidAs) {
try {
if (writer == null || cols == null || cols.isEmpty()) {
return false;
}
Data2DPrecentage operate = Data2DPrecentage.create(this)
.setType(Data2DPrecentage.Type.ColumnsPass1)
.setToNegative(toNegative);
operate.setInvalidAs(invalidAs).setScale(scale)
.setCols(cols).setTask(task).start();
if (operate.isFailed()) {
return false;
}
double[] colsSum = operate.getColValues();
List<String> row = new ArrayList<>();
row.add(message("Column") + "-" + message("Summation"));
for (int c = 0; c < cols.size(); c++) {
row.add(DoubleTools.scale(colsSum[c], scale) + "");
}
if (otherCols != null) {
for (int c : otherCols) {
row.add(null);
}
}
List<Data2DColumn> targetColumns = makePercentageColumns(cols, otherCols, ObjectType.Columns);
writer.setColumns(targetColumns)
.setHeaderNames(Data2DColumnTools.toNames(targetColumns));
operate = Data2DPrecentage.create(this)
.setType(Data2DPrecentage.Type.ColumnsPass2)
.setToNegative(toNegative)
.setColValues(colsSum)
.setFirstRow(row);
operate.setInvalidAs(invalidAs).setScale(scale)
.addWriter(writer)
.setCols(cols).setOtherCols(otherCols).setTask(task).start();
return !operate.isFailed() && writer.isCompleted();
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
}
public boolean percentageAll(FxTask task, Data2DWriter writer,
List<Integer> cols, List<Integer> otherCols,
int scale, String toNegative, InvalidAs invalidAs) {
try {
if (writer == null || cols == null || cols.isEmpty()) {
return false;
}
Data2DPrecentage operate = Data2DPrecentage.create(this)
.setType(Data2DPrecentage.Type.AllPass1)
.setToNegative(toNegative);
operate.setInvalidAs(invalidAs).setScale(scale)
.setCols(cols).setTask(task).start();
if (operate.isFailed()) {
return false;
}
List<Data2DColumn> targetColumns = makePercentageColumns(cols, otherCols, ObjectType.All);
writer.setColumns(targetColumns)
.setHeaderNames(Data2DColumnTools.toNames(targetColumns));
List<String> row = new ArrayList<>();
row.add(message("All") + "-" + message("Summation"));
double sum = operate.gettValue();
row.add(NumberTools.format(sum, scale));
for (int c : cols) {
row.add(null);
}
if (otherCols != null) {
for (int c : otherCols) {
row.add(null);
}
}
operate = Data2DPrecentage.create(this)
.setType(Data2DPrecentage.Type.AllPass2)
.setToNegative(toNegative).settValue(sum)
.setFirstRow(row);
operate.setInvalidAs(invalidAs).setScale(scale)
.addWriter(writer)
.setCols(cols).setOtherCols(otherCols).setTask(task).start();
return !operate.isFailed() && writer.isCompleted();
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
}
public boolean percentageRows(FxTask task, Data2DWriter writer,
List<Integer> cols, List<Integer> otherCols,
int scale, String toNegative, InvalidAs invalidAs) {
try {
if (writer == null || cols == null || cols.isEmpty()) {
return false;
}
List<Data2DColumn> targetColumns = makePercentageColumns(cols, otherCols, ObjectType.Rows);
writer.setColumns(targetColumns)
.setHeaderNames(Data2DColumnTools.toNames(targetColumns));
Data2DOperate operate = Data2DPrecentage.create(this)
.setType(Data2DPrecentage.Type.Rows)
.setToNegative(toNegative);
operate.setInvalidAs(invalidAs).setScale(scale)
.addWriter(writer)
.setCols(cols).setOtherCols(otherCols).setTask(task).start();
return !operate.isFailed() && writer.isCompleted();
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
}
public boolean frequency(FxTask task, Data2DWriter writer,
Frequency frequency, List<Data2DColumn> outputColumns,
int col, int scale) {
try {
if (writer == null || frequency == null || outputColumns == null || col < 0) {
return false;
}
writer.setColumns(outputColumns)
.setHeaderNames(Data2DColumnTools.toNames(outputColumns));
Data2DOperate operate = Data2DFrequency.create(this)
.setFrequency(frequency).setColIndex(col)
.addWriter(writer)
.setScale(scale)
.setTask(task).start();
return !operate.isFailed() && writer.isCompleted();
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
}
public boolean normalizeMinMaxColumns(FxTask task, Data2DWriter writer,
List<Integer> cols, List<Integer> otherCols,
double from, double to, boolean rowNumber, boolean colName, int scale, InvalidAs invalidAs) {
try {
if (writer == null || cols == null || cols.isEmpty()) {
return false;
}
int colLen = cols.size();
DoubleStatistic[] sData = new DoubleStatistic[colLen];
for (int c = 0; c < colLen; c++) {
sData[c] = new DoubleStatistic();
sData[c].invalidAs = invalidAs;
}
DescriptiveStatistic selections = DescriptiveStatistic.all(false)
.add(StatisticType.Sum)
.add(StatisticType.MaximumQ4)
.add(StatisticType.MinimumQ0);
Data2DOperate operate = Data2DStatistic.create(this)
.setStatisticData(sData)
.setStatisticCalculation(selections)
.setType(Data2DStatistic.Type.ColumnsPass1)
.setInvalidAs(invalidAs)
.setCols(cols).setScale(scale).setTask(task).start();
if (operate == null || operate.isFailed()) {
return false;
}
for (int c = 0; c < colLen; c++) {
double d = sData[c].maximum - sData[c].minimum;
sData[c].dTmp = (to - from) / (d == 0 ? AppValues.TinyDouble : d);
}
List<Data2DColumn> targetColumns = targetColumns(cols, otherCols, rowNumber, message("Normalize"));
writer.setColumns(targetColumns)
.setHeaderNames(Data2DColumnTools.toNames(targetColumns))
.setWriteHeader(colName);
operate = Data2DNormalize.create(this)
.setType(Data2DNormalize.Type.MinMaxColumns)
.setStatisticData(sData).setFrom(from)
.addWriter(writer)
.setInvalidAs(invalidAs).setIncludeRowNumber(rowNumber)
.setCols(cols).setOtherCols(otherCols)
.setScale(scale).setTask(task).start();
return !operate.isFailed() && writer.isCompleted();
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
}
public boolean normalizeSumColumns(FxTask task, Data2DWriter writer,
List<Integer> cols, List<Integer> otherCols,
boolean rowNumber, boolean colName, int scale, InvalidAs invalidAs) {
try {
if (writer == null || cols == null || cols.isEmpty()) {
return false;
}
int colLen = cols.size();
DoubleStatistic[] sData = new DoubleStatistic[colLen];
for (int c = 0; c < colLen; c++) {
sData[c] = new DoubleStatistic();
sData[c].invalidAs = invalidAs;
}
DescriptiveStatistic selections = DescriptiveStatistic.all(false);
Data2DOperate operate = Data2DStatistic.create(this)
.setType(Data2DStatistic.Type.ColumnsPass1)
.setStatisticData(sData)
.setStatisticCalculation(selections)
.setSumAbs(true).setInvalidAs(invalidAs)
.setCols(cols).setScale(scale).setTask(task).start();
if (operate == null) {
return false;
}
double[] colValues = new double[colLen];
for (int c = 0; c < colLen; c++) {
if (sData[c].sum == 0) {
colValues[c] = 1d / AppValues.TinyDouble;
} else {
colValues[c] = 1d / sData[c].sum;
}
}
List<Data2DColumn> targetColumns = targetColumns(cols, otherCols, rowNumber, message("Normalize"));
writer.setColumns(targetColumns)
.setHeaderNames(Data2DColumnTools.toNames(targetColumns))
.setWriteHeader(colName);
operate = Data2DNormalize.create(this)
.setType(Data2DNormalize.Type.SumColumns)
.setColValues(colValues)
.addWriter(writer)
.setInvalidAs(invalidAs).setIncludeRowNumber(rowNumber)
.setCols(cols).setOtherCols(otherCols)
.setScale(scale).setTask(task).start();
return !operate.isFailed() && writer.isCompleted();
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
}
public boolean normalizeZscoreColumns(FxTask task, Data2DWriter writer,
List<Integer> cols, List<Integer> otherCols,
boolean rowNumber, boolean colName, int scale, InvalidAs invalidAs) {
try {
if (writer == null || cols == null || cols.isEmpty()) {
return false;
}
int colLen = cols.size();
DoubleStatistic[] sData = new DoubleStatistic[colLen];
for (int c = 0; c < colLen; c++) {
sData[c] = new DoubleStatistic();
sData[c].invalidAs = invalidAs;
}
DescriptiveStatistic selections = DescriptiveStatistic.all(false)
.add(StatisticType.PopulationStandardDeviation);
Data2DOperate operate = Data2DStatistic.create(this)
.setStatisticData(sData)
.setStatisticCalculation(selections)
.setType(Data2DStatistic.Type.ColumnsPass1)
.setInvalidAs(invalidAs)
.setCols(cols).setScale(scale).setTask(task).start();
if (operate == null) {
return false;
}
operate = Data2DStatistic.create(this)
.setStatisticData(sData)
.setStatisticCalculation(selections)
.setType(Data2DStatistic.Type.ColumnsPass2)
.setCols(cols).setScale(scale).setTask(task).start();
if (operate == null) {
return false;
}
List<Data2DColumn> targetColumns = targetColumns(cols, otherCols, rowNumber, message("Normalize"));
writer.setColumns(targetColumns)
.setHeaderNames(Data2DColumnTools.toNames(targetColumns))
.setWriteHeader(colName);
operate = Data2DNormalize.create(this)
.setType(Data2DNormalize.Type.ZscoreColumns)
.setStatisticData(sData)
.addWriter(writer)
.setInvalidAs(invalidAs).setIncludeRowNumber(rowNumber)
.setCols(cols).setOtherCols(otherCols)
.setScale(scale).setTask(task).start();
return !operate.isFailed() && writer.isCompleted();
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
}
public boolean normalizeMinMaxAll(FxTask task, Data2DWriter writer,
List<Integer> cols, List<Integer> otherCols,
double from, double to, boolean rowNumber, boolean colName, int scale, InvalidAs invalidAs) {
try {
if (writer == null || cols == null || cols.isEmpty()) {
return false;
}
DoubleStatistic sData = new DoubleStatistic();
sData.invalidAs = invalidAs;
DescriptiveStatistic selections = DescriptiveStatistic.all(false)
.add(StatisticType.Sum)
.add(StatisticType.MaximumQ4)
.add(StatisticType.MinimumQ0);
Data2DOperate operate = Data2DStatistic.create(this)
.setStatisticAll(sData)
.setStatisticCalculation(selections)
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | true |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/DataMatrix.java | alpha/MyBox/src/main/java/mara/mybox/data2d/DataMatrix.java | package mara.mybox.data2d;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.Random;
import mara.mybox.data2d.writer.Data2DWriter;
import mara.mybox.data2d.writer.DataMatrixWriter;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.ColumnDefinition.ColumnType;
import mara.mybox.db.table.TableData2DDefinition;
import mara.mybox.tools.DoubleTools;
import mara.mybox.tools.FileNameTools;
import mara.mybox.tools.FloatTools;
import mara.mybox.tools.IntTools;
import mara.mybox.tools.LongTools;
import mara.mybox.tools.NumberTools;
import mara.mybox.tools.StringTools;
import mara.mybox.tools.TextFileTools;
import mara.mybox.value.AppPaths;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2021-10-18
* @License Apache License Version 2.0
*/
public class DataMatrix extends DataFileText {
public static final String MatrixDelimiter = "|";
public DataMatrix() {
dataType = DataType.Matrix;
sheet = "Double";
delimiter = MatrixDelimiter;
charset = Charset.forName("UTF-8");
hasHeader = false;
}
public DataMatrix(String type) {
sheet = type;
}
// public AbstractRealMatrix realMatrix(Connection conn) {
// int rows = (int) pagination.rowsNumber;
// int cols = (int) colsNumber;
// if (cols > blockMatrixThreshold) {
// return new BlockRealMatrix(rows, cols);
// } else if (tableMatrixCell.size(conn) < rows * cols * sparseMatrixThreshold) {
// return new OpenMapRealMatrix(rows, cols);
// } else {
// return new Array2DRowRealMatrix(rows, cols);
// }
// }
@Override
public String guessDelimiter() {
return MatrixDelimiter;
}
@Override
public boolean checkForLoad() {
if (charset == null && file != null) {
charset = TextFileTools.charset(file);
}
if (charset == null) {
charset = Charset.forName("UTF-8");
}
delimiter = MatrixDelimiter;
hasHeader = false;
return true;
}
@Override
public boolean checkForSave() {
if (dataName == null || dataName.isBlank()) {
dataName = message("Matrix") + " "
+ pagination.rowsNumber + "x" + colsNumber;
}
return true;
}
@Override
public boolean defaultColNotNull() {
return true;
}
@Override
public String defaultColValue() {
return "0";
}
@Override
public ColumnDefinition.ColumnType defaultColumnType() {
if (sheet == null) {
sheet = "Double";
}
switch (sheet.toLowerCase()) {
case "float":
return ColumnType.Float;
case "integer":
return ColumnType.Integer;
case "long":
return ColumnType.Long;
case "short":
return ColumnType.Short;
case "numberboolean":
return ColumnType.NumberBoolean;
case "double":
default:
return ColumnType.Double;
}
}
@Override
public String randomString(Random random, boolean nonNegative) {
if (sheet == null) {
sheet = "Double";
}
switch (sheet.toLowerCase()) {
case "float":
return NumberTools.format(FloatTools.random(random, maxRandom, nonNegative), scale);
case "integer":
return StringTools.format(IntTools.random(random, maxRandom, nonNegative));
case "long":
return StringTools.format(LongTools.random(random, maxRandom, nonNegative));
case "short":
return StringTools.format((short) IntTools.random(random, maxRandom, nonNegative));
case "numberboolean":
return random.nextInt(2) + "";
case "double":
default:
return NumberTools.format(DoubleTools.random(random, maxRandom, nonNegative), scale);
}
}
@Override
public String getTypeName() {
if (sheet == null) {
sheet = "Double";
}
switch (sheet.toLowerCase()) {
case "float":
return message("FloatMatrix");
case "integer":
return message("IntegerMatrix");
case "long":
return message("LongMatrix");
case "short":
return message("ShortMatrix");
case "numberboolean":
return message("BooleanMatrix");
case "double":
default:
return message("DoubleMatrix");
}
}
@Override
public Data2DWriter selfWriter() {
DataMatrixWriter writer = new DataMatrixWriter();
initSelfWriter(writer);
writer.setDataType(sheet)
.setCharset(Charset.forName("utf-8"))
.setDelimiter(DataMatrix.MatrixDelimiter)
.setWriteHeader(false)
.setTargetData(this);
return writer;
}
public String toString(double d) {
if (DoubleTools.invalidDouble(d)) {
return Double.NaN + "";
} else {
return NumberTools.format(d, scale);
}
}
/*
static
*/
public static double toDouble(String d) {
try {
return Double.parseDouble(d.replaceAll(",", ""));
} catch (Exception e) {
return 0;
}
}
public static File file(String dataname) {
try {
return new File(AppPaths.getMatrixPath() + File.separator
+ FileNameTools.filter(dataname + "_" + new Date().getTime())
+ ".txt");
} catch (Exception e) {
return null;
}
}
public static DataMatrix makeMatrix(String type, int colsNumber, int rowsNumber, short scale, int max) {
try {
String dataName = type + "_" + colsNumber + "x" + rowsNumber;
File file = file(dataName);
DataMatrix matrix = new DataMatrix();
matrix.setFile(file).setSheet(type)
.setDataName(dataName)
.setScale(scale).setMaxRandom(max)
.setColsNumber(colsNumber)
.setRowsNumber(rowsNumber);
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, matrix.getCharset(), false))) {
String line;
Random random = new Random();
for (int i = 0; i < rowsNumber; i++) {
line = matrix.randomString(random, false);
for (int j = 1; j < colsNumber; j++) {
line += DataMatrix.MatrixDelimiter + matrix.randomString(random, false);
}
writer.write(line + "\n");
}
writer.flush();
} catch (Exception ex) {
}
new TableData2DDefinition().updateData(matrix);
return matrix;
} catch (Exception e) {
return null;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/DataTable.java | alpha/MyBox/src/main/java/mara/mybox/data2d/DataTable.java | package mara.mybox.data2d;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import mara.mybox.calculation.DescriptiveStatistic;
import mara.mybox.calculation.DescriptiveStatistic.StatisticType;
import mara.mybox.calculation.DoubleStatistic;
import mara.mybox.data2d.writer.Data2DWriter;
import mara.mybox.data2d.writer.DataTableWriter;
import mara.mybox.db.DerbyBase;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.ColumnDefinition.InvalidAs;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.db.data.Data2DDefinition;
import mara.mybox.db.data.Data2DRow;
import mara.mybox.db.table.BaseTableTools;
import mara.mybox.db.table.TableData2D;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.fxml.image.FxColorTools;
import mara.mybox.tools.DoubleTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2021-10-18
* @License Apache License Version 2.0
*/
public class DataTable extends Data2D {
protected TableData2D tableData2D;
public DataTable() {
dataType = DataType.DatabaseTable;
tableData2D = new TableData2D();
}
public int type() {
return type(DataType.DatabaseTable);
}
public void cloneAll(DataTable d) {
try {
if (d == null) {
return;
}
super.cloneAttributesFrom(d);
tableData2D = d.tableData2D;
if (tableData2D == null) {
tableData2D = new TableData2D();
}
tableData2D.setTableName(sheet);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
@Override
public void resetData() {
super.resetData();
tableData2D.reset();
}
public boolean readDefinitionFromDB(Connection conn, String tname) {
try {
if (conn == null || tname == null) {
return false;
}
resetData();
sheet = DerbyBase.fixedIdentifier(tname);
tableData2D.setTableName(sheet);
tableData2D.readDefinitionFromDB(conn, sheet);
List<ColumnDefinition> dbColumns = tableData2D.getColumns();
List<Data2DColumn> dataColumns = new ArrayList<>();
if (dbColumns != null) {
for (ColumnDefinition dbColumn : dbColumns) {
Data2DColumn dataColumn = new Data2DColumn();
dataColumn.cloneFrom(dbColumn);
dataColumns.add(dataColumn);
}
}
return recordTable(conn, sheet, dataColumns, comments);
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
}
public boolean recordTable(Connection conn, String tableName,
List<Data2DColumn> dataColumns, String comments) {
try {
sheet = DerbyBase.fixedIdentifier(tableName);
dataName = sheet;
colsNumber = dataColumns.size();
this.comments = comments;
if (BaseTableTools.isInternalTable(dataName)) {
dataType = DataType.InternalTable;
}
tableData2DDefinition.writeTable(conn, this);
conn.commit();
for (Data2DColumn column : dataColumns) {
column.setDataID(dataID);
column.setColumnName(DerbyBase.fixedIdentifier(column.getColumnName()));
}
columns = dataColumns;
tableData2DColumn.save(conn, dataID, dataColumns);
conn.commit();
return true;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
MyBoxLog.error(e);
return false;
}
}
@Override
public boolean checkForLoad() {
if (dataName == null) {
dataName = sheet;
}
if (tableData2D == null) {
tableData2D = new TableData2D();
}
tableData2D.setTableName(sheet);
return super.checkForLoad();
}
@Override
public Data2DDefinition queryDefinition(Connection conn) {
return tableData2DDefinition.queryTable(conn, sheet, dataType);
}
@Override
public boolean loadColumns(Connection conn) {
try {
columns = null;
if (conn == null || dataID < 0 || sheet == null) {
return false;
}
tableData2D.readDefinitionFromDB(conn, sheet);
List<ColumnDefinition> dbColumns = tableData2D.getColumns();
if (dbColumns == null) {
return false;
}
columns = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < dbColumns.size(); i++) {
ColumnDefinition dbColumn = dbColumns.get(i);
dbColumn.setIndex(i).setBaseID(-1);
if (savedColumns != null) {
for (Data2DColumn savedColumn : savedColumns) {
if (dbColumn.getColumnName().equalsIgnoreCase(savedColumn.getColumnName())) {
dbColumn.setLabel(savedColumn.getLabel());
dbColumn.setBaseID(savedColumn.getColumnID());
dbColumn.setIndex(savedColumn.getIndex());
dbColumn.setType(savedColumn.getType());
dbColumn.setFormat(savedColumn.getFormat());
dbColumn.setScale(savedColumn.getScale());
dbColumn.setColor(savedColumn.getColor());
dbColumn.setWidth(savedColumn.getWidth());
dbColumn.setEditable(savedColumn.isEditable());
if (dbColumn.getDefaultValue() == null) {
dbColumn.setDefaultValue(savedColumn.getDefaultValue());
}
dbColumn.setDescription(savedColumn.getDescription());
break;
}
}
}
if (dbColumn.getColor() == null) {
dbColumn.setColor(FxColorTools.randomColor(random));
}
if (dbColumn.isAuto()) {
dbColumn.setEditable(false);
}
}
Collections.sort(dbColumns, new Comparator<ColumnDefinition>() {
@Override
public int compare(ColumnDefinition v1, ColumnDefinition v2) {
int diff = v1.getIndex() - v2.getIndex();
if (diff == 0) {
return 0;
} else if (diff > 0) {
return 1;
} else {
return -1;
}
}
});
for (int i = 0; i < dbColumns.size(); i++) {
ColumnDefinition column = dbColumns.get(i);
column.setIndex(i);
}
for (ColumnDefinition dbColumn : dbColumns) {
Data2DColumn column = new Data2DColumn();
column.cloneFrom(dbColumn);
column.setDataID(dataID).setColumnID(dbColumn.getBaseID());
columns.add(column);
}
colsNumber = columns.size();
tableData2DColumn.save(conn, dataID, columns);
tableData2DDefinition.updateData(conn, this);
return true;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
}
@Override
public List<String> readColumnNames() {
return null;
}
@Override
public Data2DColumn columnByName(String name) {
try {
if (name == null || name.isBlank()) {
return null;
}
for (Data2DColumn c : columns) {
if (name.equalsIgnoreCase(c.getColumnName())) {
return c;
}
}
} catch (Exception e) {
}
return null;
}
public Data2DRow fromTableRow(List<String> values, InvalidAs invalidAs) {
try {
if (columns == null || values == null || values.isEmpty()) {
return null;
}
Data2DRow data2DRow = tableData2D.newRow();
try {
data2DRow.setRowIndex(Integer.parseInt(values.get(0)));
} catch (Exception e) {
data2DRow.setRowIndex(-1);
}
for (int i = 0; i < Math.min(columns.size(), values.size() - 1); i++) {
Data2DColumn column = columns.get(i);
String name = column.getColumnName();
data2DRow.setValue(name, column.fromString(values.get(i + 1), invalidAs));
}
return data2DRow;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public String pageQuery() {
String sql = "SELECT * FROM " + sheet;
String orderby = null;
for (ColumnDefinition column : tableData2D.getPrimaryColumns()) {
if (orderby != null) {
orderby += "," + column.getColumnName();
} else {
orderby = column.getColumnName();
}
}
if (orderby != null && !orderby.isBlank()) {
sql += " ORDER BY " + orderby;
}
sql += " OFFSET " + pagination.startRowOfCurrentPage + " ROWS FETCH NEXT "
+ pagination.pageSize + " ROWS ONLY";
return sql;
}
@Override
public long savePageData(FxTask task) {
try (Connection conn = DerbyBase.getConnection()) {
return savePageData(task, conn);
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return -1;
}
}
public long savePageData(FxTask task, Connection conn) {
try {
List<Data2DRow> dbRows = tableData2D.query(conn, pageQuery());
List<Data2DRow> pageRows = new ArrayList<>();
conn.setAutoCommit(false);
if (pageData != null) {
for (int i = 0; i < pageData.size(); i++) {
Data2DRow row = fromTableRow(pageData.get(i), InvalidAs.Empty);
if (row != null) {
pageRows.add(row);
tableData2D.writeData(conn, row);
}
}
}
if (dbRows != null) {
for (Data2DRow drow : dbRows) {
boolean exist = false;
for (Data2DRow prow : pageRows) {
if (tableData2D.sameRow(drow, prow)) {
exist = true;
break;
}
}
if (!exist) {
tableData2D.deleteData(conn, drow);
}
}
}
conn.commit();
pagination.rowsNumber = tableData2D.size(conn);
saveAttributes(conn);
return pagination.rowsNumber;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return -1;
}
}
@Override
public long saveAttributes(FxTask task, Data2D attributes) {
if (attributes == null) {
return -1;
}
try (Connection conn = DerbyBase.getConnection()) {
if (savePageData(task, conn) < 0) {
return -1;
}
List<String> currentNames = columnNames();
List<String> newNames = new ArrayList<>();
for (Data2DColumn column : attributes.columns) {
String name = column.getColumnName();
newNames.add(name);
if (currentNames.contains(name) && column.getIndex() < 0) {
tableData2D.dropColumn(conn, name);
conn.commit();
currentNames.remove(name);
}
}
for (String name : currentNames) {
if (!newNames.contains(name)) {
tableData2D.dropColumn(conn, name);
conn.commit();
}
}
for (Data2DColumn column : attributes.columns) {
String name = column.getColumnName();
if (!currentNames.contains(name)) {
tableData2D.addColumn(conn, column);
conn.commit();
}
}
attributes.pagination.rowsNumber = pagination.rowsNumber;
attributes.tableChanged = false;
attributes.pagination.currentPage = pagination.currentPage;
cloneAttributesFrom(attributes);
return pagination.rowsNumber;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return -1;
}
}
@Override
public Data2DWriter selfWriter() {
DataTableWriter writer = new DataTableWriter();
initSelfWriter(writer);
writer.setTargetTable(this)
.setTargetData(this)
.setRecordTargetFile(false);
return writer;
}
public Data2DRow makeRow(List<String> values, DataTableWriter writer) {
try {
if (columns == null || values == null || values.isEmpty()) {
return null;
}
List<Data2DColumn> vColumns = new ArrayList<>();
for (Data2DColumn c : columns) {
if (!c.isAuto()) {
vColumns.add(c);
}
}
Data2DRow data2DRow = tableData2D.newRow();
int rowSize = values.size();
for (int i = 0; i < values.size(); i++) {
Data2DColumn column = vColumns.get(i);
String name = column.getColumnName();
String value = i < rowSize ? values.get(i) : null;
if ((writer.validateValue || writer.invalidAs == InvalidAs.Fail)
&& !column.validValue(value)) {
writer.failStop(message("InvalidData") + ". "
+ message("Column") + ":" + column.getColumnName() + " "
+ message("Value") + ": " + value);
return null;
}
data2DRow.setValue(name, column.fromString(value, writer.invalidAs));
}
return data2DRow;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
@Override
public int drop() {
if (sheet == null || sheet.isBlank()) {
return -4;
}
try (Connection conn = DerbyBase.getConnection();) {
return drop(conn, sheet);
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return -5;
}
}
public int drop(Connection conn) {
return drop(conn, sheet);
}
public int drop(Connection conn, String name) {
if (name == null || name.isBlank()) {
return -4;
}
return tableData2DDefinition.deleteUserTable(conn, name);
}
public Object mode(Connection conn, String colName) {
if (colName == null || colName.isBlank()) {
return null;
}
Object mode = null;
String sql = "SELECT " + colName + ", count(*) AS mybox99_mode FROM " + sheet
+ " GROUP BY " + colName + " ORDER BY mybox99_mode DESC FETCH FIRST ROW ONLY";
if (task != null) {
task.setInfo(sql);
}
try (PreparedStatement statement = conn.prepareStatement(sql);
ResultSet results = statement.executeQuery()) {
if (results.next()) {
mode = results.getObject(DerbyBase.savedName(colName));
}
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
return mode;
}
// https://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math4/stat/descriptive/rank/Percentile.html
public Object percentile(Connection conn, Data2DColumn column, int p) {
if (column == null || p <= 0 || p > 100) {
return null;
}
Object percentile = null;
int n = tableData2D.size(conn);
if (n == 0) {
return null;
}
int offset, num;
double d = 0;
if (n == 1) {
offset = 0;
num = 1;
} else {
double pos = p * (n + 1) / 100d;
if (pos < 1) {
offset = 0;
num = 1;
} else if (pos >= n) {
offset = n - 1;
num = 1;
} else {
offset = (int) Math.floor(pos);
d = pos - offset;
num = 2;
}
}
String colName = column.getColumnName();
String sql = "SELECT " + colName + " FROM " + sheet + " ORDER BY " + colName
+ " OFFSET " + offset + " ROWS FETCH NEXT " + num + " ROWS ONLY";
if (task != null) {
task.setInfo(sql);
}
try (PreparedStatement statement = conn.prepareStatement(sql);
ResultSet results = statement.executeQuery()) {
Object first = null;
if (results.next()) {
first = column.value(results);
}
if (num == 1) {
percentile = first;
} else if (num == 2) {
if (results.next()) {
Object second = column.value(results);;
try {
double lower = Double.parseDouble(first + "");
double upper = Double.parseDouble(second + "");
percentile = lower + d * (upper - lower);
} catch (Exception e) {
percentile = first;
}
} else {
percentile = first;
}
}
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
return percentile;
}
@Override
public DoubleStatistic[] statisticByColumnsForStored(List<Integer> cols, DescriptiveStatistic selections) {
if (cols == null || cols.isEmpty() || selections == null) {
return null;
}
try (Connection conn = DerbyBase.getConnection()) {
int colLen = cols.size();
DoubleStatistic[] sData = new DoubleStatistic[colLen];
for (int c = 0; c < cols.size(); c++) {
Data2DColumn column = columns.get(cols.get(c));
DoubleStatistic colStatistic = column.getStatistic();
if (colStatistic == null) {
colStatistic = new DoubleStatistic();
column.setStatistic(colStatistic);
}
colStatistic.invalidAs = selections.invalidAs;
colStatistic.options = selections;
sData[c] = colStatistic;
if (selections.include(StatisticType.Median)) {
colStatistic.medianValue = percentile(conn, column, 50);
try {
colStatistic.median = Double.parseDouble(colStatistic.medianValue + "");
} catch (Exception ex) {
colStatistic.median = DoubleTools.value(colStatistic.invalidAs);
}
}
Object q1 = null, q3 = null;
if (selections.include(StatisticType.UpperQuartile) || selections.needOutlier()) {
q3 = percentile(conn, column, 75);
colStatistic.upperQuartileValue = q3;
try {
colStatistic.upperQuartile = Double.parseDouble(q3 + "");
} catch (Exception ex) {
colStatistic.upperQuartile = DoubleTools.value(colStatistic.invalidAs);
}
}
if (selections.include(StatisticType.LowerQuartile) || selections.needOutlier()) {
q1 = percentile(conn, column, 25);
colStatistic.lowerQuartileValue = q1;
try {
colStatistic.lowerQuartile = Double.parseDouble(q1 + "");
} catch (Exception ex) {
colStatistic.lowerQuartile = DoubleTools.value(colStatistic.invalidAs);
}
}
if (selections.include(StatisticType.UpperExtremeOutlierLine)) {
try {
double d1 = Double.parseDouble(q1 + "");
double d3 = Double.parseDouble(q3 + "");
colStatistic.upperExtremeOutlierLine = d3 + 3 * (d3 - d1);
} catch (Exception e) {
colStatistic.upperExtremeOutlierLine = DoubleTools.value(colStatistic.invalidAs);
}
}
if (selections.include(StatisticType.UpperMildOutlierLine)) {
try {
double d1 = Double.parseDouble(q1 + "");
double d3 = Double.parseDouble(q3 + "");
colStatistic.upperMildOutlierLine = d3 + 1.5 * (d3 - d1);
} catch (Exception e) {
colStatistic.upperMildOutlierLine = DoubleTools.value(colStatistic.invalidAs);
}
}
if (selections.include(StatisticType.LowerMildOutlierLine)) {
try {
double d1 = Double.parseDouble(q1 + "");
double d3 = Double.parseDouble(q3 + "");
colStatistic.lowerMildOutlierLine = d1 - 1.5 * (d3 - d1);
} catch (Exception e) {
colStatistic.lowerMildOutlierLine = DoubleTools.value(colStatistic.invalidAs);
}
}
if (selections.include(StatisticType.LowerExtremeOutlierLine)) {
try {
double d1 = Double.parseDouble(q1 + "");
double d3 = Double.parseDouble(q3 + "");
colStatistic.lowerExtremeOutlierLine = d1 - 3 * (d3 - d1);
} catch (Exception e) {
colStatistic.lowerExtremeOutlierLine = DoubleTools.value(colStatistic.invalidAs);
}
}
if (selections.include(StatisticType.Mode)) {
colStatistic.modeValue = mode(conn, column.getColumnName());
try {
colStatistic.mode = Double.parseDouble(colStatistic.modeValue + "");
} catch (Exception ex) {
colStatistic.mode = DoubleTools.value(colStatistic.invalidAs);
}
}
}
return sData;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
return null;
}
}
/*
get/set
*/
public TableData2D getTableData2D() {
return tableData2D;
}
public void setTableData2D(TableData2D tableData2D) {
this.tableData2D = tableData2D;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/Data2D_Attributes.java | alpha/MyBox/src/main/java/mara/mybox/data2d/Data2D_Attributes.java | package mara.mybox.data2d;
import java.util.List;
import javafx.collections.ObservableList;
import mara.mybox.controller.BaseController;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.db.data.Data2DDefinition;
import mara.mybox.db.data.Data2DStyle;
import mara.mybox.db.table.TableData2DColumn;
import mara.mybox.db.table.TableData2DDefinition;
import mara.mybox.db.table.TableData2DStyle;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
/**
* @Author Marai
* @CreateDate 2021-10-18
* @License Apache License Version 2.0
*/
public abstract class Data2D_Attributes extends Data2DDefinition {
public BaseController controller;
public TableData2DDefinition tableData2DDefinition;
public TableData2DColumn tableData2DColumn;
public TableData2DStyle tableData2DStyle;
public List<Data2DColumn> columns, savedColumns;
public int newColumnIndex;
public List<Data2DStyle> styles;
public DataFilter filter;
public ObservableList<List<String>> pageData;
public boolean tableChanged, dataLoaded;
public FxTask task, backgroundTask;
public String error;
public enum TargetType {
CSV, Excel, Text, Matrix, DatabaseTable, SystemClipboard, MyBoxClipboard,
JSON, XML, HTML, PDF, Replace, Insert, Append
}
public Data2D_Attributes() {
tableData2DDefinition = new TableData2DDefinition();
tableData2DColumn = new TableData2DColumn();
tableData2DStyle = new TableData2DStyle();
styles = null;
initData();
}
private void initData() {
resetDefinition();
columns = null;
savedColumns = null;
newColumnIndex = -1;
dataLoaded = true;
tableChanged = false;
styles = null;
filter = null;
error = null;
pageData = null;
task = null;
backgroundTask = null;
}
public void resetData() {
initData();
}
public void cloneAttributesFrom(Data2D_Attributes d) {
try {
dataID = d.getDataID();
dataType = d.getType();
copyAttributesFrom(d);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void copyAttributesFrom(Data2D_Attributes d) {
try {
super.copyAllAttributes(d);
copyTaskAttributes(d);
copyPageAttributes(d);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void copyTaskAttributes(Data2D_Attributes d) {
try {
if (d == null) {
return;
}
task = d.task;
backgroundTask = d.backgroundTask;
error = d.error;
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void copyPageAttributes(Data2D_Attributes d) {
try {
if (d == null) {
return;
}
copyDataAttributes(d);
pageData = d.pageData;
tableData2DDefinition = d.tableData2DDefinition;
tableData2DColumn = d.tableData2DColumn;
columns = d.columns;
savedColumns = d.savedColumns;
newColumnIndex = d.newColumnIndex;
styles = d.styles;
pagination.copyFrom(d.pagination);
tableChanged = d.tableChanged;
dataLoaded = d.dataLoaded;
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
/*
get/set
*/
public BaseController getController() {
return controller;
}
public Data2D setController(BaseController controller) {
this.controller = controller;
return (Data2D) this;
}
public TableData2DDefinition getTableData2DDefinition() {
return tableData2DDefinition;
}
public void setTableData2DDefinition(TableData2DDefinition tableData2DDefinition) {
this.tableData2DDefinition = tableData2DDefinition;
}
public TableData2DColumn getTableData2DColumn() {
return tableData2DColumn;
}
public void setTableData2DColumn(TableData2DColumn tableData2DColumn) {
this.tableData2DColumn = tableData2DColumn;
}
public TableData2DStyle getTableData2DStyle() {
return tableData2DStyle;
}
public void setTableData2DStyle(TableData2DStyle tableData2DStyle) {
this.tableData2DStyle = tableData2DStyle;
}
public List<Data2DColumn> getColumns() {
return columns;
}
public Data2D_Attributes setColumns(List<Data2DColumn> columns) {
this.columns = columns;
return this;
}
@Override
public long getColsNumber() {
colsNumber = columns != null ? columns.size() : -1;
return colsNumber;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public boolean isTableChanged() {
return tableChanged;
}
public void setTableChanged(boolean tableChanged) {
this.tableChanged = tableChanged;
}
public ObservableList<List<String>> getPageData() {
return pageData;
}
public List<Data2DColumn> getSavedColumns() {
return savedColumns;
}
public void setSavedColumns(List<Data2DColumn> savedColumns) {
this.savedColumns = savedColumns;
}
public List<Data2DStyle> getStyles() {
return styles;
}
public DataFilter getFilter() {
return filter;
}
public void setFilter(DataFilter filter) {
this.filter = filter;
}
public Data2D_Attributes setStyles(List<Data2DStyle> styles) {
this.styles = styles;
return this;
}
public FxTask getTask() {
return task;
}
public Data2D_Attributes setTask(FxTask task) {
this.task = task;
return this;
}
public FxTask getBackgroundTask() {
return backgroundTask;
}
public void setBackgroundTask(FxTask backgroundTask) {
this.backgroundTask = backgroundTask;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/DataFilter.java | alpha/MyBox/src/main/java/mara/mybox/data2d/DataFilter.java | package mara.mybox.data2d;
import java.util.List;
import mara.mybox.calculation.ExpressionCalculator;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-7-7
* @License Apache License Version 2.0
*/
public class DataFilter {
private String sourceScript, filledScript;
public long passedNumber, maxPassed;
public boolean matchFalse, passed;
public FxTask task;
public ExpressionCalculator calculator;
public DataFilter() {
init();
}
public DataFilter(String script, boolean matchFalse) {
init();
sourceScript = script;
filledScript = script;
this.matchFalse = matchFalse;
}
private void init() {
maxPassed = -1;
matchFalse = false;
resetNumber();
calculator = new ExpressionCalculator();
}
public void resetNumber() {
passedNumber = 0;
passed = false;
}
public void start(FxTask task, Data2D data2D) {
resetNumber();
this.task = task;
calculator.reset();
}
public void stop() {
resetNumber();
task = null;
calculator.reset();
}
public static DataFilter create() {
return new DataFilter();
}
public boolean scriptEmpty() {
return sourceScript == null || sourceScript.isBlank();
}
public boolean needFilter() {
return !scriptEmpty() || maxPassed > 0;
}
public boolean reachMaxPassed() {
return maxPassed > 0 && passedNumber > maxPassed;
}
public boolean readResult(boolean calculateSuccess) {
passed = false;
if (calculateSuccess) {
if (matchFalse) {
passed = "false".equals(calculator.getResult());
} else {
passed = "true".equals(calculator.getResult());
}
}
if (passed) {
passedNumber++;
}
handleError(calculator.getError());
return passed;
}
public boolean filterTableRow(Data2D data2D, List<String> tableRow, long tableRowIndex) {
if (tableRow == null) {
passed = false;
return false;
}
if (sourceScript == null || sourceScript.isBlank()) {
passed = true;
passedNumber++;
return true;
}
return readResult(calculator.calculateTableRowExpression(data2D, filledScript, tableRow, tableRowIndex));
}
public boolean filterDataRow(Data2D data2D, List<String> dataRow, long dataRowIndex) {
try {
handleError(null);
if (dataRow == null || data2D == null) {
passed = false;
return false;
}
if (sourceScript == null || sourceScript.isBlank()) {
passed = true;
passedNumber++;
return true;
}
return readResult(calculator.calculateDataRowExpression(data2D, filledScript, dataRow, dataRowIndex));
} catch (Exception e) {
passed = false;
MyBoxLog.error(e);
return false;
}
}
public String getError() {
return calculator.getError();
}
public String getResult() {
return calculator.getResult();
}
public void handleError(String error) {
// if (error != null && AppValues.Alpha) {
// if (task != null) {
// task.setError(error);
// }
// MyBoxLog.debug(error + "\n" + sourceScript);
// }
}
public void clear() {
sourceScript = null;
filledScript = null;
maxPassed = -1;
matchFalse = false;
passedNumber = 0;
passed = false;
task = null;
calculator.reset();
}
@Override
public String toString() {
String string = sourceScript == null ? "" : sourceScript;
if (matchFalse) {
string += "\n" + message("MatchFalse");
}
if (maxPassed > 0) {
string += "\n" + message("MaximumNumber") + ": " + maxPassed;
}
return string;
}
/*
get/set
*/
public FxTask getTask() {
return task;
}
public DataFilter setTask(FxTask task) {
this.task = task;
return this;
}
public String getSourceScript() {
return sourceScript;
}
public DataFilter setSourceScript(String sourceScript) {
this.sourceScript = sourceScript;
this.filledScript = sourceScript;
return this;
}
public String getFilledScript() {
return filledScript;
}
public DataFilter setFilledScript(String filledScript) {
this.filledScript = filledScript;
return this;
}
public long getPassedNumber() {
return passedNumber;
}
public DataFilter setPassedNumber(long passedNumber) {
this.passedNumber = passedNumber;
return this;
}
public long getMaxPassed() {
return maxPassed;
}
public DataFilter setMaxPassed(long maxPassed) {
this.maxPassed = maxPassed;
return this;
}
public boolean isMatchFalse() {
return matchFalse;
}
public DataFilter setMatchFalse(boolean matchFalse) {
this.matchFalse = matchFalse;
return this;
}
public boolean isPassed() {
return passed;
}
public DataFilter setPassed(boolean passed) {
this.passed = passed;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/DataFileCSV.java | alpha/MyBox/src/main/java/mara/mybox/data2d/DataFileCSV.java | package mara.mybox.data2d;
import java.io.File;
import java.io.FileWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import mara.mybox.data.StringTable;
import mara.mybox.data2d.writer.Data2DWriter;
import mara.mybox.data2d.writer.DataFileCSVWriter;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.tools.CsvTools;
import mara.mybox.tools.FileNameTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.TextTools;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
/**
* @Author Mara
* @CreateDate 2021-10-17
* @License Apache License Version 2.0
*/
public class DataFileCSV extends DataFileText {
public DataFileCSV() {
dataType = DataType.CSV;
}
@Override
public String[] delimters() {
String[] delimiters = {",", " ", "|", "@", ";", ":", "*",
"%", "$", "_", "&", "-", "=", "!", "\"", "'", "<", ">", "#"};
return delimiters;
}
public CSVFormat cvsFormat() {
if (delimiter == null || delimiter.isEmpty()) {
delimiter = ",";
}
return CsvTools.csvFormat(delimiter, hasHeader);
}
@Override
public Data2DWriter selfWriter() {
DataFileCSVWriter writer = new DataFileCSVWriter();
initSelfWriter(writer);
writer.setCharset(charset)
.setDelimiter(delimiter)
.setTargetData(this);
return writer;
}
/*
static
*/
public static DataFileCSV tmpCSV(String dname) {
try {
DataFileCSV dataFileCSV = new DataFileCSV();
File csvFile = dataFileCSV.tmpFile(dname, "tmp", "csv");
dataFileCSV.setFile(csvFile).setDataName(dname)
.setCharset(Charset.forName("UTF-8"))
.setDelimiter(",")
.setHasHeader(true);
return dataFileCSV;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static File csvFile(FxTask task, File tmpFile,
String delimeter, List<String> cols, List<List<String>> data) {
if (tmpFile == null) {
return null;
}
if (cols == null || cols.isEmpty()) {
if (data == null || data.isEmpty()) {
return null;
}
}
if (delimeter == null || delimeter.isEmpty()) {
delimeter = ",";
}
boolean hasHeader = cols != null && !cols.isEmpty();
try (CSVPrinter csvPrinter = CsvTools.csvPrinter(tmpFile, delimeter, hasHeader)) {
if (hasHeader) {
csvPrinter.printRecord(cols);
}
if (data != null) {
for (int r = 0; r < data.size(); r++) {
if (task != null && task.isCancelled()) {
csvPrinter.close();
return null;
}
csvPrinter.printRecord(data.get(r));
}
}
} catch (Exception e) {
MyBoxLog.console(e);
if (task != null) {
task.setError(e.toString());
}
return null;
}
return tmpFile;
}
public static DataFileCSV save(FxTask task, File dfile, String dname, String delimeter,
List<Data2DColumn> cols, List<List<String>> data) {
try {
if (cols == null || cols.isEmpty()) {
if (data == null || data.isEmpty()) {
return null;
}
}
List<Data2DColumn> targetColumns = new ArrayList<>();
List<String> names = null;
if (cols != null) {
names = new ArrayList<>();
for (Data2DColumn c : cols) {
names.add(c.getColumnName());
targetColumns.add(c.copy());
}
}
DataFileCSV dataFileCSV = new DataFileCSV();
dataFileCSV.setTask(task);
if (dfile == null) {
dfile = FileTmpTools.getTempFile(".csv");
}
dfile = csvFile(task, dfile, delimeter, names, data);
if (dfile == null) {
return null;
}
dataFileCSV.setColumns(targetColumns)
.setFile(dfile)
.setCharset(Charset.forName("UTF-8"))
.setDelimiter(delimeter)
.setHasHeader(!targetColumns.isEmpty())
.setColsNumber(targetColumns.size())
.setRowsNumber(data.size());
dataFileCSV.saveAttributes();
dataFileCSV.stopTask();
return dataFileCSV;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
MyBoxLog.error(e.toString());
return null;
}
}
public static LinkedHashMap<File, Boolean> save(FxTask task, File path,
String filePrefix, List<StringTable> tables) {
if (tables == null || tables.isEmpty()) {
return null;
}
try {
LinkedHashMap<File, Boolean> files = new LinkedHashMap<>();
String[][] data;
int count = 1;
CSVFormat csvFormat = CsvTools.csvFormat();
for (StringTable stringTable : tables) {
List<List<String>> tableData = stringTable.getData();
if (tableData == null || tableData.isEmpty()
|| (task != null && !task.isWorking())) {
continue;
}
data = TextTools.toArray(task, tableData);
if (data == null || data.length == 0) {
continue;
}
List<String> names = stringTable.getNames();
boolean withName = names != null && !names.isEmpty();
String title = stringTable.getTitle();
File csvFile = new File(path + File.separator
+ FileNameTools.filter((filePrefix == null || filePrefix.isBlank() ? "" : filePrefix + "_")
+ (title == null || title.isBlank() ? "_" + count : title))
+ ".csv");
try (CSVPrinter csvPrinter = new CSVPrinter(new FileWriter(csvFile, Charset.forName("UTF-8")), csvFormat)) {
if (withName) {
csvPrinter.printRecord(names);
}
for (int r = 0; r < data.length; r++) {
if (task != null && !task.isWorking()) {
csvPrinter.close();
return null;
}
csvPrinter.printRecord(Arrays.asList(data[r]));
}
} catch (Exception e) {
MyBoxLog.error(e);
}
if (csvFile.exists()) {
files.put(csvFile, withName);
count++;
}
}
return files;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/DataFileExcel.java | alpha/MyBox/src/main/java/mara/mybox/data2d/DataFileExcel.java | package mara.mybox.data2d;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.util.List;
import mara.mybox.data2d.operate.Data2DReadDefinition;
import mara.mybox.data2d.writer.Data2DWriter;
import mara.mybox.data2d.writer.DataFileExcelWriter;
import mara.mybox.db.data.Data2DDefinition;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.DateTools;
import mara.mybox.tools.FileCopyTools;
import mara.mybox.tools.FileDeleteTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.FileTools;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
/**
* @Author Mara
* @CreateDate 2021-10-17
* @License Apache License Version 2.0
*/
public class DataFileExcel extends DataFile {
public static final String CommentsMarker = "#";
protected List<String> sheetNames;
protected boolean currentSheetOnly;
public DataFileExcel() {
dataType = DataType.Excel;
}
public void cloneAll(DataFileExcel d) {
try {
if (d == null) {
return;
}
super.cloneAttributesFrom(d);
sheetNames = d.sheetNames;
currentSheetOnly = d.currentSheetOnly;
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
@Override
public void resetData() {
super.resetData();
sheetNames = null;
}
@Override
public Data2DDefinition queryDefinition(Connection conn) {
if (conn == null || dataType == null || file == null || sheet == null) {
return null;
}
return tableData2DDefinition.queryFileSheet(conn, dataType, file, sheet);
}
public void initFile(File file, String sheetName) {
super.initFile(file);
sheet = sheetName;
sheetNames = null;
}
@Override
public boolean checkForLoad() {
if (sheet == null) {
sheet = "sheet1";
}
return true;
}
@Override
public boolean checkForSave() {
if (sheet == null) {
sheet = "sheet1";
}
if (dataName == null || dataName.isBlank()) {
if (!isTmpData()) {
dataName = file.getName();
} else {
dataName = DateTools.nowString();
}
dataName += " - " + sheet;
}
return true;
}
@Override
public long loadDataDefinition(Connection conn) {
Data2DReadDefinition reader = Data2DReadDefinition.create(this);
if (reader == null) {
hasHeader = false;
return -2;
}
reader.setTask(task).start();
return super.loadDataDefinition(conn);
}
public boolean newSheet(String sheetName) {
if (file == null || !file.exists() || file.length() == 0) {
return false;
}
File tmpFile = FileTmpTools.getTempFile();
File tmpDataFile = FileTmpTools.getTempFile();
FileCopyTools.copyFile(file, tmpDataFile);
try (Workbook targetBook = WorkbookFactory.create(tmpDataFile)) {
Sheet targetSheet = targetBook.createSheet(sheetName);
List<List<String>> data = tmpData(3, 3);
for (int r = 0; r < data.size(); r++) {
if (task == null || task.isCancelled()) {
break;
}
List<String> values = data.get(r);
Row targetRow = targetSheet.createRow(r);
for (int col = 0; col < values.size(); col++) {
Cell targetCell = targetRow.createCell(col, CellType.STRING);
targetCell.setCellValue(values.get(col));
}
}
try (FileOutputStream fileOut = new FileOutputStream(tmpFile)) {
targetBook.write(fileOut);
}
} catch (Exception e) {
error = e.toString();
return false;
}
try {
FileDeleteTools.delete(tmpDataFile);
if (tmpFile == null || !tmpFile.exists()) {
return false;
}
if (FileTools.override(tmpFile, file)) {
initFile(file);
hasHeader = false;
sheet = sheetName;
tableData2DDefinition.insertData(this);
return true;
} else {
return false;
}
} catch (Exception e) {
error = e.toString();
return false;
}
}
public boolean renameSheet(String newName) {
if (file == null || !file.exists() || sheet == null) {
return false;
}
String oldName = sheet;
File tmpFile = FileTmpTools.getTempFile();
File tmpDataFile = FileTmpTools.getTempFile();
FileCopyTools.copyFile(file, tmpDataFile);
try (Workbook book = WorkbookFactory.create(tmpDataFile)) {
book.setSheetName(book.getSheetIndex(sheet), newName);
try (FileOutputStream fileOut = new FileOutputStream(tmpFile)) {
book.write(fileOut);
}
} catch (Exception e) {
error = e.toString();
return false;
}
try {
FileDeleteTools.delete(tmpDataFile);
if (tmpFile == null || !tmpFile.exists()) {
return false;
}
if (FileTools.override(tmpFile, file)) {
sheet = newName;
sheetNames.set(sheetNames.indexOf(oldName), sheet);
tableData2DDefinition.updateData(this);
return true;
} else {
return false;
}
} catch (Exception e) {
error = e.toString();
return false;
}
}
public int deleteSheet(String name) {
if (file == null || !file.exists()) {
return -1;
}
File tmpFile = FileTmpTools.getTempFile();
File tmpDataFile = FileTmpTools.getTempFile();
FileCopyTools.copyFile(file, tmpDataFile);
int index = -1;
try (Workbook targetBook = WorkbookFactory.create(tmpDataFile)) {
index = targetBook.getSheetIndex(name);
if (index >= 0) {
targetBook.removeSheetAt(index);
try (FileOutputStream fileOut = new FileOutputStream(tmpFile)) {
targetBook.write(fileOut);
}
}
} catch (Exception e) {
error = e.toString();
return -1;
}
try {
FileDeleteTools.delete(tmpDataFile);
if (tmpFile == null || !tmpFile.exists()) {
return -1;
}
if (index < 0) {
return -1;
}
if (FileTools.override(tmpFile, file)) {
return index;
} else {
return -1;
}
} catch (Exception e) {
error = e.toString();
return -1;
}
}
@Override
public Data2DWriter selfWriter() {
DataFileExcelWriter writer = new DataFileExcelWriter();
initSelfWriter(writer);
writer.setBaseFile(file)
.setSheetName(sheet)
.setTargetData(this);
return writer;
}
/*
get/set
*/
public List<String> getSheetNames() {
return sheetNames;
}
public void setSheetNames(List<String> sheetNames) {
this.sheetNames = sheetNames;
}
public boolean isCurrentSheetOnly() {
return currentSheetOnly;
}
public DataFileExcel setCurrentSheetOnly(boolean currentSheetOnly) {
this.currentSheetOnly = currentSheetOnly;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/TmpTable.java | alpha/MyBox/src/main/java/mara/mybox/data2d/TmpTable.java | package mara.mybox.data2d;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import mara.mybox.calculation.ExpressionCalculator;
import mara.mybox.data.DataSort;
import mara.mybox.data.FindReplaceString;
import mara.mybox.data2d.DataTableGroup.TimeType;
import mara.mybox.data2d.tools.Data2DColumnTools;
import mara.mybox.data2d.tools.Data2DTableTools;
import mara.mybox.data2d.writer.Data2DWriter;
import mara.mybox.data2d.writer.DataFileCSVWriter;
import mara.mybox.data2d.writer.DataTableWriter;
import mara.mybox.db.Database;
import mara.mybox.db.DerbyBase;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.ColumnDefinition.ColumnType;
import mara.mybox.db.data.ColumnDefinition.InvalidAs;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.db.data.Data2DRow;
import static mara.mybox.db.table.BaseTable.StringMaxLength;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.tools.DateTools;
import mara.mybox.tools.FileTmpTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-12-2
* @License Apache License Version 2.0
*/
public class TmpTable extends DataTable {
public static String TmpTablePrefix = "MYBOXTMP__";
public static String ExpressionColumnName = "MYBOX_GROUP_EXPRESSION__999";
protected Data2D sourceData;
protected List<Data2DColumn> sourceReferColumns;
protected List<Integer> sourcePickIndice, sourceReferIndice;
protected List<String> orders, groupEqualColumnNames;
protected int valueIndexOffset, timeIndex, expressionIndex;
protected String targetName, groupRangeColumnName, groupTimeColumnName,
groupExpression, tmpOrderby;
protected boolean importData, forStatistic, includeRowNumber, includeColName;
protected TimeType groupTimeType;
protected InvalidAs invalidAs;
protected List<List<String>> importRows;
protected Calendar calendar;
protected ExpressionCalculator expressionCalculator;
protected FindReplaceString findReplace;
public TmpTable() {
init();
}
public final void init() {
sourceData = null;
sourcePickIndice = null;
sourceReferColumns = null;
orders = null;
groupEqualColumnNames = null;
groupRangeColumnName = null;
groupTimeColumnName = null;
groupTimeType = null;
groupExpression = null;
timeIndex = -1;
expressionIndex = -1;
expressionCalculator = null;
importData = forStatistic = includeRowNumber = includeColName = false;
valueIndexOffset = -1;
invalidAs = InvalidAs.Skip;
targetName = null;
importRows = null;
tmpOrderby = "";
calendar = Calendar.getInstance();
}
public boolean createTable() {
try (Connection conn = DerbyBase.getConnection()) {
return createTable(conn);
} catch (Exception e) {
showError(task, e.toString());
return false;
}
}
public boolean createTable(Connection conn) {
try {
if (sourceData == null) {
showError(task, message("InvalidData"));
return false;
}
if (targetName == null) {
targetName = sourceData.getName();
}
List<Data2DColumn> sourceColumns = sourceData.getColumns();
if (sourceColumns == null || sourceColumns.isEmpty()) {
sourceData.loadColumns(conn);
}
if (sourceColumns == null || sourceColumns.isEmpty()) {
showError(task, message("InvalidData"));
return false;
}
valueIndexOffset = 1;
List<Data2DColumn> tmpColumns = new ArrayList<>();
if (includeRowNumber) {
tmpColumns.add(new Data2DColumn(message("SourceRowNumber"), ColumnType.Long));
valueIndexOffset++;
}
sourceReferIndice = new ArrayList<>();
sourceReferColumns = new ArrayList<>();
for (int i = 0; i < sourcePickIndice.size(); i++) {
int col = sourcePickIndice.get(i);
Data2DColumn sourceColumn = sourceColumns.get(col);
sourceReferColumns.add(sourceColumn);
sourceReferIndice.add(col);
Data2DColumn tableColumn = sourceColumn.copy();
tableColumn.setLength(StringMaxLength);
tableColumn.setType(forStatistic ? ColumnType.Double : ColumnType.String);
tmpColumns.add(tableColumn);
}
timeIndex = -1;
if (groupEqualColumnNames != null && !groupEqualColumnNames.isEmpty()) {
for (String name : groupEqualColumnNames) {
Data2DColumn sourceColumn = sourceData.columnByName(name);
sourceReferColumns.add(sourceColumn);
Data2DColumn tableColumn = sourceColumn.copy();
tmpColumns.add(tableColumn);
sourceReferIndice.add(sourceData.colOrder(name));
}
} else if (groupRangeColumnName != null && !groupRangeColumnName.isBlank()) {
Data2DColumn sourceColumn = sourceData.columnByName(groupRangeColumnName);
sourceReferColumns.add(sourceColumn);
Data2DColumn tableColumn = sourceColumn.copy();
tableColumn.setType(ColumnType.Double);
tmpColumns.add(tableColumn);
sourceReferIndice.add(sourceData.colOrder(groupRangeColumnName));
} else if (groupTimeColumnName != null && !groupTimeColumnName.isBlank()) {
Data2DColumn sourceColumn = sourceData.columnByName(groupTimeColumnName);
sourceReferColumns.add(sourceColumn);
Data2DColumn tableColumn = sourceColumn.copy();
tableColumn.setType(ColumnType.Long);
tmpColumns.add(tableColumn);
timeIndex = sourceReferIndice.size();
sourceReferIndice.add(sourceData.colOrder(groupTimeColumnName));
} else if (groupExpression != null && !groupExpression.isBlank()) {
tmpColumns.add(new Data2DColumn(ExpressionColumnName, ColumnType.String));
expressionIndex = sourceReferIndice.size();
Data2DColumn sourceColumn = sourceData.column(0);
sourceReferColumns.add(sourceColumn);
sourceReferIndice.add(0);
expressionCalculator = new ExpressionCalculator();
}
int sortStartIndex = -1;
if (orders != null && !orders.isEmpty()) {
sortStartIndex = sourceReferIndice.size();
List<String> sortNames = DataSort.parseNames(orders);
for (String name : sortNames) {
Data2DColumn sourceColumn = sourceData.columnByName(name);
sourceReferColumns.add(sourceColumn);
Data2DColumn tableColumn = sourceColumn.copy();
tmpColumns.add(tableColumn);
sourceReferIndice.add(sourceData.colOrder(name));
}
}
DataTable dataTable = Data2DTableTools.createTable(task, conn, null, tmpColumns);
if (dataTable == null) {
showError(task, message("Failed") + ": " + message("CreateTable"));
return false;
}
sheet = dataTable.getSheet();
columns = dataTable.getColumns();
colsNumber = columns.size();
tableData2D = dataTable.getTableData2D();
dataName = dataTable.getName();
if (importData) {
importData(conn);
}
if (sortStartIndex > 0) {
List<DataSort> sorts = DataSort.parse(orders);
List<DataSort> tmpsorts = new ArrayList<>();
for (DataSort sort : sorts) {
String sortName = sort.getName();
for (int i = sortStartIndex; i < sourceReferColumns.size(); i++) {
if (sortName.equals(sourceReferColumns.get(i).getColumnName())) {
sortName = columnName(i + valueIndexOffset);
break;
}
}
tmpsorts.add(new DataSort(sortName, sort.isAscending()));
}
tmpOrderby = DataSort.toString(tmpsorts);
} else {
tmpOrderby = null;
}
} catch (Exception e) {
showError(task, e.toString());
return false;
}
return true;
}
public long importData(Connection conn) {
try {
if (conn == null || sourceData == null || columns == null || columns.isEmpty()) {
return -1;
}
if (importRows != null) {
return importRows(conn);
}
DataTableWriter writer = new DataTableWriter();
writer.setTargetTable(this)
.setColumns(columns)
.setHeaderNames(Data2DColumnTools.toNames(columns))
.setWriteHeader(false);
return sourceData.copy(task, writer, sourceData.columnIndices(),
includeRowNumber, invalidAs);
} catch (Exception e) {
showError(task, e.toString());
return -4;
}
}
// sourceRow should include values of all source columns
@Override
public Data2DRow makeRow(List<String> sourceRow, DataTableWriter writer) {
return makeRow(sourceRow, writer.invalidAs);
}
public Data2DRow makeRow(List<String> sourceRow, InvalidAs invalidAs) {
try {
if (columns == null || sourceRow == null || sourceRow.isEmpty()) {
return null;
}
Data2DRow data2DRow = tableData2D.newRow();
long index;
List<String> values;
if (includeRowNumber) {
String rowNum = sourceRow.get(0);
index = Long.parseLong(rowNum);
data2DRow.setValue(column(1).getColumnName(), index);
values = sourceRow.subList(1, sourceRow.size());
} else {
index = -1;
values = sourceRow;
}
int rowSize = values.size();
for (int i = 0; i < sourceReferIndice.size(); i++) {
int col = sourceReferIndice.get(i);
if (col < 0 || col >= rowSize) {
continue;
}
Data2DColumn targetColumn = column(i + valueIndexOffset);
Object tmpValue;
if (i == expressionIndex) {
expressionCalculator.calculateDataRowExpression(sourceData, groupExpression, values, index);
tmpValue = expressionCalculator.getResult();
} else {
Data2DColumn sourceColumn = sourceData.column(col);
String sourceValue = values.get(col);
switch (targetColumn.getType()) {
case String:
tmpValue = sourceValue;
break;
case Double:
tmpValue = sourceColumn.toDouble(sourceValue);
break;
case Long:
if (timeIndex != i) {
tmpValue = targetColumn.fromString(sourceValue, invalidAs);
} else {
Date d = DateTools.encodeDate(sourceValue);
if (d == null) {
tmpValue = targetColumn.fromString(sourceValue, invalidAs);
} else {
calendar.setTime(d);
switch (groupTimeType) {
case Century:
int year = calendar.get(Calendar.YEAR);
int cYear = (year / 100) * 100;
if (year % 100 == 0) {
calendar.set(cYear, 0, 1, 0, 0, 0);
} else {
calendar.set(cYear + 1, 0, 1, 0, 0, 0);
}
break;
case Year:
calendar.set(calendar.get(Calendar.YEAR), 0, 1, 0, 0, 0);
break;
case Month:
calendar.set(calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
1, 0, 0, 0);
break;
case Day:
calendar.set(calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
0, 0, 0);
break;
case Hour:
calendar.set(calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
calendar.get(Calendar.HOUR_OF_DAY),
0, 0);
break;
case Minute:
calendar.set(calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
0);
break;
case Second:
calendar.set(calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
calendar.get(Calendar.SECOND));
break;
}
tmpValue = calendar.getTime().getTime();
}
}
break;
default:
tmpValue = targetColumn.fromString(sourceValue, invalidAs);
}
}
data2DRow.setValue(targetColumn.getColumnName(), tmpValue);
}
return data2DRow;
} catch (Exception e) {
showError(task, e.toString());
return null;
}
}
public long importRows(Connection conn) {
if (conn == null || importRows == null || importRows.isEmpty()) {
return -1;
}
try (PreparedStatement insert = conn.prepareStatement(tableData2D.insertStatement())) {
pagination.rowsNumber = 0;
conn.setAutoCommit(false);
for (List<String> row : importRows) {
Data2DRow data2DRow = makeRow(row, invalidAs);
if (tableData2D.setInsertStatement(conn, insert, data2DRow)) {
insert.addBatch();
if (++pagination.rowsNumber % Database.BatchSize == 0) {
insert.executeBatch();
conn.commit();
if (task != null) {
task.setInfo(message("Inserted") + ": " + pagination.rowsNumber);
}
}
}
}
insert.executeBatch();
conn.commit();
if (task != null) {
task.setInfo(message("Inserted") + ": " + pagination.rowsNumber);
}
conn.setAutoCommit(true);
return pagination.rowsNumber;
} catch (Exception e) {
showError(task, e.toString());
return -4;
}
}
public DataFileCSV sort(int maxSortResults) {
try {
if (sourceData == null) {
return null;
}
DataFileCSVWriter writer = new DataFileCSVWriter();
writer.setPrintFile(FileTmpTools.getTempFile(".csv"));
List<Data2DColumn> targetColumns = new ArrayList<>();
List<String> names = new ArrayList<>();
if (includeRowNumber) {
targetColumns.add(new Data2DColumn(message("SourceRowNumber"), ColumnDefinition.ColumnType.Long));
names.add(message("SourceRowNumber"));
}
for (int i : sourcePickIndice) {
Data2DColumn column = sourceData.column(i).copy();
String name = DerbyBase.checkIdentifier(names, column.getColumnName(), true);
column.setColumnName(name);
targetColumns.add(column);
}
writer.setColumns(targetColumns)
.setHeaderNames(names)
.setWriteHeader(false);
if (!sort(task, writer, maxSortResults)) {
return null;
}
return (DataFileCSV) writer.getTargetData();
} catch (Exception e) {
showError(task, e.toString());
return null;
}
}
public boolean sort(FxTask currentTask, Data2DWriter writer, int maxSortResults) {
if (writer == null || sourceData == null) {
return false;
}
String sql = "SELECT * FROM " + sheet
+ (tmpOrderby != null && !tmpOrderby.isBlank() ? " ORDER BY " + tmpOrderby : "");
if (maxSortResults > 0) {
sql += " FETCH FIRST " + maxSortResults + " ROWS ONLY";
}
if (currentTask != null) {
currentTask.setInfo(sql);
}
writer.openWriter();
try (ResultSet query = DerbyBase.getConnection().prepareStatement(sql).executeQuery()) {
if (includeColName) {
writer.writeRow(writer.getHeaderNames());
}
long count = 0;
String numberName = columnName(1);
while (query.next()) {
if (currentTask != null && !currentTask.isWorking()) {
break;
}
Data2DRow dataRow = tableData2D.readData(query);
List<String> rowValues = new ArrayList<>();
if (includeRowNumber) {
Object v = dataRow.getValue(numberName);
rowValues.add(v == null ? null : v + "");
}
for (int i = 0; i < sourcePickIndice.size(); i++) {
Data2DColumn tmpColumn = columns.get(i + valueIndexOffset);
Object v = dataRow.getValue(tmpColumn.getColumnName());
rowValues.add(v == null ? null : v + "");
}
writer.writeRow(rowValues);
count++;
}
} catch (Exception e) {
showError(currentTask, e.toString());
return false;
}
writer.closeWriter();
return true;
}
public boolean transpose(FxTask currentTask, Data2DWriter writer, boolean firstColumnAsNames) {
if (writer == null || sourceData == null) {
return false;
}
writer.setColumns(null).setHeaderNames(null).setWriteHeader(false).openWriter();
try (Connection conn = DerbyBase.getConnection()) {
String idName = columns.get(0).getColumnName();
List<Data2DColumn> targetColumns = new ArrayList<>();
List<Data2DColumn> dataColumns = new ArrayList<>();
// skip id column
if (firstColumnAsNames && includeRowNumber) {
dataColumns.add(columns.get(2));
dataColumns.add(columns.get(1));
for (int i = 3; i < columns.size(); i++) {
dataColumns.add(columns.get(i));
}
} else {
for (int i = 1; i < columns.size(); i++) {
dataColumns.add(columns.get(i));
}
}
for (int i = 0; i < dataColumns.size(); i++) {
if (currentTask != null && !currentTask.isWorking()) {
break;
}
Data2DColumn column = dataColumns.get(i);
String columnName = column.getColumnName();
List<String> rowValues = new ArrayList<>();
String sql = "SELECT " + idName + "," + columnName + " FROM " + sheet + " ORDER BY " + idName;
if (currentTask != null) {
currentTask.setInfo(sql);
}
try (PreparedStatement statement = conn.prepareStatement(sql);
ResultSet results = statement.executeQuery()) {
String sname = DerbyBase.savedName(columnName);
while (results.next()) {
if (currentTask != null && !currentTask.isWorking()) {
break;
}
rowValues.add(results.getString(sname));
}
} catch (Exception e) {
showError(currentTask, e.toString());
return false;
}
if (i == 0) {
int cNumber = rowValues.size();
List<String> names = new ArrayList<>();
if (firstColumnAsNames) {
for (int c = 0; c < cNumber; c++) {
String name = rowValues.get(c);
if (name == null || name.isBlank()) {
name = message("Columns") + (c + 1);
}
DerbyBase.checkIdentifier(names, name, true);
}
} else {
for (int c = 1; c <= cNumber; c++) {
names.add(message("Column") + c);
}
}
if (includeColName) {
String name = DerbyBase.checkIdentifier(names, message("ColumnName"), false);
names.add(0, name);
}
for (int c = 0; c < names.size(); c++) {
targetColumns.add(new Data2DColumn(names.get(c), ColumnType.String));
}
writer.setColumns(targetColumns).setHeaderNames(names).setWriteHeader(true);
writer.writeRow(names);
}
if (includeColName) {
rowValues.add(0, columnName);
}
writer.writeRow(rowValues);
}
} catch (Exception e) {
showError(currentTask, e.toString());
return false;
}
writer.closeWriter();
return true;
}
public int parametersOffset() {
return sourcePickIndice.size() + valueIndexOffset;
}
public Data2DColumn parameterSourceColumn() {
return sourceReferColumns.get(sourcePickIndice.size());
}
public FindReplaceString findReplace() {
if (findReplace == null) {
findReplace = FindReplaceString.create().
setOperation(FindReplaceString.Operation.ReplaceAll)
.setIsRegex(false).setCaseInsensitive(false).setMultiline(false);
}
return findReplace;
}
public String tmpScript(String script) {
if (script == null || script.isBlank()) {
return null;
}
String tmpScript = script;
for (int i = 0; i < sourcePickIndice.size(); i++) {
if (task == null || task.isCancelled()) {
return null;
}
int col = sourcePickIndice.get(i);
String sourceName = sourceData.columnName(col);
String tmpName = columnName(i + valueIndexOffset);
tmpScript = findReplace().replace(task, script, "#{" + sourceName + "}", "#{" + tmpName + "}");
}
return tmpScript;
}
public void showError(FxTask currentTask, String err) {
if (currentTask != null) {
currentTask.setError(err);
} else {
MyBoxLog.error(err);
}
}
/*
static
*/
public static String tmpTableName() {
return TmpTablePrefix + DateTools.nowString3();
}
public static String tmpTableName(String sourceName) {
return TmpTablePrefix + sourceName + DateTools.nowString3();
}
public static TmpTable toStatisticTable(Data2D sourceData, FxTask task,
List<Integer> cols, InvalidAs invalidAs) {
if (cols == sourceData || cols == null || cols.isEmpty()) {
return null;
}
TmpTable tmpTable = new TmpTable().setSourceData(sourceData)
.setSourcePickIndice(cols)
.setImportData(true)
.setForStatistic(true)
.setIncludeRowNumber(false)
.setInvalidAs(invalidAs);
tmpTable.setTask(task);
if (tmpTable.createTable()) {
return tmpTable;
} else {
return null;
}
}
/*
set
*/
public TmpTable setSourceData(Data2D sourceData) {
this.sourceData = sourceData;
return this;
}
public TmpTable setSourcePickIndice(List<Integer> sourcePickIndice) {
this.sourcePickIndice = sourcePickIndice;
return this;
}
public TmpTable setTargetName(String targetName) {
this.targetName = targetName;
return this;
}
public TmpTable setImportData(boolean importData) {
this.importData = importData;
return this;
}
public TmpTable setForStatistic(boolean forStatistic) {
this.forStatistic = forStatistic;
return this;
}
public TmpTable setIncludeRowNumber(boolean includeRowNumber) {
this.includeRowNumber = includeRowNumber;
return this;
}
public TmpTable setIncludeColName(boolean includeColName) {
this.includeColName = includeColName;
return this;
}
public TmpTable setOrders(List<String> orders) {
this.orders = orders;
return this;
}
public TmpTable setGroupEqualColumnNames(List<String> groupEqualColumnNames) {
this.groupEqualColumnNames = groupEqualColumnNames;
return this;
}
public TmpTable setGroupRangleColumnName(String groupRangleColumnName) {
this.groupRangeColumnName = groupRangleColumnName;
return this;
}
public TmpTable setGroupTimeColumnName(String groupTimeColumnName) {
this.groupTimeColumnName = groupTimeColumnName;
return this;
}
public TmpTable setGroupTimeType(TimeType groupTimeType) {
this.groupTimeType = groupTimeType;
return this;
}
public TmpTable setGroupExpression(String groupExpression) {
this.groupExpression = groupExpression;
return this;
}
public TmpTable setInvalidAs(InvalidAs invalidAs) {
this.invalidAs = invalidAs;
return this;
}
public TmpTable setImportRows(List<List<String>> importRows) {
this.importRows = importRows;
return this;
}
/*
get
*/
public Data2D getSourceData() {
return sourceData;
}
public List<Integer> getSourcePickIndice() {
return sourcePickIndice;
}
public List<Integer> getSourceReferIndice() {
return sourceReferIndice;
}
public void setSourceReferIndice(List<Integer> sourceReferIndice) {
this.sourceReferIndice = sourceReferIndice;
}
public List<String> getOrders() {
return orders;
}
public String getTmpOrderby() {
return tmpOrderby;
}
public List<String> getGroupEqualColumnNames() {
return groupEqualColumnNames;
}
public int getValueIndexOffset() {
return valueIndexOffset;
}
public String getTargetName() {
return targetName;
}
public String getGroupRangeColumnName() {
return groupRangeColumnName;
}
public String getGroupExpression() {
return groupExpression;
}
public boolean isImportData() {
return importData;
}
public boolean isForStatistic() {
return forStatistic;
}
public boolean isIncludeRowNumber() {
return includeRowNumber;
}
public boolean isIncludeColName() {
return includeColName;
}
public InvalidAs getInvalidAs() {
return invalidAs;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/DataInternalTable.java | alpha/MyBox/src/main/java/mara/mybox/data2d/DataInternalTable.java | package mara.mybox.data2d;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.db.DerbyBase;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.db.table.BaseTable;
import static mara.mybox.db.table.BaseTableTools.internalTables;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2022-2-12
* @License Apache License Version 2.0
*/
public class DataInternalTable extends DataTable {
public DataInternalTable() {
dataType = DataType.InternalTable;
}
@Override
public int type() {
return type(DataType.InternalTable);
}
@Override
public boolean loadColumns(Connection conn) {
try {
columns = null;
if (dataID < 0 || sheet == null) {
return false;
}
BaseTable internalTable = internalTables().get(sheet.toUpperCase());
if (internalTable == null) {
dataType = DataType.DatabaseTable;
return super.loadColumns(conn);
}
List<ColumnDefinition> dbColumns = internalTable.getColumns();
if (dbColumns == null) {
return false;
}
columns = new ArrayList<>();
colsNumber = dbColumns.size();
for (int i = 0; i < colsNumber; i++) {
ColumnDefinition dbColumn = dbColumns.get(i);
Data2DColumn dataColumn = new Data2DColumn();
dataColumn.cloneFrom(dbColumn);
String columnName = DerbyBase.fixedIdentifier(dbColumn.getColumnName());
dataColumn.setColumnName(columnName);
dataColumn.setData2DDefinition(this)
.setDataID(dataID).setColumnID(-1).setIndex(i);
if (savedColumns != null) {
for (Data2DColumn savedColumn : savedColumns) {
if (columnName.equalsIgnoreCase(savedColumn.getColumnName())) {
dataColumn.setColumnID(savedColumn.getColumnID());
break;
}
}
}
columns.add(dataColumn);
}
tableData2DColumn.save(conn, dataID, columns);
tableData2DDefinition.updateData(conn, this);
tableData2D.readDefinitionFromDB(conn, sheet);
tableData2D.setColumns(dbColumns);
return true;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/DataFileText.java | alpha/MyBox/src/main/java/mara/mybox/data2d/DataFileText.java | package mara.mybox.data2d;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.nio.charset.Charset;
import java.util.List;
import mara.mybox.data.FindReplaceString;
import mara.mybox.data2d.writer.Data2DWriter;
import mara.mybox.data2d.writer.DataFileTextWriter;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.FileTools;
import mara.mybox.tools.TextFileTools;
import mara.mybox.tools.TextTools;
import static mara.mybox.tools.TextTools.validLine;
/**
* @Author Mara
* @CreateDate 2021-10-17
* @License Apache License Version 2.0
*/
public class DataFileText extends DataFile {
public static final String CommentsMarker = "#";
public DataFileText() {
dataType = DataType.Texts;
}
public String[] delimters() {
String[] delimiters = {",", " ", " ", " ", "\t", "|", "@",
";", ":", "*", "%", "$", "_", "&", "-", "=", "!", "\"",
"'", "<", ">", "#"};
return delimiters;
}
@Override
public boolean checkForLoad() {
if (charset == null && file != null) {
charset = TextFileTools.charset(file);
}
if (charset == null) {
charset = Charset.forName("UTF-8");
}
if (delimiter == null || delimiter.isEmpty()) {
delimiter = guessDelimiter();
}
if (delimiter == null || delimiter.isEmpty()) {
delimiter = ",";
}
return super.checkForLoad();
}
public String guessDelimiter() {
if (file == null) {
return null;
}
String[] delimiters = delimters();
if (charset == null) {
charset = TextFileTools.charset(file);
}
if (charset == null) {
charset = Charset.forName("UTF-8");
}
File validFile = FileTools.removeBOM(task, file);
if (validFile == null || (task != null && !task.isWorking())) {
return null;
}
try (BufferedReader reader = new BufferedReader(new FileReader(validFile, charset))) {
String line1 = reader.readLine();
while (line1 != null && !validLine(line1)) {
line1 = reader.readLine();
}
if (line1 == null) {
return null;
}
int[] count1 = new int[delimiters.length];
int maxCount1 = 0, maxCountIndex1 = -1;
for (int i = 0; i < delimiters.length; i++) {
if (task != null && !task.isWorking()) {
reader.close();
return null;
}
count1[i] = FindReplaceString.count(task, line1, delimiters[i]);
if (task != null && !task.isWorking()) {
reader.close();
return null;
}
// MyBoxLog.console(">>" + values[i] + "<<< " + count1[i]);
if (count1[i] > maxCount1) {
maxCount1 = count1[i];
maxCountIndex1 = i;
}
}
// MyBoxLog.console(maxCount1);
String line2 = reader.readLine();
while (line2 != null && !validLine(line2)) {
if (task != null && !task.isWorking()) {
reader.close();
return null;
}
line2 = reader.readLine();
}
if (line2 == null) {
if (maxCountIndex1 >= 0) {
return delimiters[maxCountIndex1];
} else {
hasHeader = false;
return null;
}
}
int[] count2 = new int[delimiters.length];
int maxCount2 = 0, maxCountIndex2 = -1;
for (int i = 0; i < delimiters.length; i++) {
if (task != null && !task.isWorking()) {
reader.close();
return null;
}
count2[i] = FindReplaceString.count(task, line2, delimiters[i]);
if (task != null && !task.isWorking()) {
reader.close();
return null;
}
// MyBoxLog.console(">>" + values[i] + "<<< " + count1[i]);
if (count1[i] == count2[i] && count2[i] > maxCount2) {
maxCount2 = count2[i];
maxCountIndex2 = i;
}
}
// MyBoxLog.console(maxCount2);
if (maxCountIndex2 >= 0) {
return delimiters[maxCountIndex2];
} else {
if (maxCountIndex1 >= 0) {
return delimiters[maxCountIndex1];
} else {
hasHeader = false;
return null;
}
}
} catch (Exception e) {
// MyBoxLog.console(e.toString());
}
hasHeader = false;
return null;
}
public List<String> parseFileLine(String line) {
return TextTools.parseLine(line, delimiter);
}
public List<String> readValidLine(BufferedReader reader) {
if (reader == null) {
return null;
}
List<String> values = null;
try {
String line;
while ((line = reader.readLine()) != null) {
values = parseFileLine(line);
if (values != null && !values.isEmpty()) {
break;
}
}
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
MyBoxLog.console(e);
}
return values;
}
@Override
public Data2DWriter selfWriter() {
DataFileTextWriter writer = new DataFileTextWriter();
initSelfWriter(writer);
writer.setCharset(charset).setDelimiter(delimiter).setTargetData(this);
return writer;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/DataFile.java | alpha/MyBox/src/main/java/mara/mybox/data2d/DataFile.java | package mara.mybox.data2d;
import java.sql.Connection;
import java.util.List;
import mara.mybox.data2d.operate.Data2DReadColumnNames;
import mara.mybox.db.data.Data2DDefinition;
import mara.mybox.tools.FileTools;
/**
* @Author Mara
* @CreateDate 2021-10-18
* @License Apache License Version 2.0
*/
public abstract class DataFile extends Data2D {
@Override
public Data2DDefinition queryDefinition(Connection conn) {
if (conn == null || dataType == null || file == null || !file.exists()) {
return null;
}
return tableData2DDefinition.queryFile(conn, dataType, file);
}
@Override
public List<String> readColumnNames() {
if (!FileTools.hasData(file)) {
return null;
}
Data2DReadColumnNames reader = Data2DReadColumnNames.create(this);
if (reader == null) {
hasHeader = false;
return null;
}
reader.setTask(task).start();
return reader.getNames();
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/Data2D_Edit.java | alpha/MyBox/src/main/java/mara/mybox/data2d/Data2D_Edit.java | package mara.mybox.data2d;
import java.io.File;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import mara.mybox.data.SetValue;
import mara.mybox.data2d.modify.Data2DClear;
import mara.mybox.data2d.modify.Data2DDelete;
import mara.mybox.data2d.modify.Data2DModify;
import mara.mybox.data2d.modify.Data2DSaveAttributes;
import mara.mybox.data2d.modify.Data2DSavePage;
import mara.mybox.data2d.modify.Data2DSetValue;
import mara.mybox.data2d.modify.DataTableClear;
import mara.mybox.data2d.modify.DataTableDelete;
import mara.mybox.data2d.modify.DataTableSetValue;
import mara.mybox.data2d.operate.Data2DOperate;
import mara.mybox.data2d.operate.Data2DReadPage;
import mara.mybox.data2d.operate.Data2DReadTotal;
import mara.mybox.data2d.writer.Data2DWriter;
import mara.mybox.db.DerbyBase;
import mara.mybox.db.data.ColumnDefinition.InvalidAs;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.db.data.Data2DDefinition;
import mara.mybox.db.data.Data2DStyle;
import mara.mybox.db.table.TableData2DDefinition;
import mara.mybox.db.table.TableData2DStyle;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.fxml.image.FxColorTools;
import mara.mybox.tools.CsvTools;
import mara.mybox.tools.DateTools;
import mara.mybox.tools.FileDeleteTools;
import static mara.mybox.tools.FileTmpTools.getTempFile;
import mara.mybox.tools.TextFileTools;
import static mara.mybox.tools.TextTools.delimiterValue;
import static mara.mybox.value.Languages.message;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public abstract class Data2D_Edit extends Data2D_Filter {
public abstract Data2DDefinition queryDefinition(Connection conn);
public abstract List<String> readColumnNames();
public abstract Data2DWriter selfWriter();
/*
read
*/
public boolean checkForLoad() {
return true;
}
public long loadDataDefinition(Connection conn) {
if (isTmpData()) {
checkForLoad();
return -1;
}
try {
Data2DDefinition definition = queryDefinition(conn);
if (definition != null) {
cloneFrom(definition);
}
checkForLoad();
if (definition == null) {
definition = tableData2DDefinition.insertData(conn, this);
conn.commit();
dataID = definition.getDataID();
} else {
tableData2DDefinition.updateData(conn, this);
conn.commit();
dataID = definition.getDataID();
savedColumns = tableData2DColumn.read(conn, dataID);
}
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
MyBoxLog.debug(e);
return -1;
}
return dataID;
}
public boolean deleteDataDefinition() {
try (Connection conn = DerbyBase.getConnection()) {
if (dataID < 0) {
return false;
}
return tableData2DDefinition.deleteDefinition(conn, dataID) > 0;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
MyBoxLog.debug(e);
return false;
}
}
public boolean loadColumns(Connection conn) {
try {
columns = null;
List<String> colNames = readColumnNames();
if (colNames == null || colNames.isEmpty()) {
hasHeader = false;
columns = savedColumns;
} else {
List<String> validNames = new ArrayList<>();
columns = new ArrayList<>();
for (int i = 0; i < colNames.size(); i++) {
String name = colNames.get(i);
Data2DColumn column;
if (savedColumns != null && i < savedColumns.size()) {
column = savedColumns.get(i);
if (!hasHeader) {
name = column.getColumnName();
}
} else {
column = new Data2DColumn(name, defaultColumnType());
}
String vname = (name == null || name.isBlank()) ? message("Column") + (i + 1) : name;
vname = DerbyBase.checkIdentifier(validNames, vname, true);
column.setColumnName(vname);
columns.add(column);
}
}
if (columns != null && !columns.isEmpty()) {
Random random = new Random();
for (int i = 0; i < columns.size(); i++) {
Data2DColumn column = columns.get(i);
column.setDataID(dataID);
column.setIndex(i);
if (column.getColor() == null) {
column.setColor(FxColorTools.randomColor(random));
}
if (!isTable()) {
column.setAuto(false);
column.setIsPrimaryKey(false);
}
if (isMatrix()) {
column.setType(defaultColumnType());
}
}
colsNumber = columns.size();
if (dataID >= 0 && conn != null) {
tableData2DColumn.save(conn, dataID, columns);
tableData2DDefinition.updateData(conn, this);
}
} else {
colsNumber = 0;
if (dataID >= 0 && conn != null) {
tableData2DColumn.clearColumns(conn, dataID);
tableData2DDefinition.updateData(conn, this);
tableData2DStyle.clear(conn, dataID);
}
}
return true;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
MyBoxLog.debug(e);
return false;
}
}
public long readTotal() {
pagination.rowsNumber = -1;
Data2DOperate opearte = Data2DReadTotal.create(this)
.setTask(backgroundTask).start();
if (opearte != null) {
pagination.rowsNumber = opearte.getSourceRowIndex();
}
try (Connection conn = DerbyBase.getConnection()) {
tableData2DDefinition.updateData(conn, this);
} catch (Exception e) {
if (backgroundTask != null) {
backgroundTask.setError(e.toString());
}
MyBoxLog.error(e);
}
return pagination.rowsNumber;
}
public List<List<String>> loadPageData(Connection conn) {
if (!hasColumns()) {
pagination.startRowOfCurrentPage = pagination.endRowOfCurrentPage = 0;
return null;
}
if (pagination.startRowOfCurrentPage < 0) {
pagination.startRowOfCurrentPage = 0;
}
pagination.endRowOfCurrentPage = pagination.startRowOfCurrentPage;
Data2DReadPage reader = Data2DReadPage.create(this).setConn(conn);
if (reader == null) {
pagination.startRowOfCurrentPage = pagination.endRowOfCurrentPage = 0;
return null;
}
reader.setTask(task).start();
List<List<String>> rows = reader.getRows();
if (rows != null) {
pagination.endRowOfCurrentPage = pagination.startRowOfCurrentPage + rows.size();
}
loadPageStyles(conn);
return rows;
}
public void loadPageStyles(Connection conn) {
styles = new ArrayList<>();
if (dataID < 0 || pagination.startRowOfCurrentPage >= pagination.endRowOfCurrentPage) {
return;
}
try (PreparedStatement statement = conn.prepareStatement(TableData2DStyle.QueryStyles)) {
statement.setLong(1, dataID);
conn.setAutoCommit(true);
try (ResultSet results = statement.executeQuery()) {
while (results.next()) {
Data2DStyle style = tableData2DStyle.readData(results);
if (style != null) {
styles.add(style);
}
}
}
} catch (Exception e) {
MyBoxLog.error(e);
if (task != null) {
task.setError(e.toString());
}
}
try {
List<String> scripts = new ArrayList<>();
for (int i = 0; i < styles.size(); i++) {
Data2DStyle style = styles.get(i);
scripts.add(style.getFilter());
}
scripts = calculateScriptsStatistic(scripts);
for (int i = 0; i < styles.size(); i++) {
Data2DStyle style = styles.get(i);
style.setFilter(scripts.get(i));
}
} catch (Exception e) {
MyBoxLog.error(e);
if (task != null) {
task.setError(e.toString());
}
}
}
public void countPageSize() {
try {
pagination.rowsNumber = pagination.rowsNumber + (tableRowsNumber()
- (pagination.endRowOfCurrentPage - pagination.startRowOfCurrentPage));
colsNumber = tableColsNumber();
if (colsNumber <= 0) {
hasHeader = false;
}
} catch (Exception e) {
MyBoxLog.error(e);
}
}
/*
modify
*/
public Data2DWriter initSelfWriter(Data2DWriter writer) {
if (writer != null) {
writer.setWriteHeader(hasHeader)
.setDataName(dataName)
.setPrintFile(file)
.setColumns(columns)
.setHeaderNames(columnNames())
.setTargetScale(scale)
.setTargetMaxRandom(maxRandom)
.setWriteComments(true)
.setTargetComments(comments)
.setRecordTargetFile(true)
.setRecordTargetData(true);
}
return writer;
}
public long savePageData(FxTask task) {
try {
Data2DModify operate = Data2DSavePage.save(this);
if (operate == null) {
return -2;
}
operate.setTask(task).start();
if (operate.isFailed()) {
return -3;
}
return operate.rowsCount();
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
MyBoxLog.error(e);
return -4;
}
}
public long saveAttributes(FxTask task, Data2D attributes) {
try {
if (attributes == null) {
return -1;
}
Data2DModify operate = Data2DSaveAttributes.create(this, attributes);
if (operate == null) {
return -2;
}
operate.setTask(task).start();
if (operate.isFailed()) {
return -3;
}
attributes.pagination.rowsNumber = operate.rowsCount();
attributes.tableChanged = false;
attributes.pagination.currentPage = pagination.currentPage;
cloneAttributesFrom(attributes);
return attributes.pagination.rowsNumber;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
MyBoxLog.error(e);
return -4;
}
}
public long setValue(FxTask task, String colName, String value) {
try {
List<Integer> cols = new ArrayList<>();
cols.add(colOrder(colName));
SetValue setValue = new SetValue()
.setType(SetValue.ValueType.Value)
.setParameter(value);
return setValue(task, cols, setValue, InvalidAs.Fail);
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
MyBoxLog.error(e);
return -4;
}
}
public long setValue(FxTask task, List<Integer> cols,
SetValue setValue, InvalidAs invalidAs) {
try {
if (!hasData() || cols == null || cols.isEmpty()) {
return -1;
}
Data2DOperate operate = isTable()
? new DataTableSetValue((DataTable) this, setValue)
: Data2DSetValue.create(this, setValue);
if (operate == null) {
return -2;
}
operate.setCols(cols).setInvalidAs(invalidAs)
.setTask(task).start();
if (operate.isFailed()) {
return -3;
}
tableChanged = false;
return operate.getHandledCount();
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
MyBoxLog.error(e);
return -4;
}
}
public long deleteRows(FxTask task) {
try {
if (!hasData()) {
return -1;
}
Data2DOperate operate = isTable()
? new DataTableDelete((DataTable) this)
: Data2DDelete.create(this);
if (operate == null) {
return -2;
}
operate.setTask(task).start();
if (operate.isFailed()) {
return -3;
}
return operate.getHandledCount();
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
MyBoxLog.error(e);
return -4;
}
}
public long clearData(FxTask task) {
try {
if (!hasData()) {
return -1;
}
Data2DOperate operate = isTable()
? new DataTableClear((DataTable) this)
: Data2DClear.create(this);
if (operate == null) {
return -2;
}
operate.setTask(task).start();
if (operate.isFailed()) {
return -3;
}
tableChanged = false;
return operate.getHandledCount();
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
MyBoxLog.error(e);
return -4;
}
}
public String encodeCSV(FxTask task, String delimiterName,
boolean displayRowNames, boolean displayColNames, boolean formatData) {
if (!hasColumns()) {
return "";
}
if (delimiterName == null) {
delimiterName = ",";
}
try {
File tmpFile = getTempFile(".csv");
List<String> cols = null;
if (displayColNames) {
cols = new ArrayList<>();
if (displayRowNames) {
cols.add(message("TableRowNumber"));
cols.add(message("DataRowNumber"));
}
cols.addAll(columnNames());
}
tmpFile = DataFileCSV.csvFile(task, tmpFile, delimiterValue(delimiterName),
cols, pageRows(displayRowNames, formatData));
if (tmpFile == null || !tmpFile.exists()) {
return "";
}
String page = TextFileTools.readTexts(task, tmpFile, Charset.forName("UTF-8"));
FileDeleteTools.delete(tmpFile);
return page;
} catch (Exception e) {
MyBoxLog.error(e);
return "";
}
}
public List<List<String>> decodeCSV(FxTask task, String text, String delimiterName, boolean hasHeader) {
if (text == null || delimiterName == null) {
return null;
}
try {
List<List<String>> data = new ArrayList<>();
File tmpFile = getTempFile(".csv");
TextFileTools.writeFile(tmpFile, text, Charset.forName("UTF-8"));
if (tmpFile == null || !tmpFile.exists()) {
return null;
}
try (CSVParser parser = CsvTools.csvParser(tmpFile, delimiterValue(delimiterName), hasHeader)) {
if (hasHeader) {
data.add(parser.getHeaderNames());
}
for (CSVRecord record : parser) {
if (task != null && task.isCancelled()) {
return null;
}
data.add(record.toList());
}
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
data = null;
}
FileDeleteTools.delete(tmpFile);
return data;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return null;
}
}
/*
save
*/
public boolean checkForSave() {
if (dataName == null || dataName.isBlank()) {
if (file != null && !isTmpData()) {
dataName = file.getName();
} else {
dataName = DateTools.nowString();
}
}
return true;
}
public boolean saveAttributes() {
try (Connection conn = DerbyBase.getConnection()) {
return saveAttributes(conn);
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
MyBoxLog.error(e);
return false;
}
}
public boolean saveAttributes(Connection conn) {
return saveAttributes(conn, (Data2D) this, columns);
}
public static boolean saveAttributes(Data2D d, List<Data2DColumn> cols) {
if (d == null) {
return false;
}
try (Connection conn = DerbyBase.getConnection()) {
return saveAttributes(conn, d, cols);
} catch (Exception e) {
if (d.getTask() != null) {
d.getTask().setError(e.toString());
}
MyBoxLog.error(e);
return false;
}
}
public static boolean saveAttributes(Connection conn, Data2D d, List<Data2DColumn> inColumns) {
if (d == null) {
return false;
}
if (conn == null) {
return saveAttributes(d, inColumns);
}
try {
if (!d.checkForSave() || !d.checkForLoad()) {
return false;
}
Data2DDefinition def;
long did = d.getDataID();
d.setModifyTime(new Date());
d.setColsNumber(inColumns == null ? 0 : inColumns.size());
TableData2DDefinition tableData2DDefinition = d.getTableData2DDefinition();
if (did >= 0) {
def = tableData2DDefinition.updateData(conn, d);
} else {
def = d.queryDefinition(conn);
if (def == null) {
def = tableData2DDefinition.insertData(conn, d);
} else {
d.setDataID(def.getDataID());
def = tableData2DDefinition.updateData(conn, d);
}
}
conn.commit();
did = def.getDataID();
if (did < 0) {
return false;
}
d.cloneFrom(def);
if (inColumns != null && !inColumns.isEmpty()) {
try {
List<Data2DColumn> targetColumns = new ArrayList<>();
for (int i = 0; i < inColumns.size(); i++) {
Data2DColumn column = inColumns.get(i).cloneAll();
if (column.getDataID() != did) {
column.setColumnID(-1);
}
column.setDataID(did);
column.setIndex(i);
if (!d.isTable()) {
column.setIsPrimaryKey(false);
column.setAuto(false);
}
if (d.isMatrix()) {
column.setType(d.defaultColumnType());
}
targetColumns.add(column);
}
d.getTableData2DColumn().save(conn, did, targetColumns);
d.setColumns(targetColumns);
} catch (Exception e) {
if (d.getTask() != null) {
d.getTask().setError(e.toString());
}
MyBoxLog.error(e);
}
} else {
d.getTableData2DColumn().clear(d);
d.setColumns(null);
}
return true;
} catch (Exception e) {
if (d.getTask() != null) {
d.getTask().setError(e.toString());
}
MyBoxLog.error(e);
return false;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/writer/HtmlWriter.java | alpha/MyBox/src/main/java/mara/mybox/data2d/writer/HtmlWriter.java | package mara.mybox.data2d.writer;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.nio.charset.Charset;
import mara.mybox.controller.WebBrowserController;
import mara.mybox.data.StringTable;
import mara.mybox.db.data.VisitHistory;
import mara.mybox.fxml.style.HtmlStyles;
import mara.mybox.tools.FileDeleteTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.FileTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-1-29
* @License Apache License Version 2.0
*/
public class HtmlWriter extends Data2DWriter {
protected BufferedWriter fileWriter;
protected String css;
public HtmlWriter() {
fileSuffix = "htm";
css = HtmlStyles.TableStyle;
}
@Override
public boolean openWriter() {
try {
if (!super.openWriter()) {
return false;
}
if (printFile == null) {
showInfo(message("InvalidParameter") + ": " + message("TargetFile"));
return false;
}
showInfo(message("Writing") + " " + printFile.getAbsolutePath());
tmpFile = FileTmpTools.getTempFile(".htm");
fileWriter = new BufferedWriter(new FileWriter(tmpFile, Charset.forName("utf-8")));
StringBuilder s = new StringBuilder();
s.append("<HTML>\n").
append(indent).append("<HEAD>\n").
append(indent).append(indent).
append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n");
if (css != null && !css.isBlank()) {
s.append(indent).append(indent).append("<style type=\"text/css\">\n");
s.append(indent).append(indent).append(indent).append(css).append("\n");
s.append(indent).append(indent).append("</style>\n");
}
s.append(indent).append("</HEAD>\n").append(indent).append("<BODY>\n");
StringTable table = new StringTable(writeHeader ? headerNames : null);
if (writeComments && targetComments != null && !targetComments.isBlank()) {
table.setComments(targetComments);
}
s.append(StringTable.tablePrefix(table));
fileWriter.write(s.toString());
status = Status.Openned;
return true;
} catch (Exception e) {
showError(e.toString());
return false;
}
}
@Override
public void printTargetRow() {
try {
if (printRow == null) {
return;
}
fileWriter.write(StringTable.tableRow(printRow));
} catch (Exception e) {
showError(e.toString());
}
}
@Override
public void finishWork() {
try {
if (fileWriter == null || printFile == null) {
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
if (isFailed() || tmpFile == null || !tmpFile.exists()) {
fileWriter.close();
fileWriter = null;
FileDeleteTools.delete(tmpFile);
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
if (targetRowIndex == 0) {
fileWriter.close();
fileWriter = null;
FileDeleteTools.delete(tmpFile);
showInfo(message("NoData") + ": " + printFile);
status = Status.NoData;
return;
}
fileWriter.write(StringTable.tableSuffix(new StringTable(headerNames)));
fileWriter.write(indent + "<BODY>\n</HTML>\n");
fileWriter.flush();
fileWriter.close();
fileWriter = null;
if (!FileTools.override(tmpFile, printFile)) {
FileDeleteTools.delete(tmpFile);
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
if (printFile == null || !printFile.exists()) {
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
recordFileGenerated(printFile, VisitHistory.FileType.Html);
status = Status.Created;
} catch (Exception e) {
showError(e.toString());
}
}
@Override
public boolean showResult() {
if (printFile == null) {
return false;
}
WebBrowserController.openFile(printFile);
return true;
}
/*
get/set
*/
public String getCss() {
return css;
}
public HtmlWriter setCss(String css) {
this.css = css;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/writer/MyBoxClipboardWriter.java | alpha/MyBox/src/main/java/mara/mybox/data2d/writer/MyBoxClipboardWriter.java | package mara.mybox.data2d.writer;
import java.io.FileWriter;
import java.nio.charset.Charset;
import mara.mybox.controller.DataInMyBoxClipboardController;
import mara.mybox.data2d.Data2D;
import mara.mybox.data2d.DataClipboard;
import mara.mybox.db.data.Data2DDefinition;
import mara.mybox.tools.CsvTools;
import mara.mybox.tools.FileDeleteTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.FileTools;
import static mara.mybox.value.Languages.message;
import org.apache.commons.csv.CSVPrinter;
/**
* @Author Mara
* @CreateDate 2022-1-29
* @License Apache License Version 2.0
*/
public class MyBoxClipboardWriter extends Data2DWriter {
protected DataClipboard clip;
protected CSVPrinter printer;
public MyBoxClipboardWriter() {
fileSuffix = "csv";
}
@Override
public boolean openWriter() {
try {
if (!super.openWriter()) {
return false;
}
if (printFile == null) {
printFile = DataClipboard.newFile();
}
if (printFile == null) {
showInfo(message("InvalidParameter") + ": " + message("TargetFile"));
return false;
}
showInfo(message("Writing") + " " + printFile.getAbsolutePath());
tmpFile = FileTmpTools.getTempFile();
printer = new CSVPrinter(new FileWriter(tmpFile,
Charset.forName("UTF-8")), CsvTools.csvFormat());
if (writeHeader && headerNames != null) {
printer.printRecord(headerNames);
}
status = Status.Openned;
return true;
} catch (Exception e) {
showError(e.toString());
return false;
}
}
@Override
public void printTargetRow() {
try {
if (printRow == null) {
return;
}
printer.printRecord(printRow);
} catch (Exception e) {
showError(e.toString());
}
}
@Override
public void finishWork() {
try {
if (printer == null) {
showInfo(message("Failed") + ": " + printFile);
return;
}
printer.flush();
printer.close();
printer = null;
if (isFailed() || tmpFile == null || !tmpFile.exists()) {
FileDeleteTools.delete(tmpFile);
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
if (targetRowIndex == 0) {
FileDeleteTools.delete(tmpFile);
showInfo(message("NoData") + ": " + printFile);
status = Status.NoData;
return;
}
if (!FileTools.override(tmpFile, printFile)) {
FileDeleteTools.delete(tmpFile);
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
if (printFile == null || !printFile.exists()) {
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
if (targetData == null) {
targetData = Data2D.create(Data2DDefinition.DataType.MyBoxClipboard);
}
targetData.setCharset(Charset.forName("UTF-8")).setDelimiter(",");
saveTargetData(true, columns);
DataInMyBoxClipboardController.update();
showInfo(message("Generated") + ": " + printFile + " "
+ message("FileSize") + ": " + printFile.length());
showInfo(message("RowsNumber") + ": " + targetRowIndex);
status = Status.Created;
} catch (Exception e) {
showError(e.toString());
}
}
@Override
public boolean showResult() {
if (targetData == null) {
return false;
}
DataInMyBoxClipboardController.open(targetData);
return true;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/writer/DataFileTextWriter.java | alpha/MyBox/src/main/java/mara/mybox/data2d/writer/DataFileTextWriter.java | package mara.mybox.data2d.writer;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.nio.charset.Charset;
import mara.mybox.data2d.Data2D;
import static mara.mybox.data2d.DataFileText.CommentsMarker;
import mara.mybox.db.data.Data2DDefinition;
import mara.mybox.db.data.VisitHistory;
import mara.mybox.tools.FileDeleteTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.FileTools;
import mara.mybox.tools.TextFileTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-1-29
* @License Apache License Version 2.0
*/
public class DataFileTextWriter extends Data2DWriter {
protected BufferedWriter fileWriter;
protected Charset charset;
protected String delimiter;
public DataFileTextWriter() {
fileSuffix = "txt";
}
@Override
public boolean openWriter() {
try {
if (!super.openWriter()) {
return false;
}
if (printFile == null) {
showInfo(message("InvalidParameter") + ": " + message("TargetFile"));
return false;
}
showInfo(message("Writing") + " " + printFile.getAbsolutePath());
tmpFile = FileTmpTools.getTempFile(".txt");
if (charset == null) {
charset = Charset.forName("utf-8");
}
if (delimiter == null) {
delimiter = ",";
}
fileWriter = new BufferedWriter(new FileWriter(tmpFile, charset));
if (writeComments && targetComments != null && !targetComments.isBlank()) {
for (String line : targetComments.split("\n")) {
fileWriter.write(CommentsMarker + " " + line + "\n");
}
}
if (writeHeader && headerNames != null) {
TextFileTools.writeLine(task(), fileWriter, headerNames, delimiter);
}
status = Status.Openned;
return true;
} catch (Exception e) {
showError(e.toString());
return false;
}
}
@Override
public void printTargetRow() {
try {
if (printRow == null) {
return;
}
TextFileTools.writeLine(task(), fileWriter, printRow, delimiter);
} catch (Exception e) {
showError(e.toString());
}
}
@Override
public void finishWork() {
try {
if (fileWriter == null || printFile == null) {
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
fileWriter.flush();
fileWriter.close();
fileWriter = null;
if (isFailed() || tmpFile == null || !tmpFile.exists()) {
FileDeleteTools.delete(tmpFile);
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
if (targetRowIndex == 0) {
FileDeleteTools.delete(tmpFile);
showInfo(message("NoData") + ": " + printFile);
status = Status.NoData;
return;
}
if (!FileTools.override(tmpFile, printFile)) {
FileDeleteTools.delete(tmpFile);
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
if (printFile == null || !printFile.exists()) {
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
recordFileGenerated(printFile, VisitHistory.FileType.Text);
if (recordTargetData) {
recordTargetData();
}
status = Status.Created;
} catch (Exception e) {
showError(e.toString());
}
}
public void recordTargetData() {
try {
if (targetData == null) {
targetData = Data2D.create(Data2DDefinition.DataType.Texts);
}
targetData.setCharset(charset).setDelimiter(delimiter);
saveTargetData(writeHeader && headerNames != null, columns);
} catch (Exception e) {
showError(e.toString());
}
}
/*
get/set
*/
public Charset getCharset() {
return charset;
}
public DataFileTextWriter setCharset(Charset charset) {
this.charset = charset;
return this;
}
public String getDelimiter() {
return delimiter;
}
public DataFileTextWriter setDelimiter(String delimiter) {
this.delimiter = delimiter;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/writer/Data2DWriter.java | alpha/MyBox/src/main/java/mara/mybox/data2d/writer/Data2DWriter.java | package mara.mybox.data2d.writer;
import java.io.File;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.ControlTargetFile;
import mara.mybox.controller.Data2DManufactureController;
import mara.mybox.data2d.Data2D;
import mara.mybox.data2d.Data2D_Attributes.TargetType;
import static mara.mybox.data2d.Data2D_Attributes.TargetType.Append;
import static mara.mybox.data2d.Data2D_Attributes.TargetType.CSV;
import static mara.mybox.data2d.Data2D_Attributes.TargetType.DatabaseTable;
import static mara.mybox.data2d.Data2D_Attributes.TargetType.Excel;
import static mara.mybox.data2d.Data2D_Attributes.TargetType.HTML;
import static mara.mybox.data2d.Data2D_Attributes.TargetType.Insert;
import static mara.mybox.data2d.Data2D_Attributes.TargetType.JSON;
import static mara.mybox.data2d.Data2D_Attributes.TargetType.Matrix;
import static mara.mybox.data2d.Data2D_Attributes.TargetType.MyBoxClipboard;
import static mara.mybox.data2d.Data2D_Attributes.TargetType.PDF;
import static mara.mybox.data2d.Data2D_Attributes.TargetType.Replace;
import static mara.mybox.data2d.Data2D_Attributes.TargetType.SystemClipboard;
import static mara.mybox.data2d.Data2D_Attributes.TargetType.Text;
import static mara.mybox.data2d.Data2D_Attributes.TargetType.XML;
import mara.mybox.data2d.operate.Data2DOperate;
import mara.mybox.db.DerbyBase;
import mara.mybox.db.data.ColumnDefinition.InvalidAs;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.value.AppVariables;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-8-16
* @License Apache License Version 2.0
*/
public abstract class Data2DWriter {
protected Data2D targetData;
protected Data2DOperate operate;
protected File printFile, tmpFile;
protected ControlTargetFile targetFileController;
protected List<String> headerNames, printRow;
protected List<Data2DColumn> columns;
public boolean writeHeader, writeComments, validateValue,
formatValues, recordTargetFile, recordTargetData;
protected String indent = " ", dataName, fileSuffix, value, targetComments;
protected long targetRowIndex;
protected Connection conn;
protected int rowSize;
protected short targetScale;
protected int targetMaxRandom;
public InvalidAs invalidAs;
public Status status;
public enum Status {
Unknown, Openned, Writing, Created, NoData, Failed
}
public Data2DWriter() {
operate = null;
targetFileController = null;
formatValues = false;
validateValue = false;
writeHeader = writeComments = recordTargetFile = recordTargetData = true;
invalidAs = null;
targetData = null;
status = Status.Unknown;
}
public boolean checkParameters() {
if (operate != null) {
if (invalidAs == null) {
invalidAs = operate.getInvalidAs();
}
}
validateValue = AppVariables.rejectInvalidValueWhenSave;
// if ((targetComments == null || targetComments.isBlank())
// && operate != null && operate.getSourceData() != null) {
// targetComments = operate.getSourceData().getComments();
// }
return true;
}
public boolean resetWriter() {
targetRowIndex = 0;
status = Status.Unknown;
return true;
}
public boolean openWriter() {
if (!checkParameters()) {
return false;
}
resetWriter();
return true;
}
public void writeRow(List<String> inRow) {
try {
printRow = null;
if (inRow == null || inRow.isEmpty()) {
return;
}
printRow = new ArrayList<>();
rowSize = inRow.size();
for (int i = 0; i < columns.size(); i++) {
Data2DColumn column = columns.get(i);
value = i < rowSize ? inRow.get(i) : null;
if ((validateValue || invalidAs == InvalidAs.Fail)
&& !column.validValue(value)) {
failStop(message("InvalidData") + ". "
+ message("Column") + ":" + column.getColumnName() + " "
+ message("Value") + ": " + value);
return;
}
if (formatValues) {
value = column.formatString(value, invalidAs);
}
printRow.add(value);
}
printTargetRow();
targetRowIndex++;
if (targetRowIndex % 100 == 0) {
showInfo(message("Written") + ": " + targetRowIndex);
}
} catch (Exception e) {
showError(e.toString());
}
}
public void printTargetRow() {
}
public FxTask task() {
if (operate != null) {
return operate.getTask();
} else {
return null;
}
}
public long sourceRowIndex() {
if (operate != null) {
return operate.getSourceRowIndex();
} else {
return -1;
}
}
public void closeWriter() {
try {
finishWork();
if (operate == null && conn != null) {
conn.commit();
conn.close();
conn = null;
}
} catch (Exception e) {
showError(e.toString());
}
}
public void finishWork() {
}
/*
value/status
*/
public Connection conn() {
if (operate != null) {
conn = operate.conn();
} else {
conn = DerbyBase.getConnection();
}
return conn;
}
public Data2D sourceData() {
if (operate != null) {
return operate.getSourceData();
} else {
return null;
}
}
public boolean showResult() {
if (targetData == null) {
return false;
}
Data2DManufactureController.openDef(targetData);
if (operate != null && operate.getController() != null) {
operate.getController().setIconified(true);
}
return true;
}
public void showInfo(String info) {
if (operate != null) {
operate.showInfo(info);
}
}
public void recordFileGenerated(File file, int type) {
if (file == null || !file.exists()) {
return;
}
showInfo(message("Generated") + ": " + file + " "
+ message("FileSize") + ": " + file.length());
showInfo(message("RowsNumber") + ": " + targetRowIndex);
if (!recordTargetFile || operate == null) {
return;
}
BaseController c = operate.getController();
if (c != null) {
c.recordFileWritten(conn(), file, type, type);
}
operate.addPrintedFile(file);
}
public void saveTargetData(boolean hasHeader, List<Data2DColumn> saveColumns) {
try {
if (targetData == null) {
return;
}
targetData.setTask(task())
.setFile(printFile)
.setHasHeader(writeHeader && headerNames != null)
.setDataName(dataName)
.setColsNumber(columns.size())
.setRowsNumber(targetRowIndex)
.setComments(targetComments)
.setScale(targetScale)
.setMaxRandom(targetMaxRandom);
Data2D.saveAttributes(conn(), targetData, saveColumns);
} catch (Exception e) {
showError(e.toString());
}
}
final public void showError(String error) {
if (operate != null) {
operate.showError(error);
} else {
MyBoxLog.error(error);
}
}
public void stop() {
if (operate != null) {
operate.stop();
}
}
public void failStop(String error) {
if (operate != null) {
operate.failStop(error);
}
}
public void setFailed() {
if (operate != null) {
operate.setFailed();
}
}
public boolean isFailed() {
return operate != null && operate.isFailed();
}
public boolean isStopped() {
return operate != null && operate.isStopped();
}
public boolean isCompleted() {
return status == Status.Created || status == Status.NoData;
}
/*
static
*/
public static Data2DWriter getWriter(TargetType targetType) {
try {
if (targetType == null) {
return null;
}
Data2DWriter writer = null;
switch (targetType) {
case CSV:
writer = new DataFileCSVWriter();
break;
case Excel:
writer = new DataFileExcelWriter();
break;
case Text:
writer = new DataFileTextWriter();
break;
case Matrix:
writer = new DataMatrixWriter();
break;
case DatabaseTable:
writer = new DataTableWriter();
break;
case MyBoxClipboard:
writer = new MyBoxClipboardWriter();
break;
case SystemClipboard:
writer = new SystemClipboardWriter();
break;
case HTML:
writer = new HtmlWriter();
break;
case PDF:
writer = new PdfWriter();
break;
case JSON:
writer = new JsonWriter();
break;
case XML:
writer = new XmlWriter();
break;
case Replace:
case Insert:
case Append:
writer = new SystemClipboardWriter();
break;
}
return writer;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
/*
get/set
*/
public Data2D getTargetData() {
return targetData;
}
public Data2DWriter setTargetData(Data2D targetData) {
this.targetData = targetData;
return this;
}
public Data2DOperate getOperate() {
return operate;
}
public Data2DWriter setOperate(Data2DOperate operate) {
this.operate = operate;
return this;
}
public File getPrintFile() {
return printFile;
}
public Data2DWriter setPrintFile(File printFile) {
this.printFile = printFile;
return this;
}
public ControlTargetFile getTargetFileController() {
return targetFileController;
}
public Data2DWriter setTargetFileController(ControlTargetFile targetFileController) {
this.targetFileController = targetFileController;
return this;
}
public List<String> getHeaderNames() {
return headerNames;
}
public Data2DWriter setHeaderNames(List<String> headerNames) {
this.headerNames = headerNames;
return this;
}
public List<String> getPrintRow() {
return printRow;
}
public Data2DWriter setTargetRow(List<String> targetRow) {
this.printRow = targetRow;
return this;
}
public List<Data2DColumn> getColumns() {
return columns;
}
public Data2DWriter setColumns(List<Data2DColumn> columns) {
this.columns = columns;
return this;
}
public boolean isWriteHeader() {
return writeHeader;
}
public Data2DWriter setWriteHeader(boolean writeHeader) {
this.writeHeader = writeHeader;
return this;
}
public boolean isWriteComments() {
return writeComments;
}
public Data2DWriter setWriteComments(boolean writeComments) {
this.writeComments = writeComments;
return this;
}
public String getTargetComments() {
return targetComments;
}
public Data2DWriter setTargetComments(String targetComments) {
this.targetComments = targetComments;
return this;
}
public short getTargetScale() {
return targetScale;
}
public Data2DWriter setTargetScale(short targetScale) {
this.targetScale = targetScale;
return this;
}
public int getTargetMaxRandom() {
return targetMaxRandom;
}
public Data2DWriter setTargetMaxRandom(int targetMaxRandom) {
this.targetMaxRandom = targetMaxRandom;
return this;
}
public Status getStatus() {
return status;
}
public Data2DWriter setStatus(Status status) {
this.status = status;
return this;
}
public boolean isFormatValues() {
return formatValues;
}
public Data2DWriter setFormatValues(boolean formatValues) {
this.formatValues = formatValues;
return this;
}
public boolean isValidateValue() {
return validateValue;
}
public Data2DWriter setValidateValue(boolean validateValue) {
this.validateValue = validateValue;
return this;
}
public String getIndent() {
return indent;
}
public Data2DWriter setIndent(String indent) {
this.indent = indent;
return this;
}
public String getDataName() {
return dataName;
}
public Data2DWriter setDataName(String dataName) {
this.dataName = dataName;
return this;
}
public String getFileSuffix() {
return fileSuffix;
}
public Data2DWriter setFileSuffix(String fileSuffix) {
this.fileSuffix = fileSuffix;
return this;
}
public boolean isRecordTargetFile() {
return recordTargetFile;
}
public Data2DWriter setRecordTargetFile(boolean recordTargetFile) {
this.recordTargetFile = recordTargetFile;
return this;
}
public boolean isRecordTargetData() {
return recordTargetData;
}
public Data2DWriter setRecordTargetData(boolean recordTargetData) {
this.recordTargetData = recordTargetData;
return this;
}
public long getTargetRowIndex() {
return targetRowIndex;
}
public Data2DWriter setTargetRowIndex(long targetRowIndex) {
this.targetRowIndex = targetRowIndex;
return this;
}
public InvalidAs getInvalidAs() {
return invalidAs;
}
public void setInvalidAs(InvalidAs invalidAs) {
this.invalidAs = invalidAs;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/writer/DataFileCSVWriter.java | alpha/MyBox/src/main/java/mara/mybox/data2d/writer/DataFileCSVWriter.java | package mara.mybox.data2d.writer;
import java.io.FileWriter;
import java.nio.charset.Charset;
import mara.mybox.data2d.Data2D;
import mara.mybox.db.data.Data2DDefinition;
import mara.mybox.db.data.VisitHistory;
import mara.mybox.tools.CsvTools;
import mara.mybox.tools.FileDeleteTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.FileTools;
import static mara.mybox.value.Languages.message;
import org.apache.commons.csv.CSVPrinter;
/**
* @Author Mara
* @CreateDate 2022-1-29
* @License Apache License Version 2.0
*/
public class DataFileCSVWriter extends Data2DWriter {
protected CSVPrinter printer;
protected Charset charset;
protected String delimiter;
public DataFileCSVWriter() {
fileSuffix = "csv";
}
@Override
public boolean openWriter() {
try {
if (!super.openWriter()) {
return false;
}
if (printFile == null) {
showInfo(message("InvalidParameter") + ": " + message("TargetFile"));
return false;
}
showInfo(message("Writing") + " " + printFile.getAbsolutePath());
tmpFile = FileTmpTools.getTempFile(".csv");
if (charset == null) {
charset = Charset.forName("utf-8");
}
if (delimiter == null) {
delimiter = ",";
}
printer = new CSVPrinter(new FileWriter(tmpFile, charset),
CsvTools.csvFormat(delimiter));
if (writeComments && targetComments != null && !targetComments.isBlank()) {
printer.printComment(targetComments);
}
if (writeHeader && headerNames != null) {
printer.printRecord(headerNames);
}
status = Status.Openned;
return true;
} catch (Exception e) {
showError(e.toString());
return false;
}
}
@Override
public void printTargetRow() {
try {
if (printRow == null) {
return;
}
printer.printRecord(printRow);
} catch (Exception e) {
showError(e.toString());
}
}
@Override
public void finishWork() {
try {
if (printer == null || printFile == null) {
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
printer.flush();
printer.close();
printer = null;
if (isFailed() || tmpFile == null || !tmpFile.exists()) {
FileDeleteTools.delete(tmpFile);
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
if (targetRowIndex == 0) {
FileDeleteTools.delete(tmpFile);
showInfo(message("NoData") + ": " + printFile);
status = Status.NoData;
return;
}
if (!FileTools.override(tmpFile, printFile)) {
FileDeleteTools.delete(tmpFile);
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
if (printFile == null || !printFile.exists()) {
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
recordFileGenerated(printFile, VisitHistory.FileType.CSV);
if (recordTargetData) {
if (targetData == null) {
targetData = Data2D.create(Data2DDefinition.DataType.CSV);
}
targetData.setCharset(charset).setDelimiter(delimiter);
saveTargetData(writeHeader && headerNames != null, columns);
}
status = Status.Created;
} catch (Exception e) {
showError(e.toString());
}
}
/*
get/set
*/
public CSVPrinter getPrinter() {
return printer;
}
public Charset getCharset() {
return charset;
}
public DataFileCSVWriter setCharset(Charset cvsCharset) {
this.charset = cvsCharset;
return this;
}
public String getDelimiter() {
return delimiter;
}
public DataFileCSVWriter setDelimiter(String csvDelimiter) {
this.delimiter = csvDelimiter;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/writer/DataTableWriter.java | alpha/MyBox/src/main/java/mara/mybox/data2d/writer/DataTableWriter.java | package mara.mybox.data2d.writer;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.data2d.DataTable;
import mara.mybox.data2d.tools.Data2DTableTools;
import mara.mybox.db.Database;
import mara.mybox.db.data.Data2DRow;
import mara.mybox.db.table.TableData2D;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-1-29
* @License Apache License Version 2.0
*/
public class DataTableWriter extends Data2DWriter {
protected DataTable targetTable;
protected String targetTableName, targetTableDesciption;
protected List<String> keys;
protected String idName;
protected boolean dropExisted;
protected TableData2D tableData2D;
protected PreparedStatement insert;
@Override
public boolean openWriter() {
try {
if (!super.openWriter()) {
return false;
}
conn = conn();
if (conn == null) {
return false;
}
if (targetTable == null) {
targetTable = Data2DTableTools.createTable(task(), conn, targetTableName,
columns, keys, targetTableDesciption, idName, dropExisted);
if (targetTable == null) {
return false;
}
} else {
columns = targetTable.getColumns();
}
tableData2D = targetTable.getTableData2D();
conn.setAutoCommit(false);
targetRowIndex = 0;
String sql = tableData2D.insertStatement();
showInfo(sql);
insert = conn.prepareStatement(sql);
targetData = targetTable;
validateValue = true;
showInfo(message("Writing") + " " + targetTable.getName());
status = Status.Openned;
return true;
} catch (Exception e) {
showError(e.toString());
return false;
}
}
@Override
public void writeRow(List<String> inRow) {
try {
printRow = null;
if (inRow == null || inRow.isEmpty() || conn == null || targetTable == null) {
return;
}
printRow = new ArrayList<>();
Data2DRow data2DRow = targetTable.makeRow(inRow, this);
if (data2DRow == null || data2DRow.isEmpty()) {
return;
}
if (tableData2D.setInsertStatement(conn, insert, data2DRow)) {
insert.addBatch();
if (++targetRowIndex % Database.BatchSize == 0) {
insert.executeBatch();
conn.commit();
showInfo(message("Inserted") + ": " + targetRowIndex);
}
}
} catch (Exception e) {
showError(e.toString());
}
}
@Override
public void finishWork() {
try {
if (conn == null || targetTable == null || insert == null) {
showInfo(message("Failed"));
status = Status.Failed;
return;
}
if (isFailed()) {
insert.close();
showInfo(message("Failed"));
status = Status.Failed;
return;
}
insert.executeBatch();
conn.commit();
insert.close();
targetData = targetTable;
saveTargetData(targetTable.isHasHeader(), targetTable.getColumns());
showInfo(message("Generated") + ": " + targetTable.getSheet() + " "
+ message("RowsNumber") + ": " + targetRowIndex);
status = targetRowIndex == 0 ? Status.NoData : Status.Created;
} catch (Exception e) {
showError(e.toString());
}
}
/*
get/set
*/
public DataTable getTargetTable() {
return targetTable;
}
public DataTableWriter setTargetTable(DataTable targetTable) {
this.targetTable = targetTable;
return this;
}
public String getTargetTableName() {
return targetTableName;
}
public DataTableWriter setTargetTableName(String targetTableName) {
this.targetTableName = targetTableName;
return this;
}
public String getTargetTableDesciption() {
return targetTableDesciption;
}
public DataTableWriter setTargetTableDesciption(String targetTableDesciption) {
this.targetTableDesciption = targetTableDesciption;
return this;
}
public List<String> getKeys() {
return keys;
}
public DataTableWriter setKeys(List<String> keys) {
this.keys = keys;
return this;
}
public String getIdName() {
return idName;
}
public DataTableWriter setIdName(String idName) {
this.idName = idName;
return this;
}
public boolean isDropExisted() {
return dropExisted;
}
public DataTableWriter setDropExisted(boolean dropExisted) {
this.dropExisted = dropExisted;
return this;
}
public PreparedStatement getInsert() {
return insert;
}
public DataTableWriter setInsert(PreparedStatement insert) {
this.insert = insert;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/writer/DataFileExcelWriter.java | alpha/MyBox/src/main/java/mara/mybox/data2d/writer/DataFileExcelWriter.java | package mara.mybox.data2d.writer;
import java.io.File;
import java.io.FileOutputStream;
import mara.mybox.data2d.Data2D;
import static mara.mybox.data2d.DataFileExcel.CommentsMarker;
import mara.mybox.db.data.Data2DDefinition;
import mara.mybox.db.data.VisitHistory;
import mara.mybox.tools.FileCopyTools;
import mara.mybox.tools.FileDeleteTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.FileTools;
import static mara.mybox.value.Languages.message;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* @Author Mara
* @CreateDate 2022-1-29
* @License Apache License Version 2.0
*/
public class DataFileExcelWriter extends Data2DWriter {
protected Workbook xssfBook;
protected Sheet xssfSheet;
protected String sheetName;
protected boolean currentSheetOnly;
protected File baseFile;
protected int rowIndex;
public DataFileExcelWriter() {
fileSuffix = "xlsx";
currentSheetOnly = false;
}
@Override
public boolean openWriter() {
try {
if (!super.openWriter()) {
return false;
}
if (printFile == null) {
showInfo(message("InvalidParameter") + ": " + message("TargetFile"));
return false;
}
showInfo(message("Writing") + " " + printFile.getAbsolutePath());
tmpFile = FileTmpTools.getTempFile(".xlsx");
if (sheetName == null) {
sheetName = "sheet1";
}
if (!currentSheetOnly && baseFile != null && baseFile.exists()) {
try (Workbook sourceBook = WorkbookFactory.create(baseFile)) {
int sheetsNumber = sourceBook.getNumberOfSheets();
if (sheetsNumber == 1) {
xssfBook = new XSSFWorkbook();
xssfSheet = xssfBook.createSheet(sheetName);
} else {
FileCopyTools.copyFile(baseFile, tmpFile);
xssfBook = WorkbookFactory.create(tmpFile);
int index = sourceBook.getSheetIndex(sheetName);
if (index >= 0) {
xssfBook.removeSheetAt(index);
xssfSheet = xssfBook.createSheet(sheetName);
xssfBook.setSheetOrder(sheetName, index);
} else {
xssfSheet = xssfBook.createSheet(sheetName);
}
}
} catch (Exception e) {
showError(e.toString());
return false;
}
} else {
xssfBook = new XSSFWorkbook();
xssfSheet = xssfBook.createSheet(sheetName);
}
xssfSheet.setDefaultColumnWidth(20);
rowIndex = 0;
if (writeComments && targetComments != null && !targetComments.isBlank()) {
String[] rows = targetComments.split("\n");
for (String row : rows) {
Row commentsRow = xssfSheet.createRow(rowIndex++);
Cell cell = commentsRow.createCell(0, CellType.STRING);
cell.setCellValue(CommentsMarker + " " + row);
}
}
if (writeHeader && headerNames != null) {
Row titleRow = xssfSheet.createRow(rowIndex++);
CellStyle horizontalCenter = xssfBook.createCellStyle();
horizontalCenter.setAlignment(HorizontalAlignment.CENTER);
for (int i = 0; i < headerNames.size(); i++) {
Cell cell = titleRow.createCell(i, CellType.STRING);
cell.setCellValue(headerNames.get(i));
cell.setCellStyle(horizontalCenter);
}
}
status = Status.Openned;
return true;
} catch (Exception e) {
showError(e.toString());
return false;
}
}
@Override
public void printTargetRow() {
try {
if (printRow == null) {
return;
}
Row sheetRow = xssfSheet.createRow(rowIndex++);
for (int i = 0; i < printRow.size(); i++) {
Cell cell = sheetRow.createCell(i, CellType.STRING);
cell.setCellValue(printRow.get(i));
}
} catch (Exception e) {
showError(e.toString());
}
}
@Override
public void finishWork() {
try {
if (xssfBook == null || xssfSheet == null || tmpFile == null) {
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
for (int i = 0; i < headerNames.size(); i++) {
xssfSheet.autoSizeColumn(i);
}
try (FileOutputStream fileOut = new FileOutputStream(tmpFile)) {
xssfBook.write(fileOut);
}
xssfBook.close();
xssfBook = null;
if (isFailed() || !tmpFile.exists()) {
FileDeleteTools.delete(tmpFile);
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
if (targetRowIndex == 0) {
FileDeleteTools.delete(tmpFile);
showInfo(message("NoData") + ": " + printFile);
status = Status.NoData;
return;
}
if (!FileTools.override(tmpFile, printFile, true)) {
FileDeleteTools.delete(tmpFile);
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
if (printFile == null || !printFile.exists()) {
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
recordFileGenerated(printFile, VisitHistory.FileType.Excel);
if (recordTargetData) {
if (targetData == null) {
targetData = Data2D.create(Data2DDefinition.DataType.Excel);
}
targetData.setSheet(sheetName);
saveTargetData(writeHeader && headerNames != null, columns);
}
status = Status.Created;
} catch (Exception e) {
showError(e.toString());
}
}
/*
get/set
*/
public File getBaseFile() {
return baseFile;
}
public DataFileExcelWriter setBaseFile(File baseFile) {
this.baseFile = baseFile;
return this;
}
public String getSheetName() {
return sheetName;
}
public DataFileExcelWriter setSheetName(String sheetName) {
this.sheetName = sheetName;
return this;
}
public DataFileExcelWriter setCurrentSheetOnly(boolean currentSheetOnly) {
this.currentSheetOnly = currentSheetOnly;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/writer/PdfWriter.java | alpha/MyBox/src/main/java/mara/mybox/data2d/writer/PdfWriter.java | package mara.mybox.data2d.writer;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.controller.PdfViewController;
import mara.mybox.data.PaginatedPdfTable;
import mara.mybox.db.data.VisitHistory;
import mara.mybox.tools.FileDeleteTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.FileTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-1-29
* @License Apache License Version 2.0
*/
public class PdfWriter extends Data2DWriter {
protected PaginatedPdfTable pdfTable;
protected List<List<String>> pageRows;
public PdfWriter() {
fileSuffix = "pdf";
}
@Override
public boolean openWriter() {
try {
if (!super.openWriter()) {
return false;
}
if (printFile == null) {
showInfo(message("InvalidParameter") + ": " + message("TargetFile"));
return false;
}
showInfo(message("Writing") + " " + printFile.getAbsolutePath());
tmpFile = FileTmpTools.getTempFile(".pdf");
if (pdfTable == null) {
pdfTable = PaginatedPdfTable.create();
}
pdfTable.setColumns(headerNames).createDoc(tmpFile);
status = Status.Openned;
return true;
} catch (Exception e) {
showError(e.toString());
return false;
}
}
@Override
public void printTargetRow() {
try {
if (printRow == null) {
return;
}
if (pageRows == null) {
pageRows = new ArrayList<>();
}
if (pageRows.size() >= pdfTable.getRowsPerPage()) {
pdfTable.writePage(pageRows);
pageRows = new ArrayList<>();
}
pageRows.add(printRow);
} catch (Exception e) {
showError(e.toString());
}
}
@Override
public void finishWork() {
try {
if (pdfTable == null || printFile == null) {
showInfo(message("Failed") + ": " + printFile);
return;
}
if (pageRows != null && !pageRows.isEmpty()) {
pdfTable.writePage(pageRows);
}
pageRows = null;
pdfTable.closeDoc();
pdfTable = null;
if (isFailed() || tmpFile == null || !tmpFile.exists()) {
FileDeleteTools.delete(tmpFile);
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
if (targetRowIndex == 0) {
FileDeleteTools.delete(tmpFile);
showInfo(message("NoData") + ": " + printFile);
status = Status.NoData;
return;
}
if (!FileTools.override(tmpFile, printFile)) {
FileDeleteTools.delete(tmpFile);
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
if (printFile == null || !printFile.exists()) {
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
recordFileGenerated(printFile, VisitHistory.FileType.PDF);
status = Status.Created;
} catch (Exception e) {
showError(e.toString());
}
}
@Override
public boolean showResult() {
if (printFile == null || !printFile.exists()) {
return false;
}
PdfViewController.open(printFile);
return true;
}
/*
get/set
*/
public PaginatedPdfTable getPdfTable() {
return pdfTable;
}
public PdfWriter setPdfTable(PaginatedPdfTable pdfTable) {
this.pdfTable = pdfTable;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/writer/DataMatrixWriter.java | alpha/MyBox/src/main/java/mara/mybox/data2d/writer/DataMatrixWriter.java | package mara.mybox.data2d.writer;
import java.nio.charset.Charset;
import mara.mybox.data2d.Data2D;
import mara.mybox.data2d.DataMatrix;
import mara.mybox.db.data.Data2DDefinition;
/**
* @Author Mara
* @CreateDate 2025-3-17
* @License Apache License Version 2.0
*/
public class DataMatrixWriter extends DataFileTextWriter {
protected String dataType;
public DataMatrixWriter() {
fileSuffix = "txt";
}
@Override
public boolean openWriter() {
try {
charset = Charset.forName("utf-8");
delimiter = DataMatrix.MatrixDelimiter;
writeHeader = false;
return super.openWriter();
} catch (Exception e) {
showError(e.toString());
return false;
}
}
@Override
public void recordTargetData() {
try {
if (targetData == null) {
targetData = Data2D.create(Data2DDefinition.DataType.Matrix);
}
targetData.setCharset(charset).setDelimiter(delimiter)
.setSheet(dataType != null ? dataType : "Double");
saveTargetData(writeHeader && headerNames != null, columns);
} catch (Exception e) {
showError(e.toString());
}
}
/*
get/set
*/
public String getDataType() {
return dataType;
}
public DataMatrixWriter setDataType(String dataType) {
this.dataType = dataType;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/writer/JsonWriter.java | alpha/MyBox/src/main/java/mara/mybox/data2d/writer/JsonWriter.java | package mara.mybox.data2d.writer;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.nio.charset.Charset;
import mara.mybox.controller.JsonEditorController;
import mara.mybox.db.data.VisitHistory;
import mara.mybox.tools.FileDeleteTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.FileTools;
import mara.mybox.tools.JsonTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-1-29
* @License Apache License Version 2.0
*/
public class JsonWriter extends Data2DWriter {
protected BufferedWriter fileWriter;
protected boolean isFirstRow, isFirstField;
public JsonWriter() {
fileSuffix = "json";
}
@Override
public boolean openWriter() {
try {
if (!super.openWriter()) {
return false;
}
if (printFile == null) {
showInfo(message("InvalidParameter") + ": " + message("TargetFile"));
return false;
}
showInfo(message("Writing") + " " + printFile.getAbsolutePath());
tmpFile = FileTmpTools.getTempFile(".json");
fileWriter = new BufferedWriter(new FileWriter(tmpFile, Charset.forName("UTF-8")));
StringBuilder s = new StringBuilder();
s.append("{\"Data\": [\n");
fileWriter.write(s.toString());
isFirstRow = true;
status = Status.Openned;
return true;
} catch (Exception e) {
showError(e.toString());
return false;
}
}
@Override
public void printTargetRow() {
try {
if (printRow == null) {
return;
}
StringBuilder s = new StringBuilder();
if (isFirstRow) {
isFirstRow = false;
} else {
s.append(",\n");
}
s.append(indent).append("{").append("\n");
isFirstField = true;
for (int i = 0; i < headerNames.size(); i++) {
value = printRow.get(i);
if (value == null) {
continue;
}
if (isFirstField) {
isFirstField = false;
} else {
s.append(",\n");
}
s.append(indent).append(indent)
.append("\"").append(headerNames.get(i)).append("\": ")
.append(JsonTools.encode(value));
}
s.append(indent).append("\n").append(indent).append("}");
fileWriter.write(s.toString());
} catch (Exception e) {
showError(e.toString());
}
}
@Override
public void finishWork() {
try {
if (fileWriter == null || printFile == null) {
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
if (isFailed() || tmpFile == null || !tmpFile.exists()) {
fileWriter.close();
fileWriter = null;
FileDeleteTools.delete(tmpFile);
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
if (targetRowIndex == 0) {
fileWriter.close();
fileWriter = null;
FileDeleteTools.delete(tmpFile);
showInfo(message("NoData") + ": " + printFile);
status = Status.NoData;
return;
}
fileWriter.write("\n]}\n");
fileWriter.flush();
fileWriter.close();
fileWriter = null;
if (!FileTools.override(tmpFile, printFile)) {
FileDeleteTools.delete(tmpFile);
showInfo(message("Failed") + ": " + printFile);
status = Status.NoData;
return;
}
if (printFile == null || !printFile.exists()) {
showInfo(message("Failed") + ": " + printFile);
status = Status.NoData;
return;
}
recordFileGenerated(printFile, VisitHistory.FileType.JSON);
status = Status.Created;
} catch (Exception e) {
showError(e.toString());
}
}
@Override
public boolean showResult() {
if (printFile == null || !printFile.exists()) {
return false;
}
JsonEditorController.open(printFile);
return true;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/writer/SystemClipboardWriter.java | alpha/MyBox/src/main/java/mara/mybox/data2d/writer/SystemClipboardWriter.java | package mara.mybox.data2d.writer;
import java.util.List;
import mara.mybox.controller.BaseController;
import mara.mybox.fxml.TextClipboardTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-1-29
* @License Apache License Version 2.0
*/
public class SystemClipboardWriter extends Data2DWriter {
protected BaseController controller;
protected StringBuilder builder;
@Override
public boolean openWriter() {
try {
if (!super.openWriter()) {
return false;
}
showInfo(message("Writing") + " " + message("SystemClipboard"));
builder = new StringBuilder();
if (writeHeader && headerNames != null) {
appendRow(headerNames);
}
status = Status.Openned;
return true;
} catch (Exception e) {
showError(e.toString());
return false;
}
}
@Override
public void printTargetRow() {
appendRow(printRow);
}
public void appendRow(List<String> row) {
if (builder == null || row == null) {
return;
}
String s = null;
for (String v : row) {
if (s == null) {
s = v;
} else {
s += "," + v;
}
}
builder.append(s).append("\n");
}
@Override
public void finishWork() {
if (isFailed() || builder == null) {
showInfo(message("Failed"));
status = Status.Failed;
return;
}
if (targetRowIndex == 0 || builder.isEmpty()) {
showInfo(message("NoData"));
status = Status.NoData;
return;
}
status = Status.Created;
}
@Override
public boolean showResult() {
if (builder == null || builder.isEmpty()) {
return false;
}
TextClipboardTools.copyToSystemClipboard(
controller != null ? controller : operate.getController(),
builder.toString());
return true;
}
/*
set
*/
public SystemClipboardWriter setController(BaseController controller) {
this.controller = controller;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/writer/ListWriter.java | alpha/MyBox/src/main/java/mara/mybox/data2d/writer/ListWriter.java | package mara.mybox.data2d.writer;
import java.util.ArrayList;
import java.util.List;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-1-29
* @License Apache License Version 2.0
*/
public class ListWriter extends Data2DWriter {
protected List<List<String>> rows;
@Override
public boolean openWriter() {
try {
if (!super.openWriter()) {
return false;
}
showInfo(message("Writing") + " " + message("SystemClipboard"));
rows = new ArrayList<>();
if (writeHeader && headerNames != null) {
rows.add(headerNames);
}
status = Status.Openned;
return true;
} catch (Exception e) {
showError(e.toString());
return false;
}
}
@Override
public void printTargetRow() {
if (printRow == null) {
return;
}
rows.add(printRow);
}
@Override
public void finishWork() {
if (isFailed() || rows == null) {
showInfo(message("Failed"));
status = Status.Failed;
return;
}
if (targetRowIndex == 0 || rows.isEmpty()) {
showInfo(message("NoData"));
status = Status.NoData;
return;
}
status = Status.Created;
}
@Override
public boolean showResult() {
return true;
}
public List<List<String>> getRows() {
return rows;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/writer/XmlWriter.java | alpha/MyBox/src/main/java/mara/mybox/data2d/writer/XmlWriter.java | package mara.mybox.data2d.writer;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.nio.charset.Charset;
import mara.mybox.controller.XmlEditorController;
import mara.mybox.db.data.VisitHistory;
import mara.mybox.tools.FileDeleteTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.FileTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-1-29
* @License Apache License Version 2.0
*/
public class XmlWriter extends Data2DWriter {
protected BufferedWriter fileWriter;
public XmlWriter() {
fileSuffix = "xml";
}
@Override
public boolean openWriter() {
try {
if (!super.openWriter()) {
return false;
}
if (printFile == null) {
showInfo(message("InvalidParameter") + ": " + message("TargetFile"));
return false;
}
showInfo(message("Writing") + " " + printFile.getAbsolutePath());
tmpFile = FileTmpTools.getTempFile(".xml");
fileWriter = new BufferedWriter(new FileWriter(tmpFile, Charset.forName("UTF-8")));
StringBuilder s = new StringBuilder();
s.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
.append("<Data>\n");
fileWriter.write(s.toString());
status = Status.Openned;
return true;
} catch (Exception e) {
showError(e.toString());
return false;
}
}
@Override
public void printTargetRow() {
try {
if (printRow == null) {
return;
}
StringBuilder s = new StringBuilder();
s.append(indent).append("<Row>").append("\n");
for (int i = 0; i < headerNames.size(); i++) {
value = printRow.get(i);
if (value == null || value.isBlank()) {
continue;
}
s.append(indent).append(indent)
.append("<Col name=\"").append(headerNames.get(i)).append("\" >")
.append("<![CDATA[").append(value).append("]]>")
.append("</Col>").append("\n");
}
s.append(indent).append("</Row>").append("\n");
fileWriter.write(s.toString());
} catch (Exception e) {
showError(e.toString());
}
}
@Override
public void finishWork() {
try {
if (fileWriter == null || printFile == null) {
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
if (isFailed() || tmpFile == null || !tmpFile.exists()) {
fileWriter.close();
fileWriter = null;
FileDeleteTools.delete(tmpFile);
showInfo(message("Failed") + ": " + printFile);
status = Status.Failed;
return;
}
if (targetRowIndex == 0) {
fileWriter.close();
fileWriter = null;
FileDeleteTools.delete(tmpFile);
showInfo(message("NoData") + ": " + printFile);
status = Status.NoData;
return;
}
fileWriter.write("</Data>\n");
fileWriter.flush();
fileWriter.close();
fileWriter = null;
if (!FileTools.override(tmpFile, printFile)) {
FileDeleteTools.delete(tmpFile);
showInfo(message("Failed") + ": " + printFile);
status = Status.NoData;
return;
}
if (printFile == null || !printFile.exists()) {
showInfo(message("Failed") + ": " + printFile);
status = Status.NoData;
return;
}
recordFileGenerated(printFile, VisitHistory.FileType.XML);
status = Status.Created;
} catch (Exception e) {
showError(e.toString());
}
}
@Override
public boolean showResult() {
if (printFile == null) {
return false;
}
XmlEditorController.open(printFile);
return true;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/tools/Data2DConvertTools.java | alpha/MyBox/src/main/java/mara/mybox/data2d/tools/Data2DConvertTools.java | package mara.mybox.data2d.tools;
import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import mara.mybox.data.StringTable;
import mara.mybox.data2d.Data2D;
import mara.mybox.data2d.Data2D_Attributes;
import mara.mybox.data2d.DataFileCSV;
import mara.mybox.data2d.DataTable;
import mara.mybox.data2d.TmpTable;
import mara.mybox.data2d.operate.Data2DOperate;
import mara.mybox.data2d.operate.Data2DSingleColumn;
import mara.mybox.data2d.writer.DataFileCSVWriter;
import mara.mybox.db.DerbyBase;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.tools.CsvTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.FileTools;
import mara.mybox.tools.HtmlWriteTools;
import mara.mybox.tools.TextFileTools;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
/**
* @Author Mara
* @CreateDate 2023-9-12
* @License Apache License Version 2.0
*/
public class Data2DConvertTools {
public static File targetFile(String prefix, Data2D_Attributes.TargetType type) {
if (type == null) {
return null;
}
String ext;
switch (type) {
case Excel:
ext = "xlsx";
break;
case Text:
case Matrix:
ext = "txt";
break;
default:
ext = type.name().toLowerCase();
break;
}
return FileTmpTools.generateFile(prefix, ext);
}
public static DataFileCSV write(FxTask task, ResultSet results) {
try {
DataFileCSVWriter writer = new DataFileCSVWriter();
writer.setPrintFile(FileTmpTools.getTempFile(".csv"));
if (!Data2DTableTools.write(task, null, writer, results, null, 8, ColumnDefinition.InvalidAs.Empty)) {
return null;
}
return (DataFileCSV) writer.getTargetData();
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return null;
}
}
public static DataTable singleColumn(FxTask task, Data2D sourceData, List<Integer> cols) {
if (sourceData == null) {
return null;
}
try (Connection conn = DerbyBase.getConnection()) {
List<Data2DColumn> columns = sourceData.getColumns();
if (columns == null || columns.isEmpty()) {
sourceData.loadColumns(conn);
}
if (columns == null || columns.isEmpty()) {
return null;
}
List<Data2DColumn> referColumns = new ArrayList<>();
referColumns.add(new Data2DColumn("data", ColumnDefinition.ColumnType.Double));
DataTable dataTable = Data2DTableTools.createTable(task, conn,
TmpTable.tmpTableName(), referColumns, null, sourceData.getComments(), null, true);
dataTable.setDataName(sourceData.getName());
dataTable.copyDataAttributes(sourceData);
if (cols == null || cols.isEmpty()) {
cols = new ArrayList<>();
for (int i = 0; i < columns.size(); i++) {
cols.add(i);
}
}
Data2DOperate reader = Data2DSingleColumn.create(sourceData)
.setConn(conn).setWriterTable(dataTable)
.setCols(cols).setTask(task).start();
if (reader != null && !reader.isFailed()) {
conn.commit();
return dataTable;
} else {
return null;
}
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return null;
}
}
public static String toHtml(FxTask task, DataFileCSV data) {
StringTable table = new StringTable(data.getDataName());
File file = FileTools.removeBOM(task, data.getFile());
if (file == null) {
return null;
}
try (CSVParser parser = CSVParser.parse(file, data.getCharset(),
CsvTools.csvFormat(data.getDelimiter(), data.isHasHeader()))) {
if (data.isHasHeader()) {
List<String> names = parser.getHeaderNames();
table.setNames(names);
}
Iterator<CSVRecord> iterator = parser.iterator();
while (iterator.hasNext() && (task == null || task.isWorking())) {
CSVRecord csvRecord = iterator.next();
if (csvRecord == null) {
continue;
}
List<String> htmlRow = new ArrayList<>();
for (String v : csvRecord) {
htmlRow.add(v != null ? HtmlWriteTools.codeToHtml(v) : null);
}
table.add(htmlRow);
}
table.setComments(data.getComments());
return table.html();
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return null;
}
}
public static File toHtmlFile(FxTask task, DataFileCSV data, File htmlFile) {
String html = toHtml(task, data);
if (html == null) {
return null;
}
return TextFileTools.writeFile(htmlFile, html);
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/tools/Data2DPageTools.java | alpha/MyBox/src/main/java/mara/mybox/data2d/tools/Data2DPageTools.java | package mara.mybox.data2d.tools;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.data.StringTable;
import mara.mybox.data2d.Data2D;
import mara.mybox.data2d.DataFilter;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.style.HtmlStyles;
import mara.mybox.tools.HtmlWriteTools;
import mara.mybox.tools.StringTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2023-9-12
* @License Apache License Version 2.0
*/
public class Data2DPageTools {
public static String pageToHtml(Data2D data2d, DataFilter styleFilter,
boolean isForm, boolean showColumns, boolean showRowNumber, boolean showTitle) {
if (isForm) {
return pageToHtmlForm(data2d, styleFilter, showColumns, showRowNumber, showTitle);
} else {
return pageToHtmlTable(data2d, styleFilter, showColumns, showRowNumber, showTitle);
}
}
public static String pageToHtmlTable(Data2D data2d, DataFilter styleFilter,
boolean showColumns, boolean showRowNumber, boolean showTitle) {
try {
int rNumber = data2d.tableRowsNumber();
int cNumber = data2d.tableColsNumber();
if (rNumber <= 0 || cNumber <= 0) {
return null;
}
List<String> names;
if (showColumns) {
names = new ArrayList<>();
if (showRowNumber) {
names.add(message("TableRowNumber"));
names.add(message("DataRowNumber"));
}
for (int i = 0; i < cNumber; i++) {
names.add(data2d.columnLabel(i));
}
} else {
names = null;
}
StringTable table = new StringTable(names);
if (showTitle) {
table.setTitle(data2d.printName())
.setComments(data2d.getComments());
}
for (int i = 0; i < rNumber; i++) {
List<String> pageRow = data2d.pageRow(i, true);
List<String> htmlRow = new ArrayList<>();
if (showRowNumber) {
htmlRow.add("" + (i + 1));
htmlRow.add(pageRow.get(0));
}
for (int col = 0; col < cNumber; col++) {
String value = pageRow.get(col + 1);
value = value == null ? "" : HtmlWriteTools.codeToHtml(value);
String style = data2d.cellStyle(styleFilter, i, data2d.columnName(col));
if (style != null && !style.isBlank()) {
style = style.replace("-fx-font-size:", "font-size:")
.replace("-fx-text-fill:", "color:")
.replace("-fx-background-color:", "background-color:")
.replace("-fx-font-weight: bolder", "font-weight:bold");
value = "<SPAN style=\"" + style + "\">" + value + "</SPAN>";
}
htmlRow.add(value);
}
table.add(htmlRow);
}
return table.html();
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static String pageToHtmlForm(Data2D data2d, DataFilter styleFilter,
boolean showColumns, boolean showRowNumber, boolean showTitle) {
try {
int rNumber = data2d.tableRowsNumber();
int cNumber = data2d.tableColsNumber();
if (rNumber <= 0 || cNumber <= 0) {
return null;
}
StringBuilder s = new StringBuilder();
if (showTitle) {
s.append("<H2>").append(HtmlWriteTools.codeToHtml(data2d.printName())).append("</H2>\n");
if (data2d.getComments() != null) {
s.append("<P>").append(HtmlWriteTools.codeToHtml(data2d.getComments())).append("</P>\n");
}
}
for (int r = 0; r < rNumber; r++) {
StringTable table = new StringTable();
List<String> dataRow = data2d.pageRow(r, true);
if (showRowNumber) {
List<String> htmlRow = new ArrayList<>();
if (showColumns) {
htmlRow.add(message("TableRowNumber"));
}
htmlRow.add("" + (r + 1));
table.add(htmlRow);
htmlRow = new ArrayList<>();
if (showColumns) {
htmlRow.add(message("DataRowNumber"));
}
htmlRow.add(dataRow.get(0));
table.add(htmlRow);
}
for (int col = 0; col < cNumber; col++) {
List<String> htmlRow = new ArrayList<>();
if (showColumns) {
htmlRow.add(data2d.columnLabel(col));
}
String value = dataRow.get(col + 1);
value = value == null ? "" : HtmlWriteTools.codeToHtml(value);
String style = data2d.cellStyle(styleFilter, r, data2d.columnName(col));
if (style != null && !style.isBlank()) {
style = style.replace("-fx-font-size:", "font-size:")
.replace("-fx-text-fill:", "color:")
.replace("-fx-background-color:", "background-color:")
.replace("-fx-font-weight: bolder", "font-weight:bold");
value = "<SPAN style=\"" + style + "\">" + value + "</SPAN>";
}
htmlRow.add(value);
table.add(htmlRow);
}
s.append(table.div()).append("\n<BR><BR>\n");
}
return HtmlWriteTools.html(data2d.getTitle(),
"utf-8", HtmlStyles.DefaultStyle, s.toString());
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static String pageToTexts(Data2D data2d, String delimiterName,
boolean isForm, boolean showColumns, boolean showRowNumber, boolean showTitle) {
if (isForm) {
return pageToTextsForm(data2d, showColumns, showRowNumber, showTitle);
} else {
return pageToTextsTable(data2d, delimiterName, showColumns, showRowNumber, showTitle);
}
}
public static String pageToTextsTable(Data2D data2d, String delimiterName,
boolean showColumns, boolean showRowNumber, boolean showTitle) {
String texts = data2d.encodeCSV(null, delimiterName,
showRowNumber, showColumns, true);
if (texts == null) {
texts = "";
}
if (showTitle) {
if (data2d.getComments() != null) {
texts = data2d.getComments() + "\n\n" + texts;
}
texts = data2d.printName() + "\n\n" + texts;
}
return texts;
}
public static String pageToTextsForm(Data2D data2d,
boolean showColumns, boolean showRowNumber, boolean showTitle) {
StringBuilder s = new StringBuilder();
if (showTitle) {
s.append(data2d.printName()).append("\n\n");
if (data2d.getComments() != null) {
s.append(data2d.getComments()).append("\n\n");
}
}
for (int r = 0; r < data2d.tableRowsNumber(); r++) {
List<String> drow = data2d.pageRow(r, true);
if (drow == null) {
continue;
}
if (showRowNumber) {
if (showColumns) {
s.append(message("TableRowNumber")).append(": ");
}
s.append(r + 1).append("\n");
if (showColumns) {
s.append(message("DataRowNumber")).append(": ");
}
s.append(drow.get(0)).append("\n");
}
for (int col = 0; col < data2d.columnsNumber(); col++) {
if (showColumns) {
s.append(data2d.columnName(col)).append(": ");
}
String v = drow.get(col + 1);
if (v == null) {
continue;
}
s.append(StringTools.replaceLineBreak(v, "\\\\n")).append("\n");
}
s.append("\n");
}
return s.toString();
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/tools/Data2DColumnTools.java | alpha/MyBox/src/main/java/mara/mybox/data2d/tools/Data2DColumnTools.java | package mara.mybox.data2d.tools;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javafx.event.ActionEvent;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import mara.mybox.controller.ControlData2DColumns;
import mara.mybox.data.StringTable;
import mara.mybox.data2d.Data2D;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.dev.MyBoxLog;
import static mara.mybox.fxml.style.NodeStyleTools.attributeTextStyle;
import mara.mybox.fxml.style.StyleTools;
import mara.mybox.tools.StringTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2023-9-12
* @License Apache License Version 2.0
*/
public class Data2DColumnTools {
public static List<String> toNames(List<Data2DColumn> cols) {
return toNames(cols, false);
}
public static List<String> toNames(List<Data2DColumn> cols, boolean asLabel) {
try {
if (cols == null) {
return null;
}
List<String> names = new ArrayList<>();
for (Data2DColumn c : cols) {
names.add(asLabel ? c.getLabel() : c.getColumnName());
}
return names;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static List<Data2DColumn> toColumns(List<String> names) {
try {
if (names == null) {
return null;
}
List<Data2DColumn> cols = new ArrayList<>();
int index = -1;
for (String c : names) {
Data2DColumn col = new Data2DColumn(c, ColumnDefinition.ColumnType.String);
col.setIndex(index--);
cols.add(col);
}
return cols;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static StringTable validate(List<Data2DColumn> columns) {
try {
if (columns == null || columns.isEmpty()) {
return null;
}
List<String> colsNames = new ArrayList<>();
List<String> tNames = new ArrayList<>();
tNames.addAll(Arrays.asList(message("ID"), message("Name"), message("Reason")));
StringTable colsTable = new StringTable(tNames, message("InvalidColumns"));
for (int c = 0; c < columns.size(); c++) {
Data2DColumn column = columns.get(c);
if (!column.valid()) {
List<String> row = new ArrayList<>();
row.addAll(Arrays.asList(c + 1 + "", column.getColumnName(), message("Invalid")));
colsTable.add(row);
}
if (colsNames.contains(column.getColumnName())) {
List<String> row = new ArrayList<>();
row.addAll(Arrays.asList(c + 1 + "", column.getColumnName(), message("Duplicated")));
colsTable.add(row);
}
colsNames.add(column.getColumnName());
}
return colsTable;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static String columnInfo(Data2DColumn column) {
try {
if (column == null) {
return null;
}
StringBuilder s = new StringBuilder();
s.append("Column ID").append(": ").append(column.getColumnID()).append("\n");
s.append("Data ID").append(": ").append(column.getDataID()).append("\n");
s.append(ColumnDefinition.info(column));
return s.toString();
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static String dataInfo(Data2D data2D) {
try {
if (data2D == null) {
return null;
}
StringBuilder s = new StringBuilder();
for (Data2DColumn column : data2D.getColumns()) {
s.append(Data2DColumnTools.columnInfo(column));
s.append("----------------------------------");
}
return s.toString();
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static String majorAttributes(Data2DColumn column) {
try {
if (column == null) {
return null;
}
return column.getIndex() + " " + column.getColumnName() + " " + column.getType();
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static List<MenuItem> operationsMenus(ControlData2DColumns columnsController) {
try {
Data2D data2D = columnsController.getData2D();
if (data2D == null) {
return null;
}
List<MenuItem> items = new ArrayList<>();
MenuItem menu;
menu = new MenuItem(message("Recover"), StyleTools.getIconImageView("iconRecover.png"));
menu.setOnAction((ActionEvent event) -> {
columnsController.recoverAction();
});
items.add(menu);
items.add(new SeparatorMenuItem());
menu = new MenuItem(StringTools.menuPrefix(message("SelectRowsComments")));
menu.setStyle(attributeTextStyle());
items.add(menu);
menu = new MenuItem(message("CopyNamesToLabels"), StyleTools.getIconImageView("iconEqual.png"));
menu.setOnAction((ActionEvent event) -> {
columnsController.copyNamesToLabels();
});
items.add(menu);
if (!data2D.isTable()) {
menu = new MenuItem(message("CopyLabelsToNames"), StyleTools.getIconImageView("iconEqual.png"));
menu.setOnAction((ActionEvent event) -> {
columnsController.copyLabelsToNames();
});
items.add(menu);
menu = new MenuItem(message("FirstLineDefineNames"), StyleTools.getIconImageView("iconHeader.png"));
menu.setOnAction((ActionEvent event) -> {
columnsController.headerNames();
});
items.add(menu);
menu = new MenuItem(message("RenameWithNumbers"), StyleTools.getIconImageView("iconNumber.png"));
menu.setOnAction((ActionEvent event) -> {
columnsController.numberColumns();
});
items.add(menu);
}
menu = new MenuItem(message("RandomColors"), StyleTools.getIconImageView("iconRandom.png"));
menu.setOnAction((ActionEvent event) -> {
columnsController.randomColors();
});
items.add(menu);
return items;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/tools/Data2DRowTools.java | alpha/MyBox/src/main/java/mara/mybox/data2d/tools/Data2DRowTools.java | package mara.mybox.data2d.tools;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.db.data.Data2DRow;
/**
* @Author Mara
* @CreateDate 2023-9-12
* @License Apache License Version 2.0
*/
public class Data2DRowTools {
public static List<String> toStrings(Data2DRow drow, List<Data2DColumn> columns) {
List<String> row = new ArrayList<>();
for (Data2DColumn column : columns) {
Object value = drow.getValue(column.getColumnName());
row.add(column.toString(value));
}
return row;
}
public static Map<String, String> toNameValues(Data2DRow drow, List<Data2DColumn> columns) {
Map<String, String> values = new HashMap<>();
for (Data2DColumn column : columns) {
Object value = drow.getValue(column.getColumnName());
values.put(column.getColumnName(), column.toString(value));
}
return values;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/tools/Data2DMenuTools.java | alpha/MyBox/src/main/java/mara/mybox/data2d/tools/Data2DMenuTools.java | package mara.mybox.data2d.tools;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.CheckMenuItem;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import mara.mybox.controller.BaseData2DLoadController;
import mara.mybox.controller.Data2DManufactureController;
import mara.mybox.controller.DataFileCSVFormatController;
import mara.mybox.controller.DataFileExcelFormatController;
import mara.mybox.controller.DataFileExcelSheetsController;
import mara.mybox.controller.DataFileTextFormatController;
import mara.mybox.controller.FileBrowseController;
import mara.mybox.controller.MatricesBinaryCalculationController;
import mara.mybox.controller.MatrixUnaryCalculationController;
import mara.mybox.data2d.Data2D;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.HelpTools;
import mara.mybox.fxml.menu.MenuTools;
import static mara.mybox.fxml.style.NodeStyleTools.attributeTextStyle;
import mara.mybox.fxml.style.StyleTools;
import mara.mybox.value.AppVariables;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2022-9-15
* @License Apache License Version 2.0
*/
public class Data2DMenuTools {
public static List<MenuItem> dataMenus(Data2DManufactureController dataController) {
try {
Data2D data2D = dataController.getData2D();
if (dataController.invalidData()) {
return null;
}
List<MenuItem> items = MenuTools.initMenu(message("Data"));
boolean isTmpData = data2D.isTmpData();
boolean notLoaded = !dataController.isDataSizeLoaded();
MenuItem menu;
items.add(new SeparatorMenuItem());
menu = new MenuItem(message("DefineData"), StyleTools.getIconImageView("iconMeta.png"));
menu.setOnAction((ActionEvent event) -> {
dataController.definitionAction();
});
menu.setDisable(notLoaded);
items.add(menu);
menu = new MenuItem(message("Save") + " Ctrl+S " + message("Or") + " Alt+S",
StyleTools.getIconImageView("iconSave.png"));
menu.setOnAction((ActionEvent event) -> {
dataController.saveAction();
});
menu.setDisable(notLoaded);
items.add(menu);
items.add(new SeparatorMenuItem());
menu = new MenuItem(message("Recover") + " Ctrl+R " + message("Or") + " Alt+R",
StyleTools.getIconImageView("iconRecover.png"));
menu.setOnAction((ActionEvent event) -> {
dataController.recoverAction();
});
menu.setDisable(isTmpData);
items.add(menu);
menu = new MenuItem(message("Refresh"), StyleTools.getIconImageView("iconRefresh.png"));
menu.setOnAction((ActionEvent event) -> {
dataController.refreshAction();
});
menu.setDisable(isTmpData);
items.add(menu);
items.add(new SeparatorMenuItem());
menu = new MenuItem(message("SaveAs") + " Ctrl+B " + message("Or") + " Alt+B",
StyleTools.getIconImageView("iconSaveAs.png"));
menu.setOnAction((ActionEvent event) -> {
dataController.saveAsAction();
});
items.add(menu);
menu = new MenuItem(message("Export"), StyleTools.getIconImageView("iconExport.png"));
menu.setOnAction((ActionEvent event) -> {
dataController.exportAction();
});
items.add(menu);
if (dataController.isTableMode()) {
menu = new MenuItem(message("SnapshotWindow"), StyleTools.getIconImageView("iconSnapshot.png"));
menu.setOnAction((ActionEvent event) -> {
dataController.snapAction();
});
items.add(menu);
}
items.add(new SeparatorMenuItem());
CheckMenuItem tmpItem = new CheckMenuItem(message("Data2DTmpDataUnderGeneratedPath"));
tmpItem.setSelected(UserConfig.getBoolean("Data2DTmpDataUnderGeneratedPath", false));
tmpItem.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
UserConfig.setBoolean("Data2DTmpDataUnderGeneratedPath", tmpItem.isSelected());
}
});
items.add(tmpItem);
CheckMenuItem asktmpItem = new CheckMenuItem(message("PromptTemporaryWhenClose"));
asktmpItem.setSelected(UserConfig.getBoolean("Data2DPromptTemporaryWhenClose", true));
asktmpItem.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
UserConfig.setBoolean("Data2DPromptTemporaryWhenClose", asktmpItem.isSelected());
}
});
items.add(asktmpItem);
return items;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static List<MenuItem> operationsMenus(Data2DManufactureController dataController) {
try {
if (!dataController.hasColumns()) {
return null;
}
Data2D data2D = dataController.getData2D();
List<MenuItem> items = MenuTools.initMenu(message("Operation"));
boolean isTmp = data2D.isTmpData() || data2D.isTmpFile();
boolean noneSelected = dataController.isNoneSelected();
boolean isTableMode = dataController.isTableMode();
MenuItem menu;
menu = new MenuItem(message("AddRows") + " CTRL+N / ALT+N",
StyleTools.getIconImageView("iconNewItem.png"));
menu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
dataController.addRowsAction();
}
});
items.add(menu);
if (isTableMode) {
menu = new MenuItem(message("EditSelectedRow"), StyleTools.getIconImageView("iconEdit.png"));
menu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
dataController.editAction();
}
});
menu.setDisable(noneSelected);
items.add(menu);
menu = new MenuItem(message("DeleteSelectedRows") + " DELETE / CTRL+D / ALT+D", StyleTools.getIconImageView("iconDelete.png"));
menu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
dataController.deleteRowsAction();
}
});
menu.setDisable(noneSelected);
items.add(menu);
menu = new MenuItem(message("MoveDown"), StyleTools.getIconImageView("iconDown.png"));
menu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
dataController.moveDownAction();
}
});
menu.setDisable(noneSelected);
items.add(menu);
menu = new MenuItem(message("MoveUp"), StyleTools.getIconImageView("iconUp.png"));
menu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
dataController.moveUpAction();
}
});
menu.setDisable(noneSelected);
items.add(menu);
}
menu = new MenuItem(message("Clear") + " CTRL+L / ALT+L", StyleTools.getIconImageView("iconClear.png"));
menu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
dataController.clearAction();
}
});
items.add(menu);
items.add(new SeparatorMenuItem());
menu = new MenuItem(message("SetValues"), StyleTools.getIconImageView("iconEqual.png"));
menu.setOnAction((ActionEvent event) -> {
dataController.setValue();
});
items.add(menu);
menu = new MenuItem(message("DeleteWithConditions"), StyleTools.getIconImageView("iconDelete.png"));
menu.setOnAction((ActionEvent event) -> {
dataController.delete();
});
items.add(menu);
menu = new MenuItem(message("SetStyles"), StyleTools.getIconImageView("iconColor.png"));
menu.setOnAction((ActionEvent event) -> {
dataController.setStyles();
});
menu.setDisable(isTmp);
items.add(menu);
items.add(new SeparatorMenuItem());
menu = new MenuItem(message("CopyToSystemClipboard"), StyleTools.getIconImageView("iconCopySystem.png"));
menu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
dataController.copyToSystemClipboard();
}
});
items.add(menu);
menu = new MenuItem(message("PasteContentInSystemClipboard"), StyleTools.getIconImageView("iconPasteSystem.png"));
menu.setOnAction((ActionEvent event) -> {
dataController.pasteContentInSystemClipboard();
});
items.add(menu);
menu = new MenuItem(message("PasteContentInMyBoxClipboard"), StyleTools.getIconImageView("iconPaste.png"));
menu.setOnAction((ActionEvent event) -> {
dataController.pasteContentInMyboxClipboard();
});
items.add(menu);
if (isTableMode) {
items.add(new SeparatorMenuItem());
CheckMenuItem focusMenu = new CheckMenuItem(message("CommitModificationWhenDataCellLoseFocus"),
StyleTools.getIconImageView("iconInput.png"));
focusMenu.setSelected(AppVariables.commitModificationWhenDataCellLoseFocus);
focusMenu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
AppVariables.lostFocusCommitData(focusMenu.isSelected());
}
});
items.add(focusMenu);
}
return items;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static List<MenuItem> fileMenus(BaseData2DLoadController dataController) {
try {
Data2D data2D = dataController.getData2D();
if (dataController.invalidData() || !data2D.isDataFile()) {
return null;
}
File file = data2D.getFile();
if (file == null) {
return null;
}
List<MenuItem> items = MenuTools.initMenu(message("File"));
MenuItem menu;
if (data2D.isExcel()) {
menu = new MenuItem(message("Sheet"), StyleTools.getIconImageView("iconFrame.png"));
menu.setOnAction((ActionEvent menuItemEvent) -> {
DataFileExcelSheetsController.open(dataController);
});
items.add(menu);
}
if (!data2D.isMatrix()) {
menu = new MenuItem(message("Format"), StyleTools.getIconImageView("iconFormat.png"));
menu.setOnAction((ActionEvent menuItemEvent) -> {
if (data2D.isCSV()) {
DataFileCSVFormatController.open(dataController);
} else if (data2D.isTexts()) {
DataFileTextFormatController.open(dataController);
} else if (data2D.isExcel()) {
DataFileExcelFormatController.open(dataController);
}
});
items.add(menu);
menu = new MenuItem(message("ClearDefinitionReloadFile"), StyleTools.getIconImageView("iconRefresh.png"));
menu.setOnAction((ActionEvent menuItemEvent) -> {
data2D.deleteDataDefinition();
dataController.loadDef(data2D);
});
items.add(menu);
}
CheckMenuItem backItem = new CheckMenuItem(message("BackupWhenSave"));
backItem.setSelected(UserConfig.getBoolean("Data2DFileBackupWhenSave", true));
backItem.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
UserConfig.setBoolean("Data2DFileBackupWhenSave", backItem.isSelected());
}
});
items.add(backItem);
menu = new MenuItem(message("FileBackups"), StyleTools.getIconImageView("iconBackup.png"));
menu.setOnAction((ActionEvent menuItemEvent) -> {
dataController.openBackups("Data2DFileBackupWhenSave");
});
items.add(menu);
items.add(new SeparatorMenuItem());
menu = new MenuItem(message("SaveAs") + " Ctrl+B " + message("Or") + " Alt+B",
StyleTools.getIconImageView("iconSaveAs.png"));
menu.setOnAction((ActionEvent event) -> {
dataController.saveAsAction();
});
items.add(menu);
if (data2D.isTextFile()) {
menu = new MenuItem(message("Texts"), StyleTools.getIconImageView("iconTxt.png"));
menu.setOnAction((ActionEvent event) -> {
dataController.editTextFile();
});
items.add(menu);
}
items.add(new SeparatorMenuItem());
menu = new MenuItem(message("OpenDirectory"), StyleTools.getIconImageView("iconOpenPath.png"));
menu.setOnAction((ActionEvent event) -> {
dataController.openSourcePath();
});
items.add(menu);
menu = new MenuItem(message("BrowseFiles"), StyleTools.getIconImageView("iconList.png"));
menu.setOnAction((ActionEvent event) -> {
FileBrowseController.open(dataController);
});
items.add(menu);
menu = new MenuItem(message("SystemMethod"), StyleTools.getIconImageView("iconSystemOpen.png"));
menu.setOnAction((ActionEvent event) -> {
dataController.systemMethod();
});
items.add(menu);
return items;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static List<MenuItem> verifyMenus(Data2DManufactureController dataController) {
try {
if (!dataController.hasColumns()) {
return null;
}
List<MenuItem> items = MenuTools.initMenu(message("Verify"));
MenuItem menu = new MenuItem(message("VerifyCurrentPage"));
menu.setOnAction((ActionEvent event) -> {
dataController.verifyCurrentPage();
});
items.add(menu);
menu = new MenuItem(message("VerifyAllData"));
menu.setOnAction((ActionEvent event) -> {
dataController.verifyAllData();
});
items.add(menu);
if (dataController.getData2D().alwayRejectInvalid()) {
return items;
}
CheckMenuItem validateEditItem = new CheckMenuItem(message("RejectInvalidValueWhenEdit"));
validateEditItem.setSelected(AppVariables.rejectInvalidValueWhenEdit);
validateEditItem.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
AppVariables.rejectInvalidValueWhenEdit = validateEditItem.isSelected();
UserConfig.setBoolean("Data2DValidateEdit", AppVariables.rejectInvalidValueWhenEdit);
}
});
items.add(validateEditItem);
CheckMenuItem validateSaveItem = new CheckMenuItem(message("RejectInvalidValueWhenSave"));
validateSaveItem.setSelected(AppVariables.rejectInvalidValueWhenSave);
validateSaveItem.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
AppVariables.rejectInvalidValueWhenSave = validateSaveItem.isSelected();
UserConfig.setBoolean("Data2DValidateSave", AppVariables.rejectInvalidValueWhenSave);
}
});
items.add(validateSaveItem);
return items;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static List<MenuItem> trimMenus(BaseData2DLoadController controller) {
try {
if (!controller.hasColumns()) {
return null;
}
Data2D data2D = controller.getData2D();
List<MenuItem> items = MenuTools.initMenu(message("Trim"));
MenuItem menu;
if (data2D.isTable()) {
menu = new MenuItem(message("Query"), StyleTools.getIconImageView("iconQuery.png"));
menu.setOnAction((ActionEvent event) -> {
controller.queryTable();
});
items.add(menu);
}
menu = new MenuItem(message("CopyFilterQueryConvert"), StyleTools.getIconImageView("iconCopy.png"));
menu.setOnAction((ActionEvent event) -> {
controller.copyAction();
});
items.add(menu);
menu = new MenuItem(message("Sort"), StyleTools.getIconImageView("iconSort.png"));
menu.setOnAction((ActionEvent event) -> {
controller.sortAction();
});
items.add(menu);
menu = new MenuItem(message("Transpose"), StyleTools.getIconImageView("iconRotateRight.png"));
menu.setOnAction((ActionEvent event) -> {
controller.transposeAction();
});
items.add(menu);
menu = new MenuItem(message("Normalize"), StyleTools.getIconImageView("iconBinary.png"));
menu.setOnAction((ActionEvent event) -> {
controller.normalizeAction();
});
items.add(menu);
menu = new MenuItem(message("SplitGroup"), StyleTools.getIconImageView("iconSplit.png"));
menu.setOnAction((ActionEvent event) -> {
controller.groupAction();
});
items.add(menu);
return items;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static List<MenuItem> calMenus(BaseData2DLoadController controller) {
try {
if (!controller.hasColumns()) {
return null;
}
Data2D data2D = controller.getData2D();
List<MenuItem> items = MenuTools.initMenu(message("Calculation"));
MenuItem menu;
if (data2D.isMatrix()) {
menu = new MenuItem(message("MatrixUnaryCalculation"), StyleTools.getIconImageView("iconMatrix.png"));
menu.setOnAction((ActionEvent event) -> {
MatrixUnaryCalculationController.open(controller);
});
items.add(menu);
menu = new MenuItem(message("MatricesBinaryCalculation"), StyleTools.getIconImageView("iconMatrix.png"));
menu.setOnAction((ActionEvent event) -> {
MatricesBinaryCalculationController.open(controller);
});
items.add(menu);
}
menu = new MenuItem(message("RowExpression"), StyleTools.getIconImageView("iconNewItem.png"));
menu.setOnAction((ActionEvent event) -> {
controller.rowExpressionAction();
});
items.add(menu);
menu = new MenuItem(message("DescriptiveStatistics"), StyleTools.getIconImageView("iconStatistic.png"));
menu.setOnAction((ActionEvent event) -> {
controller.descriptiveStatisticAction();
});
items.add(menu);
menu = new MenuItem(message("GroupStatistic"), StyleTools.getIconImageView("iconAnalyse.png"));
menu.setOnAction((ActionEvent event) -> {
controller.groupStatisticAction();
});
items.add(menu);
menu = new MenuItem(message("SimpleLinearRegression"), StyleTools.getIconImageView("iconLinearPgression.png"));
menu.setOnAction((ActionEvent event) -> {
controller.simpleLinearRegression();
});
items.add(menu);
menu = new MenuItem(message("SimpleLinearRegressionCombination"), StyleTools.getIconImageView("iconLinearPgression.png"));
menu.setOnAction((ActionEvent event) -> {
controller.simpleLinearRegressionCombination();
});
items.add(menu);
menu = new MenuItem(message("MultipleLinearRegression"), StyleTools.getIconImageView("iconLinearPgression.png"));
menu.setOnAction((ActionEvent event) -> {
controller.multipleLinearRegression();
});
items.add(menu);
menu = new MenuItem(message("MultipleLinearRegressionCombination"), StyleTools.getIconImageView("iconLinearPgression.png"));
menu.setOnAction((ActionEvent event) -> {
controller.multipleLinearRegressionCombination();
});
items.add(menu);
menu = new MenuItem(message("FrequencyDistributions"), StyleTools.getIconImageView("iconDistribution.png"));
menu.setOnAction((ActionEvent event) -> {
controller.frequencyDistributions();
});
items.add(menu);
menu = new MenuItem(message("ValuePercentage"), StyleTools.getIconImageView("iconPercentage.png"));
menu.setOnAction((ActionEvent event) -> {
controller.valuePercentage();
});
items.add(menu);
return items;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static List<MenuItem> chartMenus(BaseData2DLoadController controller) {
try {
if (!controller.hasColumns()) {
return null;
}
Data2D data2D = controller.getData2D();
List<MenuItem> items = MenuTools.initMenu(message("Chart"));
MenuItem menu;
menu = new MenuItem(message("XYChart"), StyleTools.getIconImageView("iconXYChart.png"));
menu.setOnAction((ActionEvent event) -> {
controller.xyChart();
});
items.add(menu);
menu = new MenuItem(message("BubbleChart"), StyleTools.getIconImageView("iconBubbleChart.png"));
menu.setOnAction((ActionEvent event) -> {
controller.bubbleChart();
});
items.add(menu);
menu = new MenuItem(message("PieChart"), StyleTools.getIconImageView("iconPieChart.png"));
menu.setOnAction((ActionEvent event) -> {
controller.pieChart();
});
items.add(menu);
menu = new MenuItem(message("BoxWhiskerChart"), StyleTools.getIconImageView("iconBoxWhiskerChart.png"));
menu.setOnAction((ActionEvent event) -> {
controller.boxWhiskerChart();
});
items.add(menu);
menu = new MenuItem(message("SelfComparisonBarsChart"), StyleTools.getIconImageView("iconBarChartH.png"));
menu.setOnAction((ActionEvent event) -> {
controller.selfComparisonBarsChart();
});
items.add(menu);
menu = new MenuItem(message("ComparisonBarsChart"), StyleTools.getIconImageView("iconComparisonBarsChart.png"));
menu.setOnAction((ActionEvent event) -> {
controller.comparisonBarsChart();
});
items.add(menu);
menu = new MenuItem(message("XYZChart"), StyleTools.getIconImageView("iconXYZChart.png"));
menu.setOnAction((ActionEvent event) -> {
controller.xyzChart();
});
menu.setDisable(data2D.columnsNumber() < 3);
items.add(menu);
menu = new MenuItem(message("LocationDistribution"), StyleTools.getIconImageView("iconLocation.png"));
menu.setOnAction((ActionEvent event) -> {
controller.locationDistribution();
});
menu.setDisable(!data2D.includeCoordinate());
items.add(menu);
return items;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static List<MenuItem> groupChartMenus(BaseData2DLoadController controller) {
try {
if (!controller.hasColumns()) {
return null;
}
List<MenuItem> items = new ArrayList<>();
MenuItem menu;
menu = new MenuItem(message("GroupData") + " - " + message("XYChart"), StyleTools.getIconImageView("iconXYChart.png"));
menu.setOnAction((ActionEvent event) -> {
controller.groupXYChart();
});
items.add(menu);
menu = new MenuItem(message("GroupData") + " - " + message("BubbleChart"), StyleTools.getIconImageView("iconBubbleChart.png"));
menu.setOnAction((ActionEvent event) -> {
controller.groupBubbleChart();
});
items.add(menu);
menu = new MenuItem(message("GroupData") + " - " + message("PieChart"), StyleTools.getIconImageView("iconPieChart.png"));
menu.setOnAction((ActionEvent event) -> {
controller.groupPieChart();
});
items.add(menu);
menu = new MenuItem(message("GroupData") + " - " + message("BoxWhiskerChart"), StyleTools.getIconImageView("iconBoxWhiskerChart.png"));
menu.setOnAction((ActionEvent event) -> {
controller.groupBoxWhiskerChart();
});
items.add(menu);
menu = new MenuItem(message("GroupData") + " - " + message("SelfComparisonBarsChart"), StyleTools.getIconImageView("iconBarChartH.png"));
menu.setOnAction((ActionEvent event) -> {
controller.groupSelfComparisonBars();
});
items.add(menu);
menu = new MenuItem(message("GroupData") + " - " + message("ComparisonBarsChart"), StyleTools.getIconImageView("iconComparisonBarsChart.png"));
menu.setOnAction((ActionEvent event) -> {
controller.groupComparisonBars();
});
items.add(menu);
return items;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static List<MenuItem> helpMenus(BaseData2DLoadController controller) {
try {
List<MenuItem> items = MenuTools.initMenu(message("Help"));
MenuItem about2D = new MenuItem(message("AboutData2D"));
about2D.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
controller.openHtml(HelpTools.aboutData2D());
}
});
items.add(about2D);
MenuItem aboutRowExpression = new MenuItem(message("AboutRowExpression"));
aboutRowExpression.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
controller.openHtml(HelpTools.aboutRowExpression());
}
});
items.add(aboutRowExpression);
MenuItem aboutGrouping = new MenuItem(message("AboutGroupingRows"));
aboutGrouping.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
controller.openHtml(HelpTools.aboutGroupingRows());
}
});
items.add(aboutGrouping);
MenuItem aboutDataAnalysis = new MenuItem(message("AboutDataAnalysis"));
aboutDataAnalysis.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
controller.openHtml(HelpTools.aboutDataAnalysis());
}
});
items.add(aboutDataAnalysis);
items.add(new SeparatorMenuItem());
MenuItem guidemenu = new MenuItem(message("UserGuideDataTools"));
guidemenu.setStyle(attributeTextStyle());
guidemenu.setOnAction((ActionEvent event) -> {
if (Languages.isChinese()) {
controller.browse("https://mara-mybox.sourceforge.io/guide/MyBox-DataTools-zh.pdf");
} else {
controller.browse("https://mara-mybox.sourceforge.io/guide/MyBox-DataTools-en.pdf");
}
});
items.add(guidemenu);
return items;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/tools/Data2DDefinitionTools.java | alpha/MyBox/src/main/java/mara/mybox/data2d/tools/Data2DDefinitionTools.java | package mara.mybox.data2d.tools;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javafx.scene.paint.Color;
import mara.mybox.data.StringTable;
import mara.mybox.data2d.Data2D;
import mara.mybox.data2d.DataFileCSV;
import mara.mybox.data2d.DataFileExcel;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.ColumnDefinition.ColumnType;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.db.data.Data2DDefinition;
import mara.mybox.db.data.DataNode;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.CsvTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.FileTools;
import mara.mybox.tools.HtmlWriteTools;
import mara.mybox.tools.JsonTools;
import mara.mybox.tools.StringTools;
import mara.mybox.tools.XmlTools;
import static mara.mybox.tools.XmlTools.cdata;
import mara.mybox.value.AppValues;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.UserConfig;
import org.apache.commons.csv.CSVPrinter;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* @Author Mara
* @CreateDate 2023-9-12
* @License Apache License Version 2.0
*/
public class Data2DDefinitionTools {
public static List<Data2DColumn> columns() {
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message("ColumnName"), ColumnType.String));
columns.add(new Data2DColumn(message("Type"), ColumnType.String));
columns.add(new Data2DColumn(message("Label"), ColumnType.String));
columns.add(new Data2DColumn(message("Length"), ColumnType.String));
columns.add(new Data2DColumn(message("Width"), ColumnType.String));
columns.add(new Data2DColumn(message("DisplayFormat"), ColumnType.String));
columns.add(new Data2DColumn(message("NotNull"), ColumnType.Boolean));
columns.add(new Data2DColumn(message("Editable"), ColumnType.Boolean));
columns.add(new Data2DColumn(message("PrimaryKey"), ColumnType.Boolean));
columns.add(new Data2DColumn(message("AutoGenerated"), ColumnType.Boolean));
columns.add(new Data2DColumn(message("DefaultValue"), ColumnType.String));
columns.add(new Data2DColumn(message("Color"), ColumnType.String));
columns.add(new Data2DColumn(message("ToInvalidValue"), ColumnType.String));
columns.add(new Data2DColumn(message("DecimalScale"), ColumnType.String));
columns.add(new Data2DColumn(message("Century"), ColumnType.String));
columns.add(new Data2DColumn(message("FixTwoDigitYears"), ColumnType.Boolean));
columns.add(new Data2DColumn(message("Description"), ColumnType.String));
return columns;
}
public static String defInfo(Data2DDefinition def) {
String info = message("ID") + ": " + def.getDataID() + "\n";
info += message("Type") + ": " + def.getTypeName() + "\n";
info += message("DataName") + ": " + def.getDataName() + "\n";
info += message("Sheet") + ": " + def.getSheet() + "\n";
info += message("File") + ": " + def.getFile() + "\n";
info += message("ColumnsNumber") + ": " + def.getColsNumber() + "\n";
String des = def.getComments();
if (des != null && !des.isBlank()) {
info += message("Description") + ": " + des;
}
info += message("Pagination") + ": \n" + def.pagination.info() + "\n";
return info;
}
public static String dataInfo(Data2D data2d) {
String info = defInfo(data2d);
info += message("DecimalScale") + ": " + data2d.getScale() + "\n";
info += message("MaxRandom") + ": " + data2d.getMaxRandom() + "\n";
info += message("Columns") + ": " + data2d.columnNames();
return info;
}
public static String toHtml(Data2D data2d) {
try {
if (data2d == null) {
return null;
}
StringTable attrTable = new StringTable();
List<String> row = new ArrayList<>();
row.addAll(Arrays.asList(message("DataName"), data2d.getDataName()));
attrTable.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList(message("DecimalScale"), data2d.getScale() + ""));
attrTable.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList(message("MaxRandom"), data2d.getMaxRandom() + ""));
attrTable.add(row);
row = new ArrayList<>();
String comments = data2d.getComments();
if (comments != null && !comments.isBlank()) {
row.addAll(Arrays.asList(message("Description"), HtmlWriteTools.codeToHtml(comments)));
}
attrTable.add(row);
String html = attrTable.div();
List<Data2DColumn> columns = data2d.getColumns();
if (columns == null || columns.isEmpty()) {
return html;
}
List<String> names = new ArrayList<>();
names.addAll(Arrays.asList(message("ColumnName"), message("Type"),
message("Label"), message("Length"),
message("NotNull"), message("PrimaryKey")));
StringTable columnsTable = new StringTable(names);
for (ColumnDefinition column : columns) {
row = new ArrayList<>();
row.add(column.getColumnName());
row.add(message(column.getType().name()));
row.add(column.getLabel());
row.add(column.getLength() + "");
row.add(column.isNotNull() ? message("Yes") : "");
row.add(column.isIsPrimaryKey() ? message("Yes") : "");
columnsTable.add(row);
}
html += "<BR>" + StringTable.tableDiv(columnsTable);
for (ColumnDefinition column : columns) {
names = new ArrayList<>();
names.addAll(Arrays.asList(message("Key"), message("Value")));
StringTable columnTable = new StringTable(names);
row = new ArrayList<>();
row.add(message("ColumnName"));
row.add(column.getColumnName());
columnTable.add(row);
row = new ArrayList<>();
row.add(message("Type"));
row.add(message(column.getType().name()));
columnTable.add(row);
row = new ArrayList<>();
row.add(message("Label"));
row.add(column.getLabel());
columnTable.add(row);
row = new ArrayList<>();
row.add(message("Length"));
row.add(column.getLength() + "");
columnTable.add(row);
row = new ArrayList<>();
row.add(message("Width"));
row.add(column.getWidth() + "");
columnTable.add(row);
row = new ArrayList<>();
row.add(message("DisplayFormat"));
String s = column.getFormatDisplay();
row.add(s == null || s.isBlank() ? null : HtmlWriteTools.codeToHtml(s));
columnTable.add(row);
row = new ArrayList<>();
row.add(message("NotNull"));
row.add(column.isNotNull() ? message("Yes") : "");
columnTable.add(row);
row = new ArrayList<>();
row.add(message("Editable"));
row.add(column.isEditable() ? message("Yes") : "");
columnTable.add(row);
row = new ArrayList<>();
row.add(message("PrimaryKey"));
row.add(column.isIsPrimaryKey() ? message("Yes") : "");
columnTable.add(row);
row = new ArrayList<>();
row.add(message("AutoGenerated"));
row.add(column.isAuto() ? message("Yes") : "");
columnTable.add(row);
row = new ArrayList<>();
row.add(message("DefaultValue"));
s = column.getDefaultValue();
row.add(s == null || s.isBlank() ? null : HtmlWriteTools.codeToHtml(s));
columnTable.add(row);
row = new ArrayList<>();
row.add(message("Color"));
row.add(column.getColor().toString());
columnTable.add(row);
row = new ArrayList<>();
row.add(message("DecimalScale"));
row.add(column.getScale() + "");
columnTable.add(row);
row = new ArrayList<>();
row.add(message("Century"));
row.add(column.getCentury() + "");
columnTable.add(row);
row = new ArrayList<>();
row.add(message("FixTwoDigitYears"));
row.add(column.isFixTwoDigitYear() ? message("Yes") : "");
columnTable.add(row);
row = new ArrayList<>();
row.add(message("Description"));
row.add(column.getDescription());
columnTable.add(row);
html += "<BR>" + StringTable.tableDiv(columnTable);
}
return html;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static String toXML(Data2D data2d, boolean withAttributes, String prefix) {
try {
if (data2d == null) {
return null;
}
String indent = AppValues.Indent;
StringBuilder s = new StringBuilder();
s.append(prefix).append("<").append(XmlTools.xmlTag("DataDefinition")).append(">\n");
if (withAttributes) {
s.append(prefix).append(indent).append("<").append(XmlTools.xmlTag("Attributes")).append(">\n");
String v = data2d.getDataName();
if (v != null && !v.isBlank()) {
s.append(prefix).append(indent).append(indent).append("<").append(XmlTools.xmlTag("DataName")).append(">").append("<![CDATA[").append(v).append("]]>").append("</").append(XmlTools.xmlTag("DataName")).append(">\n");
}
s.append(prefix).append(indent).append(indent).append("<").append(XmlTools.xmlTag("DecimalScale")).append(">").append(data2d.getScale()).append("</").append(XmlTools.xmlTag("DecimalScale")).append(">\n");
s.append(prefix).append(indent).append(indent).append("<").append(XmlTools.xmlTag("MaxRandom")).append(">").append(data2d.getMaxRandom()).append("</").append(XmlTools.xmlTag("MaxRandom")).append(">\n");
v = data2d.getComments();
if (v != null && !v.isBlank()) {
s.append(prefix).append(indent).append(indent).append("<").append(XmlTools.xmlTag("Description")).append(">").append("<![CDATA[").append(v).append("]]>").append("</").append(XmlTools.xmlTag("Description")).append(">\n");
}
s.append(prefix).append(indent).append("</").append(XmlTools.xmlTag("Attributes")).append(">\n");
}
s.append(prefix).append(indent).append("<").append(XmlTools.xmlTag("ColumnsDefinition")).append(">\n");
List<Data2DColumn> columns = data2d.getColumns();
if (columns != null) {
for (Data2DColumn col : columns) {
if (col.getColumnName() == null) {
continue;
}
s.append(prefix).append(indent).append(indent).append("<").append(XmlTools.xmlTag("Column")).append(">\n");
s.append(prefix).append(indent).append(indent).append(indent).append("<").append(XmlTools.xmlTag("ColumnName")).append(">").append("<![CDATA[").append(col.getColumnName()).append("]]>").append("</").append(XmlTools.xmlTag("ColumnName")).append(">\n");
if (col.getType() != null) {
s.append(prefix).append(indent).append(indent).append(indent).append("<").append(XmlTools.xmlTag("Type")).append(">").append(col.getType().name()).append("</").append(XmlTools.xmlTag("Type")).append(">\n");
}
if (col.getLabel() != null) {
s.append(prefix).append(indent).append(indent).append(indent).append("<").append(XmlTools.xmlTag("Label")).append(">").append("<![CDATA[").append(col.getLabel()).append("]]>").append("</").append(XmlTools.xmlTag("Label")).append(">\n");
}
if (ColumnType.String == col.getType()) {
s.append(prefix).append(indent).append(indent).append(indent).append("<").append(XmlTools.xmlTag("Length")).append(">").append(col.getLength()).append("</").append(XmlTools.xmlTag("Length")).append(">\n");
}
s.append(prefix).append(indent).append(indent).append(indent).append("<").append(XmlTools.xmlTag("Width")).append(">").append(col.getWidth()).append("</").append(XmlTools.xmlTag("Width")).append(">\n");
if (col.getFormat() != null) {
s.append(prefix).append(indent).append(indent).append(indent).append("<").append(XmlTools.xmlTag("DisplayFormat")).append(">");
if (col.isEnumType()) {
s.append("\n").append(prefix).append(indent).append(indent).append(indent).append("<![CDATA[").append(col.getFormat()).append("]]>\n").append(indent).append(indent);
} else {
s.append(col.getFormat());
}
s.append("</").append(XmlTools.xmlTag("DisplayFormat")).append(">\n");
}
s.append(prefix).append(indent).append(indent).append(indent).append("<").append(XmlTools.xmlTag("NotNull")).append(">").append(col.isNotNull() ? "true" : "false").append("</").append(XmlTools.xmlTag("NotNull")).append(">\n");
s.append(prefix).append(indent).append(indent).append(indent).append("<").append(XmlTools.xmlTag("Editable")).append(">").append(col.isEditable() ? "true" : "false").append("</").append(XmlTools.xmlTag("Editable")).append(">\n");
s.append(prefix).append(indent).append(indent).append(indent).append("<").append(XmlTools.xmlTag("PrimaryKey")).append(">").append(col.isIsPrimaryKey() ? "true" : "false").append("</").append(XmlTools.xmlTag("PrimaryKey")).append(">\n");
s.append(prefix).append(indent).append(indent).append(indent).append("<").append(XmlTools.xmlTag("AutoGenerated")).append(">").append(col.isAuto() ? "true" : "false").append("</").append(XmlTools.xmlTag("AutoGenerated")).append(">\n");
if (col.getDefaultValue() != null) {
s.append(prefix).append(indent).append(indent).append(indent).append("<").append(XmlTools.xmlTag("DefaultValue")).append(">").append("<![CDATA[").append(col.getDefaultValue()).append("]]>").append("</").append(XmlTools.xmlTag("DefaultValue")).append(">\n");
}
if (col.getColor() != null) {
s.append(prefix).append(indent).append(indent).append(indent).append("<").append(XmlTools.xmlTag("Color")).append(">").append(col.getColor()).append("</").append(XmlTools.xmlTag("Color")).append(">\n");
}
s.append(prefix).append(indent).append(indent).append(indent).append("<").append(XmlTools.xmlTag("DecimalScale")).append(">").append(col.getScale()).append("</").append(XmlTools.xmlTag("DecimalScale")).append(">\n");
s.append(prefix).append(indent).append(indent).append(indent).append("<").append(XmlTools.xmlTag("Century")).append(">").append(col.getCentury()).append("</").append(XmlTools.xmlTag("Century")).append(">\n");
s.append(prefix).append(indent).append(indent).append(indent).append("<").append(XmlTools.xmlTag("FixTwoDigitYears")).append(">").append(col.isFixTwoDigitYear() ? "true" : "false").append("</").append(XmlTools.xmlTag("FixTwoDigitYears")).append(">\n");
if (col.getDescription() != null) {
s.append(prefix).append(indent).append(indent).append(indent).append("<").append(XmlTools.xmlTag("Description")).append(">").append("<![CDATA[").append(col.getDescription()).append("]]>").append("</").append(XmlTools.xmlTag("Description")).append(">\n");
}
s.append(prefix).append(indent).append(indent).append("</").append(XmlTools.xmlTag("Column")).append(">\n");
}
}
s.append(prefix).append(indent).append("</").append(XmlTools.xmlTag("ColumnsDefinition")).append(">\n");
s.append(prefix).append("</").append(XmlTools.xmlTag("DataDefinition")).append(">\n");
return s.toString();
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static String toJSON(Data2D data2d, boolean withAttributes, String prefix) {
try {
if (data2d == null) {
return null;
}
String indent = AppValues.Indent;
StringBuilder s = new StringBuilder();
s.append(prefix).append("\"").append(message("DataDefinition")).append("\": {\n");
if (withAttributes) {
s.append(prefix).append(indent).append("\"").append(message("Attributes")).append("\": {\n");
String v = data2d.getDataName();
if (v != null && !v.isBlank()) {
s.append(prefix).append(indent).append(indent).append("\"").append(message("DataName")).append("\": ").append(JsonTools.encode(v)).append(",\n");
}
s.append(prefix).append(indent).append(indent).append("\"").append(message("DecimalScale")).append("\": ").append(data2d.getScale()).append(",\n");
s.append(prefix).append(indent).append(indent).append("\"").append(message("MaxRandom")).append("\": ").append(data2d.getMaxRandom());
v = data2d.getComments();
if (v != null && !v.isBlank()) {
s.append(",\n").append(prefix).append(indent).append(indent).append("\"").append(message("Description")).append("\": ").append(JsonTools.encode(v)).append("\n");
} else {
s.append("\n");
}
s.append(prefix).append(indent).append("},\n");
}
s.append(prefix).append(indent).append("\"").append(message("ColumnsDefinition")).append("\": [\n");
boolean firstRow = true;
List<Data2DColumn> columns = data2d.getColumns();
if (columns != null) {
for (Data2DColumn col : columns) {
if (firstRow) {
firstRow = false;
} else {
s.append(",\n");
}
s.append(prefix).append(indent).append(indent).append("{").append("\n");
if (col.getColumnName() == null) {
continue;
}
s.append(prefix).append(indent).append(indent).append(indent).append("\"").append(message("ColumnName")).append("\": ").append(JsonTools.encode(col.getColumnName()));
if (col.getType() != null) {
s.append(",\n").append(prefix).append(indent).append(indent).append(indent).append("\"").append(message("Type")).append("\": \"").append(col.getType().name()).append("\"");
}
if (col.getLabel() != null) {
s.append(",\n").append(prefix).append(indent).append(indent).append(indent).append("\"").append(message("Label")).append("\": ").append(JsonTools.encode(col.getLabel()));
}
if (ColumnType.String == col.getType()) {
s.append(",\n").append(prefix).append(indent).append(indent).append(indent).append("\"").append(message("Length")).append("\": ").append(col.getLength());
}
s.append(",\n").append(prefix).append(indent).append(indent).append(indent).append("\"").append(message("Width")).append("\": ").append(col.getWidth());
if (col.getFormat() != null) {
s.append(",\n").append(prefix).append(indent).append(indent).append(indent).append("\"").append(message("DisplayFormat")).append("\": ").append(JsonTools.encode(col.getFormat()));
}
s.append(",\n").append(prefix).append(indent).append(indent).append(indent).append("\"").append(message("NotNull")).append("\": ").append(col.isNotNull() ? "true" : "false");
s.append(",\n").append(prefix).append(indent).append(indent).append(indent).append("\"").append(message("Editable")).append("\": ").append(col.isEditable() ? "true" : "false");
s.append(",\n").append(prefix).append(indent).append(indent).append(indent).append("\"").append(message("PrimaryKey")).append("\": ").append(col.isIsPrimaryKey() ? "true" : "false");
s.append(",\n").append(prefix).append(indent).append(indent).append(indent).append("\"").append(message("AutoGenerated")).append("\": ").append(col.isAuto() ? "true" : "false");
if (col.getDefaultValue() != null) {
s.append(",\n").append(prefix).append(indent).append(indent).append(indent).append("\"").append(message("DefaultValue")).append("\": ").append(JsonTools.encode(col.getDefaultValue()));
}
if (col.getColor() != null) {
s.append(",\n").append(prefix).append(indent).append(indent).append(indent).append("\"").append(message("Color")).append("\": \"").append(col.getColor()).append("\"");
}
s.append(",\n").append(prefix).append(indent).append(indent).append(indent).append("\"").append(message("DecimalScale")).append("\": ").append(col.getScale());
s.append(",\n").append(prefix).append(indent).append(indent).append(indent).append("\"").append(message("Century")).append("\": ").append(col.getCentury());
s.append(",\n").append(prefix).append(indent).append(indent).append(indent).append("\"").append(message("FixTwoDigitYears")).append("\": ").append(col.isFixTwoDigitYear() ? "true" : "false");
if (col.getDescription() != null) {
s.append(",\n").append(prefix).append(indent).append(indent).append(indent).append("\"").append(message("Description")).append("\": ").append(JsonTools.encode(col.getDescription()));
}
s.append("\n").append(prefix).append(indent).append(indent).append("}");
}
s.append("\n").append(prefix).append(indent).append("]\n");
s.append(prefix).append("}\n");
}
return s.toString();
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static DataFileCSV toCSVFile(Data2D data2d, File file) {
try {
if (data2d == null || file == null) {
return null;
}
File tmpFile = FileTmpTools.getTempFile();
List<Data2DColumn> definition = columns();
try (CSVPrinter csvPrinter = new CSVPrinter(new FileWriter(tmpFile, Charset.forName("UTF-8")), CsvTools.csvFormat(",", true))) {
List<String> row = new ArrayList<>();
for (Data2DColumn col : definition) {
row.add(col.getColumnName());
}
csvPrinter.printRecord(row);
if (UserConfig.getBoolean("Data2DDefinitionExportAtributes", true)) {
csvPrinter.printComment("The first row defines attributes of the data. And other rows define columns.");
row.clear();
row.add(data2d.getDataName());
row.add("TableAttributes");
row.add(data2d.getMaxRandom() + "");
row.add("");
row.add("");
row.add("");
row.add("");
row.add("");
row.add("");
row.add("");
row.add("");
row.add("");
row.add("");
row.add(data2d.getScale() + "");
row.add("");
row.add("");
row.add(data2d.getComments());
csvPrinter.printRecord(row);
}
List<Data2DColumn> columns = data2d.getColumns();
if (columns != null) {
for (Data2DColumn col : columns) {
row.clear();
row.add(col.getColumnName());
row.add(col.getType().name());
row.add(col.getLabel());
row.add(ColumnType.String == col.getType() ? col.getLength() + "" : "");
row.add(col.getWidth() + "");
row.add(col.getFormat());
row.add(col.isNotNull() ? "1" : "0");
row.add(col.isEditable() ? "1" : "0");
row.add(col.isIsPrimaryKey() ? "1" : "0");
row.add(col.isAuto() ? "1" : "0");
row.add(col.getDefaultValue());
row.add(col.getColor().toString());
row.add(col.getScale() + "");
row.add(col.getCentury() + "");
row.add(col.isFixTwoDigitYear() ? "1" : "0");
row.add(col.getDescription());
csvPrinter.printRecord(row);
}
}
csvPrinter.flush();
csvPrinter.close();
}
if (!FileTools.override(tmpFile, file, true)) {
return null;
}
DataFileCSV csv = new DataFileCSV();
csv.setColumns(definition).setFile(file)
.setCharset(Charset.forName("UTF-8")).setDelimiter(",").setHasHeader(true)
.setColsNumber(definition.size());
csv.saveAttributes();
return csv;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static DataFileExcel toExcelFile(Data2D data2d, File file) {
try {
File tmpFile = FileTmpTools.getTempFile();
List<Data2DColumn> definition = columns();
try (XSSFWorkbook xssfBook = new XSSFWorkbook()) {
XSSFSheet xssfSheet = xssfBook.createSheet("sheet1");
xssfSheet.setDefaultColumnWidth(20);
int rowIndex = 0;
XSSFRow titleRow = xssfSheet.createRow(rowIndex++);
XSSFCellStyle horizontalCenter = xssfBook.createCellStyle();
horizontalCenter.setAlignment(HorizontalAlignment.CENTER);
for (int i = 0; i < definition.size(); i++) {
XSSFCell cell = titleRow.createCell(i);
cell.setCellValue(definition.get(i).getColumnName());
cell.setCellStyle(horizontalCenter);
xssfSheet.autoSizeColumn(i);
}
int cellIndex = 0;
if (UserConfig.getBoolean("Data2DDefinitionExportAtributes", true)) {
XSSFRow commentsRow = xssfSheet.createRow(rowIndex++);
commentsRow.createCell(0).setCellValue("The first row defines attributes of the data. And other rows define columns.");
XSSFRow attributesRow = xssfSheet.createRow(rowIndex++);
attributesRow.createCell(cellIndex++).setCellValue(data2d.getDataName());
attributesRow.createCell(cellIndex++).setCellValue("TableAttributes");
attributesRow.createCell(cellIndex++).setCellValue(data2d.getMaxRandom() + "");
attributesRow.createCell(cellIndex++).setCellValue("");
attributesRow.createCell(cellIndex++).setCellValue("");
attributesRow.createCell(cellIndex++).setCellValue("");
attributesRow.createCell(cellIndex++).setCellValue("");
attributesRow.createCell(cellIndex++).setCellValue("");
attributesRow.createCell(cellIndex++).setCellValue("");
attributesRow.createCell(cellIndex++).setCellValue("");
attributesRow.createCell(cellIndex++).setCellValue("");
attributesRow.createCell(cellIndex++).setCellValue("");
attributesRow.createCell(cellIndex++).setCellValue("");
attributesRow.createCell(cellIndex++).setCellValue(data2d.getScale() + "");
attributesRow.createCell(cellIndex++).setCellValue("");
attributesRow.createCell(cellIndex++).setCellValue("");
attributesRow.createCell(cellIndex++).setCellValue(data2d.getComments());
}
List<Data2DColumn> columns = data2d.getColumns();
if (columns != null) {
for (Data2DColumn col : columns) {
XSSFRow columnRow = xssfSheet.createRow(rowIndex++);
cellIndex = 0;
columnRow.createCell(cellIndex++).setCellValue(col.getColumnName());
columnRow.createCell(cellIndex++).setCellValue(col.getType().name());
columnRow.createCell(cellIndex++).setCellValue(col.getLabel());
columnRow.createCell(cellIndex++).setCellValue(ColumnType.String == col.getType() ? col.getLength() + "" : "");
columnRow.createCell(cellIndex++).setCellValue(col.getWidth() + "");
columnRow.createCell(cellIndex++).setCellValue(col.getFormat());
columnRow.createCell(cellIndex++).setCellValue(col.isNotNull() ? "1" : "0");
columnRow.createCell(cellIndex++).setCellValue(col.isEditable() ? "1" : "0");
columnRow.createCell(cellIndex++).setCellValue(col.isIsPrimaryKey() ? "1" : "0");
columnRow.createCell(cellIndex++).setCellValue(col.isAuto() ? "1" : "0");
columnRow.createCell(cellIndex++).setCellValue(col.getDefaultValue());
columnRow.createCell(cellIndex++).setCellValue(col.getColor().toString());
columnRow.createCell(cellIndex++).setCellValue(col.getScale() + "");
columnRow.createCell(cellIndex++).setCellValue(col.getCentury() + "");
columnRow.createCell(cellIndex++).setCellValue(col.isFixTwoDigitYear() ? "1" : "0");
columnRow.createCell(cellIndex++).setCellValue(col.getDescription());
}
}
try (FileOutputStream fileOut = new FileOutputStream(tmpFile)) {
xssfBook.write(fileOut);
}
xssfBook.close();
}
if (!FileTools.override(tmpFile, file, true)) {
return null;
}
DataFileExcel excel = new DataFileExcel();
excel.setColumns(definition).setFile(file).setSheet("sheet1").setHasHeader(true).setColsNumber(definition.size());
excel.saveAttributes();
return excel;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static DataFileCSV fromXML(String s) {
try {
if (s == null || s.isBlank()) {
return null;
}
Element e = XmlTools.toElement(null, null, s);
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | true |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/tools/Data2DTableTools.java | alpha/MyBox/src/main/java/mara/mybox/data2d/tools/Data2DTableTools.java | package mara.mybox.data2d.tools;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.data2d.Data2D;
import mara.mybox.data2d.DataClipboard;
import mara.mybox.data2d.DataFileCSV;
import mara.mybox.data2d.DataFileExcel;
import mara.mybox.data2d.DataFileText;
import mara.mybox.data2d.DataTable;
import mara.mybox.data2d.TmpTable;
import mara.mybox.data2d.writer.Data2DWriter;
import mara.mybox.data2d.writer.DataTableWriter;
import mara.mybox.db.Database;
import mara.mybox.db.DerbyBase;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.db.data.Data2DRow;
import mara.mybox.db.table.TableData2D;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.tools.CsvTools;
import mara.mybox.tools.DoubleTools;
import mara.mybox.tools.TextFileTools;
import static mara.mybox.value.Languages.message;
import org.apache.commons.csv.CSVPrinter;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* @Author Mara
* @CreateDate 2023-9-12
* @License Apache License Version 2.0
*/
public class Data2DTableTools {
public static DataTable makeTable(FxTask task, String tname,
List<Data2DColumn> sourceColumns, List<String> keys, String idName) {
try {
if (sourceColumns == null || sourceColumns.isEmpty()) {
return null;
}
if (tname == null || tname.isBlank()) {
tname = TmpTable.tmpTableName();
}
DataTable dataTable = new DataTable();
TableData2D tableData2D = dataTable.getTableData2D();
String tableName = DerbyBase.fixedIdentifier(tname);
tableData2D.setTableName(tableName);
List<Data2DColumn> tableColumns = new ArrayList<>();
List<String> validNames = new ArrayList<>();
if (keys == null || keys.isEmpty()) {
if (idName == null) {
idName = "id";
}
Data2DColumn idcolumn = new Data2DColumn(idName, ColumnDefinition.ColumnType.Long);
idcolumn.setAuto(true).setIsPrimaryKey(true).setNotNull(true).setEditable(false);
tableColumns.add(idcolumn);
tableData2D.addColumn(idcolumn);
validNames.add(idName);
}
for (Data2DColumn sourceColumn : sourceColumns) {
Data2DColumn dataColumn = sourceColumn.copy();
dataColumn.setAuto(false).setIsPrimaryKey(false);
String sourceColumnName = sourceColumn.getColumnName();
String columeName = DerbyBase.fixedIdentifier(sourceColumnName);
columeName = DerbyBase.checkIdentifier(validNames, columeName, true);
dataColumn.setColumnName(columeName);
if (keys != null && !keys.isEmpty()) {
dataColumn.setIsPrimaryKey(keys.contains(sourceColumnName));
}
tableColumns.add(dataColumn);
tableData2D.addColumn(dataColumn);
}
dataTable.setColumns(tableColumns).setTask(task).setSheet(tableName);
return dataTable;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return null;
}
}
public static DataTable createTable(FxTask task, Connection conn, String targetName,
List<Data2DColumn> sourceColumns, List<String> keys, String comments,
String idName, boolean dropExisted) {
try {
if (conn == null || sourceColumns == null || sourceColumns.isEmpty()) {
return null;
}
if (targetName == null || targetName.isBlank()) {
targetName = TmpTable.tmpTableName();
}
DataTable dataTable = new DataTable();
String tableName = DerbyBase.fixedIdentifier(targetName);
if (DerbyBase.exist(conn, tableName) > 0) {
if (!dropExisted) {
return null;
}
dataTable.drop(conn, tableName);
conn.commit();
}
dataTable = makeTable(task, tableName, sourceColumns, keys, idName);
if (dataTable == null) {
return null;
}
TableData2D tableData2D = dataTable.getTableData2D();
tableData2D.setTableName(dataTable.getSheet());
String sql = tableData2D.createTableStatement();
if (task != null) {
task.setInfo(sql);
}
if (conn.createStatement().executeUpdate(sql) < 0) {
return null;
}
conn.commit();
dataTable.recordTable(conn, tableName, dataTable.getColumns(), comments);
return dataTable;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
MyBoxLog.error(e);
return null;
}
}
public static DataTable createTable(FxTask task, Connection conn,
String targetName, List<Data2DColumn> columns) {
return createTable(task, conn, targetName, columns, null, null, null, true);
}
public static boolean write(FxTask task, DataTable dataTable, Data2DWriter writer,
ResultSet results, String rowNumberName, int dscale, ColumnDefinition.InvalidAs invalidAs) {
try {
if (writer == null || results == null) {
return false;
}
List<Data2DColumn> db2Columns = new ArrayList<>();
List<String> fileRow = new ArrayList<>();
List<String> names = new ArrayList<>();
List<Data2DColumn> targetColumns = new ArrayList<>();
if (rowNumberName != null) {
names.add(rowNumberName);
targetColumns.add(0, new Data2DColumn(rowNumberName, ColumnDefinition.ColumnType.Long));
}
ResultSetMetaData meta = results.getMetaData();
for (int col = 1; col <= meta.getColumnCount(); col++) {
String name = meta.getColumnName(col);
names.add(name);
Data2DColumn dc = null;
if (dataTable != null) {
dc = dataTable.columnByName(name);
if (dc != null) {
dc = dc.copy();
}
}
if (dc == null) {
dc = new Data2DColumn(name,
ColumnDefinition.sqlColumnType(meta.getColumnType(col)),
meta.isNullable(col) == ResultSetMetaData.columnNoNulls);
}
db2Columns.add(dc);
targetColumns.add(dc);
}
writer.setColumns(targetColumns).setHeaderNames(names);
if (!writer.openWriter()) {
return false;
}
long count = 0;
while (results.next() && task != null && !task.isCancelled()) {
count++;
if (rowNumberName != null) {
fileRow.add("" + count);
}
for (Data2DColumn column : db2Columns) {
Object v = column.value(results);
String s = column.toString(v);
if (column.needScale()) {
s = DoubleTools.scaleString(s, invalidAs, dscale);
}
fileRow.add(s);
}
writer.writeRow(fileRow);
fileRow.clear();
}
writer.closeWriter();
return writer.isCompleted();
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
}
public static DataTable importTable(FxTask task, String targetName,
List<Data2DColumn> cols, List<List<String>> pageRows, ColumnDefinition.InvalidAs invalidAs) {
if (cols == null || pageRows == null || pageRows.isEmpty()) {
return null;
}
DataTable dataTable = null;
try (Connection conn = DerbyBase.getConnection()) {
dataTable = createTable(task, conn, targetName, cols, null, null, null, false);
if (dataTable == null) {
return null;
}
TableData2D tableData2D = dataTable.getTableData2D();
Data2DRow data2DRow = tableData2D.newRow();
List<Data2DColumn> columns = dataTable.getColumns();
conn.setAutoCommit(false);
int count = 0;
for (List<String> row : pageRows) {
for (int i = 0; i < columns.size(); i++) {
Data2DColumn column = columns.get(i);
data2DRow.setValue(column.getColumnName(), column.fromString(row.get(i + 1), invalidAs));
}
tableData2D.insertData(conn, data2DRow);
if (++count % Database.BatchSize == 0) {
conn.commit();
if (task != null) {
task.setInfo(message("Imported") + ": " + count);
}
}
}
if (count > 0) {
dataTable.setRowsNumber(count);
dataTable.getTableData2DDefinition().updateData(conn, dataTable);
conn.commit();
if (task != null) {
task.setInfo(message("Imported") + ": " + count);
}
}
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
}
return dataTable;
}
public static long importTable(FxTask task, Connection conn,
Data2D sourceData, DataTable targetTable, List<Integer> cols,
boolean includeRowNumber, ColumnDefinition.InvalidAs invalidAs) {
try {
if (sourceData == null || conn == null || targetTable == null) {
return -1;
}
List<Data2DColumn> srcColumns = sourceData.getColumns();
if (srcColumns == null || srcColumns.isEmpty()) {
sourceData.loadColumns(conn);
}
if (srcColumns == null || srcColumns.isEmpty()) {
return -2;
}
if (cols == null || cols.isEmpty()) {
cols = new ArrayList<>();
for (int i = 0; i < srcColumns.size(); i++) {
cols.add(i);
}
}
List<Data2DColumn> targetColumns = sourceData.targetColumns(cols, includeRowNumber);
DataTableWriter writer = new DataTableWriter();
writer.setTargetTable(targetTable)
.setColumns(targetColumns)
.setHeaderNames(Data2DColumnTools.toNames(targetColumns))
.setWriteHeader(false);
return sourceData.copy(task, writer, cols, includeRowNumber, invalidAs);
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
MyBoxLog.error(e);
return -5;
}
}
public static long importTable(FxTask task, Connection conn, Data2D sourceData, DataTable dataTable) {
return Data2DTableTools.importTable(task, conn, sourceData, dataTable, null, false, ColumnDefinition.InvalidAs.Empty);
}
public static DataFileText toText(FxTask task, DataTable dataTable) {
if (task == null || dataTable == null || !dataTable.hasColumns()) {
return null;
}
File txtFile = dataTable.tmpFile(dataTable.getName(), null, "txt");
DataFileCSV csvData = toCSV(task, dataTable, txtFile, false);
if (csvData != null && txtFile != null && txtFile.exists()) {
DataFileText targetData = new DataFileText();
targetData.setColumns(csvData.getColumns())
.setFile(txtFile)
.setDataName(csvData.getName())
.setCharset(Charset.forName("UTF-8"))
.setDelimiter(",")
.setHasHeader(true)
.setColsNumber(csvData.getColsNumber())
.setRowsNumber(csvData.getRowsNumber());
targetData.saveAttributes();
return targetData;
} else {
return null;
}
}
public static String toString(FxTask task, DataTable dataTable) {
if (task == null || dataTable == null || !dataTable.hasColumns()) {
return null;
}
File txtFile = dataTable.tmpFile(dataTable.getName(), null, "txt");
DataFileCSV csvData = toCSV(task, dataTable, txtFile, false);
if (csvData != null && txtFile != null && txtFile.exists()) {
return TextFileTools.readTexts(task, txtFile);
} else {
return null;
}
}
public static DataFileCSV toCSV(FxTask task, DataTable dataTable, File file, boolean save) {
if (task == null || dataTable == null || !dataTable.hasColumns() || file == null) {
return null;
}
TableData2D tableData2D = dataTable.getTableData2D();
List<Data2DColumn> dataColumns = dataTable.getColumns();
int tcolsNumber = dataColumns.size();
int trowsNumber = 0;
String sql = tableData2D.queryAllStatement();
if (task != null) {
task.setInfo(sql);
}
try (Connection conn = DerbyBase.getConnection();
PreparedStatement statement = conn.prepareStatement(sql);
ResultSet results = statement.executeQuery();
CSVPrinter csvPrinter = new CSVPrinter(
new FileWriter(file, Charset.forName("UTF-8")), CsvTools.csvFormat(",", true))) {
csvPrinter.printRecord(dataTable.columnNames());
while (results.next() && task != null && !task.isCancelled()) {
try {
List<String> row = new ArrayList<>();
for (int col = 0; col < tcolsNumber; col++) {
Data2DColumn column = dataColumns.get(col);
Object v = column.value(results);
row.add(column.toString(v));
}
csvPrinter.printRecord(row);
trowsNumber++;
} catch (Exception e) {
// skip bad lines
MyBoxLog.error(e);
}
}
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return null;
}
if (file != null && file.exists()) {
DataFileCSV targetData = new DataFileCSV();
targetData.setColumns(dataTable.getColumns()).setDataName(dataTable.getName()).setFile(file).setCharset(Charset.forName("UTF-8")).setDelimiter(",").setHasHeader(true).setColsNumber(tcolsNumber).setRowsNumber(trowsNumber);
if (save) {
targetData.saveAttributes();
}
return targetData;
} else {
return null;
}
}
public static DataFileCSV toCSV(FxTask task, DataTable dataTable) {
File csvFile = dataTable.tmpFile(dataTable.getName(), null, "csv");
return toCSV(task, dataTable, csvFile, true);
}
public static DataFileExcel toExcel(FxTask task, DataTable dataTable) {
if (task == null || dataTable == null || !dataTable.hasColumns()) {
return null;
}
File excelFile = dataTable.tmpFile(dataTable.getName(), null, "xlsx");
String targetSheetName = message("Sheet") + "1";
TableData2D tableData2D = dataTable.getTableData2D();
List<Data2DColumn> dataColumns = dataTable.getColumns();
int tcolsNumber = dataColumns.size();
int trowsNumber = 0;
String sql = tableData2D.queryAllStatement();
if (task != null) {
task.setInfo(sql);
}
try (Connection conn = DerbyBase.getConnection();
PreparedStatement statement = conn.prepareStatement(sql);
ResultSet results = statement.executeQuery();
Workbook targetBook = new XSSFWorkbook()) {
Sheet targetSheet = targetBook.createSheet(targetSheetName);
Row targetRow = targetSheet.createRow(0);
for (int col = 0; col < tcolsNumber; col++) {
Cell targetCell = targetRow.createCell(col, CellType.STRING);
targetCell.setCellValue(dataColumns.get(col).getColumnName());
}
while (results.next() && task != null && !task.isCancelled()) {
try {
targetRow = targetSheet.createRow(++trowsNumber);
for (int col = 0; col < tcolsNumber; col++) {
Data2DColumn column = dataColumns.get(col);
Object v = column.value(results);
Cell targetCell = targetRow.createCell(col, CellType.STRING);
targetCell.setCellValue(column.toString(v));
}
} catch (Exception e) {
// skip bad lines
MyBoxLog.error(e);
}
}
try (FileOutputStream fileOut = new FileOutputStream(excelFile)) {
targetBook.write(fileOut);
}
targetBook.close();
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return null;
}
if (excelFile != null && excelFile.exists()) {
DataFileExcel targetData = new DataFileExcel();
targetData.setColumns(dataTable.getColumns()).setFile(excelFile)
.setSheet(targetSheetName).setDataName(dataTable.getName())
.setHasHeader(true).setColsNumber(tcolsNumber).setRowsNumber(trowsNumber);
targetData.saveAttributes();
return targetData;
} else {
return null;
}
}
public static DataClipboard toClip(FxTask task, DataTable dataTable) {
if (task == null || dataTable == null || !dataTable.hasColumns()) {
return null;
}
File clipFile = DataClipboard.newFile();
DataFileCSV csvData = toCSV(task, dataTable, clipFile, false);
if (csvData != null && clipFile != null && clipFile.exists()) {
return DataClipboard.create(task, csvData, dataTable.getName(), clipFile);
} else {
return null;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/reader/DataFileExcelReader.java | alpha/MyBox/src/main/java/mara/mybox/data2d/reader/DataFileExcelReader.java | package mara.mybox.data2d.reader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import mara.mybox.data2d.DataFileExcel;
import static mara.mybox.data2d.DataFileExcel.CommentsMarker;
import mara.mybox.tools.FileTools;
import mara.mybox.tools.MicrosoftDocumentTools;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
/**
* @Author Mara
* @CreateDate 2022-1-27
* @License Apache License Version 2.0
*/
public class DataFileExcelReader extends Data2DReader {
protected DataFileExcel readerExcel;
protected Iterator<Row> iterator;
public DataFileExcelReader(DataFileExcel data) {
this.readerExcel = data;
sourceData = data;
}
@Override
public void scanFile() {
if (!FileTools.hasData(sourceFile)) {
return;
}
try (Workbook wb = WorkbookFactory.create(sourceFile)) {
Sheet sourceSheet;
String sheetName = sourceData.getSheet();
if (sheetName != null) {
sourceSheet = wb.getSheet(sheetName);
} else {
sourceSheet = wb.getSheetAt(0);
sheetName = sourceSheet.getSheetName();
}
if (readerExcel != null) {
int sheetsNumber = wb.getNumberOfSheets();
List<String> sheetNames = new ArrayList<>();
for (int i = 0; i < sheetsNumber; i++) {
sheetNames.add(wb.getSheetName(i));
}
readerExcel.setSheetNames(sheetNames);
readerExcel.setSheet(sheetName);
}
iterator = sourceSheet.iterator();
operate.handleData();
wb.close();
} catch (Exception e) {
showError(e.toString());
setFailed();
}
}
@Override
public void readColumnNames() {
if (iterator == null) {
return;
}
while (iterator.hasNext() && !isStopped()) {
readRecord();
if (sourceRow == null || sourceRow.isEmpty()) {
continue;
}
makeHeader();
return;
}
}
@Override
public void readTotal() {
if (iterator == null) {
return;
}
sourceIndex = 0;
skipHeader();
while (iterator.hasNext()) {
if (isStopped()) {
sourceIndex = 0;
return;
}
readRecord();
if (sourceRow != null && !sourceRow.isEmpty()) {
++sourceIndex;
}
}
}
public void skipHeader() {
if (!readerHasHeader || iterator == null) {
return;
}
while (iterator.hasNext() && !isStopped()) {
readRecord();
if (sourceRow == null || sourceRow.isEmpty()) {
continue;
}
return;
}
}
// sourceIndex is 1-base while pageStartIndex and pageEndIndex are 0-based
@Override
public void readPage() {
if (iterator == null) {
return;
}
skipHeader();
sourceIndex = 0;
while (iterator.hasNext() && !isStopped()) {
readRecord();
if (sourceRow == null || sourceRow.isEmpty()) {
continue;
}
if (sourceIndex++ < pageStartIndex) {
continue;
}
if (sourceIndex > pageEndIndex) {
stop();
break;
}
makePageRow();
}
}
@Override
public void readRows() {
if (iterator == null) {
return;
}
skipHeader();
sourceIndex = 0;
long fileIndex = -1;
long startIndex = sourceData.pagination.startRowOfCurrentPage;
long endIndex = sourceData.pagination.endRowOfCurrentPage;
while (iterator.hasNext() && !isStopped()) {
try {
readRecord();
if (sourceRow == null || sourceRow.isEmpty()) {
continue;
}
fileIndex++;
if (fileIndex < startIndex || fileIndex >= endIndex) {
++sourceIndex;
handleRow();
} else if (fileIndex == startIndex) {
scanPage();
}
} catch (Exception e) { // skip bad lines
// showError(e.toString());
// setFailed();
}
}
}
public void readRecord() {
try {
sourceRow = null;
if (isStopped() || iterator == null) {
return;
}
Row readerFileRow = iterator.next();
if (readerFileRow == null) {
return;
}
sourceRow = new ArrayList<>();
String firstValue = null;
for (int cellIndex = readerFileRow.getFirstCellNum();
cellIndex < readerFileRow.getLastCellNum(); cellIndex++) {
String v = MicrosoftDocumentTools.cellString(readerFileRow.getCell(cellIndex));
sourceRow.add(v);
if (v != null && !v.isBlank()) {
firstValue = v;
}
}
if (firstValue != null && firstValue.startsWith(CommentsMarker)) {
if (dataComments == null) {
dataComments = firstValue;
} else {
dataComments += "\n" + firstValue;
}
sourceRow = null;
}
} catch (Exception e) {
showError(e.toString());
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/reader/DataTableReader.java | alpha/MyBox/src/main/java/mara/mybox/data2d/reader/DataTableReader.java | package mara.mybox.data2d.reader;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import mara.mybox.data2d.DataTable;
import mara.mybox.data2d.tools.Data2DRowTools;
import mara.mybox.db.data.Data2DRow;
import mara.mybox.db.table.TableData2D;
/**
* @Author Mara
* @CreateDate 2022-1-29
* @License Apache License Version 2.0
*/
public class DataTableReader extends Data2DReader {
protected DataTable readerTable;
protected TableData2D readerTableData2D;
public DataTableReader(DataTable data) {
readerTable = data;
readerTableData2D = readerTable.getTableData2D();
readerTableData2D.setTableName(readerTable.getSheet());
sourceData = data;
}
@Override
public void readColumnNames() {
try {
names = readerTable.columnNames();
} catch (Exception e) {
showError(e.toString());
}
}
@Override
public void readTotal() {
try {
sourceIndex = readerTableData2D.size(conn());
} catch (Exception e) {
showError(e.toString());
setFailed();
}
}
@Override
public void readPage() {
sourceIndex = readerTable.pagination.startRowOfCurrentPage;
String sql = readerTable.pageQuery();
// showInfo(sql);
try (PreparedStatement statement = conn().prepareStatement(sql);
ResultSet results = statement.executeQuery()) {
while (results.next()) {
makeRecord(readerTableData2D.readData(results));
sourceIndex++;
makePageRow();
}
} catch (Exception e) {
showError(e.toString());
setFailed();
}
}
@Override
public void readRows() {
sourceIndex = 0;
long tableIndex = 0;
long startIndex = sourceData.pagination.startRowOfCurrentPage;
long endIndex = sourceData.pagination.endRowOfCurrentPage;
String sql = "SELECT * FROM " + readerTable.getSheet();
// showInfo(sql);
try (PreparedStatement statement = conn().prepareStatement(sql);
ResultSet results = statement.executeQuery()) {
while (results.next() && !isStopped()) {
try {
if (tableIndex < startIndex || tableIndex >= endIndex) {
makeRecord(readerTableData2D.readData(results));
++sourceIndex;
handleRow();
} else if (tableIndex == startIndex) {
scanPage();
}
tableIndex++;
} catch (Exception e) { // skip bad lines
// showError(e.toString());
// setFailed();
}
}
} catch (Exception e) {
showError(e.toString());
setFailed();
}
}
public void makeRecord(Data2DRow row) {
try {
sourceRow = Data2DRowTools.toStrings(row, readerTable.getColumns());
} catch (Exception e) {
showError(e.toString());
setFailed();
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/reader/Data2DReader.java | alpha/MyBox/src/main/java/mara/mybox/data2d/reader/Data2DReader.java | package mara.mybox.data2d.reader;
import java.io.File;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.data2d.Data2D;
import mara.mybox.data2d.Data2D_Edit;
import mara.mybox.data2d.DataFileCSV;
import mara.mybox.data2d.DataFileExcel;
import mara.mybox.data2d.DataFileText;
import mara.mybox.data2d.DataMatrix;
import mara.mybox.data2d.DataTable;
import mara.mybox.data2d.operate.Data2DOperate;
import mara.mybox.db.DerbyBase;
import mara.mybox.fxml.FxTask;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public abstract class Data2DReader {
protected Data2D sourceData;
protected File sourceFile;
protected Data2DOperate operate;
protected long sourceIndex; // 1-based
protected long pageStartIndex, pageEndIndex; // 0-based
protected String dataComments;
protected List<String> sourceRow, names;
protected List<List<String>> rows = new ArrayList<>();
protected Connection conn;
protected boolean readerHasHeader;
public abstract void readColumnNames();
public abstract void readTotal();
public abstract void readPage();
public abstract void readRows();
public static Data2DReader create(Data2D_Edit data) {
if (data == null) {
return null;
}
if (data instanceof DataFileExcel) {
return new DataFileExcelReader((DataFileExcel) data);
} else if (data instanceof DataFileCSV) {
return new DataFileCSVReader((DataFileCSV) data);
} else if (data instanceof DataFileText) {
return new DataFileTextReader((DataFileText) data);
} else if (data instanceof DataTable) {
return new DataTableReader((DataTable) data);
} else if (data instanceof DataMatrix) {
return new DataFileTextReader((DataFileText) data);
}
return null;
}
public boolean start(boolean scanWholeFile) {
if (sourceData == null || operate == null) {
return false;
}
sourceFile = sourceData.getFile();
readerHasHeader = sourceData.isHasHeader();
sourceIndex = 0; // 1-based
pageStartIndex = sourceData.getStartRowOfCurrentPage();
pageEndIndex = pageStartIndex + sourceData.getPageSize();
dataComments = null;
names = new ArrayList<>();
rows = new ArrayList<>();
sourceRow = new ArrayList<>();
sourceData.startFilter();
if (sourceData.isTmpData()) {
scanPage();
} else if (scanWholeFile || !sourceData.hasPage()
|| sourceData.isMutiplePages() || !sourceData.isDataLoaded()) {
scanFile();
} else {
scanPage();
}
afterScanned();
return true;
}
public void scanFile() {
operate.handleData();
}
public void scanPage() {
try {
for (int r = 0; r < sourceData.tableRowsNumber(); r++) {
if (isStopped()) {
return;
}
sourceRow = sourceData.dataRow(r);
if (sourceRow == null || sourceRow.isEmpty()) {
continue;
}
++sourceIndex;
handleRow();
}
} catch (Exception e) { // skip bad lines
showError(e.toString());
// setFailed();
}
}
public void handleRow() {
try {
operate.handleRow(sourceRow, sourceIndex);
} catch (Exception e) {
showError(e.toString());
}
}
public void makeHeader() {
try {
if (sourceRow == null || sourceRow.isEmpty()) {
readerHasHeader = false;
}
names = new ArrayList<>();
if (readerHasHeader) {
for (int i = 0; i < sourceRow.size(); i++) {
String name = sourceRow.get(i);
if (name == null || name.isBlank()) {
names.add(sourceData.colPrefix() + i);
} else if (names.contains(name)) {
int index = 2;
while (names.contains(name + index)) {
index++;
}
names.add(name + index);
} else {
names.add(name);
}
}
} else {
if (sourceRow != null) {
for (int i = 1; i <= sourceRow.size(); i++) {
names.add(sourceData.colPrefix() + i);
}
}
}
sourceData.setHasHeader(readerHasHeader);
if (!sourceData.hasComments()) {
sourceData.setComments(dataComments);
}
stop();
} catch (Exception e) {
showError(e.toString());
}
}
public void makePageRow() {
List<String> row = new ArrayList<>();
for (int i = 0;
i < Math.min(sourceRow.size(), sourceData.columnsNumber()); i++) {
row.add(sourceRow.get(i));
}
for (int col = row.size(); col < sourceData.columnsNumber(); col++) {
row.add(sourceData.defaultColValue());
}
row.add(0, "" + sourceIndex);
rows.add(row);
}
public void afterScanned() {
try {
sourceData.stopFilter();
if (operate == null && conn != null) {
conn.commit();
conn.close();
conn = null;
}
} catch (Exception e) {
showError(e.toString());
}
}
/*
status
*/
public FxTask task() {
if (operate != null) {
return operate.getTask();
} else {
return null;
}
}
public Connection conn() {
if (operate != null) {
return operate.conn();
} else {
return DerbyBase.getConnection();
}
}
public void showInfo(String info) {
if (operate != null) {
operate.showInfo(info);
}
}
public void showError(String error) {
if (operate != null) {
operate.showError(error);
}
}
public void stop() {
if (operate != null) {
operate.stop();
}
}
public void setFailed() {
if (operate != null) {
operate.setFailed();
}
}
public boolean isStopped() {
return operate == null || operate.isStopped();
}
/*
get/set
*/
public Data2D getSourceData() {
return sourceData;
}
public Data2DOperate getOperate() {
return operate;
}
public void setOperate(Data2DOperate operate) {
this.operate = operate;
}
public List<String> getNames() {
return names;
}
public List<List<String>> getRows() {
return rows;
}
public long getSourceIndex() {
return sourceIndex;
}
public void setSourceIndex(long sourceIndex) {
this.sourceIndex = sourceIndex;
}
public Data2DReader setReaderData(Data2D readerData) {
this.sourceData = readerData;
return this;
}
public Data2DReader setReaderHasHeader(boolean readerHasHeader) {
this.readerHasHeader = readerHasHeader;
return this;
}
public Data2DReader setNames(List<String> names) {
this.names = names;
return this;
}
public String getDataComments() {
return dataComments;
}
public Data2DReader setDataComments(String dataComments) {
this.dataComments = dataComments;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/reader/DataFileTextReader.java | alpha/MyBox/src/main/java/mara/mybox/data2d/reader/DataFileTextReader.java | package mara.mybox.data2d.reader;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.List;
import mara.mybox.data2d.DataFileText;
import mara.mybox.tools.FileTools;
/**
* @Author Mara
* @CreateDate 2022-1-29
* @License Apache License Version 2.0
*/
public class DataFileTextReader extends Data2DReader {
protected DataFileText readerText;
protected BufferedReader textReader;
public DataFileTextReader() {
}
public DataFileTextReader(DataFileText data) {
readerText = data;
sourceData = data;
}
@Override
public void scanFile() {
File validFile = FileTools.removeBOM(task(), sourceFile);
if (validFile == null || isStopped()) {
return;
}
readerText.checkForLoad();
try (BufferedReader reader = new BufferedReader(new FileReader(validFile, readerText.getCharset()))) {
textReader = reader;
operate.handleData();
textReader = null;
reader.close();
} catch (Exception e) {
showError(e.toString());
setFailed();
}
}
protected List<String> readValidLine() {
return readerText.readValidLine(textReader);
}
protected List<String> parseFileLine(String line) {
return readerText.parseFileLine(line);
}
@Override
public void readColumnNames() {
try {
String line, comments;
while ((line = textReader.readLine()) != null && !isStopped()) {
if (line == null || line.isBlank()) {
continue;
}
if (line.startsWith(DataFileText.CommentsMarker)) {
comments = line.substring(DataFileText.CommentsMarker.length(), line.length());
if (dataComments == null) {
dataComments = comments;
} else {
dataComments += "\n" + comments;
}
continue;
}
sourceRow = parseFileLine(line);
if (sourceRow == null || sourceRow.isEmpty()) {
continue;
}
makeHeader();
return;
}
} catch (Exception e) {
showError(e.toString());
}
}
@Override
public void readTotal() {
try {
String line;
sourceIndex = 0;
skipHeader();
while ((line = textReader.readLine()) != null) {
if (isStopped()) {
sourceIndex = 0;
return;
}
List<String> row = parseFileLine(line);
if (row != null && !row.isEmpty()) {
++sourceIndex;
}
}
} catch (Exception e) {
showError(e.toString());
setFailed();
}
}
public void skipHeader() {
try {
if (!readerHasHeader || textReader == null) {
return;
}
String line;
while ((line = textReader.readLine()) != null && !isStopped()) {
sourceRow = parseFileLine(line);
if (sourceRow == null || sourceRow.isEmpty()) {
continue;
}
return;
}
} catch (Exception e) {
showError(e.toString());
setFailed();
}
}
// sourceIndex is 1-base while pageStartIndex and pageEndIndex are 0-based
@Override
public void readPage() {
if (textReader == null) {
return;
}
try {
skipHeader();
sourceIndex = 0;
String line;
while ((line = textReader.readLine()) != null && !isStopped()) {
sourceRow = parseFileLine(line);
if (sourceRow == null || sourceRow.isEmpty()) {
continue;
}
if (sourceIndex++ < pageStartIndex) {
continue;
}
if (sourceIndex > pageEndIndex) {
stop();
break;
}
makePageRow();
}
} catch (Exception e) {
showError(e.toString());
setFailed();
}
}
@Override
public void readRows() {
try {
if (textReader == null) {
return;
}
skipHeader();
sourceIndex = 0;
long fileIndex = -1;
long startIndex = sourceData.pagination.startRowOfCurrentPage;
long endIndex = sourceData.pagination.endRowOfCurrentPage;
String line;
while ((line = textReader.readLine()) != null && !isStopped()) {
sourceRow = parseFileLine(line);
if (sourceRow == null || sourceRow.isEmpty()) {
continue;
}
fileIndex++;
if (fileIndex < startIndex || fileIndex >= endIndex) {
++sourceIndex;
handleRow();
} else if (fileIndex == startIndex) {
scanPage();
}
}
} catch (Exception e) {
showError(e.toString());
setFailed();
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/reader/DataFileCSVReader.java | alpha/MyBox/src/main/java/mara/mybox/data2d/reader/DataFileCSVReader.java | package mara.mybox.data2d.reader;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import mara.mybox.data2d.DataFileCSV;
import mara.mybox.tools.FileTools;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
/**
* @Author Mara
* @CreateDate 2022-1-29
* @License Apache License Version 2.0
*/
public class DataFileCSVReader extends Data2DReader {
protected DataFileCSV readerCSV;
protected Iterator<CSVRecord> iterator;
protected CSVParser csvParser;
public DataFileCSVReader(DataFileCSV data) {
readerCSV = data;
sourceData = data;
}
@Override
public void scanFile() {
File validFile = FileTools.removeBOM(task(), sourceFile);
if (validFile == null || isStopped()) {
return;
}
readerCSV.checkForLoad();
try (CSVParser parser = CSVParser.parse(validFile, readerCSV.getCharset(), readerCSV.cvsFormat())) {
csvParser = parser;
iterator = parser.iterator();
operate.handleData();
csvParser = null;
parser.close();
} catch (Exception e) {
showError(e.toString());
setFailed();
}
}
@Override
public void readColumnNames() {
try {
if (csvParser == null) {
return;
}
sourceRow = null;
dataComments = csvParser.getHeaderComment();
if (readerHasHeader) {
try {
sourceRow = new ArrayList<>();
sourceRow.addAll(csvParser.getHeaderNames());
} catch (Exception e) {
showError(e.toString());
}
} else {
while (iterator.hasNext() && !isStopped()) {
readFileRecord();
if (sourceRow != null && !sourceRow.isEmpty()) {
break;
}
}
}
makeHeader();
} catch (Exception e) {
showError(e.toString());
}
}
@Override
public void readTotal() {
try {
sourceIndex = 0;
if (iterator == null) {
return;
}
while (iterator.hasNext()) {
if (isStopped()) {
sourceIndex = 0;
return;
}
readFileRecord();
if (sourceRow != null && !sourceRow.isEmpty()) {
++sourceIndex;
}
}
} catch (Exception e) {
showError(e.toString());
setFailed();
}
}
// sourceIndex is 1-base while pageStartIndex and pageEndIndex are 0-based
@Override
public void readPage() {
try {
if (iterator == null) {
return;
}
sourceIndex = 0;
while (iterator.hasNext() && !isStopped()) {
readFileRecord();
if (sourceRow == null || sourceRow.isEmpty()) {
continue;
}
if (sourceIndex++ < pageStartIndex) {
continue;
}
if (sourceIndex > pageEndIndex) {
stop();
break;
}
makePageRow();
}
} catch (Exception e) {
showError(e.toString());
setFailed();
}
}
public void readFileRecord() {
try {
sourceRow = null;
if (isStopped() || iterator == null) {
return;
}
CSVRecord csvRecord = iterator.next();
if (csvRecord == null) {
return;
}
sourceRow = new ArrayList<>();
for (String v : csvRecord) {
sourceRow.add(v);
}
} catch (Exception e) {
showError(e.toString());
}
}
@Override
public void readRows() {
try {
if (iterator == null) {
return;
}
sourceIndex = 0;
long fileIndex = -1;
long startIndex = sourceData.pagination.startRowOfCurrentPage;
long endIndex = sourceData.pagination.endRowOfCurrentPage;
while (iterator.hasNext() && !isStopped()) {
try {
readFileRecord();
if (sourceRow == null || sourceRow.isEmpty()) {
continue;
}
fileIndex++;
if (fileIndex < startIndex || fileIndex >= endIndex) {
++sourceIndex;
handleRow();
} else if (fileIndex == startIndex) {
scanPage();
}
} catch (Exception e) { // skip bad lines
// showError(e.toString());
// setFailed();
}
}
} catch (Exception e) {
showError(e.toString());
setFailed();
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadPage.java | alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadPage.java | package mara.mybox.data2d.operate;
import java.sql.Connection;
import java.util.List;
import mara.mybox.data2d.Data2D_Edit;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public class Data2DReadPage extends Data2DOperate {
public static Data2DReadPage create(Data2D_Edit data) {
Data2DReadPage op = new Data2DReadPage();
return op.setSourceData(data) ? op : null;
}
@Override
public boolean go() {
return reader.start(true);
}
@Override
public void handleData() {
reader.readPage();
}
public List<List<String>> getRows() {
return reader.getRows();
}
/*
set
*/
public Data2DReadPage setConn(Connection conn) {
this.conn = conn;
closeConn = false;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadDefinition.java | alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadDefinition.java | package mara.mybox.data2d.operate;
import mara.mybox.data2d.Data2D_Edit;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public class Data2DReadDefinition extends Data2DOperate {
public static Data2DReadDefinition create(Data2D_Edit data) {
Data2DReadDefinition op = new Data2DReadDefinition();
return op.setSourceData(data) ? op : null;
}
@Override
public void handleData() {
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DGroup.java | alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DGroup.java | package mara.mybox.data2d.operate;
import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.data2d.Data2D_Edit;
import mara.mybox.data2d.DataFileCSV;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.CsvTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.FileTools;
import static mara.mybox.value.Languages.message;
import org.apache.commons.csv.CSVPrinter;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public class Data2DGroup extends Data2DOperate {
protected long splitSize, startIndex, currentSize;
protected String prefix;
protected List<Data2DColumn> targetColumns;
protected List<String> names;
protected File currentFile;
protected List<DataFileCSV> files;
protected CSVPrinter csvPrinter;
public static Data2DGroup create(Data2D_Edit data) {
Data2DGroup op = new Data2DGroup();
return op.setSourceData(data) ? op : null;
}
@Override
public boolean checkParameters() {
try {
if (!super.checkParameters() || cols == null || cols.isEmpty() || splitSize <= 0) {
return false;
}
startIndex = 1;
currentSize = 0;
prefix = sourceData.getName();
names = new ArrayList<>();
targetColumns = new ArrayList<>();
for (int c : cols) {
Data2DColumn column = sourceData.column(c);
names.add(column.getColumnName());
targetColumns.add(column.copy());
}
if (includeRowNumber) {
targetColumns.add(0, new Data2DColumn(message("SourceRowNumber"), ColumnDefinition.ColumnType.Long));
}
files = new ArrayList<>();
return true;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
}
@Override
public boolean handleRow() {
try {
targetRow = null;
if (sourceRow == null) {
return false;
}
targetRow = new ArrayList<>();
for (int col : cols) {
if (col >= 0 && col < sourceRow.size()) {
targetRow.add(sourceRow.get(col));
} else {
targetRow.add(null);
}
}
if (targetRow.isEmpty()) {
return false;
}
if (currentFile == null) {
currentFile = FileTmpTools.getTempFile(".csv");
csvPrinter = CsvTools.csvPrinter(currentFile);
csvPrinter.printRecord(names);
startIndex = sourceRowIndex;
}
if (includeRowNumber) {
targetRow.add(0, sourceRowIndex + "");
}
csvPrinter.printRecord(targetRow);
currentSize++;
if (currentSize % splitSize == 0) {
closeFile();
}
return true;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
}
public void closeFile() {
try {
if (csvPrinter == null) {
return;
}
csvPrinter.flush();
csvPrinter.close();
csvPrinter = null;
File file = sourceData.tmpFile(prefix + "_" + startIndex + "-" + sourceRowIndex, null, "csv");
if (FileTools.override(currentFile, file) && file.exists()) {
DataFileCSV dataFileCSV = new DataFileCSV();
dataFileCSV.setTask(task);
dataFileCSV.setColumns(targetColumns)
.setFile(file)
.setCharset(Charset.forName("UTF-8"))
.setDelimiter(",")
.setHasHeader(true)
.setColsNumber(targetColumns.size())
.setRowsNumber(currentSize);
dataFileCSV.saveAttributes();
dataFileCSV.stopTask();
files.add(dataFileCSV);
}
currentFile = null;
currentSize = 0;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
}
}
@Override
public boolean end() {
closeFile();
return super.end();
}
/*
set
*/
public Data2DGroup setSplitSize(int splitSize) {
this.splitSize = splitSize;
return this;
}
/*
get
*/
public List<DataFileCSV> getFiles() {
return files;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadColumnNames.java | alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadColumnNames.java | package mara.mybox.data2d.operate;
import java.util.List;
import mara.mybox.data2d.Data2D_Edit;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public class Data2DReadColumnNames extends Data2DOperate {
public static Data2DReadColumnNames create(Data2D_Edit data) {
Data2DReadColumnNames op = new Data2DReadColumnNames();
return op.setSourceData(data) ? op : null;
}
@Override
public boolean checkParameters() {
if (!super.checkParameters()) {
return false;
}
sourceData.checkForLoad();
return true;
}
@Override
public boolean go() {
return reader.start(true);
}
@Override
public void handleData() {
reader.readColumnNames();
}
public List<String> getNames() {
return reader.getNames();
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DVerify.java | alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DVerify.java | package mara.mybox.data2d.operate;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import mara.mybox.data2d.Data2D;
import mara.mybox.data2d.Data2D_Edit;
import mara.mybox.data2d.tools.Data2DColumnTools;
import mara.mybox.data2d.writer.DataFileCSVWriter;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.dev.MyBoxLog;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public class Data2DVerify extends Data2DOperate {
private DataFileCSVWriter writer;
public static Data2DVerify create(Data2D_Edit data) {
Data2DVerify op = new Data2DVerify();
return op.setSourceData(data) ? op : null;
}
@Override
public boolean checkParameters() {
File csvFile = sourceData.tmpFile(sourceData.getName(), "Verify", "csv");
writer = new DataFileCSVWriter();
writer.setPrintFile(csvFile);
List<Data2DColumn> columns = columns();
writer.setColumns(columns)
.setHeaderNames(Data2DColumnTools.toNames(columns))
.setWriteHeader(true);
addWriter(writer);
return super.checkParameters();
}
@Override
public void handleRow(List<String> row, long index) {
sourceRow = row;
sourceRowIndex = index;
if (sourceRow == null) {
return;
}
List<List<String>> invalids = verify(sourceData, sourceRowIndex, sourceRow);
if (invalids != null) {
for (List<String> invalid : invalids) {
writer.writeRow(invalid);
}
}
}
@Override
public boolean end() {
try {
if (writer == null || writer.getTargetRowIndex() <= 0) {
writer.recordTargetData = false;
}
return super.end();
} catch (Exception e) {
showError(e.toString());
return false;
}
}
@Override
public boolean openResults() {
if (writer == null) {
return false;
}
if (writer.getTargetRowIndex() <= 0) {
controller.popInformation(message("RowsNumber") + ": " + sourceRowIndex + "\n"
+ message("AllValuesValid"), 5000);
return true;
}
return super.openResults();
}
/*
static
*/
public static List<Data2DColumn> columns() {
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message("Row"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message("Column"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message("Invalid"), ColumnDefinition.ColumnType.String));
return columns;
}
public static List<String> columnNames() {
return Data2DColumnTools.toNames(columns());
}
public static List<List<String>> verify(Data2D data, long rowIndex, List<String> row) {
try {
List< List<String>> invalids = new ArrayList<>();
int rowSize = row.size();
for (int c = 0; c < data.columnsNumber(); c++) {
Data2DColumn column = data.column(c);
if (column.isAuto()) {
continue;
}
String value = c < rowSize ? row.get(c) : null;
String item = null;
if (column.isNotNull() && (value == null || value.isBlank())) {
item = message("Null");
} else if (!column.validValue(value)) {
item = message(column.getType().name());
} else if (!data.validValue(value)) {
item = message("TextDataComments");
}
if (item == null) {
continue;
}
List<String> invalid = new ArrayList<>();
invalid.addAll(Arrays.asList((rowIndex + 1) + "", column.getColumnName(), item));
invalids.add(invalid);
}
return invalids;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DOperate.java | alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DOperate.java | package mara.mybox.data2d.operate;
import java.io.File;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javafx.application.Platform;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.BaseLogsController;
import mara.mybox.data2d.Data2D;
import mara.mybox.data2d.Data2D_Edit;
import mara.mybox.data2d.reader.Data2DReader;
import mara.mybox.data2d.writer.Data2DWriter;
import mara.mybox.db.DerbyBase;
import mara.mybox.db.data.ColumnDefinition.InvalidAs;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public abstract class Data2DOperate {
protected BaseController controller;
protected Data2DReader reader;
protected List<Data2DWriter> writers;
protected Data2D sourceData;
protected File sourceFile, targetPath, targetFile;
protected List<String> sourceRow, targetRow;
protected FxTask task;
protected List<Integer> cols, otherCols;
protected int colsLen, scale = -1;
protected boolean includeRowNumber, writeHeader, rowPassFilter, reachMaxFiltered;
protected boolean stopped, needCheckTask, failed, closeConn;
protected long sourceRowIndex; // 1-based
protected long handledCount;
protected InvalidAs invalidAs;
protected Connection conn;
protected List<File> printedFiles;
public Data2DOperate() {
closeConn = true;
}
public String info() {
String s = getClass().toString() + "\n";
if (controller != null) {
s += "controller: " + controller.getClass() + "\n";
}
if (reader != null) {
s += "reader: " + reader.getClass() + "\n";
}
if (sourceData != null) {
s += sourceData.info();
}
return s;
}
/*
reader
*/
public boolean setSourceData(Data2D_Edit data) {
reader = Data2DReader.create(data);
if (reader == null) {
return false;
}
sourceData = reader.getSourceData();
sourceFile = sourceData.getFile();
task = sourceData.getTask();
reader.setOperate(this);
return true;
}
/*
writers
*/
public Data2DOperate addWriter(Data2DWriter writer) {
if (writer == null) {
return this;
}
if (writers == null) {
writers = new ArrayList<>();
}
writers.add(writer.setOperate(this));
return this;
}
public boolean openWriters() {
if (writers == null) {
return true;
}
for (Data2DWriter writer : writers) {
assignPrintFile(writer);
if (!writer.openWriter()) {
failStop(null);
end();
return false;
}
}
return true;
}
public void assignPrintFile(Data2DWriter writer) {
if (writer != null && targetFile != null) {
writer.setPrintFile(targetFile);
}
}
public Data2DOperate addPrintedFile(File file) {
if (file == null || !file.exists()) {
return this;
}
if (printedFiles == null) {
printedFiles = new ArrayList<>();
}
printedFiles.add(file);
return this;
}
public boolean closeWriters() {
if (writers == null) {
return true;
}
for (Data2DWriter writer : writers) {
writer.closeWriter();
}
return true;
}
/*
run
*/
public Data2DOperate start() {
if (!checkParameters() || !go()) {
failStop(null);
}
end();
return this;
}
public boolean checkParameters() {
handledCount = 0;
sourceRowIndex = 0;
sourceRow = null;
targetRow = null;
stopped = false;
failed = false;
rowPassFilter = false;
reachMaxFiltered = false;
if (sourceData == null) {
return false;
}
if (scale < 0) {
scale = sourceData.getScale();
}
if (task != null) {
controller = task.getController();
}
if (task == null) {
controller = sourceData.getController();
}
return openWriters();
}
public boolean go() {
return reader.start(false);
}
public void handleData() {
reader.readRows();
}
public void handleRow(List<String> row, long index) {
sourceRow = row;
sourceRowIndex = index;
targetRow = null;
rowPassFilter = sourceData.filterDataRow(sourceRow, sourceRowIndex);
reachMaxFiltered = sourceData.filterReachMaxPassed();
if (reachMaxFiltered) {
stopped = true;
} else if (rowPassFilter) {
if (handleRow()) {
writeRow();
handledCount++;
}
}
}
public boolean handleRow() {
return false;
}
public void writeRow() {
if (writers == null || targetRow == null) {
return;
}
for (Data2DWriter writer : writers) {
writer.writeRow(targetRow);
}
}
public boolean end() {
try {
closeWriters();
if (conn != null) {
conn.commit();
if (closeConn) {
conn.close();
}
conn = null;
}
return true;
} catch (Exception e) {
showError(e.toString());
return false;
}
}
public boolean openResults() {
if (writers == null || writers.isEmpty()) {
return false;
}
new Timer().schedule(new TimerTask() {
@Override
public void run() {
Platform.runLater(() -> {
for (Data2DWriter writer : writers) {
if (writer.showResult()) {
showInfo(writer.getFileSuffix() + " written.");
} else {
showInfo(writer.getFileSuffix() + " no data.");
}
}
});
Platform.requestNextPulse();
}
}, 200);
return true;
}
/*
status
*/
public Connection conn() {
try {
if (conn == null || conn.isClosed()) {
conn = DerbyBase.getConnection();
}
return conn;
} catch (Exception e) {
showError(e.toString());
setFailed();
return null;
}
}
public FxTask getTask() {
if (task == null && controller != null) {
task = controller.getTask();
}
return task;
}
public void showInfo(String info) {
if (info == null || info.isBlank()) {
return;
}
// MyBoxLog.console(info);
if (controller != null) {
if (controller instanceof BaseLogsController) {
((BaseLogsController) controller).updateLogs(info);
} else if (task != null) {
task.setInfo(info);
} else {
controller.popInformation(info);
}
} else if (task != null) {
task.setInfo(info);
}
}
public void showError(String error) {
if (error == null || error.isBlank()) {
return;
}
// MyBoxLog.console(error);
if (controller != null) {
if (controller instanceof BaseLogsController) {
((BaseLogsController) controller).showLogs(error);
} else if (task != null) {
task.setError(error);
} else {
controller.displayError(error);
}
} else if (task != null) {
task.setError(error);
} else {
MyBoxLog.error(error);
}
}
public void stop() {
stopped = true;
// showInfo(message("Stopped"));
}
public boolean isStopped() {
return stopped;
}
public void setFailed() {
failed = true;
showInfo(message("Failed"));
}
public void failStop(String error) {
fail(error);
stop();
}
public void fail(String error) {
setFailed();
showError(error);
}
public boolean isFailed() {
return failed;
}
/*
set
*/
public Data2DOperate setTask(FxTask task) {
this.task = task;
return this;
}
public Data2DOperate setCols(List<Integer> cols) {
this.cols = cols;
if (cols == null) {
colsLen = 0;
} else {
colsLen = cols.size();
}
return this;
}
public Data2DOperate setOtherCols(List<Integer> otherCols) {
this.otherCols = otherCols;
return this;
}
public Data2DOperate setReader(Data2DReader reader) {
this.reader = reader;
return this;
}
public Data2DOperate setData2D(Data2D data2D) {
this.sourceData = data2D;
return this;
}
public boolean isWriteHeader() {
return writeHeader;
}
public Data2DOperate setWriteHeader(boolean writeHeader) {
this.writeHeader = writeHeader;
return this;
}
public Data2DOperate setIncludeRowNumber(boolean includeRowNumber) {
this.includeRowNumber = includeRowNumber;
return this;
}
public Data2DOperate setSourceRow(List<String> sourceRow) {
this.sourceRow = sourceRow;
return this;
}
public Data2DOperate setRowIndex(long rowIndex) {
this.sourceRowIndex = rowIndex;
return this;
}
public Data2DOperate setScale(int scale) {
this.scale = scale;
return this;
}
public Data2DOperate setInvalidAs(InvalidAs invalidAs) {
this.invalidAs = invalidAs;
return this;
}
public List<Data2DWriter> getWriters() {
return writers;
}
public Data2DOperate setWriters(List<Data2DWriter> writers) {
this.writers = writers;
return this;
}
public Data2DOperate setController(BaseController controller) {
this.controller = controller;
return this;
}
/*
get
*/
public Data2DReader getReader() {
return reader;
}
public Data2D getSourceData() {
return sourceData;
}
public File getSourceFile() {
return sourceFile;
}
public int getScale() {
return scale;
}
public BaseController getController() {
return controller;
}
public long getSourceRowIndex() {
return reader.getSourceIndex();
}
public long getHandledCount() {
return handledCount;
}
public InvalidAs getInvalidAs() {
return invalidAs;
}
public List<File> getPrintedFiles() {
return printedFiles;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DSimpleLinearRegression.java | alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DSimpleLinearRegression.java | package mara.mybox.data2d.operate;
import mara.mybox.calculation.SimpleLinearRegression;
import mara.mybox.data2d.Data2D_Edit;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.DoubleTools;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public class Data2DSimpleLinearRegression extends Data2DOperate {
protected SimpleLinearRegression simpleRegression;
protected double x, y;
public static Data2DSimpleLinearRegression create(Data2D_Edit data) {
Data2DSimpleLinearRegression op = new Data2DSimpleLinearRegression();
return op.setSourceData(data) ? op : null;
}
@Override
public boolean checkParameters() {
return super.checkParameters()
&& cols != null && !cols.isEmpty()
&& simpleRegression != null;
}
@Override
public boolean handleRow() {
try {
targetRow = null;
if (sourceRow == null) {
return false;
}
x = DoubleTools.toDouble(sourceRow.get(cols.get(0)), invalidAs);
y = DoubleTools.toDouble(sourceRow.get(cols.get(1)), invalidAs);
targetRow = simpleRegression.addData(sourceRowIndex, x, y);
return true;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
}
/*
set
*/
public Data2DSimpleLinearRegression setSimpleRegression(SimpleLinearRegression simpleRegression) {
this.simpleRegression = simpleRegression;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadColumns.java | alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadColumns.java | package mara.mybox.data2d.operate;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.data2d.Data2D_Edit;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public class Data2DReadColumns extends Data2DOperate {
protected List<List<String>> rows;
public static Data2DReadColumns create(Data2D_Edit data) {
Data2DReadColumns op = new Data2DReadColumns();
return op.setSourceData(data) ? op : null;
}
@Override
public boolean checkParameters() {
if (!super.checkParameters() || cols == null || cols.isEmpty()) {
return false;
}
rows = new ArrayList<>();
return true;
}
@Override
public boolean handleRow() {
try {
if (sourceRow == null) {
return false;
}
List<String> row = new ArrayList<>();
for (int col : cols) {
if (col >= 0 && col < sourceRow.size()) {
row.add(sourceRow.get(col));
} else {
row.add(null);
}
}
if (row.isEmpty()) {
return false;
}
if (includeRowNumber) {
row.add(0, sourceRowIndex + "");
}
rows.add(row);
return true;
} catch (Exception e) {
showError(e.toString());
return false;
}
}
/*
get
*/
public List<List<String>> getRows() {
return rows;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DCopy.java | alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DCopy.java | package mara.mybox.data2d.operate;
import java.util.ArrayList;
import mara.mybox.data2d.Data2D_Edit;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public class Data2DCopy extends Data2DOperate {
private String value;
private int rowSize;
public static Data2DCopy create(Data2D_Edit data) {
Data2DCopy op = new Data2DCopy();
return op.setSourceData(data) ? op : null;
}
@Override
public boolean checkParameters() {
return super.checkParameters() && cols != null && !cols.isEmpty();
}
@Override
public boolean handleRow() {
try {
targetRow = null;
if (sourceRow == null) {
return false;
}
targetRow = new ArrayList<>();
rowSize = sourceRow.size();
for (int col : cols) {
if (col >= 0 && col < rowSize) {
value = sourceRow.get(col);
} else {
value = null;
}
targetRow.add(value);
}
if (targetRow.isEmpty()) {
return false;
}
if (includeRowNumber) {
targetRow.add(0, sourceRowIndex + "");
}
return true;
} catch (Exception e) {
showError(e.toString());
return false;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DNormalize.java | alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DNormalize.java | package mara.mybox.data2d.operate;
import java.util.ArrayList;
import mara.mybox.calculation.DoubleStatistic;
import mara.mybox.calculation.Normalization;
import mara.mybox.data2d.Data2D_Edit;
import mara.mybox.tools.DoubleTools;
import mara.mybox.value.AppValues;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public class Data2DNormalize extends Data2DOperate {
protected Type type;
protected DoubleStatistic[] statisticData;
protected DoubleStatistic statisticAll;
protected double[] colValues;
protected double from, to, tValue;
protected Normalization.Algorithm a;
public static enum Type {
MinMaxColumns, SumColumns, ZscoreColumns,
Rows, MinMaxAll, SumAll, ZscoreAll
}
public static Data2DNormalize create(Data2D_Edit data) {
Data2DNormalize op = new Data2DNormalize();
return op.setSourceData(data) ? op : null;
}
@Override
public boolean checkParameters() {
if (!super.checkParameters()
|| cols == null || cols.isEmpty() || type == null || invalidAs == null) {
return false;
}
switch (type) {
case MinMaxColumns:
case ZscoreColumns:
if (statisticData == null) {
return false;
}
if (cols == null || cols.isEmpty() || type == null || invalidAs == null) {
return false;
}
break;
case SumColumns:
if (colValues == null) {
return false;
}
break;
case Rows:
if (a == null) {
return false;
}
break;
case MinMaxAll:
case ZscoreAll:
if (statisticAll == null) {
return false;
}
break;
}
return true;
}
@Override
public boolean handleRow() {
switch (type) {
case MinMaxColumns:
return handleNormalizeMinMaxColumns();
case SumColumns:
return handleNormalizeSumColumns();
case ZscoreColumns:
return handleNormalizeZscoreColumns();
case Rows:
return handleNormalizeRows(a);
case MinMaxAll:
return handleNormalizeMinMaxAll();
case SumAll:
return handleNormalizeSumAll();
case ZscoreAll:
return handleNormalizeZscoreAll();
}
return false;
}
public boolean handleNormalizeMinMaxColumns() {
try {
targetRow = null;
if (sourceRow == null) {
return false;
}
targetRow = new ArrayList<>();
if (includeRowNumber) {
targetRow.add("" + sourceRowIndex);
}
for (int c = 0; c < colsLen; c++) {
int i = cols.get(c);
if (i < 0 || i >= sourceRow.size()) {
targetRow.add(null);
} else {
String s = sourceRow.get(i);
double v = DoubleTools.toDouble(s, invalidAs);
if (DoubleTools.invalidDouble(v)) {
targetRow.add(null);
} else {
v = from + statisticData[c].dTmp * (v - statisticData[c].minimum);
targetRow.add(DoubleTools.scale(v, scale) + "");
}
}
}
if (otherCols != null) {
for (int c : otherCols) {
if (c < 0 || c >= sourceRow.size()) {
targetRow.add(null);
} else {
targetRow.add(sourceRow.get(c));
}
}
}
return true;
} catch (Exception e) {
return false;
}
}
public boolean handleNormalizeSumColumns() {
try {
targetRow = null;
if (sourceRow == null) {
return false;
}
targetRow = new ArrayList<>();
if (includeRowNumber) {
targetRow.add("" + sourceRowIndex);
}
for (int c = 0; c < colsLen; c++) {
int i = cols.get(c);
if (i < 0 || i >= sourceRow.size()) {
targetRow.add(null);
} else {
String s = sourceRow.get(i);
double v = DoubleTools.toDouble(s, invalidAs);
if (DoubleTools.invalidDouble(v)) {
targetRow.add(null);
} else {
v = v * colValues[c];
targetRow.add(DoubleTools.scale(v, scale) + "");
}
}
}
if (otherCols != null) {
for (int c : otherCols) {
if (c < 0 || c >= sourceRow.size()) {
targetRow.add(null);
} else {
targetRow.add(sourceRow.get(c));
}
}
}
return true;
} catch (Exception e) {
return false;
}
}
public boolean handleNormalizeZscoreColumns() {
try {
targetRow = null;
if (sourceRow == null) {
return false;
}
targetRow = new ArrayList<>();
if (includeRowNumber) {
targetRow.add("" + sourceRowIndex);
}
for (int c = 0; c < colsLen; c++) {
int i = cols.get(c);
if (i < 0 || i >= sourceRow.size()) {
targetRow.add(null);
} else {
String s = sourceRow.get(i);
double v = DoubleTools.toDouble(s, invalidAs);
if (DoubleTools.invalidDouble(v)) {
targetRow.add(null);
} else {
double k = statisticData[c].getPopulationStandardDeviation();
if (k == 0) {
k = AppValues.TinyDouble;
}
v = (v - statisticData[c].mean) / k;
targetRow.add(DoubleTools.scale(v, scale) + "");
}
}
}
if (otherCols != null) {
for (int c : otherCols) {
if (c < 0 || c >= sourceRow.size()) {
targetRow.add(null);
} else {
targetRow.add(sourceRow.get(c));
}
}
}
return true;
} catch (Exception e) {
return false;
}
}
public boolean handleNormalizeMinMaxAll() {
try {
targetRow = null;
if (sourceRow == null) {
return false;
}
targetRow = new ArrayList<>();
if (includeRowNumber) {
targetRow.add("" + sourceRowIndex);
}
for (int c = 0; c < colsLen; c++) {
int i = cols.get(c);
if (i < 0 || i >= sourceRow.size()) {
targetRow.add(null);
} else {
String s = sourceRow.get(i);
double v = DoubleTools.toDouble(s, invalidAs);
if (DoubleTools.invalidDouble(v)) {
targetRow.add(null);
} else {
v = from + statisticAll.dTmp * (v - statisticAll.minimum);
targetRow.add(DoubleTools.scale(v, scale) + "");
}
}
}
if (otherCols != null) {
for (int c : otherCols) {
if (c < 0 || c >= sourceRow.size()) {
targetRow.add(null);
} else {
targetRow.add(sourceRow.get(c));
}
}
}
return true;
} catch (Exception e) {
return false;
}
}
public boolean handleNormalizeSumAll() {
try {
targetRow = null;
if (sourceRow == null) {
return false;
}
targetRow = new ArrayList<>();
if (includeRowNumber) {
targetRow.add("" + sourceRowIndex);
}
for (int c = 0; c < colsLen; c++) {
int i = cols.get(c);
if (i < 0 || i >= sourceRow.size()) {
targetRow.add(null);
} else {
String s = sourceRow.get(i);
double v = DoubleTools.toDouble(s, invalidAs);
if (DoubleTools.invalidDouble(v)) {
targetRow.add(null);
} else {
v = v * tValue;
targetRow.add(DoubleTools.scale(v, scale) + "");
}
}
}
if (otherCols != null) {
for (int c : otherCols) {
if (c < 0 || c >= sourceRow.size()) {
targetRow.add(null);
} else {
targetRow.add(sourceRow.get(c));
}
}
}
return true;
} catch (Exception e) {
return false;
}
}
public boolean handleNormalizeZscoreAll() {
try {
targetRow = null;
if (sourceRow == null) {
return false;
}
targetRow = new ArrayList<>();
if (includeRowNumber) {
targetRow.add("" + sourceRowIndex);
}
for (int c = 0; c < colsLen; c++) {
int i = cols.get(c);
if (i < 0 || i >= sourceRow.size()) {
targetRow.add(null);
} else {
String s = sourceRow.get(i);
double v = DoubleTools.toDouble(s, invalidAs);
if (DoubleTools.invalidDouble(v)) {
targetRow.add(null);
} else {
double k = statisticAll.getPopulationStandardDeviation();
if (k == 0) {
k = AppValues.TinyDouble;
}
v = (v - statisticAll.mean) / k;
targetRow.add(DoubleTools.scale(v, scale) + "");
}
}
}
if (otherCols != null) {
for (int c : otherCols) {
if (c < 0 || c >= sourceRow.size()) {
targetRow.add(null);
} else {
targetRow.add(sourceRow.get(c));
}
}
}
return true;
} catch (Exception e) {
return false;
}
}
public boolean handleNormalizeRows(Normalization.Algorithm a) {
try {
targetRow = null;
if (sourceRow == null) {
return false;
}
targetRow = new ArrayList<>();
if (includeRowNumber) {
targetRow.add("" + sourceRowIndex);
}
String[] values = new String[colsLen];
for (int c = 0; c < colsLen; c++) {
int i = cols.get(c);
if (i < 0 || i >= sourceRow.size()) {
values[c] = DoubleTools.value(invalidAs) + "";
} else {
values[c] = sourceRow.get(i);
}
}
values = Normalization.create()
.setA(a).setFrom(from).setTo(to).setInvalidAs(invalidAs)
.setSourceVector(values)
.calculate();
if (values == null) {
return false;
}
for (String s : values) {
double d = DoubleTools.toDouble(s, invalidAs);
if (DoubleTools.invalidDouble(d)) {
targetRow.add(null);
} else {
targetRow.add(DoubleTools.scale(d, scale) + "");
}
}
if (otherCols != null) {
for (int c : otherCols) {
if (c < 0 || c >= sourceRow.size()) {
targetRow.add(null);
} else {
targetRow.add(sourceRow.get(c));
}
}
}
return true;
} catch (Exception e) {
return false;
}
}
/*
set
*/
public Data2DNormalize setType(Type type) {
this.type = type;
return this;
}
public Data2DNormalize setStatisticData(DoubleStatistic[] statisticData) {
this.statisticData = statisticData;
return this;
}
public Data2DNormalize setStatisticAll(DoubleStatistic statisticAll) {
this.statisticAll = statisticAll;
return this;
}
public Data2DNormalize setColValues(double[] colValues) {
this.colValues = colValues;
return this;
}
public Data2DNormalize setFrom(double from) {
this.from = from;
return this;
}
public Data2DNormalize setTo(double to) {
this.to = to;
return this;
}
public Data2DNormalize settValue(double tValue) {
this.tValue = tValue;
return this;
}
public Data2DNormalize setA(Normalization.Algorithm a) {
this.a = a;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DStatistic.java | alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DStatistic.java | package mara.mybox.data2d.operate;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.calculation.DescriptiveStatistic;
import mara.mybox.calculation.DescriptiveStatistic.StatisticType;
import mara.mybox.calculation.DoubleStatistic;
import mara.mybox.data2d.Data2D_Edit;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.DoubleTools;
import org.apache.commons.math3.stat.descriptive.moment.Skewness;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public class Data2DStatistic extends Data2DOperate {
protected Type type;
protected DoubleStatistic[] statisticData;
protected DoubleStatistic statisticAll;
protected DescriptiveStatistic statisticCalculation;
protected double[] colValues;
protected List<Skewness> skewnessList;
protected Skewness skewnessAll;
protected boolean sumAbs;
public static enum Type {
ColumnsPass1, ColumnsPass2, Rows, AllPass1, AllPass2
}
public static Data2DStatistic create(Data2D_Edit data) {
Data2DStatistic op = new Data2DStatistic();
return op.setSourceData(data) ? op : null;
}
@Override
public boolean checkParameters() {
if (!super.checkParameters()
|| cols == null || cols.isEmpty() || type == null
|| statisticCalculation == null) {
return false;
}
switch (type) {
case ColumnsPass1:
if (statisticData == null) {
return false;
}
colValues = new double[colsLen];
if (statisticCalculation.include(StatisticType.Skewness)) {
skewnessList = new ArrayList<>();
for (int i = 0; i < cols.size(); i++) {
skewnessList.add(new Skewness());
}
}
break;
case ColumnsPass2:
if (statisticData == null) {
return false;
}
for (int i = 0; i < cols.size(); i++) {
statisticData[i].dTmp = 0;
}
break;
case AllPass1:
if (statisticAll == null) {
return false;
}
if (statisticCalculation.include(StatisticType.Skewness)) {
skewnessAll = new Skewness();
}
break;
case AllPass2:
if (statisticAll == null) {
return false;
}
statisticAll.dTmp = 0;
break;
case Rows:
break;
default:
return false;
}
return true;
}
@Override
public boolean handleRow() {
switch (type) {
case ColumnsPass1:
return handleStatisticColumnsPass1();
case ColumnsPass2:
return handleStatisticColumnsPass2();
case AllPass1:
return handleStatisticAllPass1();
case AllPass2:
return handleStatisticAllPass2();
case Rows:
return handleStatisticRows();
}
return false;
}
public boolean handleStatisticColumnsPass1() {
try {
for (int i = 0; i < colsLen; i++) {
int col = cols.get(i);
if (col < 0 || col >= sourceRow.size()) {
continue;
}
String s = sourceRow.get(col);
double v = DoubleTools.toDouble(s, invalidAs);
if (DoubleTools.invalidDouble(v)) {
switch (invalidAs) {
case Zero:
v = 0;
break;
default:
statisticData[i].invalidCount++;
continue;
}
}
statisticData[i].count++;
if (sumAbs) {
statisticData[i].sum += Math.abs(v);
} else {
statisticData[i].sum += v;
}
if (statisticCalculation.include(StatisticType.MaximumQ4) && v > statisticData[i].maximum) {
statisticData[i].maximum = v;
}
if (statisticCalculation.include(StatisticType.MinimumQ0) && v < statisticData[i].minimum) {
statisticData[i].minimum = v;
}
if (statisticCalculation.include(StatisticType.GeometricMean)) {
statisticData[i].geometricMean = statisticData[i].geometricMean * v;
}
if (statisticCalculation.include(StatisticType.SumOfSquares)) {
statisticData[i].sumSquares += v * v;
}
if (statisticCalculation.include(StatisticType.Skewness)) {
skewnessList.get(i).increment(v);
}
}
return true;
} catch (Exception e) {
return false;
}
}
public boolean handleStatisticColumnsPass2() {
try {
for (int c = 0; c < colsLen; c++) {
if (statisticData[c].count == 0) {
continue;
}
int i = cols.get(c);
if (i < 0 || i >= sourceRow.size()) {
continue;
}
String s = sourceRow.get(i);
double v = DoubleTools.toDouble(s, invalidAs);
if (DoubleTools.invalidDouble(v)) {
switch (invalidAs) {
case Zero:
v = 0;
break;
default:
continue;
}
}
v = v - statisticData[c].mean;
statisticData[c].dTmp += v * v;
}
return true;
} catch (Exception e) {
return false;
}
}
public boolean handleStatisticAllPass1() {
try {
for (int c = 0; c < colsLen; c++) {
int i = cols.get(c);
if (i < 0 || i >= sourceRow.size()) {
continue;
}
String s = sourceRow.get(i);
double v = DoubleTools.toDouble(s, invalidAs);
if (DoubleTools.invalidDouble(v)) {
switch (invalidAs) {
case Zero:
v = 0;
break;
default:
statisticAll.invalidCount++;
continue;
}
}
statisticAll.count++;
statisticAll.sum += v;
if (statisticCalculation.include(StatisticType.MaximumQ4) && v > statisticAll.maximum) {
statisticAll.maximum = v;
}
if (statisticCalculation.include(StatisticType.MinimumQ0) && v < statisticAll.minimum) {
statisticAll.minimum = v;
}
if (statisticCalculation.include(StatisticType.GeometricMean)) {
statisticAll.geometricMean = statisticAll.geometricMean * v;
}
if (statisticCalculation.include(StatisticType.SumOfSquares)) {
statisticAll.sumSquares += v * v;
}
if (statisticCalculation.include(StatisticType.Skewness)) {
skewnessAll.increment(v);
}
}
return true;
} catch (Exception e) {
return false;
}
}
public boolean handleStatisticAllPass2() {
try {
for (int c = 0; c < colsLen; c++) {
if (statisticAll.count == 0) {
continue;
}
int i = cols.get(c);
if (i < 0 || i >= sourceRow.size()) {
continue;
}
String s = sourceRow.get(i);
double v = DoubleTools.toDouble(s, invalidAs);
if (DoubleTools.invalidDouble(v)) {
switch (invalidAs) {
case Zero:
v = 0;
break;
default:
continue;
}
}
v = v - statisticAll.mean;
statisticAll.dTmp += v * v;
}
return true;
} catch (Exception e) {
return false;
}
}
public boolean handleStatisticRows() {
try {
targetRow = null;
if (sourceRow == null) {
return false;
}
targetRow = new ArrayList<>();
int startIndex;
if (statisticCalculation.getCategoryName() == null) {
targetRow.add("" + sourceRowIndex);
startIndex = 0;
} else {
targetRow.add(sourceRow.get(cols.get(0)));
startIndex = 1;
}
String[] values = new String[colsLen - startIndex];
for (int c = startIndex; c < colsLen; c++) {
int i = cols.get(c);
if (i < 0 || i >= sourceRow.size()) {
continue;
}
values[c - startIndex] = sourceRow.get(i);
}
DoubleStatistic statistic = new DoubleStatistic(values, statisticCalculation);
targetRow.addAll(statistic.toStringList());
return true;
} catch (Exception e) {
return false;
}
}
@Override
public boolean end() {
try {
switch (type) {
case ColumnsPass1:
for (int c = 0; c < colsLen; c++) {
if (statisticData[c].count > 0) {
if (!DoubleTools.invalidDouble(statisticData[c].sum)) {
statisticData[c].mean = statisticData[c].sum / statisticData[c].count;
} else {
statisticData[c].mean = Double.NaN;
}
if (statisticCalculation.include(StatisticType.GeometricMean)) {
if (!DoubleTools.invalidDouble(statisticData[c].geometricMean)) {
statisticData[c].geometricMean = Math.pow(statisticData[c].geometricMean, 1d / statisticData[c].count);
} else {
statisticData[c].geometricMean = Double.NaN;
}
}
} else {
statisticData[c].mean = Double.NaN;
statisticData[c].geometricMean = Double.NaN;
}
if (statisticCalculation.include(StatisticType.Skewness)) {
statisticData[c].skewness = skewnessList.get(c).getResult();
}
if (statisticData[c].maximum == -Double.MAX_VALUE) {
statisticData[c].maximum = Double.NaN;
}
if (statisticData[c].minimum == Double.MAX_VALUE) {
statisticData[c].minimum = Double.NaN;
}
}
break;
case ColumnsPass2:
for (int c = 0; c < colsLen; c++) {
if (statisticData[c].count > 0 && !DoubleTools.invalidDouble(statisticData[c].dTmp)) {
statisticData[c].populationVariance = statisticData[c].dTmp / statisticData[c].count;
statisticData[c].sampleVariance = statisticData[c].dTmp / (statisticData[c].count - 1);
if (statisticCalculation.include(StatisticType.PopulationStandardDeviation)) {
statisticData[c].populationStandardDeviation = Math.sqrt(statisticData[c].populationVariance);
}
if (statisticCalculation.include(StatisticType.SampleStandardDeviation)) {
statisticData[c].sampleStandardDeviation = Math.sqrt(statisticData[c].sampleVariance);
}
} else {
statisticData[c].populationVariance = Double.NaN;
statisticData[c].sampleVariance = Double.NaN;
statisticData[c].populationStandardDeviation = Double.NaN;
statisticData[c].sampleStandardDeviation = Double.NaN;
}
}
break;
case AllPass1:
if (statisticAll.count > 0) {
if (!DoubleTools.invalidDouble(statisticAll.sum)) {
statisticAll.mean = statisticAll.sum / statisticAll.count;
} else {
statisticAll.mean = Double.NaN;
}
if (statisticCalculation.include(StatisticType.GeometricMean)) {
if (!DoubleTools.invalidDouble(statisticAll.geometricMean)) {
statisticAll.geometricMean = Math.pow(statisticAll.geometricMean, 1d / statisticAll.count);
} else {
statisticAll.geometricMean = Double.NaN;
}
}
} else {
statisticAll.mean = Double.NaN;
statisticAll.geometricMean = Double.NaN;
}
if (statisticCalculation.include(StatisticType.Skewness)) {
statisticAll.skewness = skewnessAll.getResult();
}
if (statisticAll.maximum == -Double.MAX_VALUE) {
statisticAll.maximum = Double.NaN;
}
if (statisticAll.minimum == Double.MAX_VALUE) {
statisticAll.minimum = Double.NaN;
}
break;
case AllPass2:
if (statisticAll.count > 0 && !DoubleTools.invalidDouble(statisticAll.dTmp)) {
statisticAll.populationVariance = statisticAll.dTmp / statisticAll.count;
statisticAll.sampleVariance = statisticAll.dTmp / (statisticAll.count - 1);
if (statisticCalculation.include(StatisticType.PopulationStandardDeviation)) {
statisticAll.populationStandardDeviation = Math.sqrt(statisticAll.populationVariance);
}
if (statisticCalculation.include(StatisticType.SampleStandardDeviation)) {
statisticAll.sampleStandardDeviation = Math.sqrt(statisticAll.sampleVariance);
}
} else {
statisticAll.populationVariance = Double.NaN;
statisticAll.sampleVariance = Double.NaN;
statisticAll.populationStandardDeviation = Double.NaN;
statisticAll.sampleStandardDeviation = Double.NaN;
}
break;
}
return super.end();
} catch (Exception e) {
MyBoxLog.error(e);
if (task != null) {
task.setError(e.toString());
}
return false;
}
}
/*
set
*/
public Data2DStatistic setType(Type type) {
this.type = type;
return this;
}
public Data2DStatistic setStatisticData(DoubleStatistic[] statisticData) {
this.statisticData = statisticData;
return this;
}
public Data2DStatistic setStatisticAll(DoubleStatistic statisticAll) {
this.statisticAll = statisticAll;
return this;
}
public Data2DStatistic setStatisticCalculation(DescriptiveStatistic statisticCalculation) {
this.statisticCalculation = statisticCalculation;
invalidAs = statisticCalculation.invalidAs;
return this;
}
public Data2DStatistic setSumAbs(boolean sumAbs) {
this.sumAbs = sumAbs;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DSingleColumn.java | alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DSingleColumn.java | package mara.mybox.data2d.operate;
import java.sql.Connection;
import mara.mybox.data2d.Data2D_Edit;
import mara.mybox.data2d.DataTable;
import mara.mybox.db.Database;
import mara.mybox.db.data.ColumnDefinition.InvalidAs;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.db.data.Data2DRow;
import mara.mybox.db.table.TableData2D;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public class Data2DSingleColumn extends Data2DOperate {
protected DataTable writerTable;
protected TableData2D writerTableData2D;
protected long count;
public static Data2DSingleColumn create(Data2D_Edit data) {
Data2DSingleColumn op = new Data2DSingleColumn();
return op.setSourceData(data) ? op : null;
}
@Override
public boolean checkParameters() {
if (!super.checkParameters()
|| cols == null || cols.isEmpty()
|| conn == null || writerTable == null) {
return false;
}
writerTableData2D = writerTable.getTableData2D();
count = 0;
return true;
}
@Override
public boolean handleRow() {
try {
if (sourceRow == null) {
return false;
}
int len = sourceRow.size();
for (int col : cols) {
if (col >= 0 && col < len) {
Data2DRow data2DRow = writerTableData2D.newRow();
Data2DColumn targetColumn = writerTable.columnByName("data");
String value = sourceRow.get(col);
if (targetColumn != null) {
data2DRow.setValue("data", targetColumn.fromString(value, InvalidAs.Empty));
writerTableData2D.insertData(conn, data2DRow);
if (++count % Database.BatchSize == 0) {
conn.commit();
}
}
}
}
return true;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
}
/*
set
*/
public Data2DSingleColumn setConn(Connection conn) {
this.conn = conn;
closeConn = false;
return this;
}
public Data2DSingleColumn setWriterTable(DataTable writerTable) {
this.writerTable = writerTable;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DRange.java | alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DRange.java | package mara.mybox.data2d.operate;
import java.util.ArrayList;
import mara.mybox.data2d.Data2D_Edit;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public class Data2DRange extends Data2DOperate {
protected long start, end; // 1-based, include end
public static Data2DRange create(Data2D_Edit data) {
Data2DRange op = new Data2DRange();
return op.setSourceData(data) ? op : null;
}
@Override
public boolean checkParameters() {
return super.checkParameters() && cols != null && !cols.isEmpty();
}
@Override
public boolean handleRow() {
try {
targetRow = null;
if (sourceRow == null) {
return false;
}
targetRow = new ArrayList<>();
for (int col : cols) {
if (col >= 0 && col < sourceRow.size()) {
targetRow.add(sourceRow.get(col));
} else {
targetRow.add(null);
}
}
if (targetRow.isEmpty() || sourceRowIndex < start) {
return false;
}
if (sourceRowIndex > end) {
stop();
return false;
}
if (includeRowNumber) {
targetRow.add(0, sourceRowIndex + "");
}
return true;
} catch (Exception e) {
showError(e.toString());
return false;
}
}
/*
set
*/
public Data2DRange setStart(long start) {
this.start = start;
return this;
}
public Data2DRange setEnd(long end) {
this.end = end;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadTotal.java | alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadTotal.java | package mara.mybox.data2d.operate;
import mara.mybox.data2d.Data2D_Edit;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public class Data2DReadTotal extends Data2DOperate {
public static Data2DReadTotal create(Data2D_Edit data) {
Data2DReadTotal op = new Data2DReadTotal();
return op.setSourceData(data) ? op : null;
}
@Override
public boolean go() {
return reader.start(true);
}
@Override
public void handleData() {
reader.readTotal();
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadRows.java | alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadRows.java | package mara.mybox.data2d.operate;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.data2d.Data2D_Edit;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public class Data2DReadRows extends Data2DOperate {
protected List<List<String>> rows;
protected long maxCount = -1;
public static Data2DReadRows create(Data2D_Edit data) {
Data2DReadRows op = new Data2DReadRows();
return op.setSourceData(data) ? op : null;
}
@Override
public boolean checkParameters() {
if (!super.checkParameters()) {
return false;
}
rows = new ArrayList<>();
return true;
}
@Override
public boolean handleRow() {
try {
if (sourceRow == null) {
return false;
}
List<String> row = new ArrayList<>();
row.addAll(sourceRow);
if (includeRowNumber) {
row.add(0, sourceRowIndex + "");
}
rows.add(row);
if (maxCount > 0 && handledCount >= maxCount) {
stopped = true;
}
return true;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
}
/*
get
*/
public List<List<String>> getRows() {
return rows;
}
public Data2DReadRows setMaxCount(long maxCount) {
this.maxCount = maxCount;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DFrequency.java | alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DFrequency.java | package mara.mybox.data2d.operate;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Iterator;
import mara.mybox.data2d.Data2D_Edit;
import mara.mybox.db.DerbyBase;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.DoubleTools;
import mara.mybox.tools.NumberTools;
import static mara.mybox.value.Languages.message;
import org.apache.commons.math3.stat.Frequency;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public class Data2DFrequency extends Data2DOperate {
protected Frequency frequency;
protected int colIndex;
public static Data2DFrequency create(Data2D_Edit data) {
Data2DFrequency op = new Data2DFrequency();
return op.setSourceData(data) ? op : null;
}
@Override
public boolean checkParameters() {
return super.checkParameters() && frequency != null && colIndex >= 0;
}
@Override
public boolean go() {
if (!sourceData.isTable() || sourceData.needFilter()) {
return reader.start(false);
} else {
return goTable();
}
}
@Override
public boolean handleRow() {
try {
frequency.addValue(sourceRow.get(colIndex));
return true;
} catch (Exception e) {
return false;
}
}
@Override
public boolean end() {
try {
targetRow = new ArrayList<>();
targetRow.add(message("All"));
targetRow.add(frequency.getSumFreq() + "");
targetRow.add("100");
writeRow();
handledCount = 1;
Iterator iterator = frequency.valuesIterator();
if (iterator != null) {
while (iterator.hasNext()) {
Object o = iterator.next();
targetRow.clear();
String value = o == null ? null : (String) o;
targetRow.add(value);
targetRow.add(frequency.getCount(value) + "");
targetRow.add(NumberTools.format(frequency.getPct(value) * 100, scale));
writeRow();
handledCount++;
}
}
frequency.clear();
return super.end();
} catch (Exception e) {
MyBoxLog.error(e);
if (task != null) {
task.setError(e.toString());
}
return false;
}
}
public boolean goTable() {
try {
int total = 0;
conn = conn();
String sql = "SELECT count(*) AS mybox99_count FROM " + sourceData.getSheet();
if (task != null) {
task.setInfo(sql);
}
try (PreparedStatement statement = conn.prepareStatement(sql);
ResultSet results = statement.executeQuery()) {
if (results.next()) {
total = results.getInt("mybox99_count");
}
} catch (Exception e) {
}
if (total == 0) {
if (task != null) {
task.setError(message("NoData"));
}
return false;
}
targetRow = new ArrayList<>();
targetRow.add(message("All"));
targetRow.add(total + "");
targetRow.add("100");
writeRow();
handledCount = 0;
String colName = sourceData.columnName(colIndex);
sql = "SELECT " + colName + ", count(*) AS mybox99_count FROM " + sourceData.getSheet()
+ " GROUP BY " + colName + " ORDER BY mybox99_count DESC";
if (task != null) {
task.setInfo(sql);
}
try (PreparedStatement statement = conn.prepareStatement(sql);
ResultSet results = statement.executeQuery()) {
String sname = DerbyBase.savedName(colName);
while (results.next() && task != null && !task.isCancelled()) {
targetRow = new ArrayList<>();
Object c = results.getObject(sname);
targetRow.add(c != null ? c.toString() : null);
int count = results.getInt("mybox99_count");
targetRow.add(count + "");
targetRow.add(DoubleTools.percentage(count, total, scale));
writeRow();
handledCount++;
}
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
return true;
}
/*
set
*/
public Data2DFrequency setFrequency(Frequency frequency) {
this.frequency = frequency;
return this;
}
public Data2DFrequency setColIndex(int colIndex) {
this.colIndex = colIndex;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DSaveAs.java | alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DSaveAs.java | package mara.mybox.data2d.operate;
import mara.mybox.data2d.Data2D_Edit;
import mara.mybox.data2d.writer.Data2DWriter;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public class Data2DSaveAs extends Data2DOperate {
public static Data2DSaveAs writeTo(Data2D_Edit data, Data2DWriter writer) {
if (data == null || writer == null) {
return null;
}
Data2DSaveAs operate = new Data2DSaveAs();
if (!operate.setSourceData(data)) {
return null;
}
operate.addWriter(writer);
return operate;
}
@Override
public boolean handleRow() {
try {
targetRow = null;
if (sourceRow == null) {
return false;
}
targetRow = sourceRow;
return true;
} catch (Exception e) {
showError(e.toString());
return false;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DSplit.java | alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DSplit.java | package mara.mybox.data2d.operate;
import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.data2d.Data2D_Edit;
import mara.mybox.data2d.DataFileCSV;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.CsvTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.FileTools;
import static mara.mybox.value.Languages.message;
import org.apache.commons.csv.CSVPrinter;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public class Data2DSplit extends Data2DOperate {
protected long splitSize, startIndex, currentSize;
protected String prefix;
protected List<Data2DColumn> targetColumns;
protected List<String> names;
protected File currentFile;
protected List<DataFileCSV> files;
protected CSVPrinter csvPrinter;
public static Data2DSplit create(Data2D_Edit data) {
Data2DSplit op = new Data2DSplit();
return op.setSourceData(data) ? op : null;
}
@Override
public boolean checkParameters() {
try {
if (!super.checkParameters()
|| cols == null || cols.isEmpty() || splitSize <= 0) {
return false;
}
startIndex = 1;
currentSize = 0;
prefix = sourceData.getName();
names = new ArrayList<>();
targetColumns = new ArrayList<>();
for (int c : cols) {
Data2DColumn column = sourceData.column(c);
names.add(column.getColumnName());
targetColumns.add(column.copy());
}
if (includeRowNumber) {
targetColumns.add(0, new Data2DColumn(message("SourceRowNumber"), ColumnDefinition.ColumnType.Long));
}
files = new ArrayList<>();
return true;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
}
@Override
public boolean handleRow() {
try {
if (sourceRow == null) {
return false;
}
List<String> row = new ArrayList<>();
for (int col : cols) {
if (col >= 0 && col < sourceRow.size()) {
row.add(sourceRow.get(col));
} else {
row.add(null);
}
}
if (row.isEmpty()) {
return false;
}
if (currentFile == null) {
currentFile = FileTmpTools.getTempFile(".csv");
csvPrinter = CsvTools.csvPrinter(currentFile);
csvPrinter.printRecord(names);
startIndex = sourceRowIndex;
}
if (includeRowNumber) {
row.add(0, sourceRowIndex + "");
}
csvPrinter.printRecord(row);
currentSize++;
if (currentSize % splitSize == 0) {
closeFile();
}
return true;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
}
public void closeFile() {
try {
if (csvPrinter == null) {
return;
}
csvPrinter.flush();
csvPrinter.close();
csvPrinter = null;
File file = sourceData.tmpFile(prefix + "_" + startIndex + "-" + sourceRowIndex, null, "csv");
if (FileTools.override(currentFile, file) && file.exists()) {
DataFileCSV dataFileCSV = new DataFileCSV();
dataFileCSV.setTask(task);
dataFileCSV.setColumns(targetColumns)
.setFile(file)
.setCharset(Charset.forName("UTF-8"))
.setDelimiter(",")
.setHasHeader(true)
.setColsNumber(targetColumns.size())
.setRowsNumber(currentSize);
dataFileCSV.saveAttributes();
dataFileCSV.stopTask();
files.add(dataFileCSV);
}
currentFile = null;
currentSize = 0;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
}
}
@Override
public boolean end() {
closeFile();
return super.end();
}
/*
set
*/
public Data2DSplit setSplitSize(int splitSize) {
this.splitSize = splitSize;
return this;
}
/*
get
*/
public List<DataFileCSV> getFiles() {
return files;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DRowExpression.java | alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DRowExpression.java | package mara.mybox.data2d.operate;
import java.util.ArrayList;
import mara.mybox.data2d.Data2D_Edit;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public class Data2DRowExpression extends Data2DOperate {
protected String script, name;
public static Data2DRowExpression create(Data2D_Edit data) {
Data2DRowExpression op = new Data2DRowExpression();
return op.setSourceData(data) ? op : null;
}
@Override
public boolean checkParameters() {
return super.checkParameters()
&& cols != null && !cols.isEmpty()
&& script != null && name != null;
}
@Override
public boolean handleRow() {
try {
targetRow = null;
if (sourceRow == null) {
return false;
}
targetRow = new ArrayList<>();
int rowSize = sourceRow.size();
for (int col : cols) {
if (col >= 0 && col < rowSize) {
targetRow.add(sourceRow.get(col));
} else {
targetRow.add(null);
}
}
if (targetRow.isEmpty()) {
return false;
}
if (includeRowNumber) {
targetRow.add(0, sourceRowIndex + "");
}
if (sourceData.calculateDataRowExpression(script, sourceRow, sourceRowIndex)) {
targetRow.add(sourceData.expressionResult());
return true;
} else {
stop();
return false;
}
} catch (Exception e) {
showError(e.toString());
return false;
}
}
/*
set
*/
public Data2DRowExpression setScript(String script) {
this.script = script;
return this;
}
public Data2DRowExpression setName(String name) {
this.name = name;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DExport.java | alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DExport.java | package mara.mybox.data2d.operate;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.controller.ControlTargetFile;
import mara.mybox.data2d.Data2D_Attributes.TargetType;
import mara.mybox.data2d.Data2D_Edit;
import mara.mybox.data2d.tools.Data2DColumnTools;
import mara.mybox.data2d.writer.Data2DWriter;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.tools.FileNameTools;
import mara.mybox.value.AppPaths;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public class Data2DExport extends Data2DOperate {
protected ControlTargetFile pathController;
protected List<Data2DColumn> columns;
protected List<String> columnNames;
protected TargetType format;
protected String indent = " ", dataName, filePrefix;
protected int maxLines, fileIndex, fileRowIndex;
public Data2DExport() {
resetExport();
}
public static Data2DExport create(Data2D_Edit data) {
Data2DExport op = new Data2DExport();
return op.setSourceData(data) ? op : null;
}
final public void resetExport() {
maxLines = -1;
format = null;
columns = null;
columnNames = null;
filePrefix = null;
fileIndex = 1;
fileRowIndex = 0;
}
@Override
public boolean checkParameters() {
return cols != null && !cols.isEmpty()
&& writers != null && !writers.isEmpty()
&& super.checkParameters();
}
@Override
public void assignPrintFile(Data2DWriter writer) {
if (writer == null) {
return;
}
if (targetFile != null) {
writer.setPrintFile(targetFile);
} else if (pathController != null) {
String name = filePrefix + (maxLines > 0 ? fileIndex : "");
writer.setPrintFile(pathController.makeTargetFile(name,
"." + writer.getFileSuffix(), targetPath));
}
}
public void checkFileSplit() {
if (maxLines > 0 && fileRowIndex >= maxLines) {
closeWriters();
fileIndex++;
fileRowIndex = 0;
openWriters();
}
}
@Override
public boolean handleRow() {
try {
targetRow = null;
if (sourceRow == null) {
return false;
}
checkFileSplit();
targetRow = new ArrayList<>();
for (int col : cols) {
if (col >= 0 && col < sourceRow.size()) {
String value = sourceRow.get(col);
targetRow.add(value);
} else {
targetRow.add(null);
}
}
if (targetRow.isEmpty()) {
return false;
}
fileRowIndex++;
if (includeRowNumber) {
targetRow.add(0, sourceRowIndex + "");
}
return true;
} catch (Exception e) {
showError(e.toString());
return false;
}
}
/*
control by external method
*/
public boolean initExport(ControlTargetFile controller, List<String> cols, String prefix) {
pathController = controller;
columnNames = cols;
columns = Data2DColumnTools.toColumns(columnNames);
return initExport(prefix);
}
public boolean initExport(String prefix) {
targetFile = null;
if (pathController == null || writers == null || writers.isEmpty()
|| columns == null || columns.isEmpty()) {
return false;
}
filePrefix = prefix != null ? prefix : "mexport";
File file = pathController.pickFile();
if (file == null) {
targetPath = new File(AppPaths.getGeneratedPath() + File.separator);
} else if (file.isDirectory()) {
targetPath = file;
} else {
targetPath = file.getParentFile();
}
if (!pathController.isIsDirectory()) {
if (file != null) {
if (!file.exists()) {
targetFile = file;
} else {
filePrefix = FileNameTools.prefix(file.getName());
}
}
}
if (includeRowNumber) {
if (columns != null) {
columns.add(0, new Data2DColumn(message("RowNumber"), ColumnDefinition.ColumnType.Long));
}
if (columnNames != null) {
columnNames.add(0, message("RowNumber"));
}
}
for (Data2DWriter writer : writers) {
writer.setColumns(columns).setHeaderNames(columnNames);
}
sourceRowIndex = 0;
fileIndex = 1;
fileRowIndex = 0;
return true;
}
public void writeRow(List<String> inRow) {
try {
if (inRow == null) {
return;
}
checkFileSplit();
targetRow = new ArrayList<>();
for (int i = 0; i < inRow.size(); i++) {
String v = inRow.get(i);
targetRow.add(v);
}
fileRowIndex++;
sourceRowIndex++;
if (includeRowNumber) {
targetRow.add(0, sourceRowIndex + "");
}
writeRow();
} catch (Exception e) {
showError(e.toString());
}
}
/*
set / get
*/
public Data2DExport setPathController(ControlTargetFile pathController) {
this.pathController = pathController;
return this;
}
public List<String> getColumnNames() {
return columnNames;
}
public Data2DExport setColumnNames(List<String> columnNames) {
this.columnNames = columnNames;
return this;
}
public List<Data2DColumn> getColumns() {
return columns;
}
public Data2DExport setColumns(List<Data2DColumn> columns) {
this.columns = columns;
return this;
}
public String getIndent() {
return indent;
}
public Data2DExport setIndent(String indent) {
this.indent = indent;
return this;
}
public String getFilePrefix() {
return filePrefix;
}
public Data2DExport setFilePrefix(String filePrefix) {
this.filePrefix = filePrefix;
return this;
}
public int getMaxLines() {
return maxLines;
}
public Data2DExport setMaxLines(int maxLines) {
this.maxLines = maxLines;
return this;
}
public File getTargetPath() {
return targetPath;
}
public Data2DExport setTargetPath(File targetPath) {
this.targetPath = targetPath;
return this;
}
public File getTargetFile() {
return targetFile;
}
public Data2DExport setTargetFile(File targetFile) {
this.targetFile = targetFile;
return this;
}
public String getDataName() {
return dataName;
}
public Data2DExport setDataName(String dataName) {
this.dataName = dataName;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DPrecentage.java | alpha/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DPrecentage.java | package mara.mybox.data2d.operate;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.data2d.Data2D_Edit;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.DoubleTools;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public class Data2DPrecentage extends Data2DOperate {
protected Type type;
protected double[] colValues;
protected double tValue;
protected String toNegative;
protected List<String> firstRow;
public static enum Type {
ColumnsPass1, ColumnsPass2, Rows, AllPass1, AllPass2
}
public static Data2DPrecentage create(Data2D_Edit data) {
Data2DPrecentage op = new Data2DPrecentage();
return op.setSourceData(data) ? op : null;
}
@Override
public boolean checkParameters() {
if (!super.checkParameters() || cols == null || cols.isEmpty() || type == null) {
return false;
}
switch (type) {
case ColumnsPass1:
colValues = new double[colsLen];
break;
case ColumnsPass2:
if (colValues == null) {
return false;
}
break;
case AllPass1:
tValue = 0d;
break;
case AllPass2:
break;
case Rows:
break;
default:
return false;
}
return true;
}
@Override
public boolean openWriters() {
if (!super.openWriters()) {
return false;
}
if (firstRow != null) {
targetRow = firstRow;
writeRow();
}
return true;
}
@Override
public boolean handleRow() {
switch (type) {
case ColumnsPass1:
return handlePercentageColumnsPass1();
case ColumnsPass2:
return handlePercentageColumnsPass2();
case AllPass1:
return handlePercentageAllPass1();
case AllPass2:
return handlePercentageAllPass2();
case Rows:
return handlePercentageRows();
}
return false;
}
public boolean handlePercentageColumnsPass1() {
try {
if (sourceRow == null) {
return false;
}
for (int c = 0; c < colsLen; c++) {
int i = cols.get(c);
if (i < 0 || i >= sourceRow.size()) {
continue;
}
double d = DoubleTools.toDouble(sourceRow.get(i), invalidAs);
if (DoubleTools.invalidDouble(d)) {
} else if (d < 0) {
if ("abs".equals(toNegative)) {
colValues[c] += Math.abs(d);
}
} else if (d > 0) {
colValues[c] += d;
}
}
return true;
} catch (Exception e) {
return false;
}
}
public boolean handlePercentageColumnsPass2() {
try {
targetRow = null;
if (sourceRow == null) {
return false;
}
targetRow = new ArrayList<>();
targetRow.add("" + sourceRowIndex);
for (int c = 0; c < colsLen; c++) {
int i = cols.get(c);
double d;
if (i >= 0 && i < sourceRow.size()) {
d = DoubleTools.toDouble(sourceRow.get(i), invalidAs);
} else {
d = DoubleTools.value(invalidAs);
}
double s = colValues[c];
if (DoubleTools.invalidDouble(d) || s == 0) {
targetRow.add(Double.NaN + "");
} else {
if (d < 0) {
if ("skip".equals(toNegative)) {
targetRow.add(Double.NaN + "");
continue;
} else if ("abs".equals(toNegative)) {
d = Math.abs(d);
} else {
d = 0;
}
}
targetRow.add(DoubleTools.percentage(d, s, scale));
}
}
if (otherCols != null) {
for (int c : otherCols) {
if (c < 0 || c >= sourceRow.size()) {
targetRow.add(null);
} else {
targetRow.add(sourceRow.get(c));
}
}
}
return true;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
}
public boolean handlePercentageAllPass1() {
try {
if (sourceRow == null) {
return false;
}
for (int c = 0; c < colsLen; c++) {
int i = cols.get(c);
if (i < 0 || i >= sourceRow.size()) {
continue;
}
double d = DoubleTools.toDouble(sourceRow.get(i), invalidAs);
if (DoubleTools.invalidDouble(d)) {
} else if (d < 0) {
if ("abs".equals(toNegative)) {
tValue += Math.abs(d);
}
} else if (d > 0) {
tValue += d;
}
}
return true;
} catch (Exception e) {
return false;
}
}
public boolean handlePercentageAllPass2() {
try {
targetRow = null;
if (sourceRow == null) {
return false;
}
targetRow = new ArrayList<>();
targetRow.add("" + sourceRowIndex);
for (int c = 0; c < colsLen; c++) {
int i = cols.get(c);
double d;
if (i >= 0 && i < sourceRow.size()) {
d = DoubleTools.toDouble(sourceRow.get(i), invalidAs);
} else {
d = DoubleTools.value(invalidAs);
}
if (DoubleTools.invalidDouble(d) || tValue == 0) {
targetRow.add(Double.NaN + "");
} else {
if (d < 0) {
if ("skip".equals(toNegative)) {
targetRow.add(Double.NaN + "");
continue;
} else if ("abs".equals(toNegative)) {
d = Math.abs(d);
} else {
d = 0;
}
}
targetRow.add(DoubleTools.percentage(d, tValue, scale));
}
}
if (otherCols != null) {
for (int c : otherCols) {
if (c < 0 || c >= sourceRow.size()) {
targetRow.add(null);
} else {
targetRow.add(sourceRow.get(c));
}
}
}
return true;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
}
public boolean handlePercentageRows() {
try {
targetRow = null;
if (sourceRow == null) {
return false;
}
targetRow = new ArrayList<>();
targetRow.add("" + sourceRowIndex);
double sum = 0;
for (int c = 0; c < colsLen; c++) {
int i = cols.get(c);
if (i >= 0 && i < sourceRow.size()) {
double d = DoubleTools.toDouble(sourceRow.get(i), invalidAs);
if (DoubleTools.invalidDouble(d)) {
} else if (d < 0) {
if ("abs".equals(toNegative)) {
sum += Math.abs(d);
}
} else if (d > 0) {
sum += d;
}
}
}
targetRow.add(DoubleTools.scale(sum, scale) + "");
for (int c = 0; c < colsLen; c++) {
int i = cols.get(c);
double d = 0;
if (i >= 0 && i < sourceRow.size()) {
d = DoubleTools.toDouble(sourceRow.get(i), invalidAs);
}
if (DoubleTools.invalidDouble(d) || sum == 0) {
targetRow.add(Double.NaN + "");
} else {
if (d < 0) {
if ("skip".equals(toNegative)) {
targetRow.add(Double.NaN + "");
continue;
} else if ("abs".equals(toNegative)) {
d = Math.abs(d);
} else {
d = 0;
}
}
targetRow.add(DoubleTools.percentage(d, sum, scale));
}
}
if (otherCols != null) {
for (int c : otherCols) {
if (c < 0 || c >= sourceRow.size()) {
targetRow.add(null);
} else {
targetRow.add(sourceRow.get(c));
}
}
}
return true;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
} else {
MyBoxLog.error(e);
}
return false;
}
}
/*
set
*/
public Data2DPrecentage setType(Type type) {
this.type = type;
return this;
}
public Data2DPrecentage setColValues(double[] colValues) {
this.colValues = colValues;
return this;
}
public Data2DPrecentage settValue(double tValue) {
this.tValue = tValue;
return this;
}
public Data2DPrecentage setToNegative(String toNegative) {
this.toNegative = toNegative;
return this;
}
public Data2DPrecentage setFirstRow(List<String> firstRow) {
this.firstRow = firstRow;
return this;
}
/*
get
*/
public double[] getColValues() {
return colValues;
}
public double gettValue() {
return tValue;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/modify/DataTableModify.java | alpha/MyBox/src/main/java/mara/mybox/data2d/modify/DataTableModify.java | package mara.mybox.data2d.modify;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import mara.mybox.data2d.DataTable;
import mara.mybox.db.data.Data2DRow;
import mara.mybox.db.table.TableData2D;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-8-16
* @License Apache License Version 2.0
*/
public abstract class DataTableModify extends Data2DModify {
protected DataTable sourceTable;
protected TableData2D tableData2D;
protected String tableName;
protected Data2DRow sourceTableRow;
protected PreparedStatement update;
public boolean setSourceTable(DataTable data) {
if (!setSourceData(data)) {
return false;
}
sourceTable = data;
tableName = sourceTable.getSheet();
tableData2D = sourceTable.getTableData2D();
tableData2D.setTableName(tableName);
return true;
}
public boolean updateTable() {
try {
if (stopped || sourceTable == null || conn == null) {
return false;
}
String sql = "SELECT count(*) FROM " + tableName;
showInfo(sql);
try (ResultSet query = conn.prepareStatement(sql).executeQuery()) {
if (query.next()) {
rowsNumber = query.getLong(1);
}
}
sourceData.setRowsNumber(rowsNumber);
if (stopped) {
return false;
}
sourceData.saveAttributes(conn);
showInfo(message("DataTable") + ": " + tableName + " "
+ message("RowsNumber") + ": " + rowsNumber);
return true;
} catch (Exception e) {
showError(e.toString());
return false;
}
}
@Override
public boolean end() {
return true;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/modify/DataTableSetValue.java | alpha/MyBox/src/main/java/mara/mybox/data2d/modify/DataTableSetValue.java | package mara.mybox.data2d.modify;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import mara.mybox.data.SetValue;
import mara.mybox.data2d.DataTable;
import mara.mybox.data2d.tools.Data2DRowTools;
import mara.mybox.db.Database;
import mara.mybox.db.DerbyBase;
import mara.mybox.db.data.Data2DRow;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-1-29
* @License Apache License Version 2.0
*/
public class DataTableSetValue extends DataTableModify {
public DataTableSetValue(DataTable data, SetValue value) {
if (!setSourceTable(data)) {
return;
}
initSetValue(value);
sourceTable = data;
}
@Override
public boolean go() {
handledCount = 0;
String sql = "SELECT * FROM " + tableName;
showInfo(sql);
try (Connection dconn = DerbyBase.getConnection();
PreparedStatement query = dconn.prepareStatement(sql);
ResultSet results = query.executeQuery();
PreparedStatement dUpdate = dconn.prepareStatement(tableData2D.updateStatement())) {
conn = dconn;
conn.setAutoCommit(false);
update = dUpdate;
while (results.next() && !stopped && !reachMaxFiltered) {
sourceTableRow = tableData2D.readData(results);
sourceRow = Data2DRowTools.toStrings(sourceTableRow, columns);
sourceRowIndex++;
setValue(sourceRow, sourceRowIndex);
}
if (!stopped) {
update.executeBatch();
conn.commit();
updateTable();
}
showInfo(message("Updated") + ": " + handledCount);
conn.close();
conn = null;
return true;
} catch (Exception e) {
failStop(e.toString());
return false;
}
}
@Override
public void writeRow() {
try {
if (stopped || !rowChanged
|| targetRow == null || targetRow.isEmpty()) {
return;
}
Data2DRow data2DRow = tableData2D.newRow();
for (int i = 0; i < columnsNumber; ++i) {
column = columns.get(i);
columnName = column.getColumnName();
data2DRow.setValue(columnName, column.fromString(targetRow.get(i), invalidAs));
}
if (tableData2D.setUpdateStatement(conn, update, data2DRow)) {
update.addBatch();
if (handledCount % Database.BatchSize == 0) {
update.executeBatch();
conn.commit();
showInfo(message("Updated") + ": " + handledCount);
}
}
} catch (Exception e) {
showError(e.toString());
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/modify/DataTableClear.java | alpha/MyBox/src/main/java/mara/mybox/data2d/modify/DataTableClear.java | package mara.mybox.data2d.modify;
import java.sql.Connection;
import mara.mybox.data2d.DataTable;
import mara.mybox.db.DerbyBase;
/**
* @Author Mara
* @CreateDate 2022-1-29
* @License Apache License Version 2.0
*/
public class DataTableClear extends DataTableModify {
public DataTableClear(DataTable data) {
setSourceTable(data);
}
@Override
public boolean go() {
try (Connection dconn = DerbyBase.getConnection()) {
conn = dconn;
String sql = "DELETE FROM " + tableName;
showInfo(sql);
handledCount = tableData2D.clearData(conn);
if (handledCount < 0) {
return false;
}
return updateTable();
} catch (Exception e) {
showError(e.toString());
return false;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DSaveAttributes.java | alpha/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DSaveAttributes.java | package mara.mybox.data2d.modify;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.data2d.Data2D;
import mara.mybox.data2d.Data2D_Edit;
import mara.mybox.db.data.Data2DColumn;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public class Data2DSaveAttributes extends Data2DModify {
protected Data2D attributes;
public static Data2DSaveAttributes create(Data2D_Edit data, Data2D attrs) {
if (data == null || attrs == null) {
return null;
}
Data2DSaveAttributes operate = new Data2DSaveAttributes();
if (!operate.setSourceData(data)) {
return null;
}
operate.attributes = attrs;
operate.initWriter();
return operate;
}
@Override
public void initWriter() {
writer = sourceData.selfWriter();
writer.setDataName(attributes.getDataName())
.setTargetData(attributes)
.setColumns(attributes.getColumns())
.setHeaderNames(attributes.columnNames())
.setTargetScale(attributes.getScale())
.setTargetMaxRandom(attributes.getMaxRandom())
.setTargetComments(attributes.getComments());
addWriter(writer);
}
@Override
public void handleRow(List<String> row, long index) {
try {
sourceRow = row;
sourceRowIndex = index;
targetRow = null;
if (sourceRow == null) {
return;
}
targetRow = new ArrayList<>();
for (Data2DColumn col : attributes.columns) {
int colIndex = col.getIndex();
if (colIndex < 0 || colIndex >= sourceRow.size()) {
targetRow.add(null);
} else {
targetRow.add(sourceRow.get(colIndex));
}
}
writeRow();
} catch (Exception e) {
showError(e.toString());
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DDelete.java | alpha/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DDelete.java | package mara.mybox.data2d.modify;
import java.util.List;
import mara.mybox.data2d.Data2D_Edit;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2022-8-16
* @License Apache License Version 2.0
*/
public class Data2DDelete extends Data2DModify {
public static Data2DDelete create(Data2D_Edit data) {
if (data == null) {
return null;
}
Data2DDelete operate = new Data2DDelete();
if (!operate.setSourceData(data)) {
return null;
}
operate.initWriter();
return operate;
}
@Override
public void handleRow(List<String> row, long index) {
try {
sourceRow = row;
sourceRowIndex = index;
targetRow = null;
rowPassFilter = sourceData.filterDataRow(sourceRow, sourceRowIndex);
reachMaxFiltered = sourceData.filterReachMaxPassed();
deleteRow(rowPassFilter && !reachMaxFiltered);
} catch (Exception e) {
MyBoxLog.console(e);
}
}
public void deleteRow(boolean handle) {
if (handle) {
handledCount++;
} else {
targetRow = sourceRow;
writeRow();
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DSetValue.java | alpha/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DSetValue.java | package mara.mybox.data2d.modify;
import java.util.List;
import mara.mybox.data.SetValue;
import mara.mybox.data2d.Data2D_Edit;
/**
* @Author Mara
* @CreateDate 2022-8-16
* @License Apache License Version 2.0
*/
public class Data2DSetValue extends Data2DModify {
public static Data2DSetValue create(Data2D_Edit data, SetValue value) {
if (data == null || value == null) {
return null;
}
Data2DSetValue operate = new Data2DSetValue();
if (!operate.setSourceData(data)
|| !operate.initSetValue(value)) {
return null;
}
operate.initWriter();
return operate;
}
@Override
public void handleRow(List<String> row, long index) {
setValue(row, index);
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DModify.java | alpha/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DModify.java | package mara.mybox.data2d.modify;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import mara.mybox.data.SetValue;
import mara.mybox.data2d.DataTable;
import mara.mybox.data2d.operate.Data2DOperate;
import mara.mybox.data2d.writer.Data2DWriter;
import mara.mybox.db.data.ColumnDefinition.InvalidAs;
import mara.mybox.db.data.Data2DColumn;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-8-16
* @License Apache License Version 2.0
*/
public abstract class Data2DModify extends Data2DOperate {
protected Data2DWriter writer;
protected long rowsNumber;
protected int columnsNumber;
protected List<Data2DColumn> columns;
protected int setValueIndex, setValueDigit;
protected SetValue setValue;
protected String setValueParameter;
protected Random random = new Random();
protected boolean valueInvalid, validateColumn, rejectInvalid, skipInvalid;
protected Data2DColumn column;
protected String columnName, currentValue, newValue;
protected boolean rowChanged, handleRow;
protected int rowSize;
public void initWriter() {
writer = sourceData.selfWriter();
addWriter(writer);
}
public boolean initSetValue(SetValue v) {
if (sourceData == null || v == null) {
return false;
}
setValue = v;
setValueDigit = setValue.countFinalDigit(sourceData.getRowsNumber());
setValueIndex = setValue.getStart();
setValueParameter = setValue.getParameter();
random = new Random();
return true;
}
@Override
public boolean checkParameters() {
// rowsNumber = 0;
valueInvalid = false;
rejectInvalid = sourceData.rejectInvalidWhenSave() || invalidAs == InvalidAs.Fail;
skipInvalid = invalidAs == InvalidAs.Skip;
validateColumn = rejectInvalid || skipInvalid;
columns = sourceData.getColumns();
columnsNumber = columns.size();
return super.checkParameters();
}
public void setValue(List<String> row, long index) {
try {
sourceRow = row;
sourceRowIndex = index;
targetRow = null;
if (sourceRow == null) {
return;
}
rowPassFilter = sourceData.filterDataRow(sourceRow, sourceRowIndex);
reachMaxFiltered = sourceData.filterReachMaxPassed();
handleRow = rowPassFilter && !reachMaxFiltered;
if (!handleRow && (sourceData instanceof DataTable)) {
return;
}
targetRow = new ArrayList<>();
rowSize = sourceRow.size();
rowChanged = false;
for (int i = 0; i < columnsNumber; i++) {
if (i < rowSize) {
currentValue = sourceRow.get(i);
} else {
currentValue = null;
}
if (handleRow && cols.contains(i)) {
column = columns.get(i);
newValue = setValue.makeValue(sourceData, column,
currentValue, sourceRow, sourceRowIndex,
setValueIndex, setValueDigit, random);
valueInvalid = setValue.valueInvalid;
if (!valueInvalid && validateColumn) {
if (!column.validValue(newValue)) {
valueInvalid = true;
}
}
if (valueInvalid) {
if (skipInvalid) {
newValue = currentValue;
} else if (rejectInvalid) {
failStop(message("InvalidData") + ". "
+ message("Column") + ":" + column.getColumnName() + " "
+ message("Value") + ": " + newValue);
return;
}
}
if ((currentValue == null && newValue != null)
|| (currentValue != null && !currentValue.equals(newValue))) {
rowChanged = true;
}
} else {
newValue = currentValue;
}
targetRow.add(newValue);
}
if (rowChanged) {
handledCount++;
setValueIndex++;
}
writeRow();
} catch (Exception e) {
showError(e.toString());
}
}
@Override
public boolean end() {
try {
if (!super.end()
|| writer == null
|| writer.getTargetData() == null) {
return false;
}
rowsNumber = writer.getTargetRowIndex();
sourceData.setRowsNumber(rowsNumber);
sourceData.setTableChanged(false);
return true;
} catch (Exception e) {
showError(e.toString());
return false;
}
}
public long rowsCount() {
if (failed) {
return -1;
} else {
return rowsNumber;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DSavePage.java | alpha/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DSavePage.java | package mara.mybox.data2d.modify;
import mara.mybox.data2d.Data2D_Edit;
/**
* @Author Mara
* @CreateDate 2022-2-25
* @License Apache License Version 2.0
*/
public class Data2DSavePage extends Data2DModify {
public static Data2DSavePage save(Data2D_Edit data) {
if (data == null) {
return null;
}
Data2DSavePage operate = new Data2DSavePage();
if (!operate.setSourceData(data)) {
return null;
}
operate.initWriter();
return operate;
}
@Override
public boolean handleRow() {
try {
targetRow = null;
if (sourceRow == null) {
return false;
}
targetRow = sourceRow;
return true;
} catch (Exception e) {
showError(e.toString());
return false;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/modify/DataTableDelete.java | alpha/MyBox/src/main/java/mara/mybox/data2d/modify/DataTableDelete.java | package mara.mybox.data2d.modify;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import mara.mybox.data2d.DataTable;
import mara.mybox.data2d.tools.Data2DRowTools;
import mara.mybox.db.Database;
import mara.mybox.db.DerbyBase;
import mara.mybox.dev.MyBoxLog;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-1-29
* @License Apache License Version 2.0
*/
public class DataTableDelete extends DataTableModify {
protected PreparedStatement delete;
public DataTableDelete(DataTable data) {
setSourceTable(data);
}
@Override
public boolean go() {
handledCount = 0;
String sql = "SELECT * FROM " + tableName;
showInfo(sql);
try (Connection dconn = DerbyBase.getConnection();
PreparedStatement statement = dconn.prepareStatement(sql);
ResultSet results = statement.executeQuery();
PreparedStatement dDelete = dconn.prepareStatement(tableData2D.deleteStatement())) {
conn = dconn;
conn.setAutoCommit(false);
delete = dDelete;
while (results.next() && !stopped && !reachMaxFiltered) {
sourceTableRow = tableData2D.readData(results);
sourceRow = Data2DRowTools.toStrings(sourceTableRow, columns);
sourceRowIndex++;
handleRow(sourceRow, sourceRowIndex);
}
if (!stopped) {
delete.executeBatch();
conn.commit();
updateTable();
}
showInfo(message("Deleted") + ": " + handledCount);
conn.close();
conn = null;
return true;
} catch (Exception e) {
failStop(e.toString());
return false;
}
}
@Override
public void handleRow(List<String> row, long index) {
try {
sourceRow = row;
sourceRowIndex = index;
targetRow = null;
rowPassFilter = sourceData.filterDataRow(sourceRow, sourceRowIndex);
reachMaxFiltered = sourceData.filterReachMaxPassed();
if (rowPassFilter && !reachMaxFiltered) {
if (tableData2D.setDeleteStatement(conn, delete, sourceTableRow)) {
delete.addBatch();
if (++handledCount % Database.BatchSize == 0) {
delete.executeBatch();
conn.commit();
showInfo(message("Deleted") + ": " + handledCount);
}
}
}
} catch (Exception e) {
MyBoxLog.console(e);
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DClear.java | alpha/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DClear.java | package mara.mybox.data2d.modify;
import mara.mybox.data2d.Data2D_Edit;
/**
* @Author Mara
* @CreateDate 2022-8-16
* @License Apache License Version 2.0
*/
public class Data2DClear extends Data2DModify {
public static Data2DClear create(Data2D_Edit data) {
if (data == null) {
return null;
}
Data2DClear operate = new Data2DClear();
if (!operate.setSourceData(data)) {
return null;
}
operate.initWriter();
return operate;
}
@Override
public boolean go() {
handledCount = sourceData.getRowsNumber();
return true;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/example/Regression.java | alpha/MyBox/src/main/java/mara/mybox/data2d/example/Regression.java | package mara.mybox.data2d.example;
import java.util.ArrayList;
import java.util.List;
import javafx.event.ActionEvent;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import mara.mybox.controller.BaseData2DLoadController;
import mara.mybox.data2d.DataFileCSV;
import static mara.mybox.data2d.example.Data2DExampleTools.makeExampleFile;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.HelpTools;
import static mara.mybox.fxml.style.NodeStyleTools.linkStyle;
import mara.mybox.fxml.style.StyleTools;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-9-15
* @License Apache License Version 2.0
*/
public class Regression {
public static Menu menu(String lang, BaseData2DLoadController controller) {
try {
Menu regressionMenu = new Menu(message(lang, "RegressionData"),
StyleTools.getIconImageView("iconLinearPgression.png"));
MenuItem menu = new MenuItem(message(lang, "IncomeHappiness"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = IncomeHappiness(lang);
if (makeExampleFile("DataAnalyse_IncomeHappiness", data)) {
controller.loadDef(data);
}
});
regressionMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "ExperienceSalary"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ExperienceSalary(lang);
if (makeExampleFile("DataAnalyse_ExperienceSalary", data)) {
controller.loadDef(data);
}
});
regressionMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "IrisSpecies"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = IrisSpecies(lang);
if (makeExampleFile("DataAnalyse_IrisSpecies", data)) {
controller.loadDef(data);
}
});
regressionMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "DiabetesPrediction"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = DiabetesPrediction(lang);
if (makeExampleFile("DataAnalyse_DiabetesPrediction", data)) {
controller.loadDef(data);
}
});
regressionMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "DiabetesPredictionStandardized"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = DiabetesPredictionStandardized(lang);
if (makeExampleFile("DataAnalyse_DiabetesPrediction_standardized", data)) {
controller.loadDef(data);
}
});
regressionMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "HeartFailure"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = HeartFailure(lang);
if (makeExampleFile("DataAnalyse_HeartFailure", data)) {
controller.loadDef(data);
}
});
regressionMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "ConcreteCompressiveStrength"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ConcreteCompressiveStrength(lang);
if (makeExampleFile("DataAnalyse_ConcreteCompressiveStrength", data)) {
controller.loadDef(data);
}
});
regressionMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "DogRadiographsDataset"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = DogRadiographsDataset(lang);
if (makeExampleFile("DataAnalyse_DogRadiographs", data)) {
controller.loadDef(data);
}
});
regressionMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "BaseballSalaries"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = BaseballSalaries(lang);
if (makeExampleFile("DataAnalyse_BaseballSalaries", data)) {
controller.loadDef(data);
}
});
regressionMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "SouthGermanCredit"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = SouthGermanCredit(lang);
if (makeExampleFile("DataAnalyse_SouthGermanCredit", data)) {
controller.loadDef(data);
}
});
regressionMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "BostonHousingPrices"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = BostonHousingPrices(lang);
if (makeExampleFile("DataAnalyse_BostonHousingPrices", data)) {
controller.loadDef(data);
}
});
regressionMenu.getItems().add(menu);
regressionMenu.getItems().add(new SeparatorMenuItem());
menu = new MenuItem(message(lang, "AboutDataAnalysis"));
menu.setStyle(linkStyle());
menu.setOnAction((ActionEvent event) -> {
controller.openHtml(HelpTools.aboutDataAnalysis());
});
regressionMenu.getItems().add(menu);
return regressionMenu;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
/*
exmaples of data 2D definition
*/
public static DataFileCSV IncomeHappiness(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "收入" : "income", ColumnDefinition.ColumnType.Double, true));
columns.add(new Data2DColumn(isChinese ? "快乐" : "happiness", ColumnDefinition.ColumnType.Double, true));
data.setColumns(columns).setDataName(message(lang, "IncomeHappiness"))
.setComments("https://www.scribbr.com/statistics/simple-linear-regression/");
return data;
}
public static DataFileCSV ExperienceSalary(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "工作经验" : "YearsExperience", ColumnDefinition.ColumnType.Double, true));
columns.add(new Data2DColumn(isChinese ? "薪资" : "Salary", ColumnDefinition.ColumnType.Double, true));
data.setColumns(columns).setDataName(message(lang, "ExperienceSalary"))
.setComments("https://github.com/krishnaik06/simple-Linear-Regression");
return data;
}
public static DataFileCSV IrisSpecies(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "花萼长度(cm)" : "SepalLengthCm", ColumnDefinition.ColumnType.Double, true));
columns.add(new Data2DColumn(isChinese ? "花萼宽度(cm)" : "SepalWidthCm", ColumnDefinition.ColumnType.Double, true));
columns.add(new Data2DColumn(isChinese ? "花瓣长度(cm)" : "PetalLengthCm", ColumnDefinition.ColumnType.Double, true));
columns.add(new Data2DColumn(isChinese ? "花瓣宽度(cm)" : "PetalWidthCm", ColumnDefinition.ColumnType.Double, true));
columns.add(new Data2DColumn(isChinese ? "种类" : "Species", ColumnDefinition.ColumnType.String, true));
data.setColumns(columns).setDataName(message(lang, "IrisSpecies"))
.setComments("http://archive.ics.uci.edu/ml/datasets/Iris");
return data;
}
public static DataFileCSV DiabetesPrediction(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "年龄" : "age", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "性别" : "sex", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "BMI(体质指数)" : "BMI(body mass index)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "BP(平均血压)" : "BP(average blood pressure)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "S1(血清指标1)" : "S1(blood serum measurement 1)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "S2(血清指标2)" : "S2(blood serum measurement 2)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "S3(血清指标3)" : "S3(blood serum measurement 3)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "S4(血清指标4)" : "S4(blood serum measurement 4)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "S5(血清指标5)" : "S5(blood serum measurement 5)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "S6(血清指标6)" : "S6(blood serum measurement 6)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "一年后病情进展" : "disease progression one year after baseline", ColumnDefinition.ColumnType.Double));
data.setColumns(columns).setDataName(message(lang, "DiabetesPrediction"))
.setComments("https://hastie.su.domains/Papers/LARS/");
return data;
}
public static DataFileCSV DiabetesPredictionStandardized(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "年龄" : "age", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "性别" : "sex", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "BMI(体质指数)" : "BMI(body mass index)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "BP(平均血压)" : "BP(average blood pressure)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "S1(血清指标1)" : "S1(blood serum measurement 1)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "S2(血清指标2)" : "S2(blood serum measurement 2)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "S3(血清指标3)" : "S3(blood serum measurement 3)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "S4(血清指标4)" : "S4(blood serum measurement 4)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "S5(血清指标5)" : "S5(blood serum measurement 5)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "S6(血清指标6)" : "S6(blood serum measurement 6)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "一年后病情进展" : "disease progression one year after baseline", ColumnDefinition.ColumnType.Double));
data.setColumns(columns).setDataName(message(lang, "DiabetesPredictionStandardized"))
.setComments("https://hastie.su.domains/Papers/LARS/ \n"
+ "first 10 columns have been normalized to have mean 0 and "
+ "Euclidean norm 1 and the last column y has been centered (mean 0).");
return data;
}
public static DataFileCSV HeartFailure(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "年龄" : "age", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "贫血" : "anaemia", ColumnDefinition.ColumnType.Boolean)
.setDescription("decrease of red blood cells or hemoglobin (boolean)"));
columns.add(new Data2DColumn(isChinese ? "肌酐磷酸激酶(CPK_mcg/L)" : "creatinine_phosphokinase(CPK_mcg/L)", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "糖尿病" : "diabetes", ColumnDefinition.ColumnType.Boolean));
columns.add(new Data2DColumn(isChinese ? "喷血分数" : "ejection fraction", ColumnDefinition.ColumnType.Integer)
.setDescription("percentage of blood leaving the heart at each contraction (percentage)"));
columns.add(new Data2DColumn(isChinese ? "高血压" : "high blood pressure", ColumnDefinition.ColumnType.Boolean));
columns.add(new Data2DColumn(isChinese ? "血小板(kiloplatelets/mL)" : "platelets(kiloplatelets/mL)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "血清肌酸酐(mg/dL)" : "serum creatinine(mg/dL)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "血清钠(mEq/L)" : "serum sodium(mEq/L)", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "性别" : "sex", ColumnDefinition.ColumnType.Boolean));
columns.add(new Data2DColumn(isChinese ? "抽烟" : "smoking", ColumnDefinition.ColumnType.Boolean));
columns.add(new Data2DColumn(isChinese ? "观察期" : "follow-up period(days)", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "死亡" : "death event", ColumnDefinition.ColumnType.Boolean));
data.setColumns(columns).setDataName(message(lang, "HeartFailure"))
.setComments("http://archive.ics.uci.edu/ml/datasets/Heart+failure+clinical+records \n"
+ "Davide Chicco, Giuseppe Jurman: \"Machine learning can predict survival of patients with heart failure "
+ "from serum creatinine and ejection fraction alone\". BMC Medical Informatics and Decision Making 20, 16 (2020)");
return data;
}
public static DataFileCSV ConcreteCompressiveStrength(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "水泥(公斤)" : "Cement(kg)", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "矿渣(公斤)" : "Blast Furnace Slag(kg)", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "煤灰(公斤)" : "Fly Ash(kg)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "水(公斤)" : "Water(kg)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "塑化剂(公斤)" : "Superplasticizer(kg)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "粗颗粒(公斤)" : "Coarse Aggregate(kg)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "细颗料(公斤)" : "Fine Aggregate(kg)", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "已使用天数" : "Age(days)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "1立方米混凝土抗压强度(兆帕)" : "Concrete compressive strength(MPa)", ColumnDefinition.ColumnType.Double));
data.setColumns(columns).setDataName(message(lang, "ConcreteCompressiveStrength"))
.setComments("http://archive.ics.uci.edu/ml/datasets/Concrete+Compressive+Strength \n"
+ "https://zhuanlan.zhihu.com/p/168747748");
return data;
}
public static DataFileCSV DogRadiographsDataset(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "透亮度有改变" : "lucency changed", ColumnDefinition.ColumnType.Boolean)
.setDescription("changed(1) or not changed(0)"));
columns.add(new Data2DColumn(isChinese ? "刀片尺寸" : "blade size", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "胫骨结节面积" : "tibial tuberosity area", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "胫骨结节宽度" : "tibial tuberosity width", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "年龄(年)" : "age in years", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "重量(公斤)" : "weight in kilograms", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "抗滚针的位置" : "location of the anti-rotational pin", ColumnDefinition.ColumnType.Boolean));
columns.add(new Data2DColumn(isChinese ? "双侧手术" : "bilateral surgery", ColumnDefinition.ColumnType.Boolean)
.setDescription("bilateral surgery(1) or unilateral surgery(0)"));
data.setColumns(columns).setDataName(message(lang, "DogRadiographsDataset"))
.setComments("https://www4.stat.ncsu.edu/~boos/var.select/lucency.html \n"
+ "Radiographic and Clinical Changes of the Tibial Tuberosity after Tibial Plateau Leveling Osteomtomy.");
return data;
}
public static DataFileCSV BaseballSalaries(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "薪水(千美元)" : "Salary (thousands of dollars)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "击球平均得分数" : "Batting average", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "上垒率" : "On-base percentage", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "跑动数" : "Number of runs", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "击球数" : "Number of hits", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "二垒数" : "Number of doubles", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "三垒数" : "Number of triples", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "全垒数" : "Number of home runs", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "打点数" : "Number of runs batted in", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "走动数" : "Number of walks", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "三振出局数" : "Number of strike-outs", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "盗垒数" : "Number of stolen bases", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "失误数" : "Number of errors", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "自由球员资格" : "free agency eligibility", ColumnDefinition.ColumnType.Boolean));
columns.add(new Data2DColumn(isChinese ? "1991/2的自由球员" : "free agent in 1991/2", ColumnDefinition.ColumnType.Boolean));
columns.add(new Data2DColumn(isChinese ? "仲裁资格" : "arbitration eligibility", ColumnDefinition.ColumnType.Boolean));
columns.add(new Data2DColumn(isChinese ? "于1991/2仲裁" : "arbitration in 1991/2", ColumnDefinition.ColumnType.Boolean));
data.setColumns(columns).setDataName(message(lang, "BaseballSalaries"))
.setComments("https://www4.stat.ncsu.edu/~boos/var.select/baseball.html \n"
+ "Salary information for 337 Major League Baseball (MLB) players who are not pitchers "
+ "and played at least one game during both the 1991 and 1992 seasons.");
return data;
}
public static DataFileCSV SouthGermanCredit(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "状态" : "status", ColumnDefinition.ColumnType.Short)
.setDescription("status of the debtor's checking account with the bank\n"
+ "1:no checking account \n"
+ "2: ... < 0 DM \n"
+ "3: 0<= ... < 200 DM \n"
+ "4: >= 200 DM \n"
+ "salary for at least 1 year"));
columns.add(new Data2DColumn(isChinese ? "持续时间(月)" : "duration(months)", ColumnDefinition.ColumnType.Short)
.setDescription("credit duration in months"));
columns.add(new Data2DColumn(isChinese ? "信用卡历史" : "credit_history", ColumnDefinition.ColumnType.Short)
.setDescription("history of compliance with previous or concurrent credit contracts\n"
+ " 0 : delay in paying off in the past \n"
+ " 1 : critical account/other credits elsewhere \n"
+ " 2 : no credits taken/all credits paid back duly\n"
+ " 3 : existing credits paid back duly till now \n"
+ " 4 : all credits at this bank paid back duly "));
columns.add(new Data2DColumn(isChinese ? "用途" : "purpose", ColumnDefinition.ColumnType.Short)
.setDescription("purpose for which the credit is needed\n"
+ " 0 : others \n"
+ " 1 : car (new) \n"
+ " 2 : car (used) \n"
+ " 3 : furniture/equipment\n"
+ " 4 : radio/television \n"
+ " 5 : domestic appliances\n"
+ " 6 : repairs \n"
+ " 7 : education \n"
+ " 8 : vacation \n"
+ " 9 : retraining \n"
+ " 10 : business "));
columns.add(new Data2DColumn(isChinese ? "金额" : "amount", ColumnDefinition.ColumnType.Short)
.setDescription("credit amount in DM (quantitative; result of monotonic transformation; "
+ "actual data and type of transformation unknown)"));
columns.add(new Data2DColumn(isChinese ? "储蓄" : "savings", ColumnDefinition.ColumnType.Short)
.setDescription("debtor's savings\n"
+ " 1 : unknown/no savings account\n"
+ " 2 : ... < 100 DM \n"
+ " 3 : 100 <= ... < 500 DM \n"
+ " 4 : 500 <= ... < 1000 DM \n"
+ " 5 : ... >= 1000 DM "));
columns.add(new Data2DColumn(isChinese ? "职业年限" : "employment_duration", ColumnDefinition.ColumnType.Short)
.setDescription("duration of debtor's employment with current employer\n"
+ " 1 : unemployed \n"
+ " 2 : < 1 yr \n"
+ " 3 : 1 <= ... < 4 yrs\n"
+ " 4 : 4 <= ... < 7 yrs\n"
+ " 5 : >= 7 yrs "));
columns.add(new Data2DColumn(isChinese ? "信贷率" : "installment_rate", ColumnDefinition.ColumnType.Short)
.setDescription("credit installments as a percentage of debtor's disposable income\n"
+ "1 : >= 35 \n"
+ " 2 : 25 <= ... < 35\n"
+ " 3 : 20 <= ... < 25\n"
+ " 4 : < 20 "));
columns.add(new Data2DColumn(isChinese ? "个人状态" : "personal_status_sex", ColumnDefinition.ColumnType.Short)
.setDescription("combined information on sex and marital status\n"
+ " 1 : male : divorced/separated \n"
+ " 2 : female : non-single or male : single\n"
+ " 3 : male : married/widowed \n"
+ " 4 : female : single "));
columns.add(new Data2DColumn(isChinese ? "其他债务人" : "other_debtors", ColumnDefinition.ColumnType.Short)
.setDescription("Is there another debtor or a guarantor for the credit\n"
+ " 1 : none \n"
+ " 2 : co-applicant\n"
+ " 3 : guarantor "));
columns.add(new Data2DColumn(isChinese ? "当前居住年限(年)" : "present_residence", ColumnDefinition.ColumnType.Short)
.setDescription("length of time (in years) the debtor lives in the present residence\n"
+ " 1 : < 1 yr \n"
+ " 2 : 1 <= ... < 4 yrs\n"
+ " 3 : 4 <= ... < 7 yrs\n"
+ " 4 : >= 7 yrs "));
columns.add(new Data2DColumn(isChinese ? "财产" : "property", ColumnDefinition.ColumnType.Short)
.setDescription("the debtor's most valuable property\n"
+ " 1 : unknown / no property \n"
+ " 2 : car or other \n"
+ " 3 : building soc. savings agr./life insurance\n"
+ " 4 : real estate "));
columns.add(new Data2DColumn(isChinese ? "年龄" : "age", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "其它贷款计划" : "other_installment_plans", ColumnDefinition.ColumnType.Short)
.setDescription("installment plans from providers other than the credit-giving bank\n"
+ " 1 : bank \n"
+ " 2 : stores\n"
+ " 3 : none"));
columns.add(new Data2DColumn(isChinese ? "居所类型" : "housing", ColumnDefinition.ColumnType.Short)
.setDescription("type of housing the debtor lives in\n"
+ " 1 : for free\n"
+ " 2 : rent \n"
+ " 3 : own "));
columns.add(new Data2DColumn(isChinese ? "信用卡数目" : "number_credits", ColumnDefinition.ColumnType.Short)
.setDescription("number of credits including the current one the debtor has (or had) at this bank\n"
+ " 1 : 1 \n"
+ " 2 : 2-3 \n"
+ " 3 : 4-5 \n"
+ " 4 : >= 6"));
columns.add(new Data2DColumn(isChinese ? "工作类型" : "job", ColumnDefinition.ColumnType.Short)
.setDescription(" 1 : unemployed/unskilled - non-resident \n"
+ " 2 : unskilled - resident \n"
+ " 3 : skilled employee/official \n"
+ " 4 : manager/self-empl./highly qualif. employee"));
columns.add(new Data2DColumn(isChinese ? "被依赖人数" : "people_liable", ColumnDefinition.ColumnType.Short)
.setDescription("number of persons who financially depend on the debtor\n"
+ " 1 : 3 or more\n"
+ " 2 : 0 to 2"));
columns.add(new Data2DColumn(isChinese ? "有电话" : "telephone", ColumnDefinition.ColumnType.Short)
.setDescription("Is there a telephone landline registered on the debtor's name? "
+ "(binary; remember that the data are from the 1970s)\n"
+ " 1 : no \n"
+ " 2 : yes (under customer name)"));
columns.add(new Data2DColumn(isChinese ? "是外籍雇员" : "foreign_worker", ColumnDefinition.ColumnType.Short)
.setDescription("Is the debtor a foreign worker\n"
+ " 1 : yes\n"
+ " 2 : no "));
columns.add(new Data2DColumn(isChinese ? "信用风险" : "credit_risk", ColumnDefinition.ColumnType.Short)
.setDescription("Has the credit contract been complied with (good) or not (bad) ?\n"
+ " 0 : bad \n"
+ " 1 : good"));
data.setColumns(columns).setDataName(message(lang, "SouthGermanCredit"))
.setComments("http://archive.ics.uci.edu/ml/datasets/South+German+Credit\n"
+ "700 good and 300 bad credits with 20 predictor variables. Data from 1973 to 1975. "
+ "Stratified sample from actual credits with bad credits heavily oversampled. A cost matrix can be used.");
return data;
}
public static DataFileCSV BostonHousingPrices(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "镇" : "town", ColumnDefinition.ColumnType.String, true));
columns.add(new Data2DColumn(isChinese ? "经度" : "longitude", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "纬度" : "latitude", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "犯罪率" : "crime_ratio", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "超过25000平米的区" : "zoned_bigger_25000", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "工业用地" : "industrial_land", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "靠近查理斯河" : "near_Charies_River", ColumnDefinition.ColumnType.Boolean));
columns.add(new Data2DColumn(isChinese ? "一氧化氮浓度" : "nitrogen_density", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "平均房间数" : "average_room_number", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "早于1940建成比率" : "built_before_1940_ratio", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "到达市中心的距离" : "distance_to_centre", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "公路可达性" : "accessbility_to_hightway", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "税率" : "tax_rate", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "学生教师比" : "pupil_teacher_ratio", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "低收入比" : "lower_class_ratio", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "价格中位数" : "median_price", ColumnDefinition.ColumnType.Double));
data.setColumns(columns).setDataName(message(lang, "BostonHousingPrices"))
.setComments("https://github.com/tomsharp/SVR/tree/master/data");
return data;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/example/Data2DExampleTools.java | alpha/MyBox/src/main/java/mara/mybox/data2d/example/Data2DExampleTools.java | package mara.mybox.data2d.example;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.CheckMenuItem;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import mara.mybox.controller.BaseData2DLoadController;
import mara.mybox.data2d.DataFileCSV;
import mara.mybox.data2d.DataFileText;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxFileTools;
import mara.mybox.fxml.style.StyleTools;
import mara.mybox.tools.FileDeleteTools;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2022-9-15
* @License Apache License Version 2.0
*/
public class Data2DExampleTools {
public static List<MenuItem> examplesMenu(BaseData2DLoadController controller) {
return examplesMenu(controller, Languages.embedFileLang());
}
public static List<MenuItem> examplesMenu(BaseData2DLoadController controller, String lang) {
try {
List<MenuItem> items = new ArrayList<>();
items.add(MyData.menu(lang, controller));
items.add(StatisticDataOfChina.menu(lang, controller));
items.add(Regression.menu(lang, controller));
items.add(Location.menu(lang, controller));
items.add(ChineseCharacters.menu(lang, controller));
items.add(Matrix.menu(lang, controller));
items.add(ProjectManagement.menu(lang, controller));
items.add(SoftwareTesting.menu(lang, controller));
items.add(new SeparatorMenuItem());
CheckMenuItem onlyMenu = new CheckMenuItem(message(lang, "ImportDefinitionOnly"),
StyleTools.getIconImageView("iconHeader.png"));
onlyMenu.setSelected(UserConfig.getBoolean("Data2DExampleImportDefinitionOnly", false));
onlyMenu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
UserConfig.setBoolean("Data2DExampleImportDefinitionOnly", onlyMenu.isSelected());
}
});
items.add(onlyMenu);
return items;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static boolean makeExampleFile(String fileName, DataFileCSV targetData) {
try {
if (fileName == null || targetData == null) {
return false;
}
File srcFile = FxFileTools.getInternalFile("/data/examples/" + fileName + ".csv");
File targetFile = targetData.tmpFile(fileName, "example", "csv");
if (targetFile.exists()) {
targetFile.delete();
}
Charset charset = Charset.forName("utf-8");
try (BufferedReader reader = new BufferedReader(new FileReader(srcFile, charset));
BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile, charset, false))) {
String line = null;
while ((line = reader.readLine()) != null && line.startsWith(DataFileText.CommentsMarker)) {
writer.write(line + System.lineSeparator());
}
if (line != null) {
List<Data2DColumn> columns = targetData.getColumns();
if (columns != null) {
String header = null;
for (Data2DColumn column : columns) {
String name = "\"" + column.getColumnName() + "\"";
if (header == null) {
header = name;
} else {
header += "," + name;
}
}
writer.write(header + System.lineSeparator());
} else {
writer.write(line + System.lineSeparator());
}
if (!UserConfig.getBoolean("Data2DExampleImportDefinitionOnly", false)) {
while ((line = reader.readLine()) != null) {
writer.write(line + System.lineSeparator());
}
}
}
writer.flush();
} catch (Exception e) {
MyBoxLog.error(e);
return false;
}
targetData.setFile(targetFile).setHasHeader(true).setCharset(charset).setDelimiter(",");
targetData.saveAttributes();
FileDeleteTools.delete(srcFile);
return true;
} catch (Exception e) {
MyBoxLog.error(e);
return false;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/example/Location.java | alpha/MyBox/src/main/java/mara/mybox/data2d/example/Location.java | package mara.mybox.data2d.example;
import java.util.ArrayList;
import java.util.List;
import javafx.event.ActionEvent;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import mara.mybox.controller.BaseData2DLoadController;
import mara.mybox.data2d.DataFileCSV;
import static mara.mybox.data2d.example.Data2DExampleTools.makeExampleFile;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.style.StyleTools;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-9-15
* @License Apache License Version 2.0
*/
public class Location {
public static Menu menu(String lang, BaseData2DLoadController controller) {
try {
Menu locationMenu = new Menu(message(lang, "LocationData"),
StyleTools.getIconImageView("iconLocation.png"));
MenuItem menu = new MenuItem(message(lang, "ChineseHistoricalCapitals"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseHistoricalCapitals(lang);
if (makeExampleFile("Location_ChineseHistoricalCapitals_" + lang, data)) {
controller.loadDef(data);
}
});
locationMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "AutumnMovementPatternsOfEuropeanGadwalls"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = AutumnMovementPatternsOfEuropeanGadwalls(lang);
if (makeExampleFile("Location_EuropeanGadwalls", data)) {
controller.loadDef(data);
}
});
locationMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "SpermWhalesGulfOfMexico"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = SpermWhalesGulfOfMexico(lang);
if (makeExampleFile("Location_SpermWhales", data)) {
controller.loadDef(data);
}
});
locationMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "EpidemicReportsCOVID19"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = EpidemicReportsCOVID19(lang);
if (makeExampleFile("Location_EpidemicReports", data)) {
controller.loadDef(data);
}
});
locationMenu.getItems().add(menu);
return locationMenu;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
/*
exmaples of data 2D definition
*/
public static DataFileCSV ChineseHistoricalCapitals(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message(lang, "Country"), ColumnDefinition.ColumnType.String, true).setWidth(140));
columns.add(new Data2DColumn(message(lang, "Capital"), ColumnDefinition.ColumnType.String, true).setWidth(200));
columns.add(new Data2DColumn(message(lang, "Longitude"), ColumnDefinition.ColumnType.Longitude));
columns.add(new Data2DColumn(message(lang, "Latitude"), ColumnDefinition.ColumnType.Latitude));
columns.add(new Data2DColumn(message(lang, "StartTime"), ColumnDefinition.ColumnType.Era).setFormat(isChinese ? "Gy" : "y G"));
columns.add(new Data2DColumn(message(lang, "EndTime"), ColumnDefinition.ColumnType.Era).setFormat(isChinese ? "Gy" : "y G"));
columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String));
data.setColumns(columns).setDataName(message(lang, "ChineseHistoricalCapitals"));
return data;
}
public static DataFileCSV AutumnMovementPatternsOfEuropeanGadwalls(String lang) {
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message(lang, "StartTime"), ColumnDefinition.ColumnType.Datetime, 180).setFixTwoDigitYear(true));
columns.add(new Data2DColumn(message(lang, "EndTime"), ColumnDefinition.ColumnType.Datetime, 180).setFixTwoDigitYear(true));
columns.add(new Data2DColumn(message(lang, "Longitude"), ColumnDefinition.ColumnType.Longitude));
columns.add(new Data2DColumn(message(lang, "Latitude"), ColumnDefinition.ColumnType.Latitude));
columns.add(new Data2DColumn(message(lang, "CoordinateSystem"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String));
data.setColumns(columns).setDataName(message(lang, "AutumnMovementPatternsOfEuropeanGadwalls"))
.setComments("https://www.datarepository.movebank.org/handle/10255/move.346");
return data;
}
public static DataFileCSV SpermWhalesGulfOfMexico(String lang) {
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message(lang, "Time"), ColumnDefinition.ColumnType.Datetime, 180).setFixTwoDigitYear(true));
columns.add(new Data2DColumn(message(lang, "Longitude"), ColumnDefinition.ColumnType.Longitude));
columns.add(new Data2DColumn(message(lang, "Latitude"), ColumnDefinition.ColumnType.Latitude));
columns.add(new Data2DColumn(message(lang, "CoordinateSystem"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String));
data.setColumns(columns).setDataName(message(lang, "SpermWhalesGulfOfMexico"))
.setComments("https://www.datarepository.movebank.org/handle/10255/move.1059");
return data;
}
public static DataFileCSV EpidemicReportsCOVID19(String lang) {
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message(lang, "Date"), ColumnDefinition.ColumnType.Date)
.setFixTwoDigitYear(false).setFormat("yyyy-MM-dd"));
columns.add(new Data2DColumn(message(lang, "Country"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Province"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Confirmed"), ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(message(lang, "Healed"), ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(message(lang, "Dead"), ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(message(lang, "Longitude"), ColumnDefinition.ColumnType.Longitude));
columns.add(new Data2DColumn(message(lang, "Latitude"), ColumnDefinition.ColumnType.Latitude));
data.setColumns(columns).setDataName(message(lang, "EpidemicReportsCOVID19"))
.setComments("https://github.com/CSSEGISandData/COVID-19");
return data;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/example/MyData.java | alpha/MyBox/src/main/java/mara/mybox/data2d/example/MyData.java | package mara.mybox.data2d.example;
import java.util.ArrayList;
import java.util.List;
import javafx.event.ActionEvent;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import mara.mybox.controller.BaseData2DLoadController;
import mara.mybox.data2d.DataFileCSV;
import static mara.mybox.data2d.example.Data2DExampleTools.makeExampleFile;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.style.StyleTools;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-9-15
* @License Apache License Version 2.0
*/
public class MyData {
public static Menu menu(String lang, BaseData2DLoadController controller) {
try {
Menu myMenu = new Menu(message(lang, "MyData"), StyleTools.getIconImageView("iconCat.png"));
MenuItem menu = new MenuItem(message(lang, "Notes"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = Notes(lang);
if (makeExampleFile("MyData_notes_" + lang, data)) {
controller.loadDef(data);
}
});
myMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "Contacts"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = Contacts(lang);
if (makeExampleFile("MyData_contacts_" + lang, data)) {
controller.loadDef(data);
}
});
myMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "CashFlow"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = CashFlow(lang);
if (makeExampleFile("MyData_cashflow_" + lang, data)) {
controller.loadDef(data);
}
});
myMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "PrivateProperty"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = PrivateProperty(lang);
if (makeExampleFile("MyData_property_" + lang, data)) {
controller.loadDef(data);
}
});
myMenu.getItems().add(menu);
myMenu.getItems().add(new SeparatorMenuItem());
menu = new MenuItem(message(lang, "Eyesight"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = Eyesight(lang);
if (makeExampleFile("MyData_eyesight", data)) {
controller.loadDef(data);
}
});
myMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "Weight"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = Weight(lang);
if (makeExampleFile("MyData_weight", data)) {
controller.loadDef(data);
}
});
myMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "Height"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = Height(lang);
if (makeExampleFile("MyData_height", data)) {
controller.loadDef(data);
}
});
myMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "Menstruation"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = Menstruation(lang);
if (makeExampleFile("MyData_menstruation", data)) {
controller.loadDef(data);
}
});
myMenu.getItems().add(menu);
return myMenu;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
/*
exmaples of data 2D definition
*/
public static DataFileCSV Notes(String lang) {
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message(lang, "Time"), ColumnDefinition.ColumnType.Datetime, 180));
columns.add(new Data2DColumn(message(lang, "Title"), ColumnDefinition.ColumnType.String, 180));
columns.add(new Data2DColumn(message(lang, "InvolvedObjects"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Location"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String, 300));
data.setColumns(columns).setDataName(message(lang, "Notes"));
return data;
}
public static DataFileCSV Contacts(String lang) {
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message(lang, "Name"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Relationship"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "PhoneNumber") + "1", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "PhoneNumber") + "2", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Email"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Address"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Birthday"), ColumnDefinition.ColumnType.Datetime));
columns.add(new Data2DColumn(message(lang, "Hobbies"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String, 300));
data.setColumns(columns).setDataName(message(lang, "Contacts"));
return data;
}
public static DataFileCSV CashFlow(String lang) {
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message(lang, "Time"), ColumnDefinition.ColumnType.Datetime, 180));
columns.add(new Data2DColumn(message(lang, "Amount"), ColumnDefinition.ColumnType.Float));
columns.add(new Data2DColumn(message(lang, "Type"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Account"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "InvolvedObjects"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String, 300));
data.setColumns(columns).setDataName(message(lang, "CashFlow"));
return data;
}
public static DataFileCSV PrivateProperty(String lang) {
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message(lang, "Time"), ColumnDefinition.ColumnType.Datetime, 180));
columns.add(new Data2DColumn(message(lang, "Amount"), ColumnDefinition.ColumnType.Float));
columns.add(new Data2DColumn(message(lang, "Type"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Account"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String, 300));
data.setColumns(columns).setDataName(message(lang, "PrivateProperty"));
return data;
}
public static DataFileCSV Eyesight(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message(lang, "Time"), ColumnDefinition.ColumnType.Datetime, true, true).setWidth(180));
columns.add(new Data2DColumn(isChinese ? "左眼" : "left eye", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "右眼" : "right eye", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "基弧" : "Radian", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String, 300));
data.setColumns(columns).setDataName(message(lang, "Eyesight"));
return data;
}
public static DataFileCSV Weight(String lang) {
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message(lang, "Time"), ColumnDefinition.ColumnType.Datetime, true, true).setWidth(180));
columns.add(new Data2DColumn(message(lang, "Weight") + "(kg)", ColumnDefinition.ColumnType.Float).setScale(2));
columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String, 300));
data.setColumns(columns).setDataName(message(lang, "Weight"));
return data;
}
public static DataFileCSV Height(String lang) {
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message(lang, "Time"), ColumnDefinition.ColumnType.Datetime, true, true).setWidth(180));
columns.add(new Data2DColumn(message(lang, "Height") + "(cm)", ColumnDefinition.ColumnType.Float).setScale(2));
columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String, 300));
data.setColumns(columns).setDataName(message(lang, "Height"));
return data;
}
public static DataFileCSV Menstruation(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message(lang, "StartTime"), ColumnDefinition.ColumnType.Datetime, true).setWidth(180));
columns.add(new Data2DColumn(message(lang, "EndTime"), ColumnDefinition.ColumnType.Datetime, true).setWidth(180));
columns.add(new Data2DColumn(isChinese ? "疼痛" : "Pain", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "卫生巾" : "Pads", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String, 300));
data.setColumns(columns).setDataName(message(lang, "Menstruation"));
return data;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/example/ChineseCharacters.java | alpha/MyBox/src/main/java/mara/mybox/data2d/example/ChineseCharacters.java | package mara.mybox.data2d.example;
import java.util.ArrayList;
import java.util.List;
import javafx.event.ActionEvent;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import mara.mybox.controller.BaseData2DLoadController;
import mara.mybox.data2d.DataFileCSV;
import static mara.mybox.data2d.example.Data2DExampleTools.makeExampleFile;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.style.StyleTools;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-9-15
* @License Apache License Version 2.0
*/
public class ChineseCharacters {
public static Menu menu(String lang, BaseData2DLoadController controller) {
try {
Menu dictionariesMenu = new Menu(message(lang, "ChineseCharacters"),
StyleTools.getIconImageView("iconWu.png"));
MenuItem menu = new MenuItem(message(lang, "ChineseCharactersStandard"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseCharactersStandard(lang);
if (makeExampleFile("ChineseCharactersStandard", data)) {
controller.loadDef(data);
}
});
dictionariesMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "ChineseRadicals"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseRadicals(lang);
if (makeExampleFile("ChineseRadicals", data)) {
controller.loadDef(data);
}
});
dictionariesMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "ChinesePinyin"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChinesePinyin(lang);
if (makeExampleFile("ChinesePinyin", data)) {
controller.loadDef(data);
}
});
dictionariesMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "ChinesePhrases"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChinesePhrases(lang);
if (makeExampleFile("ChinesePhrases", data)) {
controller.loadDef(data);
}
});
dictionariesMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "ChineseTraditional"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseTraditional(lang);
if (makeExampleFile("ChineseTraditional", data)) {
controller.loadDef(data);
}
});
dictionariesMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "ChinesePolyphone"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChinesePolyphone(lang);
if (makeExampleFile("ChinesePolyphone", data)) {
controller.loadDef(data);
}
});
dictionariesMenu.getItems().add(menu);
dictionariesMenu.getItems().add(new SeparatorMenuItem());
boolean isChinese = Languages.isChinese(lang);
Menu blcuMenu = new Menu(isChinese ? "北京语言大学的数据" : "Data from Beijing Language and Culture University");
menu = new MenuItem(isChinese ? "汉字字频-2012-人民日报" : "Counts of Chinese characters in 2012 - People's Daily");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseFrequencyBlcuCharactersPD(lang);
if (makeExampleFile("ChineseFrequency-blcu-characters-2012-People's Daily", data)) {
controller.loadDef(data);
}
});
blcuMenu.getItems().add(menu);
menu = new MenuItem(isChinese ? "历年汉字字频-人民日报" : "Yearly counts of Chinese characters - People's Daily");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseFrequencyBlcuYearlyCharactersPD(lang);
if (makeExampleFile("ChineseFrequency-blcu-characters-years-People's Daily", data)) {
controller.loadDef(data);
}
});
blcuMenu.getItems().add(menu);
menu = new MenuItem(isChinese ? "历年汉字词组-人民日报" : "Yearly counts of Chinese words - People's Daily");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseFrequencyBlcuYearlyWordsPD(lang);
if (makeExampleFile("ChineseFrequency-blcu-words-years-People's Daily", data)) {
controller.loadDef(data);
}
});
blcuMenu.getItems().add(menu);
menu = new MenuItem(isChinese ? "汉语词组-2015-新闻频道" : "Chinese words in news channel in 2015");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseFrequencyBlcuNews(lang);
if (makeExampleFile("ChineseFrequency-blcu-news-2015", data)) {
controller.loadDef(data);
}
});
blcuMenu.getItems().add(menu);
menu = new MenuItem(isChinese ? "汉语词组-2015-技术频道" : "Chinese words in technology channel in 2015");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseFrequencyBlcuTechnology(lang);
if (makeExampleFile("ChineseFrequency-blcu-technology-2015", data)) {
controller.loadDef(data);
}
});
blcuMenu.getItems().add(menu);
menu = new MenuItem(isChinese ? "汉语词组-2015-文学频道" : "Chinese words in literature channel in 2015");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseFrequencyBlcuLiterature(lang);
if (makeExampleFile("ChineseFrequency-blcu-literature-2015", data)) {
controller.loadDef(data);
}
});
blcuMenu.getItems().add(menu);
menu = new MenuItem(isChinese ? "汉语词组-2015-微博频道" : "Chinese words in weibo channel in 2015");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseFrequencyBlcuWeibo(lang);
if (makeExampleFile("ChineseFrequency-blcu-weibo-2015", data)) {
controller.loadDef(data);
}
});
blcuMenu.getItems().add(menu);
menu = new MenuItem(isChinese ? "汉语词组-2015-博客频道" : "Chinese words in blog channel in 2015");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseFrequencyBlcuBlog(lang);
if (makeExampleFile("ChineseFrequency-blcu-blog-2015", data)) {
controller.loadDef(data);
}
});
blcuMenu.getItems().add(menu);
menu = new MenuItem(isChinese ? "汉语词组-2015-频道总和" : "Chinese words in channels in 2015");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseFrequencyBlcuGlobal(lang);
if (makeExampleFile("ChineseFrequency-blcu-global-2015", data)) {
controller.loadDef(data);
}
});
blcuMenu.getItems().add(menu);
menu = new MenuItem(isChinese ? "汉语成语" : "Chinese Idioms");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseIdiomsBlcu(lang);
if (makeExampleFile("ChineseIdioms-blcu", data)) {
controller.loadDef(data);
}
});
blcuMenu.getItems().add(menu);
dictionariesMenu.getItems().add(blcuMenu);
Menu othersMenu = new Menu(message(lang, "Others"));
menu = new MenuItem(isChinese ? "国家出版局抽样统计最常用的一千个汉字" : "Mostly used chinese characters by State Publication Bureau");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseFrequencySPB(lang);
if (makeExampleFile("ChineseFrequency-State Publication Bureau", data)) {
controller.loadDef(data);
}
});
othersMenu.getItems().add(menu);
menu = new MenuItem(isChinese ? "微信公众号-汉语词频统计-2016" : "Chinese characters statistic of weixin public corpus in 2016");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseFrequencyWeixin2016(lang);
if (makeExampleFile("ChineseFrequency-weixin_public_corpus-2016", data)) {
controller.loadDef(data);
}
});
othersMenu.getItems().add(menu);
menu = new MenuItem(isChinese ? "汉字字频表(基数10亿)" : "Chinese characters statistic based on billion data");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseFrequencyBaseBillion(lang);
if (makeExampleFile("ChineseFrequency-imewlconverter-BaseBillion", data)) {
controller.loadDef(data);
}
});
othersMenu.getItems().add(menu);
menu = new MenuItem(isChinese ? "百度汉字字频表-2009" : "Chinese characters statistic from baidu in 2009");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseFrequencyBaidu2009(lang);
if (makeExampleFile("ChineseFrequency-Baidu-2009", data)) {
controller.loadDef(data);
}
});
othersMenu.getItems().add(menu);
menu = new MenuItem(isChinese ? "Google汉字字频表-2005" : "Chinese characters statistic from Google in 2005");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseFrequencyGoogle2005(lang);
if (makeExampleFile("ChineseFrequency-Google-2005", data)) {
controller.loadDef(data);
}
});
othersMenu.getItems().add(menu);
menu = new MenuItem(isChinese ? "Yahoo汉字字频表-2009" : "Chinese characters statistic from Yahoo in 2009");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseFrequencyYahoo2009(lang);
if (makeExampleFile("ChineseFrequency-Yahoo-2009", data)) {
controller.loadDef(data);
}
});
othersMenu.getItems().add(menu);
menu = new MenuItem(isChinese ? "知乎语料库" : "Chinese characters statistic of Zhihu");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseFrequencyZhihu(lang);
if (makeExampleFile("ChineseFrequency-Zhihu", data)) {
controller.loadDef(data);
}
});
othersMenu.getItems().add(menu);
menu = new MenuItem(isChinese ? "古代汉语语料库字频表" : "Chinese characters statistic in ancient China");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseFrequencyCncorpusAncient(lang);
if (makeExampleFile("ChineseFrequency-cncorpus-ancient China", data)) {
controller.loadDef(data);
}
});
othersMenu.getItems().add(menu);
menu = new MenuItem(isChinese ? "现代汉语语料库字频表" : "Chinese characters statistic in modern China");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseFrequencyCncorpusCharactersModern(lang);
if (makeExampleFile("ChineseFrequency-cncorpus-characters-modern China", data)) {
controller.loadDef(data);
}
});
othersMenu.getItems().add(menu);
menu = new MenuItem(isChinese ? "现代汉语语料库词频表" : "Chinese words statistic in modern China");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseFrequencyCncorpusWordsModern(lang);
if (makeExampleFile("ChineseFrequency-cncorpus-words-modern China", data)) {
controller.loadDef(data);
}
});
othersMenu.getItems().add(menu);
menu = new MenuItem(isChinese ? "现代汉语语料库分词类词频表" : "Chinese participles statistic in modern China");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseFrequencyCncorpusParticiplesModern(lang);
if (makeExampleFile("ChineseFrequency-cncorpus-participles-modern China", data)) {
controller.loadDef(data);
}
});
othersMenu.getItems().add(menu);
menu = new MenuItem(isChinese ? "唐诗宋词元曲" : "Chinese characters statistic about traditional literature");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseFrequencyTraditionalLiterature(lang);
if (makeExampleFile("ChineseFrequency-traditional literature", data)) {
controller.loadDef(data);
}
});
othersMenu.getItems().add(menu);
menu = new MenuItem(isChinese ? "文淵閣四庫全書" : "Chinese characters statistic of the Si Ku Quan Shu");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseFrequencySiKuQuanShu(lang);
if (makeExampleFile("ChineseFrequency-freemdict-SiKuQuanShu", data)) {
controller.loadDef(data);
}
});
othersMenu.getItems().add(menu);
menu = new MenuItem(isChinese ? "殆知阁" : "Chinese characters statistic of the Yi Zhi Ge");
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChineseFrequencyYiZhiGe(lang);
if (makeExampleFile("ChineseFrequency-mahavivo-YiZhiGe", data)) {
controller.loadDef(data);
}
});
othersMenu.getItems().add(menu);
dictionariesMenu.getItems().add(othersMenu);
return dictionariesMenu;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
/*
exmaples of data 2D definition
*/
public static DataFileCSV ChineseCharactersStandard(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "编号" : "Number", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "字" : "Character", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "级别" : "Level", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "部首" : "Radical", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "笔画数" : "Stroke Count", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "拼音" : "Pinyin", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "多音" : "Other Pinyin", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "繁体" : "Traditional", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "异形" : "Variant", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "字形" : "Glyph", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "笔顺" : "Strokes", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "拼音首" : "Pinyin Front", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "拼音尾" : "Pinyin End", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "音调" : "Tone", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "五笔" : "Wubi", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "十六进制" : "Hex", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "十进制" : "Dec", ColumnDefinition.ColumnType.String));
data.setColumns(columns).setDataName(message(lang, "ChineseCharactersStandard"));
return data;
}
public static DataFileCSV ChineseRadicals(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "部首" : "Radical", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "名字" : "Name", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "笔画数" : "Stroke Count", ColumnDefinition.ColumnType.Short));
data.setColumns(columns).setDataName(message(lang, "ChineseRadicals"));
return data;
}
public static DataFileCSV ChinesePinyin(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "拼音" : "Pinyin", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "字" : "Characters", ColumnDefinition.ColumnType.String));
data.setColumns(columns).setDataName(message(lang, "ChinesePinyin"));
return data;
}
public static DataFileCSV ChinesePhrases(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "词组" : "Phrase", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "繁体" : "Traditional", ColumnDefinition.ColumnType.String));
data.setColumns(columns).setDataName(message(lang, "ChinesePhrases"));
return data;
}
public static DataFileCSV ChineseTraditional(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "字" : "Character", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "繁体" : "Traditional", ColumnDefinition.ColumnType.String));
data.setColumns(columns).setDataName(message(lang, "ChineseTraditional"));
return data;
}
public static DataFileCSV ChinesePolyphone(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "编号" : "Number", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "字" : "Character", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "拼音" : "Pinyin", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "多音" : "Other Pinyin", ColumnDefinition.ColumnType.String));
data.setColumns(columns).setDataName(message(lang, "ChinesePolyphone"));
return data;
}
public static DataFileCSV ChineseFrequencyBlcuCharactersPD(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "汉字" : "Character", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "排名" : "Rank", ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(isChinese ? "频率" : "Frequency", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "累计频率" : "Cumulative frequency", ColumnDefinition.ColumnType.Double));
data.setColumns(columns).setDataName(isChinese ? "汉字字频-人民日报" : "Counts of Chinese characters - People's Daily");
return data;
}
public static DataFileCSV ChineseFrequencyBlcuYearlyCharactersPD(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "年份" : "Year", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "排名" : "Rank", ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(isChinese ? "汉字" : "Character", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(isChinese ? "频率" : "Frequency", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "累计频率" : "Cumulative frequency", ColumnDefinition.ColumnType.Double));
data.setColumns(columns).setDataName(isChinese ? "历年汉字字频-人民日报" : "Yearly counts of Chinese characters - People's Daily");
return data;
}
public static DataFileCSV ChineseFrequencyBlcuYearlyWordsPD(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "年份" : "Year", ColumnDefinition.ColumnType.Short));
columns.add(new Data2DColumn(isChinese ? "排名" : "Rank", ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(isChinese ? "词" : "Word", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(isChinese ? "频率" : "Frequency", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "累计频率" : "Cumulative frequency", ColumnDefinition.ColumnType.Double));
data.setColumns(columns).setDataName(isChinese ? "历年汉字词组-人民日报" : "Yearly counts of Chinese words - People's Daily");
return data;
}
public static DataFileCSV ChineseIdiomsBlcu(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "成语" : "Idiom", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "拼音" : "Pinyin", ColumnDefinition.ColumnType.String));
data.setColumns(columns).setDataName(isChinese ? "汉语成语" : "Chinese Idioms");
return data;
}
public static DataFileCSV ChineseFrequencyBlcuNews(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "词" : "Word", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "排名" : "Rank", ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long));
data.setColumns(columns).setDataName(isChinese ? "汉语词组-2015-新闻频道" : "Chinese words in news channel in 2015");
return data;
}
public static DataFileCSV ChineseFrequencyBlcuLiterature(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "词" : "Word", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "排名" : "Rank", ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long));
data.setColumns(columns).setDataName(isChinese ? "汉语词组-2015-文学频道" : "Chinese words in literature channel in 2015");
return data;
}
public static DataFileCSV ChineseFrequencyBlcuTechnology(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "词" : "Word", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "排名" : "Rank", ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long));
data.setColumns(columns).setDataName(isChinese ? "汉语词组-2015-技术频道" : "Chinese words in technology channel in 2015");
return data;
}
public static DataFileCSV ChineseFrequencyBlcuWeibo(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "词" : "Word", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "排名" : "Rank", ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long));
data.setColumns(columns).setDataName(isChinese ? "汉语词组-2015-微博频道" : "Chinese words in weibo channel in 2015");
return data;
}
public static DataFileCSV ChineseFrequencyBlcuBlog(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "词" : "Word", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "排名" : "Rank", ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long));
data.setColumns(columns).setDataName(isChinese ? "汉语词组-2015-博客频道" : "Chinese words in blog channel in 2015");
return data;
}
public static DataFileCSV ChineseFrequencyBlcuGlobal(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "词" : "Word", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "排名" : "Rank", ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long));
data.setColumns(columns).setDataName(isChinese ? "汉语词组-2015-频道总和" : "Chinese words in channels in 2015");
return data;
}
public static DataFileCSV ChineseFrequencySPB(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "排名" : "Rank", ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(isChinese ? "汉字" : "Character", ColumnDefinition.ColumnType.String));
data.setColumns(columns).setDataName(isChinese ? "国家出版局抽样统计最常用的一千个汉字"
: "Mostly used chinese characters by State Publication Bureau");
return data;
}
public static DataFileCSV ChineseFrequencyWeixin2016(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "词" : "Word", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long));
data.setColumns(columns).setDataName(isChinese ? "微信公众号-汉语词频统计-2016"
: "Chinese characters statistic of by weixin public corpus in 2016");
return data;
}
public static DataFileCSV ChineseFrequencyBaseBillion(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "汉字" : "Character", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "排名" : "Rank", ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(isChinese ? "频率" : "Frequency", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "累计频率" : "Cumulative frequency", ColumnDefinition.ColumnType.Double));
data.setColumns(columns).setDataName(isChinese ? "汉字字频表(基数10亿)" : "Chinese characters statistic based on billion data");
return data;
}
public static DataFileCSV ChineseFrequencyBaidu2009(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "汉字" : "Character", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long));
data.setColumns(columns).setDataName(isChinese ? "百度汉字字频表-2009" : "Chinese characters statistic from baidu in 2009");
return data;
}
public static DataFileCSV ChineseFrequencyGoogle2005(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "汉字" : "Character", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long));
data.setColumns(columns).setDataName(isChinese ? "Google汉字字频表-2005" : "Chinese characters statistic from Google in 2005");
return data;
}
public static DataFileCSV ChineseFrequencyYahoo2009(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "汉字" : "Character", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long));
data.setColumns(columns).setDataName(isChinese ? "Yahoo汉字字频表-2009" : "Chinese characters statistic from Yahoo in 2009");
return data;
}
public static DataFileCSV ChineseFrequencyTraditionalLiterature(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "汉字" : "Character", ColumnDefinition.ColumnType.String));
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | true |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/example/StatisticDataOfChina.java | alpha/MyBox/src/main/java/mara/mybox/data2d/example/StatisticDataOfChina.java | package mara.mybox.data2d.example;
import java.util.ArrayList;
import java.util.List;
import javafx.event.ActionEvent;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import mara.mybox.controller.BaseData2DLoadController;
import mara.mybox.data2d.DataFileCSV;
import static mara.mybox.data2d.example.Data2DExampleTools.makeExampleFile;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.dev.MyBoxLog;
import static mara.mybox.fxml.style.NodeStyleTools.linkStyle;
import mara.mybox.fxml.style.StyleTools;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-9-15
* @License Apache License Version 2.0
*/
public class StatisticDataOfChina {
public static Menu menu(String lang, BaseData2DLoadController controller) {
try {
// https://data.stats.gov.cn/index.htm
Menu chinaMenu = new Menu(message(lang, "StatisticDataOfChina"), StyleTools.getIconImageView("iconChina.png"));
MenuItem menu = new MenuItem(message(lang, "ChinaPopulation"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChinaPopulation(lang);
if (makeExampleFile("ChinaPopulation", data)) {
controller.loadDef(data);
}
});
chinaMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "ChinaCensus"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChinaCensus(lang);
if (makeExampleFile("ChinaCensus", data)) {
controller.loadDef(data);
}
});
chinaMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "ChinaGDP"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChinaGDP(lang);
if (makeExampleFile("ChinaGDP", data)) {
controller.loadDef(data);
}
});
chinaMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "ChinaCPI"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChinaCPI(lang);
if (makeExampleFile("ChinaCPI", data)) {
controller.loadDef(data);
}
});
chinaMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "ChinaFoodConsumption"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChinaFoodConsumption(lang);
if (makeExampleFile("ChinaFoods_" + lang, data)) {
controller.loadDef(data);
}
});
chinaMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "ChinaGraduates"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChinaGraduates(lang);
if (makeExampleFile("ChinaGraduates", data)) {
controller.loadDef(data);
}
});
chinaMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "ChinaMuseums"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChinaMuseums(lang);
if (makeExampleFile("ChinaMuseums", data)) {
controller.loadDef(data);
}
});
chinaMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "ChinaHealthPersonnel"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChinaHealthPersonnel(lang);
if (makeExampleFile("ChinaHealthPersonnel", data)) {
controller.loadDef(data);
}
});
chinaMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "ChinaMarriage"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChinaMarriage(lang);
if (makeExampleFile("ChinaMarriage", data)) {
controller.loadDef(data);
}
});
chinaMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "ChinaSportWorldChampions"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ChinaSportWorldChampions(lang);
if (makeExampleFile("ChinaSportWorldChampions", data)) {
controller.loadDef(data);
}
});
chinaMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "CrimesFiledByChinaPolice"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = CrimesFiledByChinaPolice(lang);
if (makeExampleFile("ChinaCrimesFiledByPolice", data)) {
controller.loadDef(data);
}
});
chinaMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "CrimesFiledByChinaProcuratorate"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = CrimesFiledByChinaProcuratorate(lang);
if (makeExampleFile("ChinaCrimesFiledByProcuratorate", data)) {
controller.loadDef(data);
}
});
chinaMenu.getItems().add(menu);
chinaMenu.getItems().add(new SeparatorMenuItem());
menu = new MenuItem(message(lang, "ChinaNationalBureauOfStatistics"));
menu.setStyle(linkStyle());
menu.setOnAction((ActionEvent event) -> {
controller.browse("https://data.stats.gov.cn/");
});
chinaMenu.getItems().add(menu);
return chinaMenu;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
/*
exmaples of data 2D definition
*/
public static DataFileCSV ChinaPopulation(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "年" : "year_", ColumnDefinition.ColumnType.String, true));
columns.add(new Data2DColumn(isChinese ? "年末总人口(万人)" : "population at year-end(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "男性人口(万人)" : "male(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "女性人口(万人)" : "female(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "城镇人口(万人)" : "urban(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "乡村人口(万人)" : "rural(ten thousand)", ColumnDefinition.ColumnType.Double));
data.setColumns(columns).setDataName(message(lang, "ChinaPopulation"))
.setComments("https://data.stats.gov.cn/index.htm");
return data;
}
public static DataFileCSV ChinaCensus(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "年" : "year_", ColumnDefinition.ColumnType.String, true));
columns.add(new Data2DColumn(isChinese ? "人口普查总人口(万人)" : "total population of census(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "男性(万人)" : "male(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "女性(万人)" : "female(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "性别比(女=100)" : "sex ratio(female=100)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "城镇(万人)" : "urban(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "乡村(万人)" : "rural(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "家庭户规模(人/户)" : "family size", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "0-14岁占比(%)" : "aged 0-14(%)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "15-64岁占比(%)" : "aged 15-64(%)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "65岁及以上占比(%)" : "aged over 65(%)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "汉族(万人)" : "han nationality population(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "汉族占比(%)" : "han nationality precentage(%)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "少数民族(万人)" : "minority nationality population(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "少数民族占比(%)" : "minority nationality precentage(%)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "每十万人口中受大专及以上教育人口数(人)" : "junior college or above education per one hundred thousand", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "每十万人口中受高中和中专教育人口数(人)" : "high school and secondary education per hundred thousand", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "每十万人口中受初中教育人口数(人)" : "junior high school education per hundred thousand", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "每十万人口中受小学教育人口数(人)" : "primary school education per hundred thousand", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "文盲人口数(万人)" : "illiteracy(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "文盲率(%)" : "illiteracy percentage(%)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "城镇化率(%)" : "urbanization rate(%)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "平均预期寿命(岁)" : "average life expectancy(years)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "男性平均预期寿命(岁)" : "male average life expectancy(years)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "女性平均预期寿命(岁)" : "female average life expectancy(years)", ColumnDefinition.ColumnType.Double));
data.setColumns(columns).setDataName(message(lang, "ChinaCensus"))
.setComments("https://data.stats.gov.cn/index.htm");
return data;
}
public static DataFileCSV ChinaGDP(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "年" : "year_", ColumnDefinition.ColumnType.String, true));
columns.add(new Data2DColumn(isChinese ? "国民总收入(GNI 亿元)" : "gross national income(GNI hundred million yuan)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "国内生产总值(GDP 亿元)" : "gross domestic product(GDP hundred million yuan)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "第一产业增加值(VA1 亿元)" : "value-added of first industry(VA1 hundred million yuan)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "第二产业增加值(VA2 亿元)" : "value-added of secondary industry(VA2 hundred million yuan)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "第三产业增加值(VA3 亿元)" : "value-added of tertiary industry(VA3 hundred million yuan)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "人均国内生产总值(元)" : "GDP per capita(yuan)", ColumnDefinition.ColumnType.Double));
data.setColumns(columns).setDataName(message(lang, "ChinaGDP"))
.setComments("https://data.stats.gov.cn/index.htm");
return data;
}
public static DataFileCSV ChinaCPI(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "年" : "year_", ColumnDefinition.ColumnType.String, true));
columns.add(new Data2DColumn(isChinese ? "居民消费价格指数(CPI 上年=100)" : "consumer price index(CPI last_year=100)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "城市居民消费价格指数(上年=100)" : "urban consumer price index(last_year=100)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "农村居民消费价格指数(上年=100)" : "rural consumer price index(last_year=100)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "商品零售价格指数(RPI 上年=100)" : "retail price index(RPI last_year=100)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "工业生产者出厂价格指数(PPI 上年=100)" : "producer price index(PPI last_year=100)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "工业生产者购进价格指数(PPIRM 上年=100)" : "producer price pndices of raw material(PPIRM last_year=100)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "固定资产投资价格指数(上年=100)" : "price indices of investment in fixed assets(last_year=100)", ColumnDefinition.ColumnType.Double));
data.setColumns(columns).setDataName(message(lang, "ChinaCPI"))
.setComments("https://data.stats.gov.cn/index.htm");
return data;
}
public static DataFileCSV ChinaFoodConsumption(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "指标" : "item", ColumnDefinition.ColumnType.String, true));
columns.add(new Data2DColumn(isChinese ? "2020年" : "year 2020", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "2019年" : "year 2019", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "2018年" : "year 2018", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "2017年" : "year 2017", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "2016年" : "year 2016", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "2015年" : "year 2015", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "2014年" : "year 2014", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "2013年" : "year 2013", ColumnDefinition.ColumnType.Double));
data.setColumns(columns).setDataName(message(lang, "ChinaFoodConsumption"))
.setComments("https://data.stats.gov.cn/index.htm");
return data;
}
public static DataFileCSV ChinaGraduates(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "年" : "year_", ColumnDefinition.ColumnType.String, true));
columns.add(new Data2DColumn(isChinese ? "普通高等学校毕业生数(万人)" : "college graduates(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "普通中学毕业生数(万人)" : "middle school graduates(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "普通高中毕业生数(万人)" : "high school graduates(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "初中毕业生数(万人)" : "junior high school graduates(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "职业中学毕业生数(万人)" : "vocational high school graduates(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "普通小学毕业生数(万人)" : "primary school graduates(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "特殊教育学校毕业生数(万人)" : "special education school graduates(ten thousand)", ColumnDefinition.ColumnType.Double));
data.setColumns(columns).setDataName(message(lang, "ChinaGraduates"))
.setComments("https://data.stats.gov.cn/index.htm");
return data;
}
public static DataFileCSV ChinaMuseums(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "年" : "year_", ColumnDefinition.ColumnType.String, true));
columns.add(new Data2DColumn(isChinese ? "博物馆机构数(个)" : "museum institutions", ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(isChinese ? "博物馆从业人员(人)" : "employed", ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(isChinese ? "博物馆文物藏品(件/套)" : "relics", ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(isChinese ? "本年博物馆从有关部门接收文物数(件/套)" : "received in the year", ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(isChinese ? "本年博物馆修复文物数(件/套)" : "fixed in the year", ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(isChinese ? "博物馆考古发掘项目(个)" : "archaeology projects", ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(isChinese ? "博物馆基本陈列(个)" : "basical exhibition", ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(isChinese ? "博物馆举办展览(个)" : "special exhibition", ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(isChinese ? "博物馆参观人次(万人次)" : "visits(ten thousand)", ColumnDefinition.ColumnType.Double));
data.setColumns(columns).setDataName(message(lang, "ChinaMuseums"))
.setComments("https://data.stats.gov.cn/index.htm");
return data;
}
public static DataFileCSV ChinaHealthPersonnel(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "年" : "year_", ColumnDefinition.ColumnType.String, true));
columns.add(new Data2DColumn(isChinese ? "卫生人员数(万人)" : "health personnel(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "卫生技术人员数(万人)" : "medical personnel(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "执业(助理)医师数(万人)" : "practitioner(assistant)(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "执业医师数(万人)" : "practitioner(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "注册护士数(万人)" : "registered nurse(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "药师数(万人)" : "pharmacist(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "乡村医生和卫生员数(万人)" : "rural(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "其他技术人员数(万人)" : "other technical personnel(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "管理人员数(万人)" : "managerial personnel(ten thousand)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "工勤技能人员数(万人)" : "worker(ten thousand)", ColumnDefinition.ColumnType.Double));
data.setColumns(columns).setDataName(message(lang, "ChinaHealthPersonnel"))
.setComments("https://data.stats.gov.cn/index.htm");
return data;
}
public static DataFileCSV ChinaMarriage(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "年" : "year_", ColumnDefinition.ColumnType.String, true));
columns.add(new Data2DColumn(isChinese ? "结婚登记(万对)" : "married(ten thousand pairs)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "内地居民登记结婚(万对)" : "mainland residents married(ten thousand pairs)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "内地居民初婚登记(万人)" : "mainland residents newly married(ten thousand persons)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "内地居民再婚登记(万人)" : "mainland residents remarried(ten thousand persons)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "涉外及港澳台居民登记结婚(万对)" : "foreigners/HongKong/Macao/Taiwan married(ten thousand pairs)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "离婚登记(万对)" : "divorced(ten thousand pairs)", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(isChinese ? "粗离婚率(千分比)" : "divorced ratio(permillage)", ColumnDefinition.ColumnType.Double));
data.setColumns(columns).setDataName(message(lang, "ChinaMarriage"))
.setComments("https://data.stats.gov.cn/index.htm");
return data;
}
public static DataFileCSV ChinaSportWorldChampions(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "年" : "year_", ColumnDefinition.ColumnType.String, true));
columns.add(new Data2DColumn(isChinese ? "世界冠军项数" : "categories of world champions", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "女子世界冠军项数" : "categories of female world champions", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "世界冠军人数" : "athletes of world champions", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "女子世界冠军人数" : "female athletes of world champions", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "世界冠军个数" : "number of world champions", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "女子世界冠军个数" : "number of female world champions", ColumnDefinition.ColumnType.Integer));
data.setColumns(columns).setDataName(message(lang, "ChinaSportWorldChampions"))
.setComments("https://data.stats.gov.cn/index.htm");
return data;
}
public static DataFileCSV CrimesFiledByChinaPolice(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "年" : "year_", ColumnDefinition.ColumnType.String, true));
columns.add(new Data2DColumn(isChinese ? "立案的刑事案件" : "filed crimes", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "杀人" : "murder", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "伤害" : "injure", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "抢劫" : "rob", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "强奸" : "rape", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "拐卖妇女儿童" : "trafficking", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "盗窃" : "steal", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "诈骗" : "scam", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "走私" : "smuggle", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "假币" : "counterfeit money", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "其他" : "others", ColumnDefinition.ColumnType.Integer));
data.setColumns(columns).setDataName(message(lang, "CrimesFiledByChinaPolice"))
.setComments("https://data.stats.gov.cn/index.htm");
return data;
}
public static DataFileCSV CrimesFiledByChinaProcuratorate(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "年" : "year_", ColumnDefinition.ColumnType.String, true));
columns.add(new Data2DColumn(isChinese ? "受案数" : "filed crimes", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "贪污贿赂" : "corruption and bribery", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "贪污" : "corruption", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "贿赂" : "bribery", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "挪用公款" : "embezzlement", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "集体私分" : "collectively dividing up state-owned properties without permission", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "巨额财产来源不明" : "huge unidentified property", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "其他贪污贿赂" : "other corruption and bribery", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "渎职" : "malfeasance", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "滥用职权" : "abuses of power", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "玩忽职守" : "neglecting of duty", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "徇私舞弊" : "favoritism", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "其他渎职" : "other malfeasance", ColumnDefinition.ColumnType.Integer));
data.setColumns(columns).setDataName(message(lang, "CrimesFiledByChinaProcuratorate"))
.setComments("https://data.stats.gov.cn/index.htm");
return data;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/example/Matrix.java | alpha/MyBox/src/main/java/mara/mybox/data2d/example/Matrix.java | package mara.mybox.data2d.example;
import javafx.event.ActionEvent;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import mara.mybox.controller.BaseData2DLoadController;
import mara.mybox.data2d.DataMatrix;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.style.StyleTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-9-15
* @License Apache License Version 2.0
*/
public class Matrix {
public static Menu menu(String lang, BaseData2DLoadController controller) {
try {
Menu locationMenu = new Menu(message(lang, "Matrix"),
StyleTools.getIconImageView("iconMatrix.png"));
short scale1 = 4, scale2 = 8;
int max = 100000;
MenuItem menu = new MenuItem(message(lang, "DoubleMatrix") + " 10*10");
menu.setOnAction((ActionEvent event) -> {
DataMatrix matrix = DataMatrix.makeMatrix("Double", 10, 10, scale1, max);
controller.loadDef(matrix);
});
locationMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "DoubleMatrix") + " "
+ message(lang, "PureDecimal") + " 10*10");
menu.setOnAction((ActionEvent event) -> {
DataMatrix matrix = DataMatrix.makeMatrix("Double", 10, 10, scale2, 1);
controller.loadDef(matrix);
});
locationMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "DoubleMatrix") + " 50*50");
menu.setOnAction((ActionEvent event) -> {
DataMatrix matrix = DataMatrix.makeMatrix("Double", 50, 50, scale1, max);
controller.loadDef(matrix);
});
locationMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "DoubleMatrix") + " "
+ message(lang, "PureDecimal") + " 50*50");
menu.setOnAction((ActionEvent event) -> {
DataMatrix matrix = DataMatrix.makeMatrix("Double", 50, 50, scale2, 1);
controller.loadDef(matrix);
});
locationMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "DoubleMatrix") + " 500*500");
menu.setOnAction((ActionEvent event) -> {
DataMatrix matrix = DataMatrix.makeMatrix("Double", 500, 500, scale1, max);
controller.loadDef(matrix);
});
locationMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "DoubleMatrix") + " 1000*1000");
menu.setOnAction((ActionEvent event) -> {
DataMatrix matrix = DataMatrix.makeMatrix("Double", 1000, 1000, scale1, max);
controller.loadDef(matrix);
});
locationMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "FloatMatrix") + " 50*50");
menu.setOnAction((ActionEvent event) -> {
DataMatrix matrix = DataMatrix.makeMatrix("Float", 50, 50, scale1, max);
controller.loadDef(matrix);
});
locationMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "FloatMatrix") + " "
+ message(lang, "PureDecimal") + " 50*50");
menu.setOnAction((ActionEvent event) -> {
DataMatrix matrix = DataMatrix.makeMatrix("Float", 50, 50, scale2, 1);
controller.loadDef(matrix);
});
locationMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "IntegerMatrix") + " 50*50");
menu.setOnAction((ActionEvent event) -> {
DataMatrix matrix = DataMatrix.makeMatrix("Integer", 50, 50, scale1, max);
controller.loadDef(matrix);
});
locationMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "BooleanMatrix") + " 50*50");
menu.setOnAction((ActionEvent event) -> {
DataMatrix matrix = DataMatrix.makeMatrix("NumberBoolean", 50, 50, scale1, max);
controller.loadDef(matrix);
});
locationMenu.getItems().add(menu);
return locationMenu;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
/*
exmaples of data 2D definition
*/
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/example/ProjectManagement.java | alpha/MyBox/src/main/java/mara/mybox/data2d/example/ProjectManagement.java | package mara.mybox.data2d.example;
import java.util.ArrayList;
import java.util.List;
import javafx.event.ActionEvent;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import mara.mybox.controller.BaseData2DLoadController;
import mara.mybox.data2d.DataFileCSV;
import static mara.mybox.data2d.example.Data2DExampleTools.makeExampleFile;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.style.StyleTools;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-9-15
* @License Apache License Version 2.0
*/
public class ProjectManagement {
public static Menu menu(String lang, BaseData2DLoadController controller) {
try {
Menu pmMenu = new Menu(message(lang, "ProjectManagement"),
StyleTools.getIconImageView("iconCalculator.png"));
MenuItem menu = new MenuItem(message(lang, "ProjectRegister"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ProjectRegister(lang);
if (makeExampleFile("PM_ProjectRegister_" + lang, data)) {
controller.loadDef(data);
}
});
pmMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "ProjectStatus"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ProjectStatus(lang);
if (makeExampleFile("PM_ProjectStatus_" + lang, data)) {
controller.loadDef(data);
}
});
pmMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "TaskRegister"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = TaskRegister(lang);
if (makeExampleFile("PM_TaskRegister_" + lang, data)) {
controller.loadDef(data);
}
});
pmMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "TaskStatus"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = TaskStatus(lang);
if (makeExampleFile("PM_TaskStatus_" + lang, data)) {
controller.loadDef(data);
}
});
pmMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "PersonRegister"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = PersonRegister(lang);
if (makeExampleFile("PM_PersonRegister_" + lang, data)) {
controller.loadDef(data);
}
});
pmMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "PersonStatus"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = PersonStatus(lang);
if (makeExampleFile("PM_PersonStatus_" + lang, data)) {
controller.loadDef(data);
}
});
pmMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "ResourceRegister"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ResourceRegister(lang);
if (makeExampleFile("PM_ResourceRegister_" + lang, data)) {
controller.loadDef(data);
}
});
pmMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "ResourceStatus"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = ResourceStatus(lang);
if (makeExampleFile("PM_ResourceStatus_" + lang, data)) {
controller.loadDef(data);
}
});
pmMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "RiskAnalysis"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = RiskAnalysis(lang);
if (makeExampleFile("PM_RiskAnalysis_" + lang, data)) {
controller.loadDef(data);
}
});
pmMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "CostRecord"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = CostRecord(lang);
if (makeExampleFile("PM_CostRecords_" + lang, data)) {
controller.loadDef(data);
}
});
pmMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "VerificationRecord"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = VerificationRecord(lang);
if (makeExampleFile("PM_VerifyRecord_" + lang, data)) {
controller.loadDef(data);
}
});
pmMenu.getItems().add(menu);
return pmMenu;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
/*
exmaples of data 2D definition
*/
public static DataFileCSV ProjectRegister(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message(lang, "ConfigurationID"), ColumnDefinition.ColumnType.String, true).setWidth(140));
columns.add(new Data2DColumn(message(lang, "Name"), ColumnDefinition.ColumnType.String, true).setWidth(200));
columns.add(new Data2DColumn(message(lang, "LastStatus"), ColumnDefinition.ColumnType.Enumeration)
.setFormat(isChinese ? "申请\n已批准\n需求分析\n设计\n实现\n测试\n验证\n维护\n已完成\n被否定\n失败\n已取消"
: "Applying\nApproved\nRequirement\nDesign\nImplementing\nTesting\nValidated\nMaintenance\nCompleted\nDenied\nFailed\nCanceled"));
columns.add(new Data2DColumn(isChinese ? "项目经理" : "Manager", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "批准者" : "Approver", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "StartTime"), ColumnDefinition.ColumnType.Datetime));
columns.add(new Data2DColumn(isChinese ? "关闭时间" : "Closed time", ColumnDefinition.ColumnType.Datetime));
columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String));
data.setColumns(columns).setDataName(isChinese ? "项目登记" : "Project register");
return data;
}
public static DataFileCSV ProjectStatus(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "项目编号" : "Project ID", ColumnDefinition.ColumnType.String, true).setWidth(140));
columns.add(new Data2DColumn(message(lang, "Status"), ColumnDefinition.ColumnType.Enumeration)
.setFormat(isChinese ? "申请\n已批准\n需求分析\n设计\n实现\n测试\n验证\n维护\n已完成\n被否定\n失败\n已取消"
: "Applying\nApproved\nRequirement\nDesign\nImplementing\nTesting\nValidated\nMaintenance\nCompleted\nDenied\nFailed\nCanceled"));
columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Recorder"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "RecordTime"), ColumnDefinition.ColumnType.Datetime));
data.setColumns(columns).setDataName(isChinese ? "项目状态" : "Project Status");
return data;
}
public static DataFileCSV TaskRegister(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message(lang, "ConfigurationID"), ColumnDefinition.ColumnType.String, true).setWidth(140));
columns.add(new Data2DColumn(isChinese ? "项目编号" : "Project ID", ColumnDefinition.ColumnType.String, true).setWidth(140));
columns.add(new Data2DColumn(message(lang, "Name"), ColumnDefinition.ColumnType.String, true).setWidth(200));
columns.add(new Data2DColumn(message(lang, "LastStatus"), ColumnDefinition.ColumnType.Enumeration)
.setFormat(isChinese ? "分派\n执行\n完成\n失败\n取消"
: "Assign\nPerform\nComplete\nFail\nCancel"));
columns.add(new Data2DColumn(isChinese ? "执行者" : "Performer", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "开始时间" : "StartTime", ColumnDefinition.ColumnType.Datetime));
columns.add(new Data2DColumn(isChinese ? "关闭时间" : "ClosedTime", ColumnDefinition.ColumnType.Datetime));
columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String));
data.setColumns(columns).setDataName(isChinese ? "任务登记" : "Task register");
return data;
}
public static DataFileCSV TaskStatus(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "任务编号" : "Task ID", ColumnDefinition.ColumnType.String, true).setWidth(140));
columns.add(new Data2DColumn(message(lang, "Status"), ColumnDefinition.ColumnType.Enumeration)
.setFormat(isChinese ? "计划\n执行\n完成\n失败\n取消"
: "Plan\nPerform\nComplete\nFail\nCancel"));
columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Recorder"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "RecordTime"), ColumnDefinition.ColumnType.Datetime));
data.setColumns(columns).setDataName(isChinese ? "任务状态" : "Task Status");
return data;
}
public static DataFileCSV PersonRegister(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message(lang, "ConfigurationID"), ColumnDefinition.ColumnType.String, true).setWidth(140));
columns.add(new Data2DColumn(isChinese ? "任务编号" : "Task ID", ColumnDefinition.ColumnType.String, true).setWidth(140));
columns.add(new Data2DColumn(message(lang, "Role"), ColumnDefinition.ColumnType.Enumeration)
.setFormat(isChinese ? "投资人\n监管者\n项目经理\n组长\n设计者\n编程者\n测试者\n其他/她"
: "Investor\nSupervisor\nProject manager\nTeam leader\nDesigner\nProgrammer\nTester\n\nOther"));
columns.add(new Data2DColumn(message(lang, "Name"), ColumnDefinition.ColumnType.String, true));
columns.add(new Data2DColumn(message(lang, "PhoneNumber"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String));
data.setColumns(columns).setDataName(isChinese ? "人员登记" : "Person register");
return data;
}
public static DataFileCSV PersonStatus(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "人员编号" : "Person ID", ColumnDefinition.ColumnType.String, true).setWidth(140));
columns.add(new Data2DColumn(message(lang, "Status"), ColumnDefinition.ColumnType.Enumeration)
.setFormat(isChinese ? "加入\n修改信息\n退出"
: "Join\nUpdate information\nQuit"));
columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Recorder"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "RecordTime"), ColumnDefinition.ColumnType.Datetime));
data.setColumns(columns).setDataName(isChinese ? "人员状态" : "Person Status");
return data;
}
public static DataFileCSV ResourceRegister(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message(lang, "ConfigurationID"), ColumnDefinition.ColumnType.String, true).setWidth(140));
columns.add(new Data2DColumn(isChinese ? "任务编号" : "Task ID", ColumnDefinition.ColumnType.String, true).setWidth(140));
columns.add(new Data2DColumn(message(lang, "Type"), ColumnDefinition.ColumnType.Enumeration)
.setFormat(isChinese ? "设备\n程序\n源代码\n文档\n数据\n其它"
: "Device\nProgram\nSource codes\nDocument\nData\nOther"));
columns.add(new Data2DColumn(message(lang, "Name"), ColumnDefinition.ColumnType.String, true));
columns.add(new Data2DColumn(message(lang, "LastStatus"), ColumnDefinition.ColumnType.Enumeration)
.setFormat(isChinese ? "正常\n出借\n出售\n废弃\n损毁\n丢失"
: "Normal\nLent\nSaled\nDiscarded\nDamaged\nLost"));
columns.add(new Data2DColumn(isChinese ? "保管者" : "Keeper", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "登记时间" : "Register time", ColumnDefinition.ColumnType.Datetime));
columns.add(new Data2DColumn(isChinese ? "失效时间" : "Invalid time", ColumnDefinition.ColumnType.Datetime));
columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String));
data.setColumns(columns).setDataName(isChinese ? "资源登记" : "Resource register");
return data;
}
public static DataFileCSV ResourceStatus(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "资源编号" : "Resource ID", ColumnDefinition.ColumnType.String, true).setWidth(140));
columns.add(new Data2DColumn(message(lang, "Status"), ColumnDefinition.ColumnType.Enumeration)
.setFormat(isChinese ? "正常\n出借\n出售\n废弃\n损毁\n丢失"
: "Normal\nLent\nSaled\nDiscarded\nDamaged\nLost"));
columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Recorder"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "RecordTime"), ColumnDefinition.ColumnType.Datetime));
data.setColumns(columns).setDataName(isChinese ? "资源状态" : "Resource Status");
return data;
}
public static DataFileCSV RiskAnalysis(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message(lang, "ConfigurationID"), ColumnDefinition.ColumnType.String, true).setWidth(140));
columns.add(new Data2DColumn(isChinese ? "任务编号" : "Task ID", ColumnDefinition.ColumnType.String, true).setWidth(140));
columns.add(new Data2DColumn(message(lang, "Type"), ColumnDefinition.ColumnType.Enumeration)
.setFormat(isChinese ? "范围\n质量\n时间\n资金\n技术\n人力\n法律\n其它"
: "Scope\nQuality\nTime\nMoney\nTechnique\nHuman\nLaw\nOther"));
columns.add(new Data2DColumn(isChinese ? "风险项" : "Risk Item", ColumnDefinition.ColumnType.String, true));
columns.add(new Data2DColumn(isChinese ? "可能性" : "Probability", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "严重性" : "Severity", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(isChinese ? "优先级" : "Priority", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(message(lang, "Description"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "影响" : "Effects", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "应急措施" : "Contingency Actions", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "分析者" : "Analyzer", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "分析时间" : "Analysis time", ColumnDefinition.ColumnType.Datetime));
data.setColumns(columns).setDataName(isChinese ? "风险分析" : "Risk Analysis");
return data;
}
public static DataFileCSV CostRecord(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "任务编号" : "Task ID", ColumnDefinition.ColumnType.String, true).setWidth(140));
columns.add(new Data2DColumn(isChinese ? "计划开始日期" : "Planned start time", ColumnDefinition.ColumnType.Date));
columns.add(new Data2DColumn(isChinese ? "计划结束日期" : "Planned end time", ColumnDefinition.ColumnType.Date));
columns.add(new Data2DColumn(isChinese ? "计划工作量(人月)" : "Planned workload(person-month)", ColumnDefinition.ColumnType.Float));
columns.add(new Data2DColumn(isChinese ? "计划成本(元)" : "Planned cost(Yuan)", ColumnDefinition.ColumnType.Float));
columns.add(new Data2DColumn(isChinese ? "计划产出" : "Planned results", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "实际开始日期" : "Actual start time", ColumnDefinition.ColumnType.Date));
columns.add(new Data2DColumn(isChinese ? "实际结束日期" : "Actual end time", ColumnDefinition.ColumnType.Date));
columns.add(new Data2DColumn(isChinese ? "实际工作量(人月)" : "Actual workload(person-month)", ColumnDefinition.ColumnType.Float));
columns.add(new Data2DColumn(isChinese ? "实际成本(元)" : "Actual cost(Yuan)", ColumnDefinition.ColumnType.Float));
columns.add(new Data2DColumn(isChinese ? "实际产出" : "Actual results", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Recorder"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "RecordTime"), ColumnDefinition.ColumnType.Datetime));
data.setColumns(columns).setDataName(isChinese ? "成本记录" : "Cost Records");
return data;
}
public static DataFileCSV VerificationRecord(String lang) {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(isChinese ? "任务编号" : "Task ID", ColumnDefinition.ColumnType.String, true).setWidth(140));
columns.add(new Data2DColumn(isChinese ? "事项" : "Item", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "通过" : "Pass", ColumnDefinition.ColumnType.Boolean));
columns.add(new Data2DColumn(isChinese ? "严重性" : "Severity", ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(message(lang, "Description"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "影响" : "Effects", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "建议" : "Suggestions", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "检验者" : "Verifier", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(isChinese ? "检验时间" : "Verification time", ColumnDefinition.ColumnType.Datetime));
data.setColumns(columns).setDataName(isChinese ? "检验记录" : "Verify Record");
return data;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/example/SoftwareTesting.java | alpha/MyBox/src/main/java/mara/mybox/data2d/example/SoftwareTesting.java | package mara.mybox.data2d.example;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import javafx.event.ActionEvent;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.BaseData2DLoadController;
import mara.mybox.data.FunctionsList;
import mara.mybox.data.StringTable;
import mara.mybox.data2d.DataFileCSV;
import static mara.mybox.data2d.example.Data2DExampleTools.makeExampleFile;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.style.StyleTools;
import mara.mybox.tools.DateTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2022-9-15
* @License Apache License Version 2.0
*/
public class SoftwareTesting {
public static Menu menu(String lang, BaseData2DLoadController controller) {
try {
Menu stMenu = new Menu(message(lang, "SoftwareTesting"), StyleTools.getIconImageView("iconVerify.png"));
MenuItem menu = new MenuItem(message(lang, "TestEnvironment"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = TestEnvironment(lang);
if (makeExampleFile("ST_TestEnvironment_" + lang, data)) {
controller.loadDef(data);
}
});
stMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "CompatibilityTesting"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = CompatibilityTesting(lang);
if (makeExampleFile("ST_CompatibilityTesting_" + lang, data)) {
controller.loadDef(data);
}
});
stMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "DetailedTesting"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = DetailedTesting(lang);
if (makeExampleFile("ST_DetailedTesting_" + lang, data)) {
controller.loadDef(data);
}
});
stMenu.getItems().add(menu);
menu = new MenuItem(message(lang, "MyBoxBaseVerificationList"));
menu.setOnAction((ActionEvent event) -> {
DataFileCSV data = MyBoxBaseVerificationList(controller, lang,
UserConfig.getBoolean("Data2DExampleImportDefinitionOnly", false));
controller.loadDef(data);
});
stMenu.getItems().add(menu);
return stMenu;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
/*
exmaples of data 2D definition
*/
public static DataFileCSV TestEnvironment(String lang) {
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message(lang, "Title"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Hardwares"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn("CPU", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Memory"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "OS"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Softwares"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Language"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Target"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String));
data.setColumns(columns).setDataName(message(lang, "TestEnvironment"));
return data;
}
public static DataFileCSV CompatibilityTesting(String lang) {
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message(lang, "TestEnvironment"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Item"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "ModifyTime"), ColumnDefinition.ColumnType.Datetime));
columns.add(new Data2DColumn(message(lang, "Description"), ColumnDefinition.ColumnType.String));
data.setColumns(columns).setDataName(message(lang, "CompatibilityTesting"));
return data;
}
public static DataFileCSV DetailedTesting(String lang) {
DataFileCSV data = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message(lang, "TestEnvironment"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Version"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Type"), ColumnDefinition.ColumnType.EnumerationEditable)
.setFormat("\n" + message(lang, "Function") + "\n"
+ message(lang, "UserInterface") + "\n" + message(lang, "Bundary") + "\n"
+ message(lang, "Invalid") + "\n"
+ message(lang, "Data") + "\n" + message(lang, "API") + "\n"
+ message(lang, "IO") + "\n" + message(lang, "Exception") + "\n"
+ message(lang, "Performance") + "\n" + message(lang, "Robustness") + "\n"
+ message(lang, "Usability") + "\n" + message(lang, "Compatibility") + "\n"
+ message(lang, "Security") + "\n" + message(lang, "Document")));
columns.add(new Data2DColumn(message(lang, "Object"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Title"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Steps"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "Status"), ColumnDefinition.ColumnType.EnumerationEditable)
.setFormat("\n" + message(lang, "NotTested") + "\n"
+ message(lang, "Testing") + "\n"
+ message(lang, "Success") + "\n"
+ message(lang, "Fail")));
columns.add(new Data2DColumn(message(lang, "ModifyTime"), ColumnDefinition.ColumnType.Datetime));
columns.add(new Data2DColumn(message(lang, "Description"), ColumnDefinition.ColumnType.String));
data.setColumns(columns).setDataName(message(lang, "DetailedTesting"));
return data;
}
public static DataFileCSV MyBoxBaseVerificationList(BaseController controller,
String lang, boolean onlyDef) {
try {
boolean isChinese = Languages.isChinese(lang);
DataFileCSV targetData = new DataFileCSV();
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message(lang, "Index"), ColumnDefinition.ColumnType.Integer));
columns.add(new Data2DColumn(message(lang, "HierarchyNumber"), ColumnDefinition.ColumnType.String));
for (int i = 1; i <= FunctionsList.MaxLevel; i++) {
columns.add(new Data2DColumn(message(lang, "Level") + " " + i, ColumnDefinition.ColumnType.String));
}
for (Data2DColumn c : columns) {
c.setEditable(false);
}
int preSize = columns.size();
columns.add(0, new Data2DColumn(message(lang, "TestEnvironment"), ColumnDefinition.ColumnType.String));
String defauleValue = "";
String format = defauleValue + "\n" + message(lang, "Success") + "\n" + message(lang, "Fail");
columns.add(new Data2DColumn(isChinese ? "打开界面" : "Open interface", ColumnDefinition.ColumnType.EnumerationEditable)
.setFormat(format));
columns.add(new Data2DColumn(isChinese ? "正常值" : "Normal values", ColumnDefinition.ColumnType.EnumerationEditable)
.setFormat(format));
columns.add(new Data2DColumn(isChinese ? "正常操作" : "Normal operations", ColumnDefinition.ColumnType.EnumerationEditable)
.setFormat(format));
columns.add(new Data2DColumn(isChinese ? "正常结果" : "Normal results", ColumnDefinition.ColumnType.EnumerationEditable)
.setFormat(format));
columns.add(new Data2DColumn(isChinese ? "边界值" : "Boundary values", ColumnDefinition.ColumnType.EnumerationEditable)
.setFormat(format));
columns.add(new Data2DColumn(isChinese ? "异常值" : "Abnormal values", ColumnDefinition.ColumnType.EnumerationEditable)
.setFormat(format));
columns.add(new Data2DColumn(isChinese ? "异常操作" : "Abnormal operations", ColumnDefinition.ColumnType.EnumerationEditable)
.setFormat(format));
columns.add(new Data2DColumn(isChinese ? "异常结果" : "Exception results", ColumnDefinition.ColumnType.EnumerationEditable)
.setFormat(format));
columns.add(new Data2DColumn(isChinese ? "提示" : "Tips", ColumnDefinition.ColumnType.EnumerationEditable)
.setFormat(format));
columns.add(new Data2DColumn(isChinese ? "按钮" : "Buttons", ColumnDefinition.ColumnType.EnumerationEditable)
.setFormat(format));
columns.add(new Data2DColumn(isChinese ? "快捷键" : "Shortcuts", ColumnDefinition.ColumnType.EnumerationEditable)
.setFormat(format));
columns.add(new Data2DColumn(isChinese ? "菜单" : "Menu", ColumnDefinition.ColumnType.EnumerationEditable)
.setFormat(format));
columns.add(new Data2DColumn(isChinese ? "响应时间" : "Response time", ColumnDefinition.ColumnType.EnumerationEditable)
.setFormat(format));
columns.add(new Data2DColumn(isChinese ? "内存占用" : "Memory occupied", ColumnDefinition.ColumnType.EnumerationEditable)
.setFormat(format));
columns.add(new Data2DColumn(isChinese ? "检验者" : "Verifier", ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message(lang, "ModifyTime"), ColumnDefinition.ColumnType.Datetime));
columns.add(new Data2DColumn(message(lang, "Description"), ColumnDefinition.ColumnType.String));
String dataName = message(lang, "MyBoxBaseVerificationList") + " - " + DateTools.nowString();
targetData.setColumns(columns).setDataName(dataName);
File targetFile = FileTmpTools.generateFile(dataName, "csv");
if (targetFile.exists()) {
targetFile.delete();
}
Charset charset = Charset.forName("utf-8");
try (BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile, charset, false))) {
String header = null;
for (Data2DColumn column : columns) {
String name = "\"" + column.getColumnName() + "\"";
if (header == null) {
header = name;
} else {
header += "," + name;
}
}
writer.write(header + System.lineSeparator());
if (!onlyDef) {
FunctionsList list = new FunctionsList(controller, false, lang);
StringTable table = list.make();
if (table == null) {
return null;
}
String values = "";
for (int i = 0; i < columns.size() - preSize; i++) {
values += "," + defauleValue;
}
String line;
for (List<String> row : table.getData()) {
line = "win";
for (String v : row) {
line += "," + v;
}
writer.write(line + values + System.lineSeparator());
}
}
writer.flush();
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
targetData.setFile(targetFile).setHasHeader(true).setCharset(charset).setDelimiter(",");
targetData.saveAttributes();
return targetData;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/BytesEditInformation.java | alpha/MyBox/src/main/java/mara/mybox/data/BytesEditInformation.java | package mara.mybox.data;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.tools.ByteTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.FileTools;
import mara.mybox.tools.StringTools;
/**
* @Author Mara
* @CreateDate 2018-12-10 13:06:33
* @License Apache License Version 2.0
*/
public class BytesEditInformation extends FileEditInformation {
public BytesEditInformation() {
editType = Edit_Type.Bytes;
}
public BytesEditInformation(File file) {
super(file);
editType = Edit_Type.Bytes;
initValues();
}
@Override
public boolean readTotalNumbers(FxTask currentTask) {
try {
if (file == null) {
return false;
}
pagination.objectsNumber = 0;
pagination.rowsNumber = 0;
pagination.pagesNumber = 1;
boolean byWidth = lineBreak == Line_Break.Width && lineBreakWidth > 0;
if (!byWidth && lineBreakValue == null) {
return false;
}
long byteIndex = 0, totalLBNumber = 0;
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) {
int bufSize = FileTools.bufSize(file, 16), bufLen;
byte[] buf = new byte[bufSize];
while ((bufLen = inputStream.read(buf)) > 0) {
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
if (bufLen < bufSize) {
buf = ByteTools.subBytes(buf, 0, bufLen);
}
byteIndex += bufLen;
if (!byWidth) {
totalLBNumber += FindReplaceString.count(currentTask,
ByteTools.bytesToHexFormat(buf), lineBreakValue);
}
}
}
pagination.objectsNumber = byteIndex;
pagination.pagesNumber = pagination.objectsNumber / pagination.pageSize;
if (pagination.objectsNumber % pagination.pageSize > 0) {
pagination.pagesNumber++;
}
if (byWidth) {
pagination.rowsNumber = pagination.objectsNumber / lineBreakWidth + 1;
} else {
pagination.rowsNumber = totalLBNumber + 1;
}
totalNumberRead = true;
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
@Override
public String readPage(FxTask currentTask, long pageNumber) {
return readObjects(currentTask, pageNumber * pagination.pageSize, pagination.pageSize);
}
@Override
public String readObjects(FxTask currentTask, long from, long number) {
if (file == null || pagination.pageSize <= 0 || from < 0 || number < 0
|| (pagination.objectsNumber > 0 && from >= pagination.objectsNumber)) {
return null;
}
boolean byWidth = lineBreak == Line_Break.Width && lineBreakWidth > 0;
if (!byWidth && lineBreakValue == null) {
return null;
}
String bufHex = null;
long pageNumber = from / pagination.pageSize, byteIndex = 0, totalLBNumber = 0, pageLBNumber = 0, pageIndex = 0;
int bufLen;
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) {
int bufSize;
byte[] buf;
boolean isCurrentPage;
while (true) {
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
isCurrentPage = pageIndex++ == pageNumber;
if (isCurrentPage) {
bufSize = (int) (Math.max(pagination.pageSize, from - pageNumber * pagination.pageSize + number));
} else {
bufSize = pagination.pageSize;
}
buf = new byte[bufSize];
bufLen = inputStream.read(buf);
if (bufLen <= 0) {
break;
}
if (bufLen < bufSize) {
buf = ByteTools.subBytes(buf, 0, bufLen);
}
byteIndex += bufLen;
if (!byWidth) {
bufHex = ByteTools.bytesToHexFormat(buf);
pageLBNumber = FindReplaceString.count(currentTask, bufHex, lineBreakValue);
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
totalLBNumber += pageLBNumber;
}
if (isCurrentPage) {
if (bufHex == null) {
bufHex = ByteTools.bytesToHexFormat(buf);
}
break;
}
}
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
if (bufHex == null) {
return null;
}
pagination.currentPage = pageNumber;
pagination.startObjectOfCurrentPage = byteIndex - bufLen;
pagination.endObjectOfCurrentPage = byteIndex;
if (byWidth) {
pagination.startRowOfCurrentPage = pagination.startObjectOfCurrentPage / lineBreakWidth;
pagination.endRowOfCurrentPage = pagination.endObjectOfCurrentPage / lineBreakWidth + 1;
} else {
pagination.startRowOfCurrentPage = totalLBNumber - pageLBNumber;
pagination.endRowOfCurrentPage = totalLBNumber + 1;
}
return bufHex;
}
@Override
public String readObject(FxTask currentTask, long index) {
return readObjects(currentTask, index, 1);
}
@Override
public String readLines(FxTask currentTask, long from, long number) {
if (file == null || from < 0 || number < 0
|| (pagination.rowsNumber > 0 && from >= pagination.rowsNumber)) {
return null;
}
boolean byWidth = lineBreak == Line_Break.Width && lineBreakWidth > 0;
if (!byWidth && lineBreakValue == null) {
return null;
}
long byteIndex = 0, totalLBNumber = 0, pageLBNumber = 0, fromLBNumber = 0, fromByteIndex = 0;
String pageHex = null;
int bufLen;
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) {
byte[] buf = new byte[(int) pagination.pageSize];
long lbEnd = Math.min(from + number, pagination.rowsNumber) - 1;
String bufHex;
while ((bufLen = inputStream.read(buf)) > 0) {
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
if (bufLen < pagination.pageSize) {
buf = ByteTools.subBytes(buf, 0, bufLen);
}
bufHex = ByteTools.bytesToHexFormat(buf);
byteIndex += bufLen;
if (byWidth) {
totalLBNumber = byteIndex / lineBreakWidth;
} else {
pageLBNumber = FindReplaceString.count(currentTask, bufHex, lineBreakValue);
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
totalLBNumber += pageLBNumber;
}
if (totalLBNumber >= from) {
if (pageHex == null) {
pageHex = bufHex;
fromLBNumber = totalLBNumber - pageLBNumber;
fromByteIndex = byteIndex - bufLen;
} else {
pageHex += bufHex;
}
if (totalLBNumber >= lbEnd) {
break;
}
}
}
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
if (pageHex == null) {
return null;
}
pagination.currentPage = fromByteIndex / pagination.pageSize;
pagination.startObjectOfCurrentPage = fromByteIndex;
pagination.endObjectOfCurrentPage = byteIndex;
if (byWidth) {
pagination.startRowOfCurrentPage = fromByteIndex / lineBreakWidth;
pagination.endRowOfCurrentPage = byteIndex / lineBreakWidth + 1;
} else {
pagination.startRowOfCurrentPage = fromLBNumber;
pagination.endRowOfCurrentPage = totalLBNumber + 1;
}
return pageHex;
}
@Override
public File filter(FxTask currentTask, boolean recordLineNumbers) {
try {
if (file == null || filterStrings == null || filterStrings.length == 0) {
return file;
}
boolean lbWidth = (lineBreak == Line_Break.Width && lineBreakWidth > 0);
if (!lbWidth && lineBreakValue == null) {
return null;
}
File targetFile = FileTmpTools.getTempFile();
int lineEnd = 0, lineStart = 0;
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile));
OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8")) {
byte[] buf = new byte[pagination.pageSize];
int bufLen;
String pageHex;
while ((bufLen = inputStream.read(buf)) > 0) {
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
if (bufLen < pagination.pageSize) {
buf = ByteTools.subBytes(buf, 0, bufLen);
}
pageHex = ByteTools.bytesToHexFormat(buf);
pageHex = ByteTools.formatHex(pageHex, lineBreak, lineBreakWidth, lineBreakValue);
String[] lines = pageHex.split("\n");
lineEnd = lineStart + lines.length - 1;
for (int i = 0; i < lines.length; ++i) {
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
lines[i] += " ";
if (isMatchFilters(lines[i])) {
if (recordLineNumbers) {
String lineNumber = StringTools.fillRightBlank(lineStart + i, 15);
writer.write(lineNumber + " " + lines[i] + System.lineSeparator());
} else {
writer.write(lines[i] + System.lineSeparator());
}
}
}
if (lbWidth) {
lineStart = lineEnd + 1;
} else {
lineStart = lineEnd;
}
}
}
return targetFile;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
@Override
public boolean writeObject(FxTask currentTask, String hex) {
try {
if (file == null || charset == null || hex == null || hex.isEmpty()) {
return false;
}
try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file))) {
byte[] bytes = ByteTools.hexFormatToBytes(hex);
outputStream.write(bytes);
}
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
@Override
public boolean writePage(FxTask currentTask, FileEditInformation sourceInfo, String hex) {
try {
MyBoxLog.console(file);
if (file == null || hex == null || hex.isEmpty()
|| sourceInfo.getFile() == null || sourceInfo.getCharset() == null) {
return false;
}
int psize = sourceInfo.pagination.pageSize;
long pageStartByte = sourceInfo.pagination.startObjectOfCurrentPage,
pLen = sourceInfo.pagination.endObjectOfCurrentPage - pageStartByte;
if (psize <= 0 || pageStartByte < 0 || pLen <= 0) {
return false;
}
File targetFile = file;
if (sourceInfo.getFile().equals(file)) {
targetFile = FileTmpTools.getTempFile();
}
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(sourceInfo.getFile()));
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile))) {
int bufSize, bufLen;
byte[] buf;
long byteIndex = 0;
while (true) {
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
if (byteIndex < pageStartByte) {
bufSize = (int) Math.min(psize, pageStartByte - byteIndex);
} else if (byteIndex == pageStartByte) {
outputStream.write(ByteTools.hexFormatToBytes(hex));
inputStream.skip(pLen);
byteIndex += pLen;
continue;
} else {
bufSize = psize;
}
buf = new byte[bufSize];
bufLen = inputStream.read(buf);
if (bufLen <= 0) {
break;
}
if (bufLen < bufSize) {
buf = ByteTools.subBytes(buf, 0, bufLen);
}
outputStream.write(buf);
byteIndex += bufLen;
}
}
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
if (sourceInfo.getFile().equals(file)) {
FileTools.override(targetFile, file);
}
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/FindReplaceTextFile.java | alpha/MyBox/src/main/java/mara/mybox/data/FindReplaceTextFile.java | package mara.mybox.data;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javafx.scene.control.IndexRange;
import mara.mybox.data.FindReplaceString.Operation;
import mara.mybox.data2d.DataFileCSV;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.tools.CsvTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.FileTools;
import static mara.mybox.value.Languages.message;
import org.apache.commons.csv.CSVPrinter;
/**
* @Author Mara
* @CreateDate 2020-11-9
* @License Apache License Version 2.0
*/
public class FindReplaceTextFile {
public static boolean countText(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) {
if (sourceInfo == null || sourceInfo.getFile() == null
|| sourceInfo.getCharset() == null || sourceInfo.getLineBreakValue() == null
|| findReplaceFile == null || findReplaceFile.getFindString() == null || findReplaceFile.getFindString().isEmpty()) {
if (findReplaceFile != null) {
findReplaceFile.setError(message("InvalidParameters"));
}
return false;
}
sourceInfo.setFindReplace(findReplaceFile);
findReplaceFile.setFileInfo(sourceInfo);
int count = 0;
File sourceFile = sourceInfo.getFile();
int maxLen = FileTools.bufSize(sourceFile, 16);
String findString = findReplaceFile.getFindString();
FindReplaceString findReplaceString = findReplaceFile.findReplaceString()
.setFindString(findString).setAnchor(0).setWrap(false);
int findLen = findReplaceFile.isIsRegex() ? maxLen : findString.length();
int backFrom, textLen, backLen = 0;
StringBuilder s = new StringBuilder();
String text, checkString, backString = "";
boolean moreLine = false;
try (BufferedReader reader = new BufferedReader(new FileReader(sourceFile, sourceInfo.getCharset()))) {
String line;
while ((line = reader.readLine()) != null) {
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
if (moreLine) {
line = "\n" + line;
} else {
moreLine = true;
}
s.append(line);
textLen = s.length();
if (textLen + backLen < maxLen) { // read as more as possible
continue;
}
text = s.toString();
checkString = backString.concat(text);
findReplaceString.setInputString(checkString)
.setAnchor(0).handleString(currentTask);
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
IndexRange lastRange = findReplaceString.getStringRange();
if (lastRange != null) {
count += findReplaceString.getCount();
if (lastRange.getEnd() == checkString.length()) {
backString = "";
} else {
backFrom = Math.max(lastRange.getStart() - backLen + 1,
Math.max(1, textLen - findLen + 1));
backString = text.substring(backFrom, textLen);
}
} else {
backFrom = Math.max(1, textLen - findLen + 1);
backString = text.substring(backFrom, textLen);
}
backLen = backString.length();
s = new StringBuilder();
}
if (!s.isEmpty()) {
findReplaceString.setInputString(backString.concat(s.toString()))
.handleString(currentTask);
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
IndexRange lastRange = findReplaceString.getStringRange();
if (lastRange != null) {
count += findReplaceString.getCount();
}
}
findReplaceFile.setCount(count);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public static boolean findNextText(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) {
try {
LongRange found = findNextTextRange(currentTask, sourceInfo, findReplaceFile);
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
if (found == null) {
return findReplaceFile != null && findReplaceFile.getError() == null;
}
String pageText = sourceInfo.readObjects(currentTask, found.getStart(), found.getLength());
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
IndexRange stringRange = pageRange(findReplaceFile);
if (stringRange == null) {
findReplaceFile.setError(message("InvalidData"));
return false;
}
findReplaceFile.setFileRange(found);
findReplaceFile.setStringRange(stringRange);
findReplaceFile.setOuputString(pageText);
return true;
} catch (Exception e) {
findReplaceFile.setError(e.toString());
MyBoxLog.debug(e);
return false;
}
}
public static LongRange findNextTextRange(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) {
if (sourceInfo == null || sourceInfo.getFile() == null
|| sourceInfo.getCharset() == null || sourceInfo.getLineBreakValue() == null
|| findReplaceFile == null || findReplaceFile.getFindString() == null
|| findReplaceFile.getFindString().isEmpty()) {
if (findReplaceFile != null) {
findReplaceFile.setError(message("InvalidParameters"));
}
return null;
}
findReplaceFile.setError(null);
findReplaceFile.setFileRange(null);
findReplaceFile.setStringRange(null);
try {
sourceInfo.setFindReplace(findReplaceFile);
findReplaceFile.setFileInfo(sourceInfo);
File sourceFile = sourceInfo.getFile();
Charset charset = sourceInfo.getCharset();
long fileLength = sourceFile.length();
long startPosition = findReplaceFile.getPosition();
if (startPosition < 0 || startPosition >= fileLength) {
if (findReplaceFile.isWrap()) {
startPosition = 0;
} else {
// findReplaceFile.setError(message("InvalidParameters"));
return null;
}
}
int maxLen = FileTools.bufSize(sourceFile, 16);
String findString = findReplaceFile.getFindString();
FindReplaceString findReplaceString = findReplaceFile.findReplaceString()
.setAnchor(0).setWrap(false).setFindString(findString);
int findLen = findReplaceFile.isIsRegex() ? maxLen : findString.length();
LongRange found = findNextTextRange(currentTask, sourceFile, charset,
findReplaceString, startPosition, fileLength, findLen);
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
if (found == null && findReplaceString.getError() != null) {
findReplaceFile.setError(findReplaceString.getError());
return null;
}
if (found == null && findReplaceFile.isWrap() && startPosition > 0 && startPosition < fileLength) {
long endPosition;
if (findReplaceFile.isIsRegex()) {
endPosition = fileLength;
} else {
endPosition = startPosition + findLen;
}
found = findNextTextRange(currentTask, sourceFile, charset,
findReplaceString, 0, endPosition, findLen);
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
if (found == null && findReplaceString.getError() != null) {
findReplaceFile.setError(findReplaceString.getError());
return null;
}
}
findReplaceFile.setFileRange(found);
return found;
} catch (Exception e) {
MyBoxLog.debug(e);
findReplaceFile.setError(e.toString());
return null;
}
}
public static LongRange findNextTextRange(FxTask currentTask, File file, Charset charset, FindReplaceString findReplaceString,
long startPosition, long endPosition, int findLen) {
if (file == null || charset == null || findReplaceString == null || startPosition >= endPosition) {
return null;
}
findReplaceString.setError(null);
findReplaceString.setStringRange(null);
try (BufferedReader reader = new BufferedReader(new FileReader(file, charset))) {
String line;
LongRange found = null;
int charIndex = 0, textLen, lineLen, backLen = 0, keepLen;
StringBuilder s = new StringBuilder();
String text, backString = "";
boolean moreLine = false, skipped = startPosition <= 0;
long textStart = startPosition;
IndexRange range;
while ((line = reader.readLine()) != null) {
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
if (moreLine) {
line = "\n" + line;
} else {
moreLine = true;
}
lineLen = line.length();
charIndex += lineLen;
if (!skipped) {
keepLen = (int) (charIndex - startPosition);
if (keepLen < 0) {
continue;
}
s = new StringBuilder();
if (keepLen > 0) { // start from startPosition
s.append(line.substring((int) (lineLen - keepLen), lineLen));
}
textLen = s.length();
skipped = true;
} else {
s.append(line);
textLen = s.length();
}
keepLen = (int) (charIndex - endPosition);
if (keepLen < 0 && textLen + backLen < findLen) { // find as early as possible
continue;
}
if (keepLen > 0) { // end at endPosition
s.delete((int) (textLen - keepLen), textLen);
textLen = s.length();
}
text = s.toString();
findReplaceString.setInputString(backString.concat(text))
.setAnchor(0).handleString(currentTask);
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
range = findReplaceString.getStringRange();
if (range != null) {
found = new LongRange();
found.setStart(textStart + range.getStart() - backLen);
found.setEnd(found.getStart() + range.getLength());
break;
} else { // backword some string to match each possible
backString = text.substring(Math.max(1, textLen - findLen + 1), textLen);
backLen = backString.length();
}
textStart += textLen;
s = new StringBuilder();
if (keepLen >= 0) {
break;
}
}
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
textLen = s.length();
if (found == null && textLen > 0 && charIndex >= startPosition && charIndex < endPosition) {
keepLen = (int) (charIndex - endPosition);
if (keepLen > 0) {
s.delete((int) (textLen - keepLen), textLen);
}
findReplaceString.setInputString(backString.concat(s.toString()))
.setAnchor(0).handleString(currentTask);
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
range = findReplaceString.getStringRange();
if (range != null) {
found = new LongRange();
found.setStart(textStart + range.getStart() - backLen);
found.setEnd(found.getStart() + range.getLength());
}
}
return found;
} catch (Exception e) {
MyBoxLog.debug(e);
findReplaceString.setError(e.toString());
return null;
}
}
public static boolean findPreviousText(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) {
try {
LongRange found = findPreviousTextRange(currentTask, sourceInfo, findReplaceFile);
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
if (found == null) {
return findReplaceFile != null && findReplaceFile.getError() == null;
}
String pageText = sourceInfo.readObjects(currentTask, found.getStart(), found.getLength());
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
IndexRange stringRange = pageRange(findReplaceFile);
if (stringRange == null) {
findReplaceFile.setError(message("InvalidData"));
return false;
}
findReplaceFile.setFileRange(found);
findReplaceFile.setStringRange(stringRange);
findReplaceFile.setOuputString(pageText);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
findReplaceFile.setError(e.toString());
return false;
}
}
public static LongRange findPreviousTextRange(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) {
if (sourceInfo == null || sourceInfo.getFile() == null
|| sourceInfo.getCharset() == null || sourceInfo.getLineBreakValue() == null
|| findReplaceFile == null || findReplaceFile.getFindString() == null
|| findReplaceFile.getFindString().isEmpty()) {
if (findReplaceFile != null) {
findReplaceFile.setError(message("InvalidParameters"));
}
return null;
}
findReplaceFile.setError(null);
findReplaceFile.setFileRange(null);
findReplaceFile.setStringRange(null);
try {
sourceInfo.setFindReplace(findReplaceFile);
findReplaceFile.setFileInfo(sourceInfo);
File sourceFile = sourceInfo.getFile();
Charset charset = sourceInfo.getCharset();
long fileLength = sourceFile.length();
long endPostion = findReplaceFile.getPosition();
if (endPostion <= 0 || endPostion > fileLength) {
if (findReplaceFile.isWrap()) {
endPostion = fileLength;
} else {
// findReplaceFile.setError(message("InvalidParameters"));
return null;
}
}
int maxLen = FileTools.bufSize(sourceFile, 16);
String findString = findReplaceFile.getFindString();
FindReplaceString findReplaceString = findReplaceFile.findReplaceString()
.setFindString(findString).setAnchor(0).setWrap(false);
int findLen = findReplaceFile.isIsRegex() ? maxLen : findString.length();
LongRange found = findPreviousTextRange(currentTask, sourceFile, charset,
findReplaceString, 0, endPostion, maxLen, findLen);
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
if (found == null && findReplaceString.getError() != null) {
findReplaceFile.setError(findReplaceString.getError());
return null;
}
if (found == null && findReplaceFile.isWrap() && endPostion > 0 && endPostion <= fileLength) {
long startPosition;
if (findReplaceFile.isIsRegex()) {
startPosition = 0;
} else {
startPosition = Math.max(0, endPostion - findLen);
}
found = findPreviousTextRange(currentTask, sourceFile, charset,
findReplaceString, startPosition, fileLength, maxLen, findLen);
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
if (found == null && findReplaceString.getError() != null) {
findReplaceFile.setError(findReplaceString.getError());
return null;
}
}
findReplaceFile.setFileRange(found);
return found;
} catch (Exception e) {
findReplaceFile.setError(e.toString());
MyBoxLog.debug(e);
return null;
}
}
public static LongRange findPreviousTextRange(FxTask currentTask, File file, Charset charset, FindReplaceString findReplaceString,
long startPosition, long endPosition, long maxLen, int findLen) {
if (file == null || charset == null || findReplaceString == null) {
return null;
}
findReplaceString.setError(null);
findReplaceString.setStringRange(null);
try (BufferedReader reader = new BufferedReader(new FileReader(file, charset))) {
String line;
LongRange found = null;
int backFrom, textLen, backLen = 0, checkLen, lineLen, keepLen;
StringBuilder s = new StringBuilder();
String text, backString = "", checkString;
boolean moreLine = false, skipped = startPosition <= 0;
long charIndex = 0, textStart = startPosition;
IndexRange range;
while ((line = reader.readLine()) != null) {
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
if (moreLine) {
line = "\n" + line;
} else {
moreLine = true;
}
lineLen = line.length();
charIndex += lineLen;
if (!skipped) { // start from startPosition
keepLen = (int) (charIndex - startPosition);
if (keepLen < 0) {
continue;
}
s = new StringBuilder();
if (keepLen > 0) {
s.append(line.substring((int) (lineLen - keepLen), lineLen));
}
textLen = s.length();
skipped = true;
} else {
s.append(line);
textLen = s.length();
}
keepLen = (int) (charIndex - endPosition); // end at startPosition
if (keepLen < 0 && textLen + backLen < maxLen) { // read as more as possible
continue;
}
if (keepLen > 0) {
s.delete((int) (textLen - keepLen), textLen);
textLen = s.length();
}
text = s.toString();
checkString = backString.concat(text);
checkLen = checkString.length();
findReplaceString.setInputString(checkString).setAnchor(checkLen)
.handleString(currentTask);
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
range = findReplaceString.getStringRange();
if (range != null) {
found = new LongRange();
found.setStart(textStart + range.getStart() - backLen);
found.setEnd(found.getStart() + range.getLength());
if (range.getEnd() == checkLen) {
backString = "";
} else {
backFrom = Math.max(1, textLen - findLen + 1);
backFrom = Math.max(range.getStart() - backLen + 1, backFrom);
backString = text.substring(backFrom, textLen);
}
} else {
backFrom = Math.max(1, textLen - findLen + 1);
backString = text.substring(backFrom, textLen);
}
backLen = backString.length();
textStart += textLen;
s = new StringBuilder();
if (keepLen >= 0) {
break;
}
}
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
textLen = s.length();
if (found == null && textLen > 0 && charIndex >= startPosition && charIndex < endPosition) {
keepLen = (int) (charIndex - endPosition);
if (keepLen > 0) {
s.delete((int) (textLen - keepLen), textLen);
}
checkString = backString.concat(s.toString());
checkLen = checkString.length();
findReplaceString.setInputString(checkString)
.setAnchor(checkLen).handleString(currentTask);
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
range = findReplaceString.getStringRange();
if (range != null) {
found = new LongRange();
found.setStart(textStart + range.getStart() - backLen);
found.setEnd(found.getStart() + range.getLength());
}
}
return found;
} catch (Exception e) {
MyBoxLog.debug(e);
findReplaceString.setError(e.toString());
return null;
}
}
public static boolean replaceFirstText(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) {
try {
if (findReplaceFile == null) {
return false;
}
String replaceString = findReplaceFile.getReplaceString();
if (replaceString == null) {
return false;
}
findReplaceFile.setOperation(Operation.FindNext);
findNextText(currentTask, sourceInfo, findReplaceFile);
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
IndexRange stringRange = findReplaceFile.getStringRange();
findReplaceFile.setOperation(Operation.ReplaceFirst);
if (stringRange == null) {
return false;
}
String pageText = findReplaceFile.getOutputString();
if (stringRange.getStart() < 0 || stringRange.getStart() > stringRange.getEnd()
|| stringRange.getEnd() > pageText.length()) {
return false;
}
String output = pageText.substring(0, stringRange.getStart())
+ replaceString
+ pageText.substring(stringRange.getEnd(), pageText.length());
findReplaceFile.setOuputString(output);
return true;
} catch (Exception e) {
findReplaceFile.setError(e.toString());
MyBoxLog.debug(e);
return false;
}
}
public static boolean replaceAllText(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) {
if (sourceInfo == null || sourceInfo.getFile() == null || findReplaceFile == null
|| sourceInfo.getCharset() == null || sourceInfo.getLineBreakValue() == null
|| findReplaceFile.getFindString() == null || findReplaceFile.getFindString().isEmpty()) {
if (findReplaceFile != null) {
findReplaceFile.setError(message("InvalidParameters"));
}
return false;
}
int total = 0;
findReplaceFile.setError(null);
findReplaceFile.setFileRange(null);
findReplaceFile.setStringRange(null);
sourceInfo.setFindReplace(findReplaceFile);
findReplaceFile.setFileInfo(sourceInfo);
File sourceFile = sourceInfo.getFile();
File tmpFile = FileTmpTools.getTempFile();
// MyBoxLog.debug(sourceFile + " --> " + tmpFile);
Charset charset = sourceInfo.getCharset();
try (BufferedReader reader = new BufferedReader(new FileReader(sourceFile, charset));
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tmpFile));
OutputStreamWriter writer = new OutputStreamWriter(outputStream, charset)) {
String findString = findReplaceFile.getFindString();
String replaceString = findReplaceFile.getReplaceString();
FindReplaceString findReplaceString = findReplaceFile.findReplaceString()
.setFindString(findString).setReplaceString(replaceString)
.setAnchor(0).setWrap(false);
int maxLen = FileTools.bufSize(sourceFile, 16);
int findLen = findReplaceFile.isIsRegex() ? maxLen : findString.length();
int backFrom, textLen, backLen = 0, lastReplacedLength;
// MyBoxLog.debug(" maxLen: " + maxLen + " findLen: " + findLen);
StringBuilder s = new StringBuilder();
boolean moreLine = false;
String line, replacedString, text, backString = "", checkedString;
IndexRange range;
while ((line = reader.readLine()) != null) {
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
if (moreLine) {
line = "\n" + line;
} else {
moreLine = true;
}
s.append(line);
textLen = s.length();
if (textLen + backLen < maxLen) { // read as more as possible
continue;
}
text = s.toString();
checkedString = backString.concat(text);
findReplaceString.setInputString(checkedString)
.setAnchor(0).handleString(currentTask);
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
range = findReplaceString.getStringRange();
if (range != null) {
replacedString = findReplaceString.getOutputString();
lastReplacedLength = findReplaceString.getLastReplacedLength();
writer.write(replacedString.substring(0, lastReplacedLength));
backString = replacedString.substring(lastReplacedLength, replacedString.length());
total += findReplaceString.getCount();
// MyBoxLog.debug(replacedString.length() + " " + lastReplacedLength + " " + backString.length() + " " + findReplaceString.getCount());
} else {
if (!backString.isEmpty()) {
writer.write(backString);
}
backFrom = Math.max(1, textLen - findLen + 1);
backString = text.substring(backFrom, textLen);
writer.write(text.substring(0, backFrom));
}
backLen = backString.length();
s = new StringBuilder();
}
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
if (!s.isEmpty()) {
// MyBoxLog.debug(backString.length() + " " + s.toString().length());
findReplaceString.setInputString(backString.concat(s.toString()))
.setAnchor(0).handleString(currentTask);
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
// MyBoxLog.debug(findReplaceString.getOutputString().length());
writer.write(findReplaceString.getOutputString());
total += findReplaceString.getCount();
}
findReplaceFile.setCount(total);
} catch (Exception e) {
MyBoxLog.debug(e);
findReplaceFile.setError(e.toString());
return false;
}
if (tmpFile != null && tmpFile.exists()) {
if (total > 0) {
findReplaceFile.backup(currentTask, sourceFile);
return FileTools.override(tmpFile, sourceFile);
} else {
return true;
}
}
return false;
}
public static IndexRange pageRange(FindReplaceFile findReplace) {
if (findReplace == null) {
return null;
}
IndexRange pageRange = null;
LongRange fileRange = findReplace.getFileRange();
FileEditInformation fileInfo = findReplace.getFileInfo();
if (fileRange != null && fileInfo != null) {
long pageStart = fileInfo.pagination.startObjectOfCurrentPage * findReplace.getUnit();
pageRange = new IndexRange((int) (fileRange.getStart() - pageStart), (int) (fileRange.getEnd() - pageStart));
}
findReplace.setStringRange(pageRange);
return pageRange;
}
public static LongRange fileRange(FindReplaceFile findReplace) {
if (findReplace == null) {
return null;
}
LongRange fileRange = null;
IndexRange pageRange = findReplace.getStringRange();
FileEditInformation fileInfo = findReplace.getFileInfo();
if (pageRange != null && fileInfo != null) {
long pageStart = fileInfo.pagination.startObjectOfCurrentPage * findReplace.getUnit();
fileRange = new LongRange(pageRange.getStart() + pageStart, pageRange.getEnd() + pageStart);
}
findReplace.setFileRange(fileRange);
return fileRange;
}
public static boolean findAllText(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) {
if (sourceInfo == null || sourceInfo.getFile() == null
|| sourceInfo.getCharset() == null || sourceInfo.getLineBreakValue() == null
|| findReplaceFile == null || findReplaceFile.getFindString() == null
|| findReplaceFile.getFindString().isEmpty()) {
if (findReplaceFile != null) {
findReplaceFile.setError(message("InvalidParameters"));
}
return false;
}
findReplaceFile.setError(null);
findReplaceFile.setFileRange(null);
findReplaceFile.setStringRange(null);
findReplaceFile.setCount(0);
findReplaceFile.setMatches(null);
findReplaceFile.setMatchesData(null);
sourceInfo.setFindReplace(findReplaceFile);
findReplaceFile.setFileInfo(sourceInfo);
File sourceFile = sourceInfo.getFile();
int maxLen = FileTools.bufSize(sourceFile, 16);
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | true |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/FindReplaceBytesFile.java | alpha/MyBox/src/main/java/mara/mybox/data/FindReplaceBytesFile.java | package mara.mybox.data;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javafx.scene.control.IndexRange;
import mara.mybox.data2d.DataFileCSV;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.tools.ByteTools;
import mara.mybox.tools.CsvTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.FileTools;
import static mara.mybox.value.Languages.message;
import org.apache.commons.csv.CSVPrinter;
/**
* @Author Mara
* @CreateDate 2020-11-9
* @License Apache License Version 2.0
*/
public class FindReplaceBytesFile {
public static boolean countBytes(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) {
if (sourceInfo == null || sourceInfo.getFile() == null || findReplaceFile == null
|| findReplaceFile.getFindString() == null || findReplaceFile.getFindString().isEmpty()) {
if (findReplaceFile != null) {
findReplaceFile.setError(message("InvalidParameters"));
}
return false;
}
sourceInfo.setFindReplace(findReplaceFile);
findReplaceFile.setFileInfo(sourceInfo);
int count = 0;
File sourceFile = sourceInfo.getFile();
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(sourceFile))) {
int pageSize = FileTools.bufSize(sourceFile, 48);
byte[] pageBytes = new byte[pageSize];
String findString = findReplaceFile.getFindString();
int findLen = findReplaceFile.isIsRegex() ? pageSize * 3 : findString.length();
FindReplaceString findReplaceString = findReplaceFile.findReplaceString()
.setFindString(findString).setAnchor(0).setWrap(false);
int bufLen, backFrom, hexLen;
String pageHex, backString = "", checkedString;
while ((bufLen = inputStream.read(pageBytes)) > 0) {
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
if (bufLen < pageSize) {
pageBytes = ByteTools.subBytes(pageBytes, 0, bufLen);
}
pageHex = ByteTools.bytesToHexFormat(pageBytes);
hexLen = pageHex.length();
checkedString = backString + pageHex;
findReplaceString.setInputString(checkedString).handleString(currentTask);
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
IndexRange lastRange = findReplaceString.getStringRange();
if (lastRange != null) {
count += findReplaceString.getCount();
if (lastRange.getEnd() == checkedString.length()) {
backString = "";
} else {
backFrom = Math.max(3, hexLen - findLen + 3);
backFrom = Math.max(lastRange.getStart() - backString.length() + 3, backFrom);
backString = pageHex.substring(backFrom, hexLen);
}
} else {
backFrom = Math.max(3, hexLen - findLen + 3);
backString = pageHex.substring(backFrom, hexLen);
}
}
findReplaceFile.setCount(count);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
findReplaceFile.setError(e.toString());
return false;
}
}
public static boolean findNextBytes(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) {
try {
LongRange found = findNextBytesRange(currentTask, sourceInfo, findReplaceFile);
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
if (found == null) {
return findReplaceFile != null && findReplaceFile.getError() == null;
}
String pageText = sourceInfo.readObjects(currentTask, found.getStart() / 3, found.getLength() / 3);
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
IndexRange stringRange = FindReplaceTextFile.pageRange(findReplaceFile);
if (stringRange == null) {
findReplaceFile.setError(message("InvalidData"));
return false;
}
findReplaceFile.setFileRange(found);
findReplaceFile.setStringRange(stringRange);
findReplaceFile.setOuputString(pageText);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
findReplaceFile.setError(e.toString());
return false;
}
}
public static LongRange findNextBytesRange(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) {
if (sourceInfo == null || sourceInfo.getFile() == null || findReplaceFile == null
|| findReplaceFile.getFindString() == null || findReplaceFile.getFindString().isEmpty()) {
if (findReplaceFile != null) {
findReplaceFile.setError(message("InvalidParameters"));
}
return null;
}
findReplaceFile.setError(null);
findReplaceFile.setFileRange(null);
findReplaceFile.setStringRange(null);
try {
sourceInfo.setFindReplace(findReplaceFile);
findReplaceFile.setFileInfo(sourceInfo);
File sourceFile = sourceInfo.getFile();
long fileLength = sourceFile.length();
long hexStartPosition = (findReplaceFile.getPosition() / 3) * 3;
long bytesStartPosition = hexStartPosition / 3;
if (bytesStartPosition < 0 || bytesStartPosition >= fileLength) {
if (findReplaceFile.isWrap()) {
hexStartPosition = 0;
bytesStartPosition = 0;
} else {
// findReplaceFile.setError(message("InvalidParameters"));
return null;
}
}
int maxBytesLen = FileTools.bufSize(sourceFile, 48);
String findString = findReplaceFile.getFindString();
FindReplaceString findReplaceString = findReplaceFile.findReplaceString()
.setFindString(findString).setAnchor(0).setWrap(false);
// findString should have been in hex format
int findHexLen = findReplaceFile.isIsRegex() ? maxBytesLen * 3 : findString.length();
LongRange found = findNextBytesRange(currentTask, sourceFile, findReplaceString, hexStartPosition, fileLength * 3, maxBytesLen, findHexLen);
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
if (found == null && findReplaceString.getError() != null) {
findReplaceFile.setError(findReplaceString.getError());
return null;
}
if (found == null && findReplaceFile.isWrap() && bytesStartPosition > 0 && bytesStartPosition < fileLength * 3) {
long hexEndPosition;
if (findReplaceFile.isIsRegex()) {
hexEndPosition = fileLength * 3;
} else {
hexEndPosition = hexStartPosition + findHexLen;
}
found = findNextBytesRange(currentTask, sourceFile, findReplaceString, 0, hexEndPosition, maxBytesLen, findHexLen);
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
}
if (found == null && findReplaceString.getError() != null) {
findReplaceFile.setError(findReplaceString.getError());
return null;
}
findReplaceFile.setFileRange(found);
return found;
} catch (Exception e) {
findReplaceFile.setError(e.toString());
MyBoxLog.debug(e);
return null;
}
}
public static LongRange findNextBytesRange(FxTask currentTask, File file, FindReplaceString findReplaceString,
long hexStartPosition, long hexEndPosition, long maxBytesLen, int findHexLen) {
if (file == null || findReplaceString == null || hexStartPosition >= hexEndPosition) {
return null;
}
findReplaceString.setError(null);
findReplaceString.setStringRange(null);
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) {
if (hexStartPosition > 0) {
inputStream.skip(hexStartPosition / 3);
}
int bufSize = (int) Math.min(maxBytesLen, (hexEndPosition - hexStartPosition) / 3);
byte[] bufBytes = new byte[bufSize];
IndexRange range;
String bufHex, backString = "";
long hexIndex = hexStartPosition;
int bufLen, backFrom, hexLen, keepLen;
LongRange found = null;
while ((bufLen = inputStream.read(bufBytes)) > 0) {
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
if (bufLen < bufSize) {
bufBytes = ByteTools.subBytes(bufBytes, 0, bufLen);
}
bufHex = ByteTools.bytesToHexFormat(bufBytes);
hexLen = bufHex.length();
hexIndex += hexLen;
keepLen = (int) (hexIndex - hexEndPosition);
if (keepLen > 0) {
bufHex = bufHex.substring(0, hexLen - keepLen);
hexLen = bufHex.length();
}
findReplaceString.setInputString(backString.concat(bufHex))
.setAnchor(0).handleString(currentTask);
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
range = findReplaceString.getStringRange();
if (range != null) {
found = new LongRange();
found.setStart(hexIndex - hexLen + range.getStart() - backString.length());
found.setEnd(found.getStart() + range.getLength());
break;
}
if (keepLen >= 0) {
break;
}
backFrom = Math.max(3, hexLen - findHexLen + 3);
if (backFrom < hexLen) {
backString = bufHex.substring(backFrom, hexLen);
} else {
backString = "";
}
}
return found;
} catch (Exception e) {
MyBoxLog.debug(e);
findReplaceString.setError(e.toString());
return null;
}
}
public static boolean findPreviousBytes(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) {
try {
LongRange found = findPreviousBytesRange(currentTask, sourceInfo, findReplaceFile);
if (found == null) {
return findReplaceFile != null && findReplaceFile.getError() == null;
}
String pageText = sourceInfo.readObjects(currentTask, found.getStart() / 3, found.getLength() / 3);
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
IndexRange stringRange = FindReplaceTextFile.pageRange(findReplaceFile);
if (stringRange == null) {
findReplaceFile.setError(message("InvalidData"));
return false;
}
findReplaceFile.setFileRange(found);
findReplaceFile.setStringRange(stringRange);
findReplaceFile.setOuputString(pageText);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
findReplaceFile.setError(e.toString());
return false;
}
}
public static LongRange findPreviousBytesRange(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) {
if (sourceInfo == null || sourceInfo.getFile() == null || findReplaceFile == null
|| findReplaceFile.getFindString() == null || findReplaceFile.getFindString().isEmpty()) {
if (findReplaceFile != null) {
findReplaceFile.setError(message("InvalidParameters"));
}
return null;
}
try {
sourceInfo.setFindReplace(findReplaceFile);
findReplaceFile.setFileInfo(sourceInfo);
File sourceFile = sourceInfo.getFile();
long fileLength = sourceFile.length();
long hexEndPosition = (findReplaceFile.getPosition() / 3) * 3;
long bytesEndPosition = hexEndPosition / 3;
if (bytesEndPosition <= 0 || bytesEndPosition > fileLength) {
if (findReplaceFile.isWrap()) {
bytesEndPosition = fileLength;
hexEndPosition = bytesEndPosition * 3;
} else {
// findReplaceFile.setError(message("InvalidParameters"));
return null;
}
}
int maxBytesLen = FileTools.bufSize(sourceFile, 48);
String findString = findReplaceFile.getFindString();
FindReplaceString findReplaceString = findReplaceFile.findReplaceString()
.setFindString(findString).setAnchor(0).setWrap(false);
// findString should have been in hex format
int findHexLen = findReplaceFile.isIsRegex() ? maxBytesLen * 3 : findString.length();
LongRange found = findPreviousBytesRange(currentTask, sourceFile, findReplaceString, 0, hexEndPosition, maxBytesLen, findHexLen);
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
if (found == null && findReplaceString.getError() != null) {
findReplaceFile.setError(findReplaceString.getError());
return null;
}
if (found == null && findReplaceFile.isWrap() && hexEndPosition > 0 && hexEndPosition <= fileLength * 3) {
long hexStartPosition;
if (findReplaceFile.isIsRegex()) {
hexStartPosition = 0;
} else {
hexStartPosition = Math.max(0, hexEndPosition - findHexLen);
}
found = findPreviousBytesRange(currentTask, sourceFile, findReplaceString, hexStartPosition, fileLength * 3, maxBytesLen, findHexLen);
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
}
if (found == null && findReplaceString.getError() != null) {
findReplaceFile.setError(findReplaceString.getError());
return null;
}
findReplaceFile.setFileRange(found);
return found;
} catch (Exception e) {
findReplaceFile.setError(e.toString());
MyBoxLog.debug(e);
return null;
}
}
public static LongRange findPreviousBytesRange(FxTask currentTask, File file, FindReplaceString findReplaceString,
long hexStartPosition, long hexEndPosition, long maxBytesLen, int findHexLen) {
if (file == null || findReplaceString == null || hexStartPosition >= hexEndPosition) {
return null;
}
findReplaceString.setError(null);
findReplaceString.setStringRange(null);
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) {
if (hexStartPosition > 0) {
inputStream.skip(hexStartPosition / 3);
}
int bufSize = (int) Math.min(maxBytesLen, (hexEndPosition - hexStartPosition) / 3);
byte[] bufBytes = new byte[bufSize];
IndexRange range;
String bufHex, backString = "", checkString;
long hexIndex = hexStartPosition;
int bufLen, backFrom, hexLen, checkLen, keepLen;
LongRange found = null;
while ((bufLen = inputStream.read(bufBytes)) > 0) {
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
if (bufLen < maxBytesLen) {
bufBytes = ByteTools.subBytes(bufBytes, 0, bufLen);
}
bufHex = ByteTools.bytesToHexFormat(bufBytes);
hexLen = bufHex.length();
hexIndex += hexLen;
keepLen = (int) (hexIndex - hexEndPosition);
if (keepLen > 0) {
bufHex = bufHex.substring(0, hexLen - keepLen);
hexLen = bufHex.length();
}
checkString = backString.concat(bufHex);
checkLen = checkString.length();
findReplaceString.setInputString(checkString)
.setAnchor(checkLen).handleString(currentTask);
if (currentTask != null && !currentTask.isWorking()) {
return null;
}
range = findReplaceString.getStringRange();
if (range != null) {
found = new LongRange();
found.setStart(hexIndex - hexLen + range.getStart() - backString.length());
found.setEnd(found.getStart() + range.getLength());
if (range.getEnd() == checkLen) {
backString = "";
} else {
backFrom = Math.max(range.getStart() - backString.length() + 3, Math.max(3, hexLen - findHexLen + 3));
if (backFrom < hexLen) {
backString = bufHex.substring(backFrom, hexLen);
} else {
backString = "";
}
}
} else {
backFrom = Math.max(3, hexLen - findHexLen + 3);
if (backFrom < hexLen) {
backString = bufHex.substring(backFrom, hexLen);
} else {
backString = "";
}
}
if (keepLen >= 0) {
break;
}
}
return found;
} catch (Exception e) {
MyBoxLog.debug(e);
findReplaceString.setError(e.toString());
return null;
}
}
public static boolean replaceFirstBytes(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) {
try {
if (findReplaceFile == null) {
return false;
}
String replaceString = findReplaceFile.getReplaceString();
if (replaceString == null) {
return false;
}
findReplaceFile.setOperation(FindReplaceString.Operation.FindNext);
findNextBytes(currentTask, sourceInfo, findReplaceFile);
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
IndexRange stringRange = findReplaceFile.getStringRange();
findReplaceFile.setOperation(FindReplaceString.Operation.ReplaceFirst);
if (stringRange == null) {
return false;
}
String pageText = findReplaceFile.getOutputString();
if (stringRange.getStart() < 0 || stringRange.getStart() > stringRange.getEnd()
|| stringRange.getEnd() > pageText.length()) {
return false;
}
String output = pageText.substring(0, stringRange.getStart())
+ replaceString
+ pageText.substring(stringRange.getEnd(), pageText.length());
findReplaceFile.setOuputString(output);
return true;
} catch (Exception e) {
findReplaceFile.setError(e.toString());
MyBoxLog.debug(e);
return false;
}
}
public static boolean replaceAllBytes(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) {
if (sourceInfo == null || sourceInfo.getFile() == null
|| findReplaceFile.getFindString() == null || findReplaceFile.getFindString().isEmpty()) {
if (findReplaceFile != null) {
findReplaceFile.setError(message("InvalidParameters"));
}
return false;
}
int total = 0;
findReplaceFile.setError(null);
findReplaceFile.setFileRange(null);
findReplaceFile.setStringRange(null);
sourceInfo.setFindReplace(findReplaceFile);
findReplaceFile.setFileInfo(sourceInfo);
File sourceFile = sourceInfo.getFile();
File tmpFile = FileTmpTools.getTempFile();
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(sourceFile));
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tmpFile))) {
int pageSize = FileTools.bufSize(sourceFile, 48);
String findString = findReplaceFile.getFindString();
String replaceString = findReplaceFile.getReplaceString();
FindReplaceString findReplaceString = findReplaceFile.findReplaceString()
.setFindString(findString).setReplaceString(replaceString)
.setAnchor(0).setWrap(false);
int findLen = findReplaceFile.isIsRegex() ? pageSize * 3 : findString.length();
byte[] pageBytes = new byte[pageSize];
IndexRange range;
String pageHex, backString = "", checkedString, replacedString;
int pageLen, backFrom, lastReplacedLength;
while ((pageLen = inputStream.read(pageBytes)) > 0) {
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
if (pageLen < pageSize) {
pageBytes = ByteTools.subBytes(pageBytes, 0, pageLen);
}
pageHex = ByteTools.bytesToHexFormat(pageBytes);
pageLen = pageHex.length();
checkedString = backString + pageHex;
findReplaceString.setInputString(checkedString)
.setAnchor(0).handleString(currentTask);
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
range = findReplaceString.getStringRange();
if (range != null) {
replacedString = findReplaceString.getOutputString();
lastReplacedLength = findReplaceString.getLastReplacedLength();
byte[] replacedBytes = ByteTools.hexFormatToBytes(replacedString.substring(0, lastReplacedLength));
outputStream.write(replacedBytes);
backString = replacedString.substring(lastReplacedLength, replacedString.length());
total += findReplaceString.getCount();
} else {
if (!backString.isEmpty()) {
byte[] backBytes = ByteTools.hexFormatToBytes(backString);
outputStream.write(backBytes);
}
backFrom = Math.max(3, pageLen - findLen + 3);
backString = pageHex.substring(backFrom, pageLen);
byte[] passBytes = ByteTools.hexFormatToBytes(pageHex.substring(0, backFrom));
outputStream.write(passBytes);
}
}
if (!backString.isEmpty()) {
byte[] backBytes = ByteTools.hexFormatToBytes(backString);
outputStream.write(backBytes);
}
} catch (Exception e) {
MyBoxLog.debug(e);
findReplaceFile.setError(e.toString());
return false;
}
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
findReplaceFile.setCount(total);
if (tmpFile != null && tmpFile.exists()) {
if (total > 0) {
findReplaceFile.backup(currentTask, sourceFile);
return FileTools.override(tmpFile, sourceFile);
} else {
return true;
}
}
return false;
}
public static boolean findAllBytes(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) {
if (sourceInfo == null || sourceInfo.getFile() == null
|| findReplaceFile.getFindString() == null || findReplaceFile.getFindString().isEmpty()) {
if (findReplaceFile != null) {
findReplaceFile.setError(message("InvalidParameters"));
}
return false;
}
findReplaceFile.setError(null);
findReplaceFile.setFileRange(null);
findReplaceFile.setStringRange(null);
findReplaceFile.setCount(0);
findReplaceFile.setMatches(null);
findReplaceFile.setMatchesData(null);
sourceInfo.setFindReplace(findReplaceFile);
findReplaceFile.setFileInfo(sourceInfo);
File sourceFile = sourceInfo.getFile();
int count = 0;
File tmpFile = FileTmpTools.getTempFile();
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(sourceFile));
CSVPrinter csvPrinter = CsvTools.csvPrinter(tmpFile)) {
int pageSize = FileTools.bufSize(sourceFile, 48);
String findString = findReplaceFile.getFindString();
String replaceString = findReplaceFile.getReplaceString();
FindReplaceString findReplaceString = findReplaceFile.findReplaceString()
.setFindString(findString).setReplaceString(replaceString)
.setAnchor(0).setWrap(false);
int findLen = findReplaceFile.isIsRegex() ? pageSize * 3 : findString.length();
byte[] pageBytes = new byte[pageSize];
IndexRange range;
String pageHex, backString = "", checkedString;
int pageLen, backFrom;
long bytesStart = 0;
List<String> names = new ArrayList<>();
names.addAll(Arrays.asList(message("Start"), message("End"), message("String")));
csvPrinter.printRecord(names);
List<String> row = new ArrayList<>();
while ((pageLen = inputStream.read(pageBytes)) > 0) {
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
if (pageLen < pageSize) {
pageBytes = ByteTools.subBytes(pageBytes, 0, pageLen);
}
pageHex = ByteTools.bytesToHexFormat(pageBytes);
pageLen = pageHex.length();
checkedString = backString + pageHex;
findReplaceString.setInputString(checkedString)
.setAnchor(0).handleString(currentTask);
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
range = findReplaceString.getStringRange();
if (range != null) {
long offset = bytesStart - backString.length();
List<FindReplaceMatch> sMatches = findReplaceString.getMatches();
if (sMatches != null && !sMatches.isEmpty()) {
for (FindReplaceMatch m : sMatches) {
row.clear();
row.add(((offset + m.getStart()) / 3 + 1) + "");
row.add((offset + m.getEnd()) / 3 + "");
row.add(m.getMatchedPrefix());
csvPrinter.printRecord(row);
count++;
}
}
backString = checkedString.length() == range.getEnd() ? ""
: checkedString.substring(range.getEnd());
} else {
backFrom = Math.max(3, pageLen - findLen + 3);
backString = pageHex.substring(backFrom, pageLen);
}
bytesStart += pageLen;
}
csvPrinter.flush();
} catch (Exception e) {
MyBoxLog.debug(e);
findReplaceFile.setError(e.toString());
return false;
}
if (currentTask != null && !currentTask.isWorking()) {
return false;
}
if (tmpFile == null || !tmpFile.exists()) {
return false;
}
if (count == 0) {
return true;
}
DataFileCSV matchesData = findReplaceFile.initMatchesData(sourceFile);
File matchesFile = matchesData.getFile();
if (!FileTools.override(tmpFile, matchesFile)) {
return false;
}
matchesData.setRowsNumber(count);
findReplaceFile.setCount(count);
findReplaceFile.setMatchesData(matchesData);
return true;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/UserLanguage.java | alpha/MyBox/src/main/java/mara/mybox/data/UserLanguage.java | package mara.mybox.data;
import java.io.File;
import java.util.Enumeration;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import mara.mybox.tools.ConfigTools;
import static mara.mybox.value.AppVariables.useChineseWhenBlankTranslation;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2019-12-27
* @License Apache License Version 2.0
*/
public class UserLanguage extends ResourceBundle {
protected Map<String, String> items;
protected String language;
public UserLanguage(String name) throws Exception {
File file = Languages.interfaceLanguageFile(name);
if (!file.exists()) {
items = null;
throw new Exception();
} else {
language = name;
items = ConfigTools.readValues(file);
}
}
public UserLanguage(Map<String, String> items) {
this.items = items;
}
public boolean isValid() {
return items != null;
}
@Override
public Object handleGetObject(String key) {
String value = null;
if (items != null) {
value = items.get(key);
}
if (value == null) {
value = useChineseWhenBlankTranslation
? Languages.BundleZhCN.getString(key)
: Languages.BundleEn.getString(key);
}
if (value == null) {
value = key;
}
return value;
}
@Override
protected Set<String> handleKeySet() {
return Languages.BundleEn.keySet();
}
/*
get/set
*/
@Override
public Enumeration<String> getKeys() {
return Languages.BundleEn.getKeys();
}
public Map<String, String> getItems() {
return items;
}
public UserLanguage setItems(Map<String, String> items) {
this.items = items;
return this;
}
public String getLanguage() {
return language;
}
public UserLanguage setLanguage(String language) {
this.language = language;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/JsonTreeNode.java | alpha/MyBox/src/main/java/mara/mybox/data/JsonTreeNode.java | package mara.mybox.data;
import com.fasterxml.jackson.core.json.JsonReadFeature;
import com.fasterxml.jackson.core.json.JsonWriteFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import java.sql.Connection;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import mara.mybox.db.DerbyBase;
import mara.mybox.dev.MyBoxLog;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2023-4-30
* @License Apache License Version 2.0
*/
public class JsonTreeNode {
public static ObjectMapper jsonMapper;
protected String title;
protected JsonNode jsonNode;
protected NodeType type;
protected final BooleanProperty selected = new SimpleBooleanProperty(false);
public static enum NodeType {
Array, Object, String, Number, Boolean, Null, Unknown
}
public JsonTreeNode() {
title = null;
jsonNode = null;
type = null;
}
public JsonTreeNode(String name, JsonNode jsonNode) {
this.title = name;
this.jsonNode = jsonNode;
if (jsonNode == null) {
type = NodeType.Unknown;
} else if (jsonNode.isNull()) {
type = NodeType.Null;
} else {
if (jsonNode.isBoolean()) {
type = NodeType.Boolean;
} else if (jsonNode.isNumber()) {
type = NodeType.Number;
} else if (jsonNode.isTextual() || jsonNode.isBinary()) {
type = NodeType.String;
} else if (jsonNode.isArray()) {
type = NodeType.Array;
} else if (jsonNode.isObject()) {
type = NodeType.Object;
} else {
type = NodeType.Unknown;
}
}
}
public String getTypename() {
return type == null ? null : message(type.name());
}
public String getValue() {
return jsonNode == null || type == NodeType.Null ? null : formatByJackson(jsonNode);
}
public boolean isValue() {
return jsonNode != null
&& type != NodeType.Array && type != NodeType.Object;
}
public boolean isArray() {
return jsonNode != null && type == NodeType.Array;
}
public boolean isObject() {
return jsonNode != null && type == NodeType.Object;
}
public boolean isNull() {
return jsonNode != null || type == NodeType.Null;
}
public boolean isString() {
return jsonNode != null || type == NodeType.String;
}
public boolean isNumber() {
return jsonNode != null || type == NodeType.Number;
}
public boolean isBoolean() {
return jsonNode != null || type == NodeType.Boolean;
}
public String stringByJackson() {
return stringByJackson(jsonNode);
}
public String formatByJackson() {
return formatByJackson(jsonNode);
}
/*
static
*/
public static ObjectMapper jsonMapper() {
if (jsonMapper == null) {
try (Connection conn = DerbyBase.getConnection()) {
JsonMapper.Builder builder = JsonMapper.builder();
if (UserConfig.getBoolean(conn, "JacksonAllowJavaComments", false)) {
builder.enable(JsonReadFeature.ALLOW_JAVA_COMMENTS);
} else {
builder.disable(JsonReadFeature.ALLOW_JAVA_COMMENTS);
}
if (UserConfig.getBoolean(conn, "JacksonAllowYamlComments", false)) {
builder.enable(JsonReadFeature.ALLOW_YAML_COMMENTS);
} else {
builder.disable(JsonReadFeature.ALLOW_YAML_COMMENTS);
}
if (UserConfig.getBoolean(conn, "JacksonAllowSingleQuotes", false)) {
builder.enable(JsonReadFeature.ALLOW_SINGLE_QUOTES);
} else {
builder.disable(JsonReadFeature.ALLOW_SINGLE_QUOTES);
}
if (UserConfig.getBoolean(conn, "JacksonAllowUnquotedFieldNames", false)) {
builder.enable(JsonReadFeature.ALLOW_UNQUOTED_FIELD_NAMES);
} else {
builder.disable(JsonReadFeature.ALLOW_UNQUOTED_FIELD_NAMES);
}
if (UserConfig.getBoolean(conn, "JacksonAllowUnescapedControlChars", false)) {
builder.enable(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS);
} else {
builder.disable(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS);
}
if (UserConfig.getBoolean(conn, "JacksonAllowBackslashEscapingAny", false)) {
builder.enable(JsonReadFeature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER);
} else {
builder.disable(JsonReadFeature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER);
}
if (UserConfig.getBoolean(conn, "JacksonAllowLeadingZerosForNumbers", false)) {
builder.enable(JsonReadFeature.ALLOW_LEADING_ZEROS_FOR_NUMBERS);
} else {
builder.disable(JsonReadFeature.ALLOW_LEADING_ZEROS_FOR_NUMBERS);
}
if (UserConfig.getBoolean(conn, "JacksonAllowLeadingPlusSignForNumbers", false)) {
builder.enable(JsonReadFeature.ALLOW_LEADING_PLUS_SIGN_FOR_NUMBERS);
} else {
builder.disable(JsonReadFeature.ALLOW_LEADING_PLUS_SIGN_FOR_NUMBERS);
}
if (UserConfig.getBoolean(conn, "JacksonAllowLeadingDecimalPointForNumbers", false)) {
builder.enable(JsonReadFeature.ALLOW_LEADING_DECIMAL_POINT_FOR_NUMBERS);
} else {
builder.disable(JsonReadFeature.ALLOW_LEADING_DECIMAL_POINT_FOR_NUMBERS);
}
if (UserConfig.getBoolean(conn, "JacksonAllowTrailingDecimalPointForNumbers", false)) {
builder.enable(JsonReadFeature.ALLOW_TRAILING_DECIMAL_POINT_FOR_NUMBERS);
} else {
builder.disable(JsonReadFeature.ALLOW_TRAILING_DECIMAL_POINT_FOR_NUMBERS);
}
if (UserConfig.getBoolean(conn, "JacksonAllowNonNumericNumbers", false)) {
builder.enable(JsonReadFeature.ALLOW_NON_NUMERIC_NUMBERS);
} else {
builder.disable(JsonReadFeature.ALLOW_NON_NUMERIC_NUMBERS);
}
if (UserConfig.getBoolean(conn, "JacksonAllowMissingValues", false)) {
builder.enable(JsonReadFeature.ALLOW_MISSING_VALUES);
} else {
builder.disable(JsonReadFeature.ALLOW_MISSING_VALUES);
}
if (UserConfig.getBoolean(conn, "JacksonAllowTrailingComma", false)) {
builder.enable(JsonReadFeature.ALLOW_TRAILING_COMMA);
} else {
builder.disable(JsonReadFeature.ALLOW_TRAILING_COMMA);
}
if (UserConfig.getBoolean(conn, "JacksonQuoteFieldNames", true)) {
builder.enable(JsonWriteFeature.QUOTE_FIELD_NAMES);
} else {
builder.disable(JsonWriteFeature.QUOTE_FIELD_NAMES);
}
if (UserConfig.getBoolean(conn, "JacksonWriteNanAsStrings", true)) {
builder.enable(JsonWriteFeature.WRITE_NAN_AS_STRINGS);
} else {
builder.disable(JsonWriteFeature.WRITE_NAN_AS_STRINGS);
}
if (UserConfig.getBoolean(conn, "JacksonWriteNumbersAsStrings", false)) {
builder.enable(JsonWriteFeature.WRITE_NUMBERS_AS_STRINGS);
} else {
builder.disable(JsonWriteFeature.WRITE_NUMBERS_AS_STRINGS);
}
if (UserConfig.getBoolean(conn, "JacksonEscapeNonASCII", false)) {
builder.enable(JsonWriteFeature.ESCAPE_NON_ASCII);
} else {
builder.disable(JsonWriteFeature.ESCAPE_NON_ASCII);
}
jsonMapper = builder.build();
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
return jsonMapper;
}
public static void resetJsonMapper() {
jsonMapper = null;
}
public static String stringByJackson(JsonNode jsonNode) {
try {
if (jsonNode == null) {
return null;
}
return jsonMapper().writeValueAsString(jsonNode);
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static String formatByJackson(JsonNode jsonNode) {
try {
if (jsonNode == null) {
return null;
}
return jsonMapper().writerWithDefaultPrettyPrinter()
.writeValueAsString(jsonNode);
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static JsonNode parseByJackson(String json) {
try {
if (json == null) {
return null;
}
return jsonMapper().readTree(json);
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
/*
set
*/
public JsonTreeNode setTitle(String title) {
this.title = title;
return this;
}
public JsonTreeNode setJsonNode(JsonNode node) {
this.jsonNode = node;
return this;
}
/*
get
*/
public String getTitle() {
return title;
}
public JsonNode getJsonNode() {
return jsonNode;
}
public NodeType getType() {
return type;
}
public BooleanProperty getSelected() {
return selected;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/FileSynchronizeAttributes.java | alpha/MyBox/src/main/java/mara/mybox/data/FileSynchronizeAttributes.java | package mara.mybox.data;
import java.util.List;
/**
* @Author Mara
* @CreateDate 2018-7-8 13:14:38
* @Version 1.0
* @License Apache License Version 2.0
*/
public class FileSynchronizeAttributes {
private boolean continueWhenError, conditionalCopy, copySubdir, copyEmpty,
copyNew, copyHidden, onlyCopyReadonly, copyExisted, onlyCopyModified,
deleteNotExisteds, notCopySome, canReplace,
copyAttrinutes, copyMTime, setPermissions;
private long modifyAfter, copiedFilesNumber, copiedDirectoriesNumber, totalFilesNumber,
totalDirectoriesNumber, totalSize, copiedSize, deletedFiles, deletedDirectories,
deletedSize, failedDeletedFiles, failedDeletedDirectories, failedDeletedSize;
private List<String> notCopyNames;
private int permissions;
public FileSynchronizeAttributes() {
continueWhenError = conditionalCopy = copySubdir = copyEmpty = copyNew = copyHidden = true;
copyExisted = onlyCopyModified = canReplace = copyAttrinutes = copyMTime = true;
onlyCopyReadonly = deleteNotExisteds = notCopySome = setPermissions = false;
copiedFilesNumber = copiedDirectoriesNumber = totalFilesNumber = totalDirectoriesNumber = 0;
totalSize = copiedSize = deletedFiles = deletedDirectories = deletedSize = 0;
failedDeletedFiles = failedDeletedDirectories = failedDeletedSize = 0;
permissions = -1;
}
public boolean isContinueWhenError() {
return continueWhenError;
}
public void setContinueWhenError(boolean continueWhenError) {
this.continueWhenError = continueWhenError;
}
public boolean isConditionalCopy() {
return conditionalCopy;
}
public void setConditionalCopy(boolean conditionalCopy) {
this.conditionalCopy = conditionalCopy;
}
public boolean isCopySubdir() {
return copySubdir;
}
public void setCopySubdir(boolean copySubdir) {
this.copySubdir = copySubdir;
}
public boolean isCopyEmpty() {
return copyEmpty;
}
public void setCopyEmpty(boolean copyEmpty) {
this.copyEmpty = copyEmpty;
}
public boolean isCopyNew() {
return copyNew;
}
public void setCopyNew(boolean copyNew) {
this.copyNew = copyNew;
}
public boolean isCopyHidden() {
return copyHidden;
}
public void setCopyHidden(boolean copyHidden) {
this.copyHidden = copyHidden;
}
public boolean isOnlyCopyReadonly() {
return onlyCopyReadonly;
}
public void setOnlyCopyReadonly(boolean onlyCopyReadonly) {
this.onlyCopyReadonly = onlyCopyReadonly;
}
public boolean isCopyExisted() {
return copyExisted;
}
public void setCopyExisted(boolean copyExisted) {
this.copyExisted = copyExisted;
}
public boolean isOnlyCopyModified() {
return onlyCopyModified;
}
public void setOnlyCopyModified(boolean onlyCopyModified) {
this.onlyCopyModified = onlyCopyModified;
}
public boolean isDeleteNotExisteds() {
return deleteNotExisteds;
}
public void setDeleteNotExisteds(boolean deleteNotExisteds) {
this.deleteNotExisteds = deleteNotExisteds;
}
public boolean isNotCopySome() {
return notCopySome;
}
public void setNotCopySome(boolean notCopySome) {
this.notCopySome = notCopySome;
}
public boolean isCanReplace() {
return canReplace;
}
public void setCanReplace(boolean canReplace) {
this.canReplace = canReplace;
}
public boolean isCopyAttrinutes() {
return copyAttrinutes;
}
public void setCopyAttrinutes(boolean copyAttrinutes) {
this.copyAttrinutes = copyAttrinutes;
}
public long getModifyAfter() {
return modifyAfter;
}
public void setModifyAfter(long modifyAfter) {
this.modifyAfter = modifyAfter;
}
public List<String> getNotCopyNames() {
return notCopyNames;
}
public void setNotCopyNames(List<String> notCopyNames) {
this.notCopyNames = notCopyNames;
}
public long getCopiedFilesNumber() {
return copiedFilesNumber;
}
public void setCopiedFilesNumber(long copiedFilesNumber) {
this.copiedFilesNumber = copiedFilesNumber;
}
public long getCopiedDirectoriesNumber() {
return copiedDirectoriesNumber;
}
public void setCopiedDirectoriesNumber(long copiedDirectoriesNumber) {
this.copiedDirectoriesNumber = copiedDirectoriesNumber;
}
public long getTotalFilesNumber() {
return totalFilesNumber;
}
public void setTotalFilesNumber(long totalFilesNumber) {
this.totalFilesNumber = totalFilesNumber;
}
public long getTotalDirectoriesNumber() {
return totalDirectoriesNumber;
}
public void setTotalDirectoriesNumber(long totalDirectoriesNumber) {
this.totalDirectoriesNumber = totalDirectoriesNumber;
}
public long getTotalSize() {
return totalSize;
}
public void setTotalSize(long totalSize) {
this.totalSize = totalSize;
}
public long getCopiedSize() {
return copiedSize;
}
public void setCopiedSize(long copiedSize) {
this.copiedSize = copiedSize;
}
public long getDeletedFiles() {
return deletedFiles;
}
public void setDeletedFiles(long deletedFiles) {
this.deletedFiles = deletedFiles;
}
public long getDeletedDirectories() {
return deletedDirectories;
}
public void setDeletedDirectories(long deletedDirectories) {
this.deletedDirectories = deletedDirectories;
}
public long getDeletedSize() {
return deletedSize;
}
public void setDeletedSize(long deletedSize) {
this.deletedSize = deletedSize;
}
public long getFailedDeletedFiles() {
return failedDeletedFiles;
}
public void setFailedDeletedFiles(long failedDeletedFiles) {
this.failedDeletedFiles = failedDeletedFiles;
}
public long getFailedDeletedDirectories() {
return failedDeletedDirectories;
}
public void setFailedDeletedDirectories(long failedDeletedDirectories) {
this.failedDeletedDirectories = failedDeletedDirectories;
}
public long getFailedDeletedSize() {
return failedDeletedSize;
}
public void setFailedDeletedSize(long failedDeletedSize) {
this.failedDeletedSize = failedDeletedSize;
}
public boolean isCopyMTime() {
return copyMTime;
}
public void setCopyMTime(boolean copyMTime) {
this.copyMTime = copyMTime;
}
public boolean isSetPermissions() {
return setPermissions;
}
public void setSetPermissions(boolean setPermissions) {
this.setPermissions = setPermissions;
}
public int getPermissions() {
return permissions;
}
public void setPermissions(int permissions) {
this.permissions = permissions;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/FxWindow.java | alpha/MyBox/src/main/java/mara/mybox/data/FxWindow.java | package mara.mybox.data;
import javafx.stage.Stage;
import javafx.stage.Window;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.BaseController_Attributes.StageType;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2023-9-13
* @License Apache License Version 2.0
*/
public class FxWindow {
protected Window window;
protected String title, type, name, modality;
protected int width, height, x, y;
protected boolean isShowing, isAlwaysOnTop, isFocused,
isChild, isFullScreen, isIconified, isMaximized, isResizable;
public FxWindow() {
init();
}
final public void init() {
window = null;
title = null;
type = null;
modality = null;
name = null;
isShowing = isAlwaysOnTop = isFocused = isChild
= isFullScreen = isIconified = isMaximized = isResizable
= false;
}
public FxWindow(Window w) {
init();
this.window = w;
if (window == null) {
return;
}
type = StageType.Normal.name();
name = window.getClass().toString();
width = (int) window.getWidth();
height = (int) window.getHeight();
x = (int) window.getX();
y = (int) window.getY();
isShowing = window.isShowing();
isFocused = window.isFocused();
if (window instanceof Stage) {
Stage stage = (Stage) window;
title = stage.getTitle();
if (null == stage.getModality()) {
modality = null;
} else {
switch (stage.getModality()) {
case APPLICATION_MODAL:
modality = message("Application");
break;
case WINDOW_MODAL:
modality = message("Window");
break;
default:
modality = null;
break;
}
}
isAlwaysOnTop = stage.isAlwaysOnTop();
isChild = stage.getOwner() != null;
isFullScreen = stage.isFullScreen();
isIconified = stage.isIconified();
isMaximized = stage.isMaximized();
isResizable = stage.isResizable();
Object u = stage.getUserData();
if (u != null && (u instanceof BaseController)) {
BaseController controller = (BaseController) u;
name = controller.getClass().toString();
type = controller.getStageType().name();
}
}
}
/*
get/set
*/
public Window getWindow() {
return window;
}
public void setWindow(Window window) {
this.window = window;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getModality() {
return modality;
}
public void setModality(String modality) {
this.modality = modality;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public boolean isIsShowing() {
return isShowing;
}
public void setIsShowing(boolean isShowing) {
this.isShowing = isShowing;
}
public boolean isIsAlwaysOnTop() {
return isAlwaysOnTop;
}
public void setIsAlwaysOnTop(boolean isAlwaysOnTop) {
this.isAlwaysOnTop = isAlwaysOnTop;
}
public boolean isIsFocused() {
return isFocused;
}
public void setIsFocused(boolean isFocused) {
this.isFocused = isFocused;
}
public boolean isIsChild() {
return isChild;
}
public void setIsChild(boolean isChild) {
this.isChild = isChild;
}
public boolean isIsFullScreen() {
return isFullScreen;
}
public void setIsFullScreen(boolean isFullScreen) {
this.isFullScreen = isFullScreen;
}
public boolean isIsIconified() {
return isIconified;
}
public void setIsIconified(boolean isIconified) {
this.isIconified = isIconified;
}
public boolean isIsMaximized() {
return isMaximized;
}
public void setIsMaximized(boolean isMaximized) {
this.isMaximized = isMaximized;
}
public boolean isIsResizable() {
return isResizable;
}
public void setIsResizable(boolean isResizable) {
this.isResizable = isResizable;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/FileUnarchive.java | alpha/MyBox/src/main/java/mara/mybox/data/FileUnarchive.java | package mara.mybox.data;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.Enumeration;
import java.util.List;
import mara.mybox.controller.BaseTaskController;
import static mara.mybox.value.Languages.message;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.io.IOUtils;
/**
* @Author Mara
* @CreateDate 2019-11-14
* @License Apache License Version 2.0
*/
// http://commons.apache.org/proper/commons-compress/examples.html
public class FileUnarchive {
protected File sourceFile, targetPath;
protected String archiver, charset, error;
protected List<String> selected;
protected int archiveSuccess, archiveFail;
protected boolean charsetIncorrect, verbose;
protected long totalFiles, totalSize;
protected BaseTaskController taskController;
protected ArchiveStreamFactory aFactory;
public FileUnarchive() {
totalFiles = totalSize = archiveFail = archiveSuccess = 0;
charsetIncorrect = false;
error = null;
selected = null;
}
public FileUnarchive create() {
return new FileUnarchive();
}
public boolean start() {
try {
if (taskController == null || sourceFile == null || archiver == null || charset == null) {
return false;
}
// archiver should have been determinied at this moment
if (archiver.equalsIgnoreCase(ArchiveStreamFactory.SEVEN_Z)) {
unarchive7z();
} else if (archiver.equalsIgnoreCase(ArchiveStreamFactory.ZIP)) {
unarchiveZip();
} else {
unarchive();
}
return true;
} catch (Exception e) {
taskController.updateLogs(e.toString());
return false;
}
}
protected void unarchive() {
if (aFactory == null) {
aFactory = new ArchiveStreamFactory();
}
try (BufferedInputStream fileIn = new BufferedInputStream(new FileInputStream(sourceFile))) {
if (archiver != null && aFactory.getInputStreamArchiveNames().contains(archiver)) {
try (ArchiveInputStream in = aFactory.createArchiveInputStream(archiver, fileIn, charset)) {
unarchive(in);
} catch (Exception e) {
unarchive(fileIn);
}
} else {
unarchive(fileIn);
}
} catch (Exception e) {
taskController.updateLogs(e.toString());
}
}
public void unarchive(BufferedInputStream fileIn) {
try {
archiver = ArchiveStreamFactory.detect(fileIn);
if (archiver == null) {
return;
}
try (ArchiveInputStream in = aFactory.createArchiveInputStream(archiver, fileIn, charset)) {
unarchive(in);
} catch (Exception ex) {
taskController.updateLogs(ex.toString());
}
} catch (Exception e) {
taskController.updateLogs(e.toString());
}
}
protected void unarchive(ArchiveInputStream in) {
try {
if (archiver == null || !aFactory.getInputStreamArchiveNames().contains(archiver)) {
return;
}
ArchiveEntry entry;
File tfile;
while ((entry = in.getNextEntry()) != null) {
if (selected != null && !selected.contains(entry.getName())) {
continue;
}
if (verbose) {
taskController.updateLogs(message("Handling...") + ": " + entry.getName());
}
if (!in.canReadEntryData(entry)) {
archiveFail++;
taskController.updateLogs(message("CanNotReadEntryData" + ":" + entry.getName()));
continue;
}
try {
tfile = new File(targetPath + File.separator + entry.getName());
tfile = taskController.makeTargetFile(tfile, tfile.getParentFile());
} catch (Exception e) {
recordError(e.toString());
continue;
}
if (entry.isDirectory()) {
archiveSuccess++;
continue;
}
try (OutputStream o = Files.newOutputStream(tfile.toPath())) {
IOUtils.copy(in, o);
} catch (Exception e) {
recordError(e.toString());
continue;
}
if (verbose) {
taskController.targetFileGenerated(tfile);
}
archiveSuccess++;
}
} catch (Exception e) {
recordError(e.toString());
}
}
protected void unarchive7z() {
try (SevenZFile sevenZFile = SevenZFile.builder().setFile(sourceFile).get()) {
SevenZArchiveEntry entry;
File tfile;
while ((entry = sevenZFile.getNextEntry()) != null) {
if (selected != null && !selected.contains(entry.getName())) {
continue;
}
if (verbose) {
taskController.updateLogs(message("Handling...") + ": " + entry.getName());
}
try {
tfile = new File(targetPath + File.separator + entry.getName());
tfile = taskController.makeTargetFile(tfile, tfile.getParentFile());
} catch (Exception e) {
recordError(e.toString());
continue;
}
if (entry.isDirectory()) {
archiveSuccess++;
continue;
}
try (FileOutputStream out = new FileOutputStream(tfile)) {
byte[] content = new byte[(int) entry.getSize()];
sevenZFile.read(content, 0, content.length);
out.write(content);
} catch (Exception e) {
recordError(e.toString());
continue;
}
if (verbose) {
taskController.targetFileGenerated(tfile);
}
archiveSuccess++;
}
} catch (Exception e) {
recordError(e.toString());
}
}
protected void unarchiveZip() {
try (ZipFile zipFile = ZipFile.builder().setFile(sourceFile).setCharset(charset).get()) {
Enumeration<ZipArchiveEntry> zEntries = zipFile.getEntries();
File tfile;
while (zEntries.hasMoreElements()) {
ZipArchiveEntry entry = zEntries.nextElement();
if (selected != null && !selected.contains(entry.getName())) {
continue;
}
if (verbose) {
taskController.updateLogs(message("Handling...") + ": " + entry.getName());
}
try {
tfile = new File(targetPath + File.separator + entry.getName());
tfile = taskController.makeTargetFile(tfile, tfile.getParentFile());
} catch (Exception e) {
recordError(e.toString());
continue;
}
if (entry.isDirectory()) {
archiveSuccess++;
continue;
}
try (FileOutputStream out = new FileOutputStream(tfile); InputStream in = zipFile.getInputStream(entry)) {
if (in != null) {
IOUtils.copy(in, out);
if (verbose) {
taskController.targetFileGenerated(tfile);
}
}
} catch (Exception e) {
recordError(e.toString());
continue;
}
archiveSuccess++;
}
} catch (Exception e) {
recordError(e.toString());
}
}
protected void recordError(String error) {
taskController.updateLogs(error);
archiveFail++;
if (error.contains("java.nio.charset.MalformedInputException")
|| error.contains("Illegal char")) {
charsetIncorrect = true;
}
}
/*
get/set
*/
public File getSourceFile() {
return sourceFile;
}
public FileUnarchive setSourceFile(File sourceFile) {
this.sourceFile = sourceFile;
return this;
}
public File getTargetPath() {
return targetPath;
}
public FileUnarchive setTargetPath(File targetPath) {
this.targetPath = targetPath;
return this;
}
public String getArchiver() {
return archiver;
}
public FileUnarchive setArchiver(String archiver) {
this.archiver = archiver;
return this;
}
public String getError() {
return error;
}
public FileUnarchive setError(String error) {
this.error = error;
return this;
}
public List<String> getSelected() {
return selected;
}
public FileUnarchive setSelected(List<String> selected) {
this.selected = selected;
return this;
}
public int getArchiveSuccess() {
return archiveSuccess;
}
public FileUnarchive setArchiveSuccess(int archiveSuccess) {
this.archiveSuccess = archiveSuccess;
return this;
}
public int getArchiveFail() {
return archiveFail;
}
public FileUnarchive setArchiveFail(int archiveFail) {
this.archiveFail = archiveFail;
return this;
}
public boolean isCharsetIncorrect() {
return charsetIncorrect;
}
public FileUnarchive setCharsetIncorrect(boolean charsetIncorrect) {
this.charsetIncorrect = charsetIncorrect;
return this;
}
public long getTotalFiles() {
return totalFiles;
}
public FileUnarchive setTotalFiles(long totalFiles) {
this.totalFiles = totalFiles;
return this;
}
public long getTotalSize() {
return totalSize;
}
public FileUnarchive setTotalSize(long totalSize) {
this.totalSize = totalSize;
return this;
}
public BaseTaskController getTaskController() {
return taskController;
}
public FileUnarchive setTaskController(BaseTaskController taskController) {
this.taskController = taskController;
return this;
}
public String getCharset() {
return charset;
}
public FileUnarchive setCharset(String charset) {
this.charset = charset;
return this;
}
public boolean isVerbose() {
return verbose;
}
public FileUnarchive setVerbose(boolean verbose) {
this.verbose = verbose;
return this;
}
public ArchiveStreamFactory getaFactory() {
return aFactory;
}
public FileUnarchive setaFactory(ArchiveStreamFactory aFactory) {
this.aFactory = aFactory;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/DoublePath.java | alpha/MyBox/src/main/java/mara/mybox/data/DoublePath.java | package mara.mybox.data;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Arc2D;
import java.awt.geom.Path2D;
import java.awt.geom.PathIterator;
import java.util.ArrayList;
import java.util.List;
import javafx.scene.shape.Path;
import mara.mybox.controller.BaseController;
import mara.mybox.data.DoublePathSegment.PathSegmentType;
import static mara.mybox.data.DoublePathSegment.PathSegmentType.Arc;
import static mara.mybox.data.DoublePathSegment.PathSegmentType.Close;
import static mara.mybox.data.DoublePathSegment.PathSegmentType.Cubic;
import static mara.mybox.data.DoublePathSegment.PathSegmentType.CubicSmooth;
import static mara.mybox.data.DoublePathSegment.PathSegmentType.Line;
import static mara.mybox.data.DoublePathSegment.PathSegmentType.LineHorizontal;
import static mara.mybox.data.DoublePathSegment.PathSegmentType.LineVertical;
import static mara.mybox.data.DoublePathSegment.PathSegmentType.Move;
import static mara.mybox.data.DoublePathSegment.PathSegmentType.Quadratic;
import static mara.mybox.data.DoublePathSegment.PathSegmentType.QuadraticSmooth;
import mara.mybox.dev.MyBoxLog;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.UserConfig;
import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.ext.awt.geom.ExtendedGeneralPath;
import org.apache.batik.svggen.SVGGeneratorContext;
import org.apache.batik.svggen.SVGPath;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
/**
* @Author Mara
* @CreateDate 2023-7-12
* @License Apache License Version 2.0
*/
public class DoublePath implements DoubleShape {
protected String content;
protected List<DoublePathSegment> segments;
protected int scale;
public DoublePath() {
init();
}
public DoublePath(BaseController controller, String content) {
init();
parseContent(controller, content);
}
public DoublePath(List<DoublePathSegment> segments) {
init();
parseSegments(segments);
}
final public void init() {
content = "";
segments = null;
scale = UserConfig.imageScale();
}
@Override
public String name() {
return message("SVGPath");
}
public final List<DoublePathSegment> parseContent(BaseController controller, String content) {
this.content = content;
segments = stringToSegments(controller, content, scale);
return segments;
}
public final String parseSegments(List<DoublePathSegment> segments) {
this.segments = segments;
content = segmentsToString(segments, " ");
return content;
}
public String typesetting(String separator) {
return segmentsToString(segments, separator);
}
@Override
public Path2D.Double getShape() {
Path2D.Double path = new Path2D.Double();
addToPath2D(path, segments);
return path;
}
@Override
public DoublePath copy() {
DoublePath path = new DoublePath();
path.setContent(content);
if (segments != null) {
List<DoublePathSegment> list = new ArrayList<>();
for (DoublePathSegment seg : segments) {
list.add(seg.copy());
}
path.setSegments(list);
}
return path;
}
@Override
public boolean isValid() {
return content != null && segments != null;
}
@Override
public boolean isEmpty() {
return !isValid() || segments.isEmpty();
}
@Override
public boolean translateRel(double offsetX, double offsetY) {
try {
if (segments == null) {
return true;
}
for (int i = 0; i < segments.size(); i++) {
DoublePathSegment seg = segments.get(i);
segments.set(i, seg.translate(offsetX, offsetY));
}
content = segmentsToString(segments, " ");
return true;
} catch (Exception e) {
MyBoxLog.error(e);
return false;
}
}
@Override
public boolean scale(double scaleX, double scaleY) {
try {
if (segments == null) {
return true;
}
for (int i = 0; i < segments.size(); i++) {
DoublePathSegment seg = segments.get(i);
segments.set(i, seg.scale(scaleX, scaleY));
}
content = segmentsToString(segments, " ");
return true;
} catch (Exception e) {
MyBoxLog.error(e);
return false;
}
}
@Override
public String pathAbs() {
try {
if (segments == null || segments.isEmpty()) {
return null;
}
String path = null;
for (DoublePathSegment seg : segments) {
if (path != null) {
path += "\n" + seg.abs();
} else {
path = seg.abs();
}
}
return path;
} catch (Exception e) {
MyBoxLog.console(e);
return null;
}
}
@Override
public String pathRel() {
try {
if (segments == null || segments.isEmpty()) {
return null;
}
String path = null;
for (DoublePathSegment seg : segments) {
if (path != null) {
path += "\n" + seg.rel();
} else {
path = seg.rel();
}
}
return path;
} catch (Exception e) {
MyBoxLog.console(e);
return null;
}
}
@Override
public String elementAbs() {
return "<path d=\"\n" + pathAbs() + "\n\"> ";
}
@Override
public String elementRel() {
return "<path d=\"\n" + pathRel() + "\n\"> ";
}
public DoublePoint lastPoint() {
if (isEmpty()) {
return null;
}
return segments.get(segments.size() - 1).getEndPoint();
}
public boolean replace(int index, DoublePathSegment seg) {
if (segments == null || index < 0 || index >= segments.size()) {
return false;
}
segments.set(index, seg);
content = segmentsToString(segments, " ");
return true;
}
public boolean insert(int index, DoublePathSegment seg) {
if (segments == null || index < 0 || index > segments.size()) {
return false;
}
segments.add(index, seg);
content = segmentsToString(segments, " ");
return true;
}
public boolean add(DoublePathSegment seg) {
if (segments == null) {
return false;
}
segments.add(seg);
content = segmentsToString(segments, " ");
return true;
}
public boolean toAbs(BaseController controller) {
try {
parseContent(controller, pathAbs());
return true;
} catch (Exception e) {
MyBoxLog.console(e);
return false;
}
}
public boolean toRel(BaseController controller) {
try {
parseContent(controller, pathRel());
return true;
} catch (Exception e) {
MyBoxLog.console(e);
return false;
}
}
public void clear() {
content = "";
segments = null;
}
/*
static
*/
public static List<DoublePathSegment> stringToSegments(BaseController controller, String content, int scale) {
if (content == null || content.isBlank()) {
return null;
}
DoublePathParser parser = new DoublePathParser().parse(controller, content, scale);
if (parser == null) {
return null;
} else {
return parser.getSegments();
}
}
public static String segmentsToString(List<DoublePathSegment> segments, String separator) {
try {
if (segments == null || segments.isEmpty()) {
return null;
}
String path = null;
for (DoublePathSegment seg : segments) {
if (path != null) {
path += separator + seg.text();
} else {
path = seg.text();
}
}
return path;
} catch (Exception e) {
MyBoxLog.console(e);
return null;
}
}
public static boolean addToPath2D(Path2D.Double path, List<DoublePathSegment> segments) {
try {
if (path == null || segments == null) {
return false;
}
for (DoublePathSegment seg : segments) {
PathSegmentType type = seg.getType();
if (type == null) {
continue;
}
switch (type) {
case Move:
path.moveTo(seg.getEndPoint().getX(), seg.getEndPoint().getY());
break;
case Line:
case LineHorizontal:
case LineVertical:
path.lineTo(seg.getEndPoint().getX(), seg.getEndPoint().getY());
break;
case Quadratic:
case QuadraticSmooth:
path.quadTo(seg.getControlPoint1().getX(), seg.getControlPoint1().getY(),
seg.getEndPoint().getX(), seg.getEndPoint().getY());
break;
case Cubic:
case CubicSmooth:
path.curveTo(seg.getControlPoint1().getX(), seg.getControlPoint1().getY(),
seg.getControlPoint2().getX(), seg.getControlPoint2().getY(),
seg.getEndPoint().getX(), seg.getEndPoint().getY());
break;
case Arc:
double angle = seg.getValue();
Arc2D arc = ExtendedGeneralPath.computeArc(
seg.getStartPoint().getX(), seg.getStartPoint().getY(),
seg.getArcRadius().getX(), seg.getArcRadius().getY(),
angle,
seg.isFlag1(), seg.isFlag2(),
seg.getEndPoint().getX(), seg.getEndPoint().getY());
// https://svn.apache.org/repos/asf/xmlgraphics/batik/branches/svg11/sources/org/apache/batik/ext/awt/geom/ExtendedGeneralPath.java
AffineTransform t = AffineTransform.getRotateInstance(
Math.toRadians(angle), arc.getCenterX(), arc.getCenterY());
Shape s = t.createTransformedShape(arc);
path.append(s, true);
break;
case Close:
path.closePath();
break;
}
}
return true;
} catch (Exception e) {
MyBoxLog.console(e);
return false;
}
}
public static List<DoublePathSegment> shapeToSegments(Shape shape) {
try {
if (shape == null) {
return null;
}
PathIterator iterator = shape.getPathIterator(null);
if (iterator == null) {
return null;
}
List<DoublePathSegment> segments = new ArrayList<>();
double[] coords = new double[6];
int index = 0;
int scale = UserConfig.imageScale();
double currentX = 0, currentY = 0;
DoublePathSegment segment;
while (!iterator.isDone()) {
int type = iterator.currentSegment(coords);
switch (type) {
case PathIterator.SEG_MOVETO:
segment = new DoublePathSegment()
.setType(PathSegmentType.Move)
.setIsAbsolute(true)
.setScale(scale)
.setEndPoint(new DoublePoint(coords[0], coords[1]))
.setEndPointRel(new DoublePoint(coords[0] - currentX, coords[1] - currentY))
.setStartPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
currentX = coords[0];
currentY = coords[1];
break;
case PathIterator.SEG_LINETO:
segment = new DoublePathSegment()
.setType(PathSegmentType.Line)
.setIsAbsolute(true)
.setScale(scale)
.setEndPoint(new DoublePoint(coords[0], coords[1]))
.setEndPointRel(new DoublePoint(coords[0] - currentX, coords[1] - currentY))
.setStartPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
currentX = coords[0];
currentY = coords[1];
break;
case PathIterator.SEG_QUADTO:
segment = new DoublePathSegment()
.setType(PathSegmentType.Quadratic)
.setIsAbsolute(true)
.setScale(scale)
.setControlPoint1(new DoublePoint(coords[0], coords[1]))
.setControlPoint1Rel(new DoublePoint(coords[0] - currentX, coords[1] - currentY))
.setEndPoint(new DoublePoint(coords[2], coords[3]))
.setEndPointRel(new DoublePoint(coords[2] - currentX, coords[3] - currentY))
.setStartPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
currentX = coords[2];
currentY = coords[3];
break;
case PathIterator.SEG_CUBICTO:
segment = new DoublePathSegment()
.setType(PathSegmentType.Cubic)
.setIsAbsolute(true)
.setScale(scale)
.setControlPoint1(new DoublePoint(coords[0], coords[1]))
.setControlPoint1Rel(new DoublePoint(coords[0] - currentX, coords[1] - currentY))
.setControlPoint2(new DoublePoint(coords[2], coords[3]))
.setControlPoint2Rel(new DoublePoint(coords[2] - currentX, coords[3] - currentY))
.setEndPoint(new DoublePoint(coords[4], coords[5]))
.setEndPointRel(new DoublePoint(coords[4] - currentX, coords[5] - currentY))
.setStartPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
currentX = coords[4];
currentY = coords[5];
break;
case PathIterator.SEG_CLOSE:
segment = new DoublePathSegment()
.setType(PathSegmentType.Close)
.setIsAbsolute(true)
.setScale(scale)
.setStartPoint(new DoublePoint(currentX, currentY))
.setIndex(index++);
segments.add(segment);
break;
}
iterator.next();
}
return segments;
} catch (Exception e) {
MyBoxLog.console(e);
return null;
}
}
public static DoublePath shapeToPathData(Shape shape) {
try {
List<DoublePathSegment> segments = shapeToSegments(shape);
if (segments == null || segments.isEmpty()) {
return null;
}
DoublePath shapeData = new DoublePath();
shapeData.parseSegments(segments);
return shapeData;
} catch (Exception e) {
MyBoxLog.console(e);
return null;
}
}
public static String shapeToStringByBatik(Shape shape) {
try {
if (shape == null) {
return null;
}
DOMImplementation impl = GenericDOMImplementation.getDOMImplementation();
Document myFactory = impl.createDocument("http://www.w3.org/2000/svg", "svg", null);
SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(myFactory);
return SVGPath.toSVGPathData(shape, ctx);
} catch (Exception e) {
MyBoxLog.console(e);
return null;
}
}
public static DoublePath shapeToPathDataByBatik(Shape shape) {
try {
String s = shapeToStringByBatik(shape);
if (s == null) {
return null;
}
DoublePath shapeData = new DoublePath();
shapeData.parseContent(null, s);
return shapeData;
} catch (Exception e) {
MyBoxLog.console(e);
return null;
}
}
public static boolean addToFxPath(Path path, List<DoublePathSegment> segments) {
try {
if (path == null || segments == null) {
return false;
}
for (DoublePathSegment seg : segments) {
path.getElements().add(DoublePathSegment.pathElement(seg));
}
return true;
} catch (Exception e) {
MyBoxLog.console(e);
return false;
}
}
public static String typesetting(BaseController controller, String content, String separator, int scale) {
try {
List<DoublePathSegment> segments = stringToSegments(controller, content, scale);
return segmentsToString(segments, separator);
} catch (Exception e) {
MyBoxLog.console(e);
return content;
}
}
public static DoublePath scale(DoublePath path, double scaleX, double scaleY) {
try {
if (path == null) {
return null;
}
DoublePath scaled = path.copy();
scaled.scale(scaleX, scaleY);
return scaled;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static DoublePath translateRel(DoublePath path, double offsetX, double offsetY) {
try {
if (path == null) {
return null;
}
DoublePath trans = path.copy();
trans.translateRel(offsetX, offsetY);
return trans;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
/*
set
*/
public void setContent(String content) {
this.content = content;
}
public void setSegments(List<DoublePathSegment> segments) {
this.segments = segments;
}
/*
get
*/
public String getContent() {
return content;
}
public List<DoublePathSegment> getSegments() {
return segments;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/Era.java | alpha/MyBox/src/main/java/mara/mybox/data/Era.java | package mara.mybox.data;
import java.util.Date;
import mara.mybox.tools.DateTools;
import mara.mybox.value.AppValues;
import mara.mybox.value.TimeFormats;
/**
* @Author Mara
* @CreateDate 2020-7-13
* @License Apache License Version 2.0
*/
/*
"1970-01-01 08:00:00 AD" = 0
"0 AD" = "1 BC" = "0" = "-0" = "0000" = "-0000" = "0001-01-01 00:00:00 BC" = -62167420800000
"1 AD" = "1" = "0001" = "0001-01-01 00:00:00" = "0001-01-01 00:00:00 AD" = -62135798400000
"202 BC" = "-203" = "-0203" = "-0203-01-01 00:00:00" = "0202-01-01 00:00:00 BC" = -68510476800000
"202 AD" = "202" = "0202" = "0202-01-01 00:00:00" = "0202-01-01 00:00:00 AD" = -55792742400000
*/
public class Era {
protected long value = AppValues.InvalidLong;
protected String format = TimeFormats.Datetime;
protected boolean ignoreAD = true;
public Era(long value) {
this.value = value;
}
public Era(long value, String format, boolean ignoreAD) {
this.value = value;
this.format = format;
this.ignoreAD = ignoreAD;
}
public Era(String s) {
Date d = DateTools.encodeDate(s);
if (d != null) {
value = d.getTime();
}
}
public String text() {
if (value == AppValues.InvalidLong) {
return null;
}
return DateTools.textEra(value, format);
}
/*
get/set
*/
public long getValue() {
return value;
}
public Era setValue(long value) {
this.value = value;
return this;
}
public String getFormat() {
return format;
}
public Era setFormat(String format) {
this.format = format;
return this;
}
public boolean isIgnoreAD() {
return ignoreAD;
}
public Era setIgnoreAD(boolean ignoreAD) {
this.ignoreAD = ignoreAD;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/PaginatedPdfTable.java | alpha/MyBox/src/main/java/mara/mybox/data/PaginatedPdfTable.java | package mara.mybox.data;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.PdfTools;
import mara.mybox.value.Languages;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
/**
* Reference: https://github.com/eduardohl/Paginated-PDFBox-Table-Sample By
* Eduardo Lomonaco
*
* @Author Mara
* @CreateDate 2020-12-10
* @License Apache License Version 2.0
*/
public class PaginatedPdfTable {
protected File file;
protected PDDocument doc;
protected List<String> columns;
protected List<Integer> columnWidths;
protected List<List<String>> rows;
protected PDRectangle pageSize;
protected String ttf, author, producer, header, footer;
protected PDFont textFont;
protected float fontSize, margin, cellMargin, contentWidth, contentHeight, rowHeight;
protected int rowsPerPage, numberOfPages, defaultZoom, currentPageNumber;
protected boolean showPageNumber;
public PaginatedPdfTable() {
pageSize = PDRectangle.A4;
margin = 20;
textFont = PdfTools.HELVETICA();
rowHeight = 24;
cellMargin = 2;
fontSize = 14;
}
public static PaginatedPdfTable create() {
return new PaginatedPdfTable();
}
public boolean createDoc(File file) {
try {
doc = null;
if (file == null) {
return false;
}
this.file = file;
// MyBoxLog.console("pageSize:" + pageSize.getWidth() + " " + pageSize.getHeight());
contentWidth = pageSize.getWidth() - 2 * margin;
contentHeight = pageSize.getHeight() - 2 * margin;
if (columnWidths == null) {
columnWidths = new ArrayList<>();
}
float totalWidth = 0;
for (int i = 0; i < columnWidths.size(); i++) {
totalWidth += columnWidths.get(i);
}
if (totalWidth > contentWidth) {
columnWidths = new ArrayList<>();
}
if (columns.size() > columnWidths.size()) {
int avg = (int) ((contentWidth - totalWidth) / (columns.size() - columnWidths.size()));
for (int i = columnWidths.size(); i < columns.size(); i++) {
columnWidths.add(avg);
}
}
doc = new PDDocument();
rowHeight = fontSize + 2 * cellMargin;
// MyBoxLog.console("fontSize:" + fontSize + " cellMargin:" + cellMargin + " rowHeight:" + rowHeight
// + " getFontBoundingBox:" + textFont.getFontDescriptor().getFontBoundingBox().getHeight());
rowsPerPage = Double.valueOf(Math.floor(contentHeight / rowHeight)).intValue() - 1;
if (ttf != null) {
textFont = PdfTools.getFont(doc, ttf);
}
currentPageNumber = 0;
// MyBoxLog.console(textFont.getName() + " " + ttf);
return true;
} catch (Exception e) {
MyBoxLog.error(e);
return false;
}
}
public void closeDoc() {
if (doc == null) {
return;
}
try {
PdfTools.setAttributes(doc, author, defaultZoom);
doc.save(file);
doc.close();
} catch (Exception e) {
MyBoxLog.error(e);
}
doc = null;
}
public void writePages() {
if (rows == null || rows.isEmpty()) {
return;
}
if (doc == null) {
if (file != null) {
doc = new PDDocument();
} else {
return;
}
}
numberOfPages = Double.valueOf(Math.ceil(rows.size() * 1f / rowsPerPage)).intValue();
// MyBoxLog.console(rowsPerPage + " " + numberOfPages);
for (int pageCount = 0; pageCount < numberOfPages; pageCount++) {
int startRange = pageCount * rowsPerPage;
int endRange = (pageCount * rowsPerPage) + rowsPerPage;
if (endRange > rows.size()) {
endRange = rows.size();
}
List<List<String>> pageRows = new ArrayList<>();
pageRows.addAll(getRows().subList(startRange, endRange));
writePage(pageRows);
}
}
public boolean writePage(List<List<String>> data) {
if (doc == null || data == null || data.isEmpty()) {
return false;
}
try {
PDPage page = new PDPage();
page.setMediaBox(pageSize);
doc.addPage(page);
try (PDPageContentStream contentStream = new PDPageContentStream(doc, page)) {
contentStream.setFont(textFont, fontSize);
float tableTopY = pageSize.getHeight() - margin;
// Draws grid and borders
float nextY = tableTopY;
for (int i = 0; i <= data.size() + 1; i++) {
writeLine(contentStream, margin, nextY, margin + getWidth(), nextY);
nextY -= rowHeight;
}
// Draw column lines
final float tableYLength = rowHeight + (rowHeight * data.size());
final float tableBottomY = tableTopY - tableYLength;
float nextX = margin;
writeLine(contentStream, nextX, tableTopY, nextX, tableBottomY);
for (int i = 0; i < getNumberOfColumns(); i++) {
nextX += columnWidths.get(i);
writeLine(contentStream, nextX, tableTopY, nextX, tableBottomY);
}
// Position cursor to start drawing content
float nextTextX = margin + cellMargin;
// Calculate center alignment for text in cell considering font height
float nextTextY = tableTopY - (rowHeight / 2)
- ((textFont.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * fontSize) / 4);
// Write column headers
writeRow(contentStream, columns, nextTextX, nextTextY);
nextTextY -= rowHeight;
nextTextX = margin + cellMargin;
// Write content
for (int i = 0; i < data.size(); i++) {
writeRow(contentStream, data.get(i), nextTextX, nextTextY);
nextTextY -= rowHeight;
nextTextX = margin + cellMargin;
}
if (header != null && !header.trim().isEmpty()) {
contentStream.beginText();
contentStream.newLineAtOffset(margin, page.getTrimBox().getHeight() - margin + 2);
contentStream.showText(header.trim());
contentStream.endText();
}
if (footer != null && !footer.trim().isEmpty()) {
contentStream.beginText();
contentStream.newLineAtOffset(margin, margin + 2);
contentStream.showText(footer.trim());
contentStream.endText();
}
if (showPageNumber) {
contentStream.beginText();
contentStream.newLineAtOffset(page.getTrimBox().getWidth() - margin * 2 + margin - 80, 5);
contentStream.showText(Languages.message("Page") + " " + (++currentPageNumber));
contentStream.endText();
}
} catch (Exception e) {
MyBoxLog.console(e);
}
return true;
} catch (Exception e) {
MyBoxLog.console(e);
return false;
}
}
public void writeLine(PDPageContentStream contentStream, float startx, float starty, float endx, float endy) {
try {
contentStream.moveTo(startx, starty);
contentStream.lineTo(endx, endy);
contentStream.stroke();
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public void writeRow(PDPageContentStream contentStream, List<String> row, float x, float y) {
try {
float nextX = x;
int actualCols = Math.min(getNumberOfColumns(), row.size());
for (int i = 0; i < actualCols; i++) {
String text = row.get(i);
contentStream.beginText();
contentStream.newLineAtOffset(nextX, y);
try {
contentStream.showText(text != null ? text : "");
} catch (Exception e) {
// MyBoxLog.console(e);
}
contentStream.endText();
nextX += columnWidths.get(i);
}
} catch (Exception e) {
MyBoxLog.error(e);
}
}
/*
get/set
*/
public Integer getNumberOfColumns() {
return this.getColumns().size();
}
public float getWidth() {
float tableWidth = 0f;
for (int width : columnWidths) {
tableWidth += width;
}
return tableWidth;
}
public float getMargin() {
return margin;
}
public PaginatedPdfTable setMargin(float margin) {
this.margin = margin;
return this;
}
public PDRectangle getPageSize() {
return pageSize;
}
public PaginatedPdfTable setPageSize(PDRectangle pageSize) {
this.pageSize = pageSize;
return this;
}
public PDFont getTextFont() {
return textFont;
}
public PaginatedPdfTable setTextFont(PDFont textFont) {
this.textFont = textFont;
return this;
}
public float getFontSize() {
return fontSize;
}
public PaginatedPdfTable setFontSize(float fontSize) {
this.fontSize = fontSize;
return this;
}
public List<String> getColumns() {
return columns;
}
public PaginatedPdfTable setColumns(List<String> columns) {
this.columns = columns;
return this;
}
public List<Integer> getColumnWidths() {
return columnWidths;
}
public PaginatedPdfTable setColumnWidths(List<Integer> columnWidths) {
this.columnWidths = columnWidths;
return this;
}
public List<List<String>> getRows() {
return rows;
}
public PaginatedPdfTable setRows(List<List<String>> rows) {
this.rows = rows;
return this;
}
public float getContentHeight() {
return contentHeight;
}
public PaginatedPdfTable setHeight(float height) {
this.contentHeight = height;
return this;
}
public float getRowHeight() {
return rowHeight;
}
public PaginatedPdfTable setRowHeight(float rowHeight) {
this.rowHeight = rowHeight;
return this;
}
public float getCellMargin() {
return cellMargin;
}
public PaginatedPdfTable setCellMargin(float cellMargin) {
this.cellMargin = cellMargin;
return this;
}
public PDDocument getDoc() {
return doc;
}
public PaginatedPdfTable setDoc(PDDocument doc) {
this.doc = doc;
return this;
}
public float getContentWidth() {
return contentWidth;
}
public PaginatedPdfTable setContentWidth(float contentWidth) {
this.contentWidth = contentWidth;
return this;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public int getRowsPerPage() {
return rowsPerPage;
}
public void setRowsPerPage(int rowsPerPage) {
this.rowsPerPage = rowsPerPage;
}
public int getNumberOfPages() {
return numberOfPages;
}
public void setNumberOfPages(int numberOfPages) {
this.numberOfPages = numberOfPages;
}
public String getTtf() {
return ttf;
}
public PaginatedPdfTable setTtf(String ttf) {
this.ttf = ttf;
return this;
}
public String getAuthor() {
return author;
}
public PaginatedPdfTable setAuthor(String author) {
this.author = author;
return this;
}
public String getProducer() {
return producer;
}
public PaginatedPdfTable setProducer(String producer) {
this.producer = producer;
return this;
}
public int getDefaultZoom() {
return defaultZoom;
}
public PaginatedPdfTable setDefaultZoom(int defaultZoom) {
this.defaultZoom = defaultZoom;
return this;
}
public String getHeader() {
return header;
}
public PaginatedPdfTable setHeader(String header) {
this.header = header;
return this;
}
public String getFooter() {
return footer;
}
public PaginatedPdfTable setFooter(String footer) {
this.footer = footer;
return this;
}
public boolean isShowPageNumber() {
return showPageNumber;
}
public PaginatedPdfTable setShowPageNumber(boolean showPageNumber) {
this.showPageNumber = showPageNumber;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/MediaInformation.java | alpha/MyBox/src/main/java/mara/mybox/data/MediaInformation.java | /*
* Apache License Version 2.0
*/
package mara.mybox.data;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javafx.scene.media.Media;
import javafx.scene.media.MediaException;
import javafx.scene.media.Track;
import javafx.util.Duration;
import mara.mybox.db.table.TableMedia;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.DateTools;
import mara.mybox.tools.FileTools;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
/**
*
* @author mara
*/
public class MediaInformation extends FileInformation {
protected String address, resolution, info, videoEncoding, audioEncoding;
protected boolean isCurrent = false, finish = false;
protected int width, height;
protected String html;
public MediaInformation(File file) {
super(file);
if (file != null) {
address = file.getAbsolutePath();
}
}
public MediaInformation(String address) {
this.address = address;
}
public MediaInformation(URI uri) {
this.address = uri.toString();
}
public static String exceptionMessage(MediaException exception) {
String msg = "";
switch (exception.getType()) {
case MEDIA_UNSUPPORTED:
String errorMsg = exception.getMessage();
if (errorMsg.contains("ERROR_MEDIA_AUDIO_FORMAT_UNSUPPORTED")) {
msg = Languages.message("AUDIO_FORMAT_UNSUPPORTED");
} else if (errorMsg.contains("ERROR_MEDIA_VIDEO_FORMAT_UNSUPPORTED")) {
msg = Languages.message("VIDEO_FORMAT_UNSUPPORTED");
} else if (errorMsg.contains("ERROR_MEDIA_AUDIO_FORMAT_UNSUPPORTED")) {
msg = Languages.message("MEDIA_UNSUPPORTED");
}
break;
case MEDIA_CORRUPTED:
case MEDIA_INACCESSIBLE:
case MEDIA_UNAVAILABLE:
case MEDIA_UNSPECIFIED:
case OPERATION_UNSUPPORTED:
msg = Languages.message(exception.getType().name());
break;
default:
msg = Languages.message("PLAYBACK_ERROR");
break;
}
return msg;
}
public URI getURI() {
try {
if (file != null) {
return file.toURI();
} else {
File f = new File(address);
if (f.exists()) {
setFileAttributes(f);
return file.toURI();
} else {
return new URI(address);
}
}
} catch (Exception e) {
return null;
}
}
public boolean readMediaInfo(Media media) {
try {
if (address == null || media == null) {
return false;
}
StringBuilder s = new StringBuilder();
s.append(message("Address")).append(getURI().toString()).append("\n");
Duration dur = media.getDuration();
if (dur != null) {
setDuration(Math.round(dur.toMillis()));
s.append(message("Duration")).append(": ").append(DateTools.datetimeMsDuration(getDuration())).append("\n");
}
if (media.getWidth() > 0 && media.getHeight() > 0) {
setWidth(media.getWidth());
setHeight(media.getHeight());
s.append(message("Resolution")).append(": ").append(getResolution()).append("\n");
}
if (getFileSize() > 0) {
s.append(message("Size")).append(": ").append(FileTools.showFileSize(getFileSize())).append("\n");
}
Map<String, Object> meta = media.getMetadata();
if (meta != null && !meta.isEmpty()) {
for (String mk : meta.keySet()) {
s.append(mk).append(": ").append(meta.get(mk).toString()).append("\n");
}
}
Map<String, Duration> markers = media.getMarkers();
if (markers != null && !markers.isEmpty()) {
for (String mk : markers.keySet()) {
s.append(mk).append(": ").append(markers.get(mk).toString()).append("\n");
}
}
List<Track> tracks = media.getTracks();
if (tracks != null && !tracks.isEmpty()) {
for (Track track : tracks) {
String name = "";
s.append("Track: ").append(track.getTrackID()).append("\n");
if (track.getName() != null) {
s.append("Name: ").append(track.getName()).append("\n");
name = track.getName();
}
if (track.getLocale() != null) {
s.append("Locale: ").append(track.getLocale().getDisplayName()).append("\n");
}
Map<String, Object> trackMeta = track.getMetadata();
if (trackMeta != null && !trackMeta.isEmpty()) {
for (String mk : trackMeta.keySet()) {
s.append(mk).append(": ").append(trackMeta.get(mk).toString()).append("\n");
if (mk.toLowerCase().contains("encoding")) {
if (name.toLowerCase().contains("audio")) {
setAudioEncoding(name + " " + trackMeta.get(mk).toString());
} else if (name.toLowerCase().contains("video")) {
setVideoEncoding(name + " " + trackMeta.get(mk).toString());
}
}
}
}
}
}
setInfo(s.toString());
setFinish(true);
makeHtml(media);
TableMedia.write(this);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
setFinish(true);
return false;
}
}
public void makeHtml(Media media) {
if (info == null) {
return;
}
StringBuilder s = new StringBuilder();
s.append("<h1 class=\"center\">").append(getAddress()).append("</h1>\n");
s.append("<hr>\n");
List<String> names = new ArrayList<>();
names.addAll(Arrays.asList(message("Name"), message("Value")));
StringTable table = new StringTable(names);
List<String> row = new ArrayList<>();
row.addAll(Arrays.asList(message("Duration"), DateTools.datetimeMsDuration(getDuration())));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList(message("Resolution"), getResolution()));
table.add(row);
if (getFileSize() > 0) {
row = new ArrayList<>();
row.addAll(Arrays.asList(message("Size"), FileTools.showFileSize(getFileSize())));
table.add(row);
}
if (getVideoEncoding() != null) {
row = new ArrayList<>();
row.addAll(Arrays.asList(message("VideoEncoding"), getVideoEncoding()));
table.add(row);
}
if (getAudioEncoding() != null) {
row = new ArrayList<>();
row.addAll(Arrays.asList(message("AudioEncoding"), getAudioEncoding()));
table.add(row);
}
s.append(StringTable.tableDiv(table));
if (media == null) {
setHtml(s.toString());
return;
}
Map<String, Object> meta = media.getMetadata();
if (meta != null && !meta.isEmpty()) {
s.append("<h2 class=\"center\">").append("MetaData").append("</h2>\n");
names = new ArrayList<>();
names.addAll(Arrays.asList(message("Meta"), message("Value")));
table = new StringTable(names);
for (String mk : meta.keySet()) {
row = new ArrayList<>();
row.addAll(Arrays.asList(mk, meta.get(mk).toString()));
table.add(row);
}
s.append(StringTable.tableDiv(table));
}
Map<String, Duration> markers = media.getMarkers();
if (markers != null && !markers.isEmpty()) {
s.append("<h2 class=\"center\">").append("Markers").append("</h2>\n");
names = new ArrayList<>();
names.addAll(Arrays.asList(message("Marker"), message("Value")));
table = new StringTable(names);
for (String mk : markers.keySet()) {
row = new ArrayList<>();
row.addAll(Arrays.asList(mk, markers.get(mk).toString()));
table.add(row);
}
s.append(StringTable.tableDiv(table));
}
List<Track> tracks = media.getTracks();
if (tracks != null && !tracks.isEmpty()) {
s.append("<h2 class=\"center\">").append("Tracks").append("</h2>\n");
for (Track track : tracks) {
s.append("<h3 class=\"center\">").append("trackID:").append(track.getTrackID()).append("</h3>\n");
names = new ArrayList<>();
names.addAll(Arrays.asList(message("Name"), message("Value")));
table = new StringTable(names);
if (track.getName() != null) {
row = new ArrayList<>();
row.addAll(Arrays.asList("Name", track.getName()));
table.add(row);
}
if (track.getLocale() != null) {
row = new ArrayList<>();
row.addAll(Arrays.asList("Locale", track.getLocale().getDisplayName()));
table.add(row);
}
Map<String, Object> trackMeta = track.getMetadata();
if (trackMeta != null && !trackMeta.isEmpty()) {
for (String mk : trackMeta.keySet()) {
row = new ArrayList<>();
row.addAll(Arrays.asList(mk, trackMeta.get(mk).toString()));
table.add(row);
}
}
s.append(StringTable.tableDiv(table));
}
}
setHtml(s.toString());
}
/*
get/set
*/
public String getVideoEncoding() {
if (videoEncoding != null) {
return videoEncoding;
} else {
return "";
}
}
public void setVideoEncoding(String videoEncoding) {
this.videoEncoding = videoEncoding;
}
public String getAudioEncoding() {
if (audioEncoding != null) {
return audioEncoding;
} else {
return "";
}
}
public void setAudioEncoding(String audioEncoding) {
this.audioEncoding = audioEncoding;
}
public String getResolution() {
if (width > 0 && height > 0) {
return width + "x" + height;
} else {
return "";
}
}
public void setResolution(String resolution) {
this.resolution = resolution;
}
public String getAddress() {
return address;
}
public boolean isIsCurrent() {
return isCurrent;
}
public void setIsCurrent(boolean isCurrent) {
this.isCurrent = isCurrent;
}
public String getInfo() {
if (info != null) {
return info;
} else {
return "";
}
}
public void setInfo(String info) {
this.info = info;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getHtml() {
if (html != null) {
return html;
} else {
return "";
}
}
public void setHtml(String html) {
this.html = html;
}
public boolean isFinish() {
return finish;
}
public void setFinish(boolean finish) {
this.finish = finish;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/Pagination.java | alpha/MyBox/src/main/java/mara/mybox/data/Pagination.java | package mara.mybox.data;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2025-2-25
* @License Apache License Version 2.0
*/
public class Pagination {
// 0-based, exclude end
public long currentPage, pagesNumber,
rowsNumber, startRowOfCurrentPage, endRowOfCurrentPage,
objectsNumber, startObjectOfCurrentPage, endObjectOfCurrentPage;
public int pageSize, defaultPageSize;
public String selection;
public ObjectType objectType;
public enum ObjectType {
Table, Text, Bytes
}
public Pagination() {
init(ObjectType.Table);
}
public Pagination(ObjectType type) {
init(type);
}
public final void init(ObjectType type) {
objectType = type != null ? type : ObjectType.Table;
switch (objectType) {
case Table:
defaultPageSize = 50;
break;
case Bytes:
defaultPageSize = 100000;
break;
case Text:
defaultPageSize = 200;
break;
}
pageSize = defaultPageSize;
reset();
}
public Pagination init(ObjectType type, int size) {
try {
init(type);
pageSize = size > 0 ? size : defaultPageSize;
} catch (Exception e) {
MyBoxLog.error(e);
}
return this;
}
public final Pagination reset() {
rowsNumber = 0;
currentPage = 0;
pagesNumber = 1;
selection = null;
startRowOfCurrentPage = 0;
endRowOfCurrentPage = 0;
startObjectOfCurrentPage = 0;
endObjectOfCurrentPage = 0;
return this;
}
public Pagination copyFrom(Pagination p) {
if (p == null) {
return this;
}
objectType = p.objectType;
pageSize = p.pageSize;
defaultPageSize = p.defaultPageSize;
rowsNumber = p.rowsNumber;
currentPage = p.currentPage;
pagesNumber = p.pagesNumber;
selection = p.selection;
startRowOfCurrentPage = p.startRowOfCurrentPage;
endRowOfCurrentPage = p.endRowOfCurrentPage;
startObjectOfCurrentPage = p.startObjectOfCurrentPage;
endObjectOfCurrentPage = p.endObjectOfCurrentPage;
return this;
}
public Pagination copyTo(Pagination p) {
if (p == null) {
p = new Pagination();
}
p.objectType = objectType;
p.pageSize = pageSize;
p.defaultPageSize = defaultPageSize;
p.rowsNumber = rowsNumber;
p.currentPage = currentPage;
p.pagesNumber = pagesNumber;
p.selection = selection;
p.startRowOfCurrentPage = startRowOfCurrentPage;
p.endRowOfCurrentPage = endRowOfCurrentPage;
p.startObjectOfCurrentPage = startObjectOfCurrentPage;
p.endObjectOfCurrentPage = endObjectOfCurrentPage;
return p;
}
public void goPage(long dataSize, long page) {
rowsNumber = dataSize < 0 ? 0 : dataSize;
if (rowsNumber <= pageSize) {
pagesNumber = 1;
} else {
pagesNumber = rowsNumber / pageSize;
if (rowsNumber % pageSize > 0) {
pagesNumber++;
}
}
currentPage = fixPage(page);
startRowOfCurrentPage = pageSize * currentPage;
selection = null;
}
public void updatePageEnd(long tableSize) {
endRowOfCurrentPage = startRowOfCurrentPage + tableSize;
}
public void updatePageSize(int size) {
if (size < 0 || pageSize == size) {
return;
}
pageSize = size;
if (rowsNumber <= pageSize) {
pagesNumber = 1;
} else {
pagesNumber = rowsNumber / pageSize;
if (rowsNumber % pageSize > 0) {
pagesNumber++;
}
}
if (startRowOfCurrentPage <= 0) {
startRowOfCurrentPage = 0;
currentPage = 0;
} else {
currentPage = startRowOfCurrentPage / pageSize;
if (startRowOfCurrentPage % pageSize > 0) {
currentPage++;
}
if (currentPage >= pagesNumber) {
currentPage = pagesNumber - 1;
}
}
}
public boolean isValidPage(long page) {
return page >= 0 && page <= pagesNumber - 1;
}
public long fixPage(long page) {
if (page >= pagesNumber) {
return pagesNumber - 1;
} else if (page < 0) {
return 0;
} else {
return page;
}
}
public boolean multipleRows() {
return rowsNumber >= 2;
}
public boolean multiplePages() {
return pagesNumber >= 2;
}
public boolean hasNextPage() {
return currentPage < pagesNumber - 1;
}
public boolean hasPreviousPage() {
return currentPage > 0;
}
public String info() {
String s = "rowsNumber:" + rowsNumber + "\n"
+ "pageSize:" + pageSize + "\n"
+ "startRowOfCurrentPage:" + startRowOfCurrentPage + "\n"
+ "endRowOfCurrentPage:" + endRowOfCurrentPage + "\n"
+ "currentPage:" + currentPage + "\n"
+ "pagesNumber:" + pagesNumber + "\n"
+ "startObjectOfCurrentPage:" + startObjectOfCurrentPage + "\n"
+ "endObjectOfCurrentPage:" + endObjectOfCurrentPage + "\n"
+ "selection:" + selection;
return s;
}
/*
get/set
*/
public long getRowsNumber() {
return rowsNumber;
}
public Pagination setRowsNumber(long rowsNumber) {
this.rowsNumber = rowsNumber;
return this;
}
public long getObjectsNumber() {
return objectsNumber;
}
public Pagination setObjectsNumber(long objectsNumber) {
this.objectsNumber = objectsNumber;
return this;
}
public long getCurrentPage() {
return currentPage;
}
public Pagination setCurrentPage(long currentPage) {
this.currentPage = currentPage;
return this;
}
public long getPagesNumber() {
return pagesNumber;
}
public Pagination setPagesNumber(long pagesNumber) {
this.pagesNumber = pagesNumber;
return this;
}
public long getStartRowOfCurrentPage() {
return startRowOfCurrentPage;
}
public Pagination setStartRowOfCurrentPage(long startRowOfCurrentPage) {
this.startRowOfCurrentPage = startRowOfCurrentPage;
return this;
}
public long getEndRowOfCurrentPage() {
return endRowOfCurrentPage;
}
public Pagination setEndRowOfCurrentPage(long endRowOfCurrentPage) {
this.endRowOfCurrentPage = endRowOfCurrentPage;
return this;
}
public int getPageSize() {
return pageSize;
}
public Pagination setPageSize(int pageSize) {
this.pageSize = pageSize;
return this;
}
public String getSelection() {
return selection;
}
public Pagination setSelection(String selection) {
this.selection = selection;
return this;
}
public long getStartObjectOfCurrentPage() {
return startObjectOfCurrentPage;
}
public Pagination setStartObjectOfCurrentPage(long startObjectOfCurrentPage) {
this.startObjectOfCurrentPage = startObjectOfCurrentPage;
return this;
}
public long getEndObjectOfCurrentPage() {
return endObjectOfCurrentPage;
}
public Pagination setEndObjectOfCurrentPage(long endObjectOfCurrentPage) {
this.endObjectOfCurrentPage = endObjectOfCurrentPage;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/DoublePathSegment.java | alpha/MyBox/src/main/java/mara/mybox/data/DoublePathSegment.java | package mara.mybox.data;
import javafx.scene.shape.ArcTo;
import javafx.scene.shape.ClosePath;
import javafx.scene.shape.CubicCurveTo;
import javafx.scene.shape.HLineTo;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.PathElement;
import javafx.scene.shape.QuadCurveTo;
import javafx.scene.shape.VLineTo;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.DoubleTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2023-7-30
* @License Apache License Version 2.0
*/
public class DoublePathSegment {
protected PathSegmentType type;
protected DoublePoint startPoint, controlPoint1, controlPoint2, endPoint, arcRadius; // absoulte coordinate
protected DoublePoint controlPoint1Rel, controlPoint2Rel, endPointRel; // relative coordinate
protected double value, valueRel;
protected boolean isAbsolute, flag1, flag2;
protected int index, scale;
public static enum PathSegmentType {
Move, Line, Quadratic, Cubic, Arc, Close,
LineHorizontal, LineVertical, QuadraticSmooth, CubicSmooth
}
public DoublePathSegment() {
index = -1;
scale = 3;
}
public String getTypeName() {
if (type == null) {
return null;
}
switch (type) {
case Move:
return message("Move");
case Line:
return message("StraightLine");
case LineHorizontal:
return message("LineHorizontal");
case LineVertical:
return message("LineVertical");
case Quadratic:
return message("QuadraticCurve");
case QuadraticSmooth:
return message("QuadraticSmooth");
case Cubic:
return message("CubicCurve");
case CubicSmooth:
return message("CubicSmooth");
case Arc:
return message("ArcCurve");
case Close:
return message("Close");
}
return null;
}
public String getCommand() {
try {
if (type == null) {
return null;
}
if (isAbsolute) {
return absCommand();
} else {
return relCommand();
}
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public String getParameters() {
try {
if (type == null) {
return null;
}
if (isAbsolute) {
return absParameters();
} else {
return relParameters();
}
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public String text() {
try {
if (type == null) {
return null;
}
if (isAbsolute) {
return abs();
} else {
return rel();
}
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public String abs() {
try {
if (type == null) {
return null;
}
return absCommand() + " " + absParameters();
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public String rel() {
try {
if (type == null) {
return null;
}
return relCommand() + " " + relParameters();
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public String absCommand() {
try {
if (type == null) {
return null;
}
switch (type) {
case Move:
return "M ";
case Line:
return "L ";
case LineHorizontal:
return "H ";
case LineVertical:
return "V ";
case Quadratic:
return "Q ";
case QuadraticSmooth:
return "T ";
case Cubic:
return "C ";
case CubicSmooth:
return "S ";
case Arc:
return "A ";
case Close:
return "Z ";
}
return null;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public String relCommand() {
try {
if (type == null) {
return null;
}
switch (type) {
case Move:
return "m ";
case Line:
return "l ";
case LineHorizontal:
return "h ";
case LineVertical:
return "v ";
case Quadratic:
return "q ";
case QuadraticSmooth:
return "t ";
case Cubic:
return "c ";
case CubicSmooth:
return "s ";
case Arc:
return "a ";
case Close:
return "z ";
}
return null;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public String absParameters() {
try {
if (type == null) {
return null;
}
switch (type) {
case Move:
case Line:
case QuadraticSmooth:
return endPoint.text(scale);
case LineHorizontal:
case LineVertical:
return DoubleTools.scaleString(value, scale);
case Quadratic:
return controlPoint1.text(scale) + " " + endPoint.text(scale);
case Cubic:
return controlPoint1.text(scale)
+ " " + controlPoint2.text(scale)
+ " " + endPoint.text(scale);
case CubicSmooth:
return controlPoint2.text(scale) + " " + endPoint.text(scale);
case Arc:
return arcRadius.text(scale)
+ " " + DoubleTools.scaleString(value, scale)
+ " " + (flag1 ? 1 : 0)
+ " " + (flag2 ? 1 : 0)
+ " " + endPoint.text(scale);
case Close:
return "";
}
return null;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public String relParameters() {
try {
if (type == null) {
return null;
}
switch (type) {
case Move:
case Line:
case QuadraticSmooth:
return endPointRel.text(scale);
case LineHorizontal:
case LineVertical:
return DoubleTools.scaleString(valueRel, scale);
case Quadratic:
return controlPoint1Rel.text(scale) + " " + endPointRel.text(scale);
case Cubic:
return controlPoint1Rel.text(scale)
+ " " + controlPoint2Rel.text(scale)
+ " " + endPointRel.text(scale);
case CubicSmooth:
return controlPoint2Rel.text(scale) + " " + endPointRel.text(scale);
case Arc:
return arcRadius.text(scale)
+ " " + DoubleTools.scaleString(value, scale)
+ " " + (flag1 ? 1 : 0)
+ " " + (flag2 ? 1 : 0)
+ " " + endPointRel.text(scale);
case Close:
return "";
}
return null;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public DoublePathSegment copy() {
try {
DoublePathSegment seg = new DoublePathSegment()
.setType(type).setIsAbsolute(isAbsolute)
.setValue(value).setValueRel(valueRel)
.setFlag1(flag1).setFlag2(flag2)
.setScale(scale).setIndex(index);
if (startPoint != null) {
seg.setStartPoint(startPoint.copy());
}
if (controlPoint1 != null) {
seg.setControlPoint1(controlPoint1.copy());
}
if (controlPoint2 != null) {
seg.setControlPoint2(controlPoint2.copy());
}
if (endPoint != null) {
seg.setEndPoint(endPoint.copy());
}
if (arcRadius != null) {
seg.setArcRadius(arcRadius.copy());
}
if (controlPoint1Rel != null) {
seg.setControlPoint1Rel(controlPoint1Rel.copy());
}
if (controlPoint2Rel != null) {
seg.setControlPoint2Rel(controlPoint2Rel.copy());
}
if (endPointRel != null) {
seg.setEndPointRel(endPointRel.copy());
}
return seg;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public DoublePathSegment translate(double offsetX, double offsetY) {
try {
if (type == null) {
return this;
}
DoublePathSegment seg = copy();
if (startPoint != null) {
seg.setStartPoint(startPoint.translate(offsetX, offsetY));
}
if (controlPoint1 != null) {
seg.setControlPoint1(controlPoint1.translate(offsetX, offsetY));
}
if (controlPoint2 != null) {
seg.setControlPoint2(controlPoint2.translate(offsetX, offsetY));
}
if (endPoint != null) {
seg.setEndPoint(endPoint.translate(offsetX, offsetY));
}
if (type == PathSegmentType.LineHorizontal) {
seg.setValue(value + offsetX);
}
if (type == PathSegmentType.LineVertical) {
seg.setValue(value + offsetY);
}
return seg;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public DoublePathSegment scale(double scaleX, double scaleY) {
try {
if (type == null) {
return this;
}
DoublePathSegment seg = copy();
if (startPoint != null) {
seg.setStartPoint(startPoint.scale(scaleX, scaleY));
}
if (controlPoint1 != null) {
seg.setControlPoint1(controlPoint1.scale(scaleX, scaleY));
}
if (controlPoint2 != null) {
seg.setControlPoint2(controlPoint2.scale(scaleX, scaleY));
}
if (endPoint != null) {
seg.setEndPoint(endPoint.scale(scaleX, scaleY));
}
if (arcRadius != null) {
seg.setArcRadius(arcRadius.scale(scaleX, scaleY));
}
if (controlPoint1Rel != null) {
seg.setControlPoint1Rel(controlPoint1Rel.scale(scaleX, scaleY));
}
if (controlPoint2Rel != null) {
seg.setControlPoint2Rel(controlPoint2Rel.scale(scaleX, scaleY));
}
if (endPointRel != null) {
seg.setEndPointRel(endPointRel.scale(scaleX, scaleY));
}
if (type == PathSegmentType.LineHorizontal) {
seg.setValue(value * scaleX);
seg.setValueRel(valueRel * scaleX);
}
if (type == PathSegmentType.LineVertical) {
seg.setValue(value * scaleY);
seg.setValueRel(valueRel * scaleY);
}
return seg;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
/*
static
*/
public static PathElement pathElement(DoublePathSegment segment) {
try {
if (segment.getType() == null) {
return null;
}
switch (segment.getType()) {
case Move:
return new MoveTo(segment.endPoint.getX(), segment.endPoint.getY());
case Line:
return new LineTo(segment.endPoint.getX(), segment.endPoint.getY());
case LineHorizontal:
return new HLineTo(segment.value);
case LineVertical:
return new VLineTo(segment.value);
case Quadratic:
case QuadraticSmooth:
return new QuadCurveTo(
segment.controlPoint1.getX(), segment.controlPoint1.getY(),
segment.endPoint.getX(), segment.endPoint.getY());
case Cubic:
case CubicSmooth:
return new CubicCurveTo(
segment.controlPoint1.getX(), segment.controlPoint1.getY(),
segment.controlPoint2.getX(), segment.controlPoint2.getY(),
segment.endPoint.getX(), segment.endPoint.getY());
case Arc:
return new ArcTo(
segment.arcRadius.getX(), segment.arcRadius.getY(),
segment.value,
segment.endPoint.getX(), segment.endPoint.getY(),
segment.flag1, segment.flag2);
case Close:
return new ClosePath();
}
return null;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
/*
set
*/
public DoublePathSegment setType(PathSegmentType type) {
this.type = type;
return this;
}
public DoublePathSegment setIsAbsolute(boolean isAbsolute) {
this.isAbsolute = isAbsolute;
return this;
}
public DoublePathSegment setValue(double value) {
this.value = value;
return this;
}
public DoublePathSegment setFlag1(boolean flag1) {
this.flag1 = flag1;
return this;
}
public DoublePathSegment setFlag2(boolean flag2) {
this.flag2 = flag2;
return this;
}
public DoublePathSegment setScale(int scale) {
this.scale = scale;
return this;
}
public DoublePathSegment setStartPoint(DoublePoint startPoint) {
this.startPoint = startPoint;
return this;
}
public DoublePathSegment setControlPoint1(DoublePoint controlPoint1) {
this.controlPoint1 = controlPoint1;
return this;
}
public DoublePathSegment setControlPoint2(DoublePoint controlPoint2) {
this.controlPoint2 = controlPoint2;
return this;
}
public DoublePathSegment setEndPoint(DoublePoint endPoint) {
this.endPoint = endPoint;
return this;
}
public DoublePathSegment setControlPoint1Rel(DoublePoint controlPoint1Rel) {
this.controlPoint1Rel = controlPoint1Rel;
return this;
}
public DoublePathSegment setControlPoint2Rel(DoublePoint controlPoint2Rel) {
this.controlPoint2Rel = controlPoint2Rel;
return this;
}
public DoublePathSegment setEndPointRel(DoublePoint endPointRel) {
this.endPointRel = endPointRel;
return this;
}
public DoublePathSegment setArcRadius(DoublePoint arcRadius) {
this.arcRadius = arcRadius;
return this;
}
public DoublePathSegment setValueRel(double valueRel) {
this.valueRel = valueRel;
return this;
}
public DoublePathSegment setIndex(int index) {
this.index = index;
return this;
}
/*
get
*/
public PathSegmentType getType() {
return type;
}
public DoublePoint getStartPoint() {
return startPoint;
}
public DoublePoint getControlPoint1() {
return controlPoint1;
}
public DoublePoint getControlPoint2() {
return controlPoint2;
}
public DoublePoint getEndPoint() {
return endPoint;
}
public boolean isIsAbsolute() {
return isAbsolute;
}
public double getValue() {
return value;
}
public boolean isFlag1() {
return flag1;
}
public boolean isFlag2() {
return flag2;
}
public int getScale() {
return scale;
}
public DoublePoint getControlPoint1Rel() {
return controlPoint1Rel;
}
public DoublePoint getControlPoint2Rel() {
return controlPoint2Rel;
}
public DoublePoint getEndPointRel() {
return endPointRel;
}
public DoublePoint getArcRadius() {
return arcRadius;
}
public double getValueRel() {
return valueRel;
}
public int getIndex() {
return index;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/DoubleEllipse.java | alpha/MyBox/src/main/java/mara/mybox/data/DoubleEllipse.java | package mara.mybox.data;
import java.awt.geom.Ellipse2D;
import static mara.mybox.tools.DoubleTools.imageScale;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2018-11-11 12:29:29
* @License Apache License Version 2.0
*/
// https://en.wikipedia.org/wiki/Ellipse
public class DoubleEllipse implements DoubleShape {
protected double x, y, width, height;
public DoubleEllipse() {
}
public static DoubleEllipse xywh(double x, double y, double width, double height) {
DoubleEllipse e = new DoubleEllipse();
e.setX(x);
e.setY(y);
e.setWidth(width);
e.setHeight(height);
return e;
}
public static DoubleEllipse xy12(double x1, double y1, double x2, double y2) {
DoubleEllipse e = new DoubleEllipse();
e.setX(Math.min(x1, x2));
e.setY(Math.min(y1, y2));
e.setWidth(Math.abs(x2 - x1));
e.setHeight(Math.abs(y2 - y1));
return e;
}
public static DoubleEllipse rect(DoubleRectangle rect) {
DoubleEllipse e = new DoubleEllipse();
e.setX(rect.getX());
e.setY(rect.getY());
e.setWidth(rect.getWidth());
e.setHeight(rect.getHeight());
return e;
}
public static DoubleEllipse ellipse(double centerX, double centerY, double radiusX, double radiusY) {
DoubleEllipse e = new DoubleEllipse();
e.setX(centerX - radiusX);
e.setY(centerY - radiusY);
e.setWidth(radiusX * 2);
e.setHeight(radiusY * 2);
return e;
}
@Override
public String name() {
return message("Ellipse");
}
public double getCenterX() {
return x + width * 0.5;
}
public double getCenterY() {
return y + height * 0.5;
}
public double getRadiusX() {
return width * 0.5;
}
public double getRadiusY() {
return height * 0.5;
}
// exclude maxX and maxY
public double getMaxX() {
return x + width;
}
public double getMaxY() {
return y + height;
}
public void setMaxX(double maxX) {
width = Math.abs(maxX - x);
}
public void setMaxY(double maxY) {
height = Math.abs(maxY - y);
}
public void changeX(double nx) {
width = width + x - nx;
x = nx;
}
public void changeY(double ny) {
height = height + y - ny;
y = ny;
}
@Override
public Ellipse2D.Double getShape() {
return new Ellipse2D.Double(x, y, width, height);
}
@Override
public boolean isValid() {
return true;
}
@Override
public boolean isEmpty() {
return !isValid() || width <= 0 || height <= 0;
}
@Override
public DoubleEllipse copy() {
return xywh(x, y, width, height);
}
@Override
public boolean translateRel(double offsetX, double offsetY) {
x += offsetX;
y += offsetY;
return true;
}
@Override
public boolean scale(double scaleX, double scaleY) {
width *= scaleX;
height *= scaleY;
return true;
}
@Override
public String pathAbs() {
double sx = imageScale(x);
double sy = imageScale(y + height / 2);
double rx = imageScale(width / 2);
double ry = imageScale(height / 2);
return "M " + sx + "," + sy + " \n"
+ "A " + rx + "," + ry + " 0,0,1 " + imageScale(x + width) + "," + sy + " \n"
+ "A " + rx + "," + ry + " 0,0,1 " + sx + "," + sy;
}
@Override
public String pathRel() {
double sx = imageScale(x);
double sy = imageScale(y + height / 2);
double rx = imageScale(width / 2);
double ry = imageScale(height / 2);
double r2 = imageScale(width);
return "M " + sx + "," + sy + " \n"
+ "a " + rx + "," + ry + " 0,0,1 " + r2 + "," + 0 + " \n"
+ "a " + rx + "," + ry + " 0,0,1 " + (-r2) + "," + 0;
}
@Override
public String elementAbs() {
return "<ellipse cx=\"" + imageScale(getCenterX()) + "\""
+ " cy=\"" + imageScale(getCenterY()) + "\""
+ " rx=\"" + imageScale(getRadiusX()) + "\""
+ " ry=\"" + imageScale(getRadiusY()) + "\"> ";
}
@Override
public String elementRel() {
return elementAbs();
}
/*
get
*/
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getWidth() {
return width;
}
public double getHeight() {
return height;
}
/*
set
*/
public void setX(double x) {
this.x = x;
}
public void setY(double y) {
this.y = y;
}
public void setWidth(double width) {
this.width = width;
}
public void setHeight(double height) {
this.height = height;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/TiffMetaField.java | alpha/MyBox/src/main/java/mara/mybox/data/TiffMetaField.java | package mara.mybox.data;
import java.util.List;
/**
* @Author Mara
* @License Apache License Version 2.0
*/
public class TiffMetaField {
private String tagNumber, name, type, description;
private List<String> values;
public static TiffMetaField create() {
return new TiffMetaField();
}
public String getTagNumber() {
return tagNumber;
}
public void setTagNumber(String tagNumber) {
this.tagNumber = tagNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<String> getValues() {
return values;
}
public void setValues(List<String> values) {
this.values = values;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/StringTable.java | alpha/MyBox/src/main/java/mara/mybox/data/StringTable.java | package mara.mybox.data;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import mara.mybox.controller.HtmlTableController;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.style.HtmlStyles;
import mara.mybox.tools.HtmlWriteTools;
/**
* @Author Mara
* @CreateDate 2019-8-19
* @License Apache License Version 2.0
*/
public class StringTable {
protected String title, style = HtmlStyles.TableStyle, comments;
protected List<List<String>> data;
protected List<String> names;
protected static String indent = " ";
public StringTable() {
}
public StringTable(List<String> names) {
this.names = names;
}
public StringTable(String title) {
this.title = title;
}
public StringTable(List<String> names, String title) {
this.names = names;
this.title = title;
data = new ArrayList<>();
}
public static StringTable create() {
return new StringTable();
}
public List<List<String>> add(List<String> row) {
if (data == null) {
data = new ArrayList<>();
}
if (row != null) {
data.add(row);
}
return data;
}
public List<List<String>> remove(int index) {
if (data == null) {
data = new ArrayList<>();
}
if (index >= 0 && index < data.size()) {
data.remove(index);
}
return data;
}
public String html() {
return tableHtml(this);
}
public String div() {
return tableDiv(this);
}
public String body() {
return body(this);
}
public void editHtml() {
HtmlWriteTools.editHtml(tableHtml(this));
}
public void htmlTable() {
HtmlTableController.open(tableHtml(this));
}
public void newLinkRow(String name, String link) {
newNameValueRow(name,
"<a href=\"" + link + "\" target=_blank>" + link + "</a>");
}
public void newNameValueRow(String name, String value) {
List<String> row = new ArrayList<>();
row.addAll(Arrays.asList(name, value));
add(row);
}
public boolean isEmpty() {
return data == null || data.isEmpty();
}
public int size() {
return data == null ? 0 : data.size();
}
/*
Static methods
*/
public static String tableHtml(StringTable table) {
if (table == null) {
return "";
}
return HtmlWriteTools.html(table.getTitle(), "utf-8", table.style, body(table));
}
public static String tablePrefix(StringTable table) {
try {
if (table == null) {
return "";
}
StringBuilder s = new StringBuilder();
String title = table.getTitle();
if (title != null && !title.isBlank()) {
s.append(indent).append(indent).append("<H2 align=\"center\">")
.append(HtmlWriteTools.codeToHtml(title)).append("</H2>\n");
}
String comments = table.getComments();
if (comments != null && !comments.trim().isEmpty()) {
s.append(indent).append(indent)
.append(HtmlWriteTools.codeToHtml(comments)).append("\n");
}
s.append(indent).append(indent).append("<DIV align=\"center\">\n");
s.append(indent).append(indent).append(indent).append("<TABLE>\n");
List<String> names = table.getNames();
if (names != null) {
s.append(indent).append(indent).append(indent).append(indent).
append("<TR style=\"font-weight:bold; \">");
for (int i = 0; i < names.size(); ++i) {
String name = names.get(i);
s.append("<TH>").append(name).append("</TH>");
}
s.append("</TR>\n");
}
return s.toString();
} catch (Exception e) {
MyBoxLog.error(e);
return "";
}
}
public static String tableRow(List<String> row) {
try {
if (row == null) {
return "";
}
StringBuilder s = new StringBuilder();
s.append(indent).append(indent).append(indent).append(indent).append("<TR>");
for (int i = 0; i < row.size(); ++i) {
String value = row.get(i);
s.append("<TD>").append(value == null ? "" : value).append("</TD>");
}
s.append("</TR>\n");
return s.toString();
} catch (Exception e) {
MyBoxLog.error(e);
return "";
}
}
public static String tableSuffix(StringTable table) {
try {
if (table == null) {
return "";
}
StringBuilder s = new StringBuilder();
List<String> names = table.getNames();
if (names != null
&& (table.getData() != null && table.getData().size() > 15)) {
s.append(indent).append(indent).append(indent).append(indent).
append("<TR style=\"font-weight:bold; \">");
for (int i = 0; i < names.size(); ++i) {
String name = names.get(i);
s.append("<TH>").append(name).append("</TH>");
}
s.append("</TR>\n");
}
s.append(indent).append(indent).append(indent).append("</TABLE>\n");
s.append(indent).append(indent).append("</DIV>\n");
return s.toString();
} catch (Exception e) {
MyBoxLog.error(e);
return "";
}
}
public static String tableDiv(StringTable table) {
try {
if (table == null) {
return "";
}
StringBuilder s = new StringBuilder();
s.append(tablePrefix(table));
if (table.getData() != null) {
for (List<String> row : table.getData()) {
s.append(tableRow(row));
}
}
s.append(tableSuffix(table));
return s.toString();
} catch (Exception e) {
MyBoxLog.error(e);
return "";
}
}
public static String body(StringTable table) {
try {
if (table == null) {
return "";
}
StringBuilder s = new StringBuilder();
s.append(indent).append("<BODY>\n");
s.append(tableDiv(table));
s.append(indent).append("</BODY>\n");
return s.toString();
} catch (Exception e) {
MyBoxLog.error(e);
return "";
}
}
/*
get/set
*/
public String getTitle() {
return title;
}
public StringTable setTitle(String title) {
this.title = title;
return this;
}
public List<List<String>> getData() {
return data;
}
public StringTable setData(List<List<String>> data) {
this.data = data;
return this;
}
public List<String> getNames() {
return names;
}
public StringTable setNames(List<String> names) {
this.names = names;
return this;
}
public String getStyle() {
return style;
}
public StringTable setStyle(String style) {
this.style = style;
return this;
}
public String getIndent() {
return indent;
}
public String getComments() {
return comments;
}
public StringTable setComments(String comments) {
this.comments = comments;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/DoubleText.java | alpha/MyBox/src/main/java/mara/mybox/data/DoubleText.java | package mara.mybox.data;
/**
* @Author Mara
* @CreateDate 2023-7-12
* @License Apache License Version 2.0
*/
public class DoubleText extends DoubleRectangle {
private String text;
public DoubleText() {
}
public static DoubleText xywh(double x, double y, double width, double height) {
DoubleText t = new DoubleText();
t.setX(x);
t.setY(y);
t.setWidth(width);
t.setHeight(height);
return t;
}
@Override
public boolean isValid() {
return text != null;
}
@Override
public boolean isEmpty() {
return !isValid();
}
/*
get/set
*/
public String getText() {
return text;
}
public DoubleText setText(String text) {
this.text = text;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/DoublePolygon.java | alpha/MyBox/src/main/java/mara/mybox/data/DoublePolygon.java | package mara.mybox.data;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static mara.mybox.tools.DoubleTools.imageScale;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2018-11-11 12:29:29
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class DoublePolygon implements DoubleShape {
private List<DoublePoint> points;
public DoublePolygon() {
points = new ArrayList<>();
}
@Override
public String name() {
return message("Polygon");
}
@Override
public java.awt.Polygon getShape() {
java.awt.Polygon polygon = new java.awt.Polygon();
for (DoublePoint p : points) {
polygon.addPoint((int) p.getX(), (int) p.getY());
}
return polygon;
}
public boolean add(double x, double y) {
points.add(new DoublePoint(x, y));
return true;
}
public boolean addAll(List<DoublePoint> ps) {
if (ps == null) {
return false;
}
points.addAll(ps);
return true;
}
public boolean addAll(String values) {
return addAll(DoublePoint.parseImageCoordinates(values));
}
public boolean setAll(List<DoublePoint> ps) {
if (ps == null) {
return false;
}
points.clear();
return addAll(ps);
}
public boolean set(int index, DoublePoint p) {
if (p == null || index < 0 || index >= points.size()) {
return false;
}
points.set(index, p);
return true;
}
public boolean remove(double x, double y) {
if (points == null || points.isEmpty()) {
return false;
}
List<Double> d = new ArrayList<>();
for (int i = 0; i < points.size(); ++i) {
DoublePoint p = points.get(i);
if (p.getX() == x && p.getY() == y) {
points.remove(i);
break;
}
}
return true;
}
public boolean remove(int i) {
if (points == null || i < 0 || i >= points.size()) {
return false;
}
points.remove(i);
return true;
}
public boolean removeLast() {
if (points == null || points.isEmpty()) {
return false;
}
if (remove(points.size() - 1)) {
return true;
} else {
return false;
}
}
@Override
public boolean isValid() {
return points != null && points.size() > 2;
}
@Override
public boolean isEmpty() {
return !isValid() || points.isEmpty();
}
public boolean same(DoublePolygon polygon) {
if (polygon == null) {
return false;
}
if (points == null || points.isEmpty()) {
return polygon.getPoints() == null || polygon.getPoints().isEmpty();
} else {
if (polygon.getPoints() == null || points.size() != polygon.getPoints().size()) {
return false;
}
}
List<DoublePoint> bPoints = polygon.getPoints();
for (int i = 0; i < points.size(); ++i) {
DoublePoint point = points.get(i);
if (!point.same(bPoints.get(i))) {
return false;
}
}
return true;
}
@Override
public DoublePolygon copy() {
DoublePolygon np = new DoublePolygon();
np.addAll(points);
return np;
}
public void clear() {
points.clear();
}
public List<DoublePoint> getPoints() {
return points;
}
public int getSize() {
if (points == null) {
return 0;
}
return points.size();
}
public List<Double> getData() {
List<Double> d = new ArrayList<>();
for (int i = 0; i < points.size(); ++i) {
d.add(points.get(i).getX());
d.add(points.get(i).getY());
}
return d;
}
public Map<String, int[]> getIntXY() {
Map<String, int[]> xy = new HashMap<>();
if (points == null || points.isEmpty()) {
return xy;
}
int[] x = new int[points.size()];
int[] y = new int[points.size()];
for (int i = 0; i < points.size(); ++i) {
x[i] = (int) Math.round(points.get(i).getX());
y[i] = (int) Math.round(points.get(i).getY());
}
xy.put("x", x);
xy.put("y", y);
return xy;
}
@Override
public boolean translateRel(double offsetX, double offsetY) {
List<DoublePoint> moved = new ArrayList<>();
for (int i = 0; i < points.size(); ++i) {
DoublePoint p = points.get(i);
moved.add(p.translate(offsetX, offsetY));
}
points.clear();
points.addAll(moved);
return true;
}
@Override
public boolean scale(double scaleX, double scaleY) {
List<DoublePoint> scaled = new ArrayList<>();
for (int i = 0; i < points.size(); ++i) {
DoublePoint p = points.get(i);
scaled.add(p.scale(scaleX, scaleY));
}
points.clear();
points.addAll(scaled);
return true;
}
@Override
public String pathAbs() {
String path = "";
DoublePoint p = points.get(0);
path += "M " + imageScale(p.getX()) + "," + imageScale(p.getY()) + "\n";
for (int i = 1; i < points.size(); i++) {
p = points.get(i);
path += "L " + imageScale(p.getX()) + "," + imageScale(p.getY()) + "\n";
}
path += "Z";
return path;
}
@Override
public String pathRel() {
String path = "";
DoublePoint p = points.get(0);
path += "M " + imageScale(p.getX()) + "," + imageScale(p.getY()) + "\n";
double lastx = p.getX();
double lasty = p.getY();
for (int i = 1; i < points.size(); i++) {
p = points.get(i);
path += "l " + imageScale(p.getX() - lastx) + "," + imageScale(p.getY() - lasty) + "\n";
lastx = p.getX();
lasty = p.getY();
}
path += "z";
return path;
}
@Override
public String elementAbs() {
return "<polygon points=\""
+ DoublePoint.toText(points, UserConfig.imageScale(), " ") + "\"> ";
}
@Override
public String elementRel() {
return elementAbs();
}
public DoublePoint get(int i) {
if (points == null || points.isEmpty()) {
return null;
}
return points.get(i);
}
public void setPoints(List<DoublePoint> points) {
this.points = points;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data/WeiboSnapParameters.java | alpha/MyBox/src/main/java/mara/mybox/data/WeiboSnapParameters.java | package mara.mybox.data;
import java.io.File;
import java.util.Date;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.PdfTools.PdfImageFormat;
import mara.mybox.value.AppVariables;
/**
* @Author Mara
* @CreateDate 2018-9-13 22:17:17
* @License Apache License Version 2.0
*/
public class WeiboSnapParameters {
private File targetPath = new File(FileTmpTools.generatePath("pdf"));
private int webWidth, retry, startPage, loadInterval, snapInterval, likeStartPage, retried, fontSize = 20;
private boolean imagePerScreen, isImageSize, addPageNumber, createPDF, createHtml, savePictures, keepPagePdf;
private boolean miao, expandComments, expandPicture, fullScreen, openPathWhenStop, useTempFiles, dithering;
private String webAddress, author, title, fontFile;
private int marginSize, pageWidth, pageHeight, jpegQuality, threshold, maxMergeSize, category, pdfScale, dpi;
private Date startMonth, endMonth;
private float zoomScale;
private File tempdir;
private PdfImageFormat format;
public static class FileCategoryType {
public static int InMonthsPaths = 0;
public static int InYearsPaths = 1;
public static int InOnePath = 2;
}
public File getTargetPath() {
return targetPath;
}
public void setTargetPath(File targetPath) {
this.targetPath = targetPath;
}
public boolean isImagePerScreen() {
return imagePerScreen;
}
public void setImagePerScreen(boolean imagePerScreen) {
this.imagePerScreen = imagePerScreen;
}
public boolean isIsImageSize() {
return isImageSize;
}
public void setIsImageSize(boolean isImageSize) {
this.isImageSize = isImageSize;
}
public String getWebAddress() {
return webAddress;
}
public void setWebAddress(String webAddress) {
this.webAddress = webAddress;
}
public Date getStartMonth() {
return startMonth;
}
public void setStartMonth(Date startMonth) {
this.startMonth = startMonth;
}
public Date getEndMonth() {
return endMonth;
}
public void setEndMonth(Date endMonth) {
this.endMonth = endMonth;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getMarginSize() {
return marginSize;
}
public void setMarginSize(int marginSize) {
this.marginSize = marginSize;
}
public int getPageWidth() {
return pageWidth;
}
public void setPageWidth(int pageWidth) {
this.pageWidth = pageWidth;
}
public int getPageHeight() {
return pageHeight;
}
public void setPageHeight(int pageHeight) {
this.pageHeight = pageHeight;
}
public int getJpegQuality() {
return jpegQuality;
}
public void setJpegQuality(int jpegQuality) {
this.jpegQuality = jpegQuality;
}
public PdfImageFormat getFormat() {
return format;
}
public void setFormat(PdfImageFormat format) {
this.format = format;
}
public int getThreshold() {
return threshold;
}
public void setThreshold(int threshold) {
this.threshold = threshold;
}
public boolean isAddPageNumber() {
return addPageNumber;
}
public void setAddPageNumber(boolean addPageNumber) {
this.addPageNumber = addPageNumber;
}
public boolean isCreatePDF() {
return createPDF;
}
public void setCreatePDF(boolean createPDF) {
this.createPDF = createPDF;
}
public boolean isCreateHtml() {
return createHtml;
}
public void setCreateHtml(boolean createHtml) {
this.createHtml = createHtml;
}
public boolean isKeepPagePdf() {
return keepPagePdf;
}
public void setKeepPagePdf(boolean keepPagePdf) {
this.keepPagePdf = keepPagePdf;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isMiao() {
return miao;
}
public void setMiao(boolean miao) {
this.miao = miao;
}
public int getRetry() {
return retry;
}
public void setRetry(int retry) {
this.retry = retry;
}
public int getMaxMergeSize() {
return maxMergeSize;
}
public void setMaxMergeSize(int maxMergeSize) {
this.maxMergeSize = maxMergeSize;
}
public boolean isExpandComments() {
return expandComments;
}
public void setExpandComments(boolean expandComments) {
this.expandComments = expandComments;
}
public boolean isFullScreen() {
return fullScreen;
}
public void setFullScreen(boolean fullScreen) {
this.fullScreen = fullScreen;
}
public boolean isSavePictures() {
return savePictures;
}
public void setSavePictures(boolean savePictures) {
this.savePictures = savePictures;
}
public boolean isExpandPicture() {
return expandPicture;
}
public void setExpandPicture(boolean expandPicture) {
this.expandPicture = expandPicture;
}
public int getCategory() {
return category;
}
public void setCategory(int category) {
this.category = category;
}
public int getWebWidth() {
return webWidth;
}
public void setWebWidth(int webWidth) {
this.webWidth = webWidth;
}
public float getZoomScale() {
return zoomScale;
}
public void setZoomScale(float zoomScale) {
this.zoomScale = zoomScale;
}
public File getTempdir() {
return tempdir;
}
public void setTempdir(File tempdir) {
if (tempdir == null || !tempdir.exists() || !tempdir.isDirectory()) {
this.tempdir = AppVariables.MyBoxTempPath;
} else {
this.tempdir = tempdir;
}
}
public int getPdfScale() {
return pdfScale;
}
public void setPdfScale(int pdfScale) {
this.pdfScale = pdfScale;
}
public boolean isOpenPathWhenStop() {
return openPathWhenStop;
}
public void setOpenPathWhenStop(boolean openPathWhenStop) {
this.openPathWhenStop = openPathWhenStop;
}
public boolean isUseTempFiles() {
return useTempFiles;
}
public void setUseTempFiles(boolean useTempFiles) {
this.useTempFiles = useTempFiles;
}
public String getFontFile() {
return fontFile;
}
public void setFontFile(String fontFile) {
this.fontFile = fontFile;
}
public boolean isDithering() {
return dithering;
}
public void setDithering(boolean dithering) {
this.dithering = dithering;
}
public int getStartPage() {
return startPage;
}
public void setStartPage(int startPage) {
this.startPage = startPage;
}
public int getLoadInterval() {
return loadInterval;
}
public void setLoadInterval(int loadInterval) {
this.loadInterval = loadInterval;
}
public int getSnapInterval() {
return snapInterval;
}
public void setSnapInterval(int snapInterval) {
this.snapInterval = snapInterval;
}
public int getDpi() {
return dpi;
}
public void setDpi(int dpi) {
this.dpi = dpi;
}
public int getLikeStartPage() {
return likeStartPage;
}
public void setLikeStartPage(int likeStartPage) {
this.likeStartPage = likeStartPage;
}
public int getRetried() {
return retried;
}
public void setRetried(int retried) {
this.retried = retried;
}
public int getFontSize() {
return fontSize;
}
public void setFontSize(int fontSize) {
this.fontSize = fontSize;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.