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/fxml/cell/TableTextTruncCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableTextTruncCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
/**
* @Author Mara
* @CreateDate 2021-7-3
* @License Apache License Version 2.0
*/
public class TableTextTruncCell<T> extends TableCell<T, String>
implements Callback<TableColumn<T, String>, TableCell<T, String>> {
@Override
public TableCell<T, String> call(TableColumn<T, String> param) {
TableCell<T, String> cell = new TableCell<T, String>() {
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
return;
}
setText(item.length() > 80 ? item.substring(0, 80) : item);
}
};
return cell;
}
}
| 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/fxml/cell/TableCheckboxCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableCheckboxCell.java | package mara.mybox.fxml.cell;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.TableRow;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.util.Callback;
/**
* @Author Mara
* @CreateDate 2021-11-13
* @License Apache License Version 2.0
*/
public class TableCheckboxCell<S, T> extends CheckBoxTableCell<S, T> {
protected SimpleBooleanProperty checked;
protected ChangeListener<Boolean> checkedListener;
protected boolean isChanging;
public TableCheckboxCell() {
checked = new SimpleBooleanProperty(false);
setSelectedStateCallback(new Callback<Integer, ObservableValue<Boolean>>() {
@Override
public synchronized ObservableValue<Boolean> call(Integer index) {
if (isChanging) {
return checked;
}
int rowIndex = rowIndex();
if (rowIndex < 0) {
return null;
}
isChanging = true;
checked.set(getCellValue(rowIndex));
isChanging = false;
return checked;
}
});
checkedListener = new ChangeListener<Boolean>() {
@Override
public synchronized void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) {
if (isChanging) {
return;
}
int rowIndex = rowIndex();
if (rowIndex < 0) {
return;
}
setCellValue(rowIndex, newValue);
}
};
checked.addListener(checkedListener);
}
protected boolean getCellValue(int rowIndex) {
return false;
}
protected void setCellValue(int rowIndex, boolean value) {
}
public int rowIndex() {
try {
TableRow row = getTableRow();
if (row == null) {
return -1;
}
int index = row.getIndex();
if (index >= 0 && index < getTableView().getItems().size()) {
return index;
} else {
return -2;
}
} catch (Exception e) {
return -3;
}
}
public SimpleBooleanProperty getSelected() {
return checked;
}
public void setSelected(SimpleBooleanProperty selected) {
this.checked = 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/fxml/cell/TableFileNameCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableFileNameCell.java | package mara.mybox.fxml.cell;
import java.awt.image.BufferedImage;
import java.io.File;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.control.IndexedCell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.image.ImageView;
import javafx.util.Callback;
import mara.mybox.controller.BaseController;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.file.ImageFileReaders;
import mara.mybox.tools.FileNameTools;
import mara.mybox.value.AppVariables;
import mara.mybox.value.FileExtensions;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:17:47
* @License Apache License Version 2.0
*/
public class TableFileNameCell<T> extends TableCell<T, String>
implements Callback<TableColumn<T, String>, TableCell<T, String>> {
protected int thumbWidth = AppVariables.thumbnailWidth;
private BaseController controller;
public TableFileNameCell(BaseController controller) {
this.controller = controller;
}
public TableFileNameCell(int imageSize) {
this.thumbWidth = imageSize;
}
@Override
public TableCell<T, String> call(TableColumn<T, String> param) {
final ImageView imageview = new ImageView();
imageview.setPreserveRatio(true);
imageview.setFitWidth(thumbWidth);
imageview.setFitHeight(thumbWidth);
TableCell<T, String> cell = new TableCell<T, String>() {
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setText(null);
setGraphic(null);
if (empty || item == null) {
return;
}
setText(item);
String suffix = FileNameTools.ext(item).toLowerCase();
if (FileExtensions.SupportedImages.contains(suffix)) {
ImageViewFileTask task = new ImageViewFileTask(controller)
.setCell(this).setView(imageview)
.setFilename(item).setThumbWidth(thumbWidth);
Thread thread = new Thread(task);
thread.setDaemon(false);
thread.start();
}
}
};
return cell;
}
public class ImageViewFileTask<Void> extends FxTask<Void> {
private IndexedCell cell;
private String filename = null;
private ImageView view = null;
private int thumbWidth = AppVariables.thumbnailWidth;
public ImageViewFileTask(BaseController controller) {
this.controller = controller;
}
public ImageViewFileTask<Void> setCell(IndexedCell cell) {
this.cell = cell;
return this;
}
public ImageViewFileTask<Void> setFilename(String filename) {
this.filename = filename;
return this;
}
public ImageViewFileTask<Void> setView(ImageView view) {
this.view = view;
return this;
}
public ImageViewFileTask<Void> setThumbWidth(int thumbWidth) {
this.thumbWidth = thumbWidth;
return this;
}
@Override
public void run() {
if (view == null || filename == null) {
return;
}
File file = new File(filename);
BufferedImage image = ImageFileReaders.readImage(this, file, thumbWidth);
if (image != null) {
Platform.runLater(new Runnable() {
@Override
public void run() {
view.setImage(SwingFXUtils.toFXImage(image, null));
if (cell != null) {
cell.setGraphic(view);
}
}
});
}
}
}
}
| 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/fxml/cell/TreeTableTextTrimCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TreeTableTextTrimCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeTableColumn;
import javafx.util.Callback;
import mara.mybox.tools.StringTools;
import mara.mybox.value.AppVariables;
/**
* @Author Mara
* @CreateDate 2023-4-9
* @License Apache License Version 2.0
*/
public class TreeTableTextTrimCell<T> extends TreeTableCell<T, String>
implements Callback<TreeTableColumn<T, String>, TreeTableCell<T, String>> {
@Override
public TreeTableCell<T, String> call(TreeTableColumn<T, String> param) {
TreeTableCell<T, String> cell = new TreeTableCell<T, String>() {
@Override
protected void updateItem(final String item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
return;
}
setText(StringTools.abbreviate(item, AppVariables.titleTrimSize));
setGraphic(null);
}
};
return cell;
}
}
| 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/fxml/cell/TableTextAreaEditCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableTextAreaEditCell.java | package mara.mybox.fxml.cell;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import javafx.util.converter.DefaultStringConverter;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.BaseInputController;
import mara.mybox.controller.TextInputController;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2022-9-22
* @License Apache License Version 2.0
*/
public class TableTextAreaEditCell<S> extends TableAutoCommitCell<S, String> {
protected BaseController parent;
protected String comments;
public TableTextAreaEditCell(BaseController parent, String comments) {
super(new DefaultStringConverter());
this.parent = parent;
this.comments = comments;
}
protected String getCellValue() {
return getItem();
}
@Override
public boolean setCellValue(String inValue) {
try {
String value = inValue;
if (value != null) {
value = value.replaceAll("\\\\n", "\n");
}
return super.setCellValue(value);
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
@Override
public void editCell() {
BaseInputController inputController = TextInputController.open(parent, name(), getCellValue());
inputController.setCommentsLabel(comments);
inputController.getNotify().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) {
setCellValue(inputController.getInputString());
inputController.close();
}
});
}
public static <S> Callback<TableColumn<S, String>, TableCell<S, String>>
create(BaseController parent, String comments) {
return new Callback<TableColumn<S, String>, TableCell<S, String>>() {
@Override
public TableCell<S, String> call(TableColumn<S, String> param) {
return new TableTextAreaEditCell<>(parent, comments);
}
};
}
}
| 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/fxml/cell/TableImageInfoCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableImageInfoCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.image.ImageView;
import javafx.util.Callback;
import mara.mybox.controller.BaseController;
import mara.mybox.fxml.image.ImageViewInfoTask;
import mara.mybox.image.data.ImageInformation;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:17:47
* @License Apache License Version 2.0
*/
public class TableImageInfoCell<T> extends TableCell<T, ImageInformation>
implements Callback<TableColumn<T, ImageInformation>, TableCell<T, ImageInformation>> {
private final BaseController controller;
public TableImageInfoCell(BaseController controller) {
this.controller = controller;
}
@Override
public TableCell<T, ImageInformation> call(TableColumn<T, ImageInformation> param) {
final ImageView imageview = new ImageView();
imageview.setPreserveRatio(true);
TableCell<T, ImageInformation> cell = new TableCell<T, ImageInformation>() {
@Override
public void updateItem(ImageInformation item, boolean empty) {
super.updateItem(item, empty);
setText(null);
setGraphic(null);
if (empty || item == null) {
return;
}
ImageViewInfoTask task = new ImageViewInfoTask(controller)
.setCell(this).setView(imageview).setItem(item);
Thread thread = new Thread(task);
thread.setDaemon(false);
thread.start();
}
};
return cell;
}
}
| 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/fxml/cell/TableDataCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableDataCell.java | package mara.mybox.fxml.cell;
import java.util.List;
import javafx.util.converter.DefaultStringConverter;
import mara.mybox.controller.BaseData2DTableController;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2022-9-26
* @License Apache License Version 2.0
*/
public class TableDataCell extends TableAutoCommitCell<List<String>, String> {
protected BaseData2DTableController dataTable;
protected Data2DColumn dataColumn;
protected final int trucSize = 200;
protected boolean supportMultipleLine;
public TableDataCell(BaseData2DTableController dataTable, Data2DColumn dataColumn) {
super(new DefaultStringConverter());
this.dataTable = dataTable;
this.dataColumn = dataColumn;
supportMultipleLine = dataTable.getData2D().supportMultipleLine() && dataColumn.supportMultipleLine();
}
protected String getCellValue() {
return getItem();
}
@Override
public boolean setCellValue(String inValue) {
try {
String value = inValue;
if (value != null && supportMultipleLine) {
value = value.replaceAll("\\\\n", "\n");
}
return super.setCellValue(value);
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
@Override
public boolean valid(String value) {
try {
if (!dataTable.getData2D().validValue(value)) {
return false;
}
if (!dataTable.getData2D().rejectInvalidWhenEdit()) {
return true;
}
return dataColumn.validValue(value);
} catch (Exception e) {
return false;
}
}
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setStyle(null);
if (empty) {
setText(null);
setGraphic(null);
return;
}
setDataStyle(item);
displayData(item);
}
public void displayData(String item) {
try {
String s = item;
if (s != null && s.length() > trucSize) {
s = s.substring(0, trucSize);
}
setText(s);
} catch (Exception e) {
setText(item);
}
}
public void setDataStyle(String item) {
try {
String style = dataTable.getData2D().cellStyle(dataTable.getStyleFilter(),
rowIndex(), dataColumn.getColumnName());
if (style != null) {
setStyle(style);
} else if (dataColumn.validValue(item)) {
setStyle(null);
} else {
setStyle(UserConfig.badStyle());
}
} catch (Exception 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/fxml/cell/ListGeographyCodeCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/ListGeographyCodeCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.ListCell;
import mara.mybox.data.GeographyCode;
/**
* @Author Mara
* @CreateDate 2020-3-21
* @License Apache License Version 2.0
*/
public class ListGeographyCodeCell extends ListCell<GeographyCode> {
@Override
protected void updateItem(GeographyCode item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setGraphic(null);
setText(null);
} else {
setText(item.getName());
}
}
}
| 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/fxml/cell/TableDataCoordinateEditCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableDataCoordinateEditCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.controller.BaseData2DTableController;
import mara.mybox.controller.Data2DCoordinatePickerController;
import mara.mybox.db.data.Data2DColumn;
/**
* @Author Mara
* @CreateDate 2022-10-8
* @License Apache License Version 2.0
*/
public class TableDataCoordinateEditCell extends TableDataEditCell {
public TableDataCoordinateEditCell(BaseData2DTableController dataTable, Data2DColumn dataColumn) {
super(dataTable, dataColumn);
}
@Override
public void editCell() {
Data2DCoordinatePickerController.open(dataTable, editingRow);
}
public static Callback<TableColumn, TableCell> create(BaseData2DTableController dataControl, Data2DColumn dataColumn) {
return new Callback<TableColumn, TableCell>() {
@Override
public TableCell call(TableColumn param) {
return new TableDataCoordinateEditCell(dataControl, dataColumn);
}
};
}
}
| 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/fxml/cell/TableNumberCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableNumberCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.text.Text;
import javafx.util.Callback;
import mara.mybox.tools.StringTools;
import mara.mybox.value.AppValues;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:24:30
* @License Apache License Version 2.0
*/
public class TableNumberCell<T> extends TableCell<T, Long>
implements Callback<TableColumn<T, Long>, TableCell<T, Long>> {
private boolean notPermitNegative = false;
public TableNumberCell(boolean notPermitNegative) {
this.notPermitNegative = notPermitNegative;
}
@Override
public TableCell<T, Long> call(TableColumn<T, Long> param) {
TableCell<T, Long> cell = new TableCell<T, Long>() {
private final Text text = new Text();
@Override
protected void updateItem(final Long item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null
|| item == AppValues.InvalidLong
|| (notPermitNegative && item < 0)) {
setText(null);
setGraphic(null);
return;
}
text.setText(StringTools.format(item));
setGraphic(text);
}
};
return cell;
}
}
| 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/fxml/cell/TableShortEnumCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableShortEnumCell.java | package mara.mybox.fxml.cell;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.ComboBoxTableCell;
import javafx.scene.input.MouseEvent;
import javafx.util.Callback;
import mara.mybox.controller.BaseData2DTableController;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.fxml.style.NodeStyleTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2021-10-26
* @License Apache License Version 2.0
*/
public class TableShortEnumCell extends ComboBoxTableCell<List<String>, String> {
protected BaseData2DTableController dataTable;
protected Data2DColumn dataColumn;
protected int maxVisibleCount;
public TableShortEnumCell(BaseData2DTableController dataTable, Data2DColumn dataColumn,
ObservableList<String> items, int maxCount, boolean editable) {
super(items);
setComboBoxEditable(editable);
maxVisibleCount = maxCount;
if (maxVisibleCount <= 0) {
maxVisibleCount = 10;
}
this.dataTable = dataTable;
this.dataColumn = dataColumn;
setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
TableView<List<String>> table = getTableView();
if (table != null && table.getItems() != null) {
int index = rowIndex();
if (index < table.getItems().size()) {
table.edit(index, getTableColumn());
}
}
}
});
}
@Override
public void startEdit() {
super.startEdit();
Node g = getGraphic();
if (g != null && g instanceof ComboBox) {
ComboBox cb = (ComboBox) g;
cb.setVisibleRowCount(maxVisibleCount);
cb.setValue(getItem());
if (isComboBoxEditable()) {
NodeStyleTools.setTooltip(cb.getEditor(), message("EditCellComments"));
}
}
}
public int rowIndex() {
try {
TableRow row = getTableRow();
if (row == null) {
return -1;
}
int index = row.getIndex();
if (index >= 0 && index < getTableView().getItems().size()) {
return index;
} else {
return -2;
}
} catch (Exception e) {
return -3;
}
}
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setStyle(null);
if (empty) {
setText(null);
setGraphic(null);
return;
}
try {
setStyle(dataTable.getData2D().cellStyle(dataTable.getStyleFilter(),
rowIndex(), dataColumn.getColumnName()));
} catch (Exception e) {
}
// setText(item);
}
public static Callback<TableColumn, TableCell> create(
BaseData2DTableController dataTable, Data2DColumn dataColumn, List<String> items,
int maxVisibleCount, boolean editable) {
return new Callback<TableColumn, TableCell>() {
@Override
public TableCell call(TableColumn param) {
ObservableList<String> olist = FXCollections.observableArrayList();
for (String item : items) {
olist.add(item);
}
return new TableShortEnumCell(dataTable, dataColumn, olist, maxVisibleCount, editable);
}
};
}
}
| 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/fxml/cell/TableDataBooleanDisplayCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableDataBooleanDisplayCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.image.ImageView;
import javafx.util.Callback;
import mara.mybox.controller.BaseData2DTableController;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.fxml.style.StyleTools;
import mara.mybox.tools.StringTools;
/**
* @Author Mara
* @CreateDate 2022-10-1
* @License Apache License Version 2.0
*/
public class TableDataBooleanDisplayCell extends TableDataCell {
protected ImageView imageview;
public TableDataBooleanDisplayCell(BaseData2DTableController dataTable, Data2DColumn dataColumn) {
super(dataTable, dataColumn);
imageview = StyleTools.getIconImageView("iconYes.png");
imageview.setPreserveRatio(true);
}
@Override
public void displayData(String item) {
setText(null);
setGraphic(StringTools.isTrue(item) ? imageview : null);
}
public static Callback<TableColumn, TableCell>
create(BaseData2DTableController dataTable, Data2DColumn dataColumn) {
return new Callback<TableColumn, TableCell>() {
@Override
public TableCell call(TableColumn param) {
return new TableDataBooleanDisplayCell(dataTable, dataColumn);
}
};
}
}
| 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/fxml/cell/TreeTableEraCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TreeTableEraCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeTableColumn;
import javafx.util.Callback;
import mara.mybox.tools.DateTools;
import mara.mybox.value.AppValues;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:24:30
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class TreeTableEraCell<T> extends TreeTableCell<T, Long>
implements Callback<TreeTableColumn<T, Long>, TreeTableCell<T, Long>> {
@Override
public TreeTableCell<T, Long> call(TreeTableColumn<T, Long> param) {
TreeTableCell<T, Long> cell = new TreeTableCell<T, Long>() {
@Override
protected void updateItem(final Long item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || item == AppValues.InvalidLong) {
setText(null);
setGraphic(null);
return;
}
setText(DateTools.textEra(item));
setGraphic(null);
}
};
return cell;
}
}
| 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/fxml/cell/TableColorEditCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableColorEditCell.java | package mara.mybox.fxml.cell;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Rectangle;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.ColorPalettePopupController;
import mara.mybox.db.table.TableColor;
import mara.mybox.fxml.image.FxColorTools;
import mara.mybox.fxml.style.NodeStyleTools;
import static mara.mybox.value.Languages.message;
/**
* Reference:
* https://stackoverflow.com/questions/24694616/how-to-enable-commit-on-focuslost-for-tableview-treetableview
* By Ogmios
*
* @Author Mara
* @CreateDate 2020-12-03
* @License Apache License Version 2.0
*/
public class TableColorEditCell<S> extends TableCell<S, Color> {
protected BaseController parent;
protected TableColor tableColor;
protected Rectangle rectangle;
protected String msgPrefix;
public TableColorEditCell(BaseController parent, TableColor tableColor) {
this.parent = parent;
this.tableColor = tableColor;
if (this.tableColor == null) {
this.tableColor = new TableColor();
}
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
rectangle = new Rectangle(30, 20);
rectangle.setStroke(Color.BLACK);
rectangle.setStrokeWidth(1);
msgPrefix = message("ClickColorToPalette");
this.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
setColor();
}
});
}
@Override
protected void updateItem(Color item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
return;
}
if (item == null) {
rectangle.setFill(Color.WHITE);
NodeStyleTools.setTooltip(rectangle, msgPrefix);
} else {
rectangle.setFill((Paint) item);
NodeStyleTools.setTooltip(rectangle, msgPrefix + "\n---------\n"
+ FxColorTools.colorNameDisplay(tableColor, item));
}
setGraphic(rectangle);
}
public void setColor() {
Node g = getGraphic();
if (g == null || !(g instanceof Rectangle)) {
return;
}
ColorPalettePopupController controller = ColorPalettePopupController.open(parent, rectangle);
controller.getSetNotify().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) {
if (controller == null) {
return;
}
colorChanged(getIndex(), (Color) rectangle.getFill());
controller.close();
}
});
}
public void colorChanged(int index, Color color) {
}
}
| 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/fxml/cell/TreeTableSelectionCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TreeTableSelectionCell.java | package mara.mybox.fxml.cell;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableView;
import javafx.scene.control.cell.CheckBoxTreeTableCell;
import javafx.util.Callback;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2021-10-26
* @License Apache License Version 2.0
*/
public class TreeTableSelectionCell<S, T> extends CheckBoxTreeTableCell<S, T> {
protected TreeTableView treeView;
protected SimpleBooleanProperty checked;
protected boolean selectingRow, checkingBox;
protected ChangeListener<Boolean> checkedListener;
protected ListChangeListener selectedListener;
public TreeTableSelectionCell(TreeTableView tView) {
treeView = tView;
checked = new SimpleBooleanProperty(false);
selectingRow = checkingBox = false;
getStyleClass().add("row-number");
// treeView.getSelectionModel().getSelectedIndices().addListener(selectedListener);
// checked.addListener(checkedListener);
setSelectedStateCallback(new Callback<Integer, ObservableValue<Boolean>>() {
@Override
public synchronized ObservableValue<Boolean> call(Integer index) {
MyBoxLog.console(index);
if (index < 0) {
return null;
}
checkingBox = true;
checked.set(isChecked());
checkingBox = false;
return checked;
}
});
selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue v, Boolean ov, Boolean nv) {
MyBoxLog.console(nv + " " + getTableRow().getIndex());
}
});
}
public boolean isChecked() {
return true;
}
@Override
public void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
}
}
public static <S, T> Callback<TreeTableColumn<S, T>, TreeTableCell<S, T>> create(TreeTableView treeView) {
return new Callback<TreeTableColumn<S, T>, TreeTableCell<S, T>>() {
@Override
public TreeTableCell<S, T> call(TreeTableColumn<S, T> param) {
return new TreeTableSelectionCell<>(treeView);
}
};
}
public SimpleBooleanProperty getSelected() {
return checked;
}
public void setSelected(SimpleBooleanProperty selected) {
this.checked = 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/fxml/cell/TablePercentageCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TablePercentageCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.tools.DoubleTools;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:17:47
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class TablePercentageCell<T> extends TableCell<T, Double>
implements Callback<TableColumn<T, Double>, TableCell<T, Double>> {
@Override
public TableCell<T, Double> call(TableColumn<T, Double> param) {
TableCell<T, Double> cell = new TableCell<T, Double>() {
@Override
public void updateItem(Double item, boolean empty) {
super.updateItem(item, empty);
setGraphic(null);
if (empty || item == null) {
setText(null);
return;
}
if (!DoubleTools.invalidDouble(item)) {
setText(DoubleTools.scale(item * 100.0d, 2) + "");
} else {
setText(null);
}
}
};
return cell;
}
}
| 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/fxml/cell/CellTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/CellTools.java | package mara.mybox.fxml.cell;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.util.Callback;
import mara.mybox.db.data.Data2DColumn;
/**
* @Author Mara
* @CreateDate 2025-12-14
* @License Apache License Version 2.0
*/
public class CellTools {
public static void makeColumnComboBox(ComboBox<Data2DColumn> colSelector) {
if (colSelector == null) {
return;
}
Callback<ListView<Data2DColumn>, ListCell<Data2DColumn>> colFactory
= new Callback<ListView<Data2DColumn>, ListCell<Data2DColumn>>() {
@Override
public ListCell<Data2DColumn> call(ListView<Data2DColumn> param) {
ListCell<Data2DColumn> cell = new ListCell<Data2DColumn>() {
@Override
public void updateItem(Data2DColumn item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
return;
}
setText(item.getLabel());
}
};
return cell;
}
};
colSelector.setButtonCell(colFactory.call(null));
colSelector.setCellFactory(colFactory);
}
public static void selectItem(ComboBox<Data2DColumn> colSelector, String name) {
if (colSelector == null || name == null) {
return;
}
for (Data2DColumn col : colSelector.getItems()) {
if (name.equals(col.getColumnName()) || name.equals(col.getLabel())) {
colSelector.getSelectionModel().select(col);
return;
}
}
}
}
| 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/fxml/cell/TableTextTrimCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableTextTrimCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.tools.StringTools;
import mara.mybox.value.AppVariables;
/**
* @Author Mara
* @CreateDate 2023-9-18
* @License Apache License Version 2.0
*/
public class TableTextTrimCell<T> extends TableCell<T, String>
implements Callback<TableColumn<T, String>, TableCell<T, String>> {
@Override
public TableCell<T, String> call(TableColumn<T, String> param) {
TableCell<T, String> cell = new TableCell<T, String>() {
@Override
protected void updateItem(final String item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
return;
}
setText(StringTools.abbreviate(item, AppVariables.titleTrimSize));
setGraphic(null);
}
};
return cell;
}
}
| 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/fxml/cell/TableLongitudeCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableLongitudeCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
/**
* @Author Mara
* @CreateDate 2020-2-22
* @License Apache License Version 2.0
*/
public class TableLongitudeCell<T> extends TableCell<T, Double>
implements Callback<TableColumn<T, Double>, TableCell<T, Double>> {
@Override
public TableCell<T, Double> call(TableColumn<T, Double> param) {
TableCell<T, Double> cell = new TableCell<T, Double>() {
@Override
public void updateItem(Double item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setGraphic(null);
setText(null);
setTextFill(null);
return;
}
if (item >= -180 && item <= 180) {
setText(item + "");
} else {
setText(null);
}
setGraphic(null);
}
};
return cell;
}
}
| 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/fxml/cell/ListImageItemCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/ListImageItemCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.ListCell;
import mara.mybox.data.ImageItem;
/**
* @Author Mara
* @CreateDate 2020-1-5
* @License Apache License Version 2.0
*/
public class ListImageItemCell extends ListCell<ImageItem> {
protected int height = 60;
public ListImageItemCell() {
}
public ListImageItemCell(int imageSize) {
this.height = imageSize;
}
@Override
public void updateItem(ImageItem item, boolean empty) {
super.updateItem(item, empty);
setText(null);
if (empty || item == null) {
setGraphic(null);
return;
}
setGraphic(item.makeNode(height, 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/fxml/cell/TableFileSizeCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableFileSizeCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.text.Text;
import javafx.util.Callback;
import mara.mybox.tools.FileTools;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:24:30
* @License Apache License Version 2.0
*/
public class TableFileSizeCell<T> extends TableCell<T, Long>
implements Callback<TableColumn<T, Long>, TableCell<T, Long>> {
@Override
public TableCell<T, Long> call(TableColumn<T, Long> param) {
TableCell<T, Long> cell = new TableCell<T, Long>() {
private final Text text = new Text();
@Override
protected void updateItem(final Long item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || item <= 0) {
setText(null);
setGraphic(null);
return;
}
text.setText(FileTools.showFileSize(item));
setGraphic(text);
}
};
return cell;
}
}
| 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/fxml/cell/TableEraCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableEraCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.data.Era;
import mara.mybox.tools.DateTools;
/**
* @Author Mara
* @CreateDate 2020-7-7
* @License Apache License Version 2.0
*/
public class TableEraCell<T> extends TableCell<T, Era>
implements Callback<TableColumn<T, Era>, TableCell<T, Era>> {
@Override
public TableCell<T, Era> call(TableColumn<T, Era> param) {
TableCell<T, Era> cell = new TableCell<T, Era>() {
@Override
public void updateItem(Era item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
return;
}
setText(DateTools.textEra(item));
setGraphic(null);
}
};
return cell;
}
}
| 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/fxml/cell/TableDataColumnCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableDataColumnCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.controller.ControlData2DColumns;
import mara.mybox.controller.Data2DColumnEditController;
/**
* @Author Mara
* @CreateDate 2022-10-4
* @License Apache License Version 2.0
*/
public class TableDataColumnCell<S, T> extends TableAutoCommitCell<S, T> {
protected ControlData2DColumns columnsControl;
public TableDataColumnCell(ControlData2DColumns columnsControl) {
super(null);
this.columnsControl = columnsControl;
}
@Override
public void editCell() {
Data2DColumnEditController.open(columnsControl, editingRow);
}
@Override
public boolean setCellValue(T value) {
return true;
}
public static <S, T> Callback<TableColumn<S, T>, TableCell<S, T>> create(ControlData2DColumns columnsControl) {
return new Callback<TableColumn<S, T>, TableCell<S, T>>() {
@Override
public TableCell<S, T> call(TableColumn<S, T> param) {
return new TableDataColumnCell(columnsControl);
}
};
}
}
| 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/fxml/cell/TableDataDisplayCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableDataDisplayCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.controller.BaseData2DTableController;
import mara.mybox.db.data.Data2DColumn;
/**
* @Author Mara
* @CreateDate 2022-9-26
* @License Apache License Version 2.0
*/
public class TableDataDisplayCell extends TableDataCell {
public TableDataDisplayCell(BaseData2DTableController dataTable, Data2DColumn dataColumn) {
super(dataTable, dataColumn);
}
@Override
public void startEdit() {
}
@Override
public void commitEdit(String inValue) {
}
@Override
public boolean commit(String value) {
return true;
}
public static Callback<TableColumn, TableCell> create(BaseData2DTableController dataTable, Data2DColumn dataColumn) {
return new Callback<TableColumn, TableCell>() {
@Override
public TableCell call(TableColumn param) {
return new TableDataDisplayCell(dataTable, dataColumn);
}
};
}
}
| 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/fxml/cell/TableMessageCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableMessageCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.value.AppVariables;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2020-02-08
* @License Apache License Version 2.0
*/
public class TableMessageCell<T> extends TableCell<T, String>
implements Callback<TableColumn<T, String>, TableCell<T, String>> {
@Override
public TableCell<T, String> call(TableColumn<T, String> param) {
TableCell<T, String> cell = new TableCell<T, String>() {
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
return;
}
setText(Languages.message(item));
setGraphic(null);
}
};
return cell;
}
}
| 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/fxml/cell/TableDataEditCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableDataEditCell.java | package mara.mybox.fxml.cell;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.controller.BaseData2DTableController;
import mara.mybox.controller.TextInputController;
import mara.mybox.db.data.Data2DColumn;
/**
* @Author Mara
* @CreateDate 2022-9-26
* @License Apache License Version 2.0
*/
public class TableDataEditCell extends TableDataCell {
public TableDataEditCell(BaseData2DTableController dataTable, Data2DColumn dataColumn) {
super(dataTable, dataColumn);
}
@Override
public void editCell() {
String s = getItem();
if (supportMultipleLine && s != null && (s.contains("\n") || s.length() > 200)) {
TextInputController inputController = TextInputController.open(dataTable, name(), s);
inputController.getNotify().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
String value = inputController.getInputString();
setCellValue(value);
inputController.close();
}
});
} else {
super.editCell();
}
}
public static Callback<TableColumn, TableCell> create(BaseData2DTableController dataTable, Data2DColumn dataColumn) {
return new Callback<TableColumn, TableCell>() {
@Override
public TableCell call(TableColumn param) {
return new TableDataEditCell(dataTable, dataColumn);
}
};
}
}
| 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/fxml/cell/TableDataDateEditCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableDataDateEditCell.java | package mara.mybox.fxml.cell;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.controller.BaseData2DTableController;
import mara.mybox.controller.DateInputController;
import mara.mybox.db.data.Data2DColumn;
/**
* @Author Mara
* @CreateDate 2022-10-2
* @License Apache License Version 2.0
*/
public class TableDataDateEditCell extends TableDataEditCell {
public TableDataDateEditCell(BaseData2DTableController dataControl, Data2DColumn dataColumn) {
super(dataControl, dataColumn);
}
@Override
public void editCell() {
DateInputController inputController
= DateInputController.open(dataTable, name(), getCellValue(), dataColumn.getType());
inputController.getNotify().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
String value = inputController.getInputString();
setCellValue(value);
inputController.close();
}
});
}
public static Callback<TableColumn, TableCell> create(BaseData2DTableController dataControl, Data2DColumn dataColumn) {
return new Callback<TableColumn, TableCell>() {
@Override
public TableCell call(TableColumn param) {
return new TableDataDateEditCell(dataControl, dataColumn);
}
};
}
}
| 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/fxml/cell/TableDoubleCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableDoubleCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.tools.DoubleTools;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:17:47
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class TableDoubleCell<T> extends TableCell<T, Double>
implements Callback<TableColumn<T, Double>, TableCell<T, Double>> {
@Override
public TableCell<T, Double> call(TableColumn<T, Double> param) {
TableCell<T, Double> cell = new TableCell<T, Double>() {
@Override
public void updateItem(Double item, boolean empty) {
super.updateItem(item, empty);
setGraphic(null);
if (empty || item == null) {
setText(null);
return;
}
if (!DoubleTools.invalidDouble(item)) {
setText(item + "");
} else {
setText(null);
}
}
};
return cell;
}
}
| 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/fxml/cell/TableTimeCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableTimeCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.tools.DateTools;
import mara.mybox.value.AppValues;
/**
* @Author Mara
* @CreateDate 2020-7-7
* @License Apache License Version 2.0
*/
public class TableTimeCell<T> extends TableCell<T, Long>
implements Callback<TableColumn<T, Long>, TableCell<T, Long>> {
@Override
public TableCell<T, Long> call(TableColumn<T, Long> param) {
TableCell<T, Long> cell = new TableCell<T, Long>() {
@Override
public void updateItem(Long item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || item == AppValues.InvalidLong) {
setText(null);
setGraphic(null);
return;
}
setText(DateTools.textEra(item));
setGraphic(null);
}
};
return cell;
}
}
| 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/fxml/cell/TableAutoCommitCell.java | alpha/MyBox/src/main/java/mara/mybox/fxml/cell/TableAutoCommitCell.java | package mara.mybox.fxml.cell;
import java.text.SimpleDateFormat;
import java.util.Date;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TablePosition;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.util.Callback;
import javafx.util.StringConverter;
import javafx.util.converter.DateTimeStringConverter;
import javafx.util.converter.DefaultStringConverter;
import mara.mybox.data.Era;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.converter.ColorStringConverter;
import mara.mybox.fxml.converter.DoubleStringFromatConverter;
import mara.mybox.fxml.converter.EraStringConverter;
import mara.mybox.fxml.converter.FloatStringFromatConverter;
import mara.mybox.fxml.converter.IntegerStringFromatConverter;
import mara.mybox.fxml.converter.LongStringFromatConverter;
import mara.mybox.fxml.converter.ShortStringFromatConverter;
import mara.mybox.fxml.style.NodeStyleTools;
import mara.mybox.value.AppVariables;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.TimeFormats;
import mara.mybox.value.UserConfig;
/**
* Reference:
* https://stackoverflow.com/questions/24694616/how-to-enable-commit-on-focuslost-for-tableview-treetableview
* By Ogmios
*
* @Author Mara
* @CreateDate 2020-12-03
* @License Apache License Version 2.0
*
* This is an old issue since 2011
* https://bugs.openjdk.java.net/browse/JDK-8089514
* https://bugs.openjdk.java.net/browse/JDK-8089311
*/
public class TableAutoCommitCell<S, T> extends TextFieldTableCell<S, T> {
protected String editingText;
protected int editingRow = -1;
protected ChangeListener<Boolean> focusListener;
protected ChangeListener<String> editListener;
protected EventHandler<KeyEvent> keyReleasedHandler;
public TableAutoCommitCell() {
this(null);
}
public TableAutoCommitCell(StringConverter<T> conv) {
super(conv);
setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
mouseClicked(event);
}
});
}
public void mouseClicked(MouseEvent event) {
startEdit();
}
public TextField editor() {
Node g = getGraphic();
if (g != null && g instanceof TextField) {
return (TextField) g;
} else {
return null;
}
}
public int size() {
try {
return getTableView().getItems().size();
} catch (Exception e) {
// MyBoxLog.debug(e);
return -1;
}
}
public int rowIndex() {
int rowIndex = -2;
try {
int v = getTableRow().getIndex();
if (v >= 0 && v < size()) {
rowIndex = v;
}
} catch (Exception e) {
}
return rowIndex;
}
public boolean isEditingRow() {
int rowIndex = rowIndex();
return rowIndex >= 0 && editingRow == rowIndex;
}
public boolean validText(String text) {
try {
return valid(getConverter().fromString(text));
} catch (Exception e) {
return false;
}
}
public boolean valid(final T value) {
return true;
}
public boolean changed(final T value) {
T oValue = getItem();
if (oValue == null) {
return value != null;
} else {
return !oValue.equals(value);
}
}
protected String name() {
return message("TableRowNumber") + " " + (rowIndex() + 1) + "\n"
+ getTableColumn().getText();
}
public boolean initEditor() {
editingRow = rowIndex();
return editingRow >= 0;
}
@Override
public void startEdit() {
try {
if (!initEditor()) {
return;
}
editCell();
} catch (Exception e) {
MyBoxLog.console(e);
}
}
public void editCell() {
try {
super.startEdit();
clearEditor();
TextField editor = editor();
if (editor == null) {
return;
}
if (focusListener == null) {
initListeners();
}
editingText = editor.getText();
editor.focusedProperty().addListener(focusListener);
editor.textProperty().addListener(editListener);
editor.setOnKeyReleased(keyReleasedHandler);
editor.setStyle(null);
NodeStyleTools.setTooltip(editor, message("EditCellComments"));
} catch (Exception e) {
MyBoxLog.console(e);
}
}
public void initListeners() {
focusListener = new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
try {
if (!newValue) {
if (AppVariables.commitModificationWhenDataCellLoseFocus && isEditingRow()) {
commitEdit(getConverter().fromString(editingText));
} else {
clearEditor();
cancelCell();
}
editingRow = -1;
}
} catch (Exception e) {
}
}
};
editListener = new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
try {
if (!isEditingRow()) {
return;
}
TextField editor = editor();
if (editor == null) {
return;
}
editingText = editor.getText();
if (validText(editingText)) {
editor.setStyle(null);
} else {
editor.setStyle(UserConfig.badStyle());
}
} catch (Exception e) {
}
}
};
keyReleasedHandler = new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
switch (event.getCode()) {
case ESCAPE:
cancelCell();
event.consume();
break;
case TAB:
if (event.isShiftDown()) {
getTableView().getSelectionModel().selectPrevious();
} else {
getTableView().getSelectionModel().selectNext();
}
event.consume();
break;
case UP:
getTableView().getSelectionModel().selectAboveCell();
event.consume();
break;
case DOWN:
getTableView().getSelectionModel().selectBelowCell();
event.consume();
break;
default:
break;
}
}
};
}
public void clearEditor() {
try {
TextField editor = editor();
if (editor == null) {
return;
}
if (focusListener != null) {
editor.focusedProperty().removeListener(focusListener);
}
if (editListener != null) {
editor.textProperty().removeListener(editListener);
}
editor.setOnKeyReleased(null);
editor.setStyle(null);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
@Override
public void commitEdit(T value) {
try {
clearEditor();
boolean valid = valid(value);
boolean changed = changed(value);
if (!isEditingRow() || !valid || !changed) {
cancelCell();
} else {
setCellValue(value);
}
editingRow = -1;
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public boolean setCellValue(T value) {
try {
if (isEditing()) {
super.commitEdit(value);
} else {
return commit(value);
}
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public boolean commit(T value) {
try {
TableView<S> table = getTableView();
if (table != null && isEditingRow()) {
TableColumn<S, T> column = getTableColumn();
if (column == null) {
cancelCell();
} else {
TablePosition<S, T> pos = new TablePosition<>(table, editingRow, column);
CellEditEvent<S, T> ev = new CellEditEvent<>(table, pos, TableColumn.editCommitEvent(), value);
Event.fireEvent(column, ev);
updateItem(value, false);
}
} else {
cancelCell();
}
if (table != null) {
table.edit(-1, null);
}
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public void cancelCell() {
editingRow = -1;
cancelEdit();
updateItem(getItem(), false);
}
/*
static
*/
public static <S> Callback<TableColumn<S, String>, TableCell<S, String>> forStringColumn() {
return new Callback<TableColumn<S, String>, TableCell<S, String>>() {
@Override
public TableCell<S, String> call(TableColumn<S, String> param) {
return new TableAutoCommitCell<>(new DefaultStringConverter());
}
};
}
public static <S> Callback<TableColumn<S, Integer>, TableCell<S, Integer>> forIntegerColumn() {
return new Callback<TableColumn<S, Integer>, TableCell<S, Integer>>() {
@Override
public TableCell<S, Integer> call(TableColumn<S, Integer> param) {
return new TableAutoCommitCell<>(new IntegerStringFromatConverter());
}
};
}
public static <S> Callback<TableColumn<S, Long>, TableCell<S, Long>> forLongColumn() {
return new Callback<TableColumn<S, Long>, TableCell<S, Long>>() {
@Override
public TableCell<S, Long> call(TableColumn<S, Long> param) {
return new TableAutoCommitCell<>(new LongStringFromatConverter());
}
};
}
public static <S> Callback<TableColumn<S, Float>, TableCell<S, Float>> forFloatColumn() {
return new Callback<TableColumn<S, Float>, TableCell<S, Float>>() {
@Override
public TableCell<S, Float> call(TableColumn<S, Float> param) {
return new TableAutoCommitCell<>(new FloatStringFromatConverter());
}
};
}
public static <S> Callback<TableColumn<S, Double>, TableCell<S, Double>> forDoubleColumn() {
return new Callback<TableColumn<S, Double>, TableCell<S, Double>>() {
@Override
public TableCell<S, Double> call(TableColumn<S, Double> param) {
return new TableAutoCommitCell<>(new DoubleStringFromatConverter());
}
};
}
public static <S> Callback<TableColumn<S, Short>, TableCell<S, Short>> forShortColumn() {
return new Callback<TableColumn<S, Short>, TableCell<S, Short>>() {
@Override
public TableCell<S, Short> call(TableColumn<S, Short> param) {
return new TableAutoCommitCell<>(new ShortStringFromatConverter());
}
};
}
public static <S> Callback<TableColumn<S, Date>, TableCell<S, Date>> forDateTimeColumn() {
return new Callback<TableColumn<S, Date>, TableCell<S, Date>>() {
@Override
public TableCell<S, Date> call(TableColumn<S, Date> param) {
return new TableAutoCommitCell<>(new DateTimeStringConverter(new SimpleDateFormat(TimeFormats.Datetime)));
}
};
}
public static <S> Callback<TableColumn<S, Era>, TableCell<S, Era>> forEraColumn() {
return new Callback<TableColumn<S, Era>, TableCell<S, Era>>() {
@Override
public TableCell<S, Era> call(TableColumn<S, Era> param) {
return new TableAutoCommitCell<>(new EraStringConverter());
}
};
}
public static <S> Callback<TableColumn<S, Color>, TableCell<S, Color>> forColorColumn() {
return new Callback<TableColumn<S, Color>, TableCell<S, Color>>() {
@Override
public TableCell<S, Color> call(TableColumn<S, Color> param) {
return new TableAutoCommitCell<>(new ColorStringConverter());
}
};
}
}
| 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/fxml/style/StyleData.java | alpha/MyBox/src/main/java/mara/mybox/fxml/style/StyleData.java | package mara.mybox.fxml.style;
/**
* @Author Mara
* @CreateDate 2019-4-26 7:16:14
* @License Apache License Version 2.0
*/
public class StyleData {
public static enum StyleColor {
Red, Blue, LightBlue, Pink, Orange, Green, Customize
}
private String id, name, comments, shortcut, iconName;
public StyleData(String id) {
this.id = id;
}
public StyleData(String id, String name, String shortcut, String iconName) {
this.id = id;
this.name = name;
this.shortcut = shortcut;
this.iconName = iconName;
}
public StyleData(String id, String name, String comments, String shortcut, String iconName) {
this.id = id;
this.name = name;
this.comments = comments;
this.shortcut = shortcut;
this.iconName = iconName;
}
/*
get/set
*/
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getShortcut() {
return shortcut;
}
public void setShortcut(String shortcut) {
this.shortcut = shortcut;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getIconName() {
return iconName;
}
public void setIconName(String iconName) {
this.iconName = iconName;
}
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/fxml/style/StyleRadioButton.java | alpha/MyBox/src/main/java/mara/mybox/fxml/style/StyleRadioButton.java | package mara.mybox.fxml.style;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2021-7-30
* @License Apache License Version 2.0
*/
public class StyleRadioButton {
public static StyleData radioButtonStyle(String id) {
if (id == null || id.isEmpty()) {
return null;
}
StyleData d = equals(id);
if (d != null) {
return d;
}
return start(id);
}
private static StyleData equals(String id) {
switch (id) {
case "miaoRadio":
return new StyleData(id, message("Meow"), message("MiaoPrompt"), "", "iconCat.png");
case "lineRadio":
return new StyleData(id, message("StraightLine"), "", "iconLine.png");
case "rectangleRadio":
return new StyleData(id, message("Rectangle"), "", "iconRectangle.png");
case "circleRadio":
return new StyleData(id, message("Circle"), "", "iconCircle.png");
case "ellipseRadio":
return new StyleData(id, message("Ellipse"), "", "iconEllipse.png");
case "polylineRadio":
return new StyleData(id, message("Polyline"), "", "iconPolyline.png");
case "polylinesRadio":
return new StyleData(id, message("Graffiti"), "", "iconPolylines.png");
case "polygonRadio":
return new StyleData(id, message("Polygon"), "", "iconStar.png");
case "quadraticRadio":
return new StyleData(id, message("QuadraticCurve"), "", "iconQuadratic.png");
case "cubicRadio":
return new StyleData(id, message("CubicCurve"), "", "iconCubic.png");
case "arcRadio":
return new StyleData(id, message("ArcCurve"), "", "iconArc.png");
case "svgRadio":
return new StyleData(id, message("SVGPath"), "", "iconSVG.png");
case "eraserRadio":
return new StyleData(id, message("Eraser"), "", "iconEraser.png");
case "mosaicRadio":
return new StyleData(id, message("Mosaic"), "", "iconMosaic.png");
case "frostedRadio":
return new StyleData(id, message("FrostedGlass"), "", "iconFrosted.png");
case "horizontalBarChartRadio":
return new StyleData(id, message("HorizontalBarChart"), "", "iconBarChartH.png");
case "barChartRadio":
return new StyleData(id, message("BarChart"), "", "iconBarChart.png");
case "stackedBarChartRadio":
return new StyleData(id, message("StackedBarChart"), "", "iconStackedBarChart.png");
case "verticalLineChartRadio":
return new StyleData(id, message("VerticalLineChart"), "", "iconLineChartV.png");
case "lineChartRadio":
return new StyleData(id, message("LineChart"), "", "iconLineChart.png");
case "pieRadio":
return new StyleData(id, message("PieChart"), "", "iconPieChart.png");
case "areaChartRadio":
return new StyleData(id, message("AreaChart"), "", "iconAreaChart.png");
case "stackedAreaChartRadio":
return new StyleData(id, message("StackedAreaChart"), "", "iconStackedAreaChart.png");
case "scatterChartRadio":
return new StyleData(id, message("ScatterChart"), "", "iconScatterChart.png");
case "bubbleChartRadio":
return new StyleData(id, message("BubbleChart"), "", "iconBubbleChart.png");
case "mapRadio":
return new StyleData(id, message("Map"), "", "iconMap.png");
case "pcxSelect":
return new StyleData(id, "pcx", message("PcxComments"), "", "");
case "setRadio":
return new StyleData(id, message("Set"), "", "");
case "plusRadio":
return new StyleData(id, message("Plus"), "", "");
case "minusRadio":
return new StyleData(id, message("Minus"), "", "");
case "filterRadio":
return new StyleData(id, message("Filter"), "", "");
case "invertRadio":
return new StyleData(id, message("Invert"), "", "");
case "colorRGBRadio":
return new StyleData(id, message("RGB"), "", "");
case "colorBrightnessRadio":
return new StyleData(id, message("Brightness"), "", "iconBrightness.png");
case "colorHueRadio":
return new StyleData(id, message("Hue"), "", "iconHue.png");
case "colorSaturationRadio":
return new StyleData(id, message("Saturation"), "", "iconSaturation.png");
case "colorRedRadio":
return new StyleData(id, message("Red"), "", "");
case "colorGreenRadio":
return new StyleData(id, message("Green"), "", "");
case "colorBlueRadio":
return new StyleData(id, message("Blue"), "", "");
case "colorYellowRadio":
return new StyleData(id, message("Yellow"), "", "");
case "colorCyanRadio":
return new StyleData(id, message("Cyan"), "", "");
case "colorMagentaRadio":
return new StyleData(id, message("Magenta"), "", "");
case "colorOpacityRadio":
return new StyleData(id, message("Opacity"), "", "iconOpacity.png");
case "listRadio":
return new StyleData(id, message("List"), "", "iconList.png");
case "thumbRadio":
return new StyleData(id, message("ThumbnailsList"), "", "iconThumbsList.png");
case "gridRadio":
return new StyleData(id, message("Grid"), "", "iconBrowse.png");
case "codesRaido":
return new StyleData(id, message("HtmlCodes"), "", "iconMeta.png");
case "treeRadio":
return new StyleData(id, message("Tree"), "", "iconTree.png");
case "richRadio":
return new StyleData(id, message("RichText"), "", "iconEdit.png");
case "mdRadio":
return new StyleData(id, "Markdown", "", "iconMarkdown.png");
case "textsRadio":
return new StyleData(id, message("Texts"), "", "iconTxt.png");
case "htmlRadio":
return new StyleData(id, message("Html"), "", "iconHtml.png");
case "ocrRadio":
return new StyleData(id, message("OCR"), "", "iconOCR.png");
case "wholeRadio":
return new StyleData(id, message("WholeImage"), "", "iconSelectAll.png");
case "matting4Radio":
return new StyleData(id, message("Matting4"), "", "iconColorFill4.png");
case "matting8Radio":
return new StyleData(id, message("Matting8"), "", "iconColorFill.png");
case "outlineRadio":
return new StyleData(id, message("Outline"), "", "iconButterfly.png");
case "imageRadio":
return new StyleData(id, message("Image"), "", "iconImage.png");
}
return null;
}
private static StyleData start(String id) {
if (id.startsWith("csv")) {
return new StyleData(id, "CSV", "", "iconCSV.png");
}
if (id.startsWith("excel")) {
return new StyleData(id, "Excel", "", "iconExcel.png");
}
if (id.startsWith("texts")) {
return new StyleData(id, message("Texts"), "", "iconTxt.png");
}
if (id.startsWith("matrix")) {
return new StyleData(id, message("Matrix"), "", "iconMatrix.png");
}
if (id.startsWith("database")) {
return new StyleData(id, message("DatabaseTable"), "", "iconDatabase.png");
}
if (id.startsWith("systemClipboard")) {
return new StyleData(id, message("SystemClipboard"), "", "iconSystemClipboard.png");
}
if (id.startsWith("myBoxClipboard")) {
return new StyleData(id, message("MyBoxClipboard"), "", "iconClipboard.png");
}
if (id.startsWith("html")) {
return new StyleData(id, "Html", "", "iconHtml.png");
}
if (id.startsWith("xml")) {
return new StyleData(id, "XML", "", "iconXML.png");
}
if (id.startsWith("pdf")) {
return new StyleData(id, "PDF", "", "iconPDF.png");
}
if (id.startsWith("json")) {
return new StyleData(id, "json", "", "iconJSON.png");
}
if (id.startsWith("table")) {
return new StyleData(id, message("Table"), "", "iconGrid.png");
}
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/fxml/style/StyleToggleButton.java | alpha/MyBox/src/main/java/mara/mybox/fxml/style/StyleToggleButton.java | package mara.mybox.fxml.style;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2021-7-30
* @License Apache License Version 2.0
*/
public class StyleToggleButton {
public static StyleData toggleButtonStyle(String id) {
if (id == null || id.isEmpty()) {
return null;
}
StyleData d = match(id);
if (d != null) {
return d;
}
return startsWith(id);
}
private static StyleData match(String id) {
switch (id) {
case "pickColorButton":
return new StyleData("pickColorButton", message("PickColor"), "", "iconPickColor.png");
case "fullScreenButton":
return new StyleData(id, message("FullScreen"), "", "iconExpand.png");
case "soundButton":
return new StyleData(id, message("Mute"), "", "iconMute.png");
}
return null;
}
private static StyleData startsWith(String id) {
if (id.startsWith("cat")) {
return new StyleData(id, message("Meow"), "", "iconCat.png");
}
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/fxml/style/HtmlStyles.java | alpha/MyBox/src/main/java/mara/mybox/fxml/style/HtmlStyles.java | package mara.mybox.fxml.style;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2021-8-1
* @License Apache License Version 2.0
*/
public class HtmlStyles {
public enum HtmlStyle {
Table, Default, Article, Console, Blackboard, Ago, Book, Grey
}
public static final String TableStyle
= " table { max-width:95%; margin : 10px; border-style: solid; border-width:2px; border-collapse: collapse;} \n"
+ " th, td { border-style: solid; border-width:1px; padding: 8px; border-collapse: collapse;} \n"
+ " th { font-weight:bold; text-align:center;} \n"
+ " tr { height: 1.2em; } \n"
+ " .center { text-align:center; max-width:95%; } \n"
+ " .valueBox { border-style: solid; border-width:1px; border-color:black; padding: 5px; border-radius:5px;} \n"
+ " .boldText { font-weight:bold; } \n";
public static final String ArticleStyle
= TableStyle
+ " body { margin:0 auto; width: 900px; } \n"
+ " img { max-width: 900px; } \n";
public static final String DefaultStyle
= ArticleStyle
+ " .valueText { color:#2e598a; } \n";
public static final String ConsoleStyle
= TableStyle
+ " body { background-color:black; color:#CCFF99; }\n"
+ " a:link {color: dodgerblue}\n"
+ " a:visited {color: #DDDDDD}\n"
+ " .valueBox { border-color:#CCFF99;}\n"
+ " .valueText { color:skyblue; }\n";
public static final String BlackboardStyle
= TableStyle
+ " body { background-color:#336633; color:white; }\n"
+ " a:link {color: aqua}\n"
+ " a:visited {color: #DDDDDD}\n"
+ " .valueBox { border-color:white; }\n"
+ " .valueText { color:wheat; }\n";
public static final String AgoStyle
= TableStyle
+ " body { background-color:darkblue; color:white; }\n"
+ " a:link {color: springgreen}\n"
+ " a:visited {color: #DDDDDD}\n"
+ " .valueBox { border-color:white;}\n"
+ " .valueText { color:yellow; }\n";
public static final String BookStyle
= TableStyle
+ " body { background-color:#F6F1EB; color:black; }\n";
public static final String GreyStyle
= TableStyle
+ " body { background-color:#ececec; color:black; }\n";
public static HtmlStyles.HtmlStyle styleName(String styleName) {
for (HtmlStyles.HtmlStyle style : HtmlStyles.HtmlStyle.values()) {
if (style.name().equals(styleName) || message(style.name()).equals(styleName)) {
return style;
}
}
return HtmlStyles.HtmlStyle.Default;
}
public static String styleValue(HtmlStyles.HtmlStyle style) {
switch (style) {
case Table:
return HtmlStyles.TableStyle;
case Default:
return HtmlStyles.DefaultStyle;
case Article:
return HtmlStyles.ArticleStyle;
case Console:
return HtmlStyles.ConsoleStyle;
case Blackboard:
return HtmlStyles.BlackboardStyle;
case Ago:
return HtmlStyles.AgoStyle;
case Book:
return HtmlStyles.BookStyle;
case Grey:
return HtmlStyles.GreyStyle;
}
return HtmlStyles.DefaultStyle;
}
public static String styleValue(String styleName) {
return styleValue(styleName(styleName));
}
}
| 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/fxml/style/StyleImageView.java | alpha/MyBox/src/main/java/mara/mybox/fxml/style/StyleImageView.java | package mara.mybox.fxml.style;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2021-7-30
* @License Apache License Version 2.0
*/
public class StyleImageView {
public static StyleData imageViewStyle(String id) {
if (id == null || id.isEmpty()) {
return null;
}
if (id.startsWith("rightTips")) {
return new StyleData(id, "", "", "iconTipsRight.png");
}
if (id.startsWith("leftPane")) {
return new StyleData(id, message("ControlLeftPane") + "\n" + message("ControlLeftPaneShortcut"), "", "iconDoubleLeft.png");
}
if (id.startsWith("rightPane")) {
return new StyleData(id, message("ControlRightPane") + "\n" + message("ControlRightPaneShortcut"), "", "iconDoubleRight.png");
}
if (id.startsWith("links")) {
return new StyleData(id, "", message("Links"), "iconLink.png");
}
if (id.startsWith("tableTipsView")) {
return new StyleData(id, "", message("TableTips"), "iconTipsRight.png");
}
if (id.toLowerCase().endsWith("tipsview")) {
switch (id) {
case "pdfPageSizeTipsView":
return new StyleData(id, "", message("PdfPageSizeComments"), "", "iconTips.png");
case "preAlphaTipsView":
return new StyleData(id, "", message("PremultipliedAlphaTips"), "", "iconTips.png");
default:
return new StyleData(id, "", "", "iconTips.png");
}
}
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/fxml/style/StyleTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/style/StyleTools.java | package mara.mybox.fxml.style;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.MessageFormat;
import java.util.List;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBase;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Control;
import javafx.scene.control.Labeled;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.Tooltip;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import mara.mybox.controller.BaseController;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxFileTools;
import mara.mybox.fxml.FxTask;
import mara.mybox.fxml.WindowTools;
import mara.mybox.fxml.image.FxColorTools;
import mara.mybox.fxml.style.StyleData.StyleColor;
import mara.mybox.image.data.PixelsOperation;
import mara.mybox.image.data.PixelsOperationFactory;
import mara.mybox.image.file.ImageFileWriters;
import mara.mybox.value.AppVariables;
import static mara.mybox.value.Colors.color;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2021-7-30
* @License Apache License Version 2.0
*/
public class StyleTools {
public static String ButtonsSourcePath = "buttons/";
/*
Style Data
*/
public static StyleData getStyleData(Node node) {
if (node == null) {
return null;
}
return getStyleData(node, node.getId());
}
public static StyleData getStyleData(Node node, String id) {
if (node == null || id == null) {
return null;
}
StyleData style = null;
if (node instanceof ImageView) {
style = StyleImageView.imageViewStyle(id);
} else if (node instanceof RadioButton) {
style = StyleRadioButton.radioButtonStyle(id);
} else if (node instanceof CheckBox) {
style = StyleCheckBox.checkBoxStyle(id);
} else if (node instanceof ToggleButton) {
style = StyleToggleButton.toggleButtonStyle(id);
} else if (node instanceof Button) {
style = StyleButton.buttonStyle(id);
}
return style;
}
public static void setStyle(Node node) {
if (node == null) {
return;
}
StyleData style = getStyleData(node);
setTips(node, style);
setIcon(node, StyleTools.getIconImageView(style));
setTextStyle(node, style, AppVariables.ControlColor);
}
public static void setTextStyle(Node node, StyleData StyleData, StyleColor colorStyle) {
try {
if (node == null || StyleData == null || !(node instanceof ButtonBase)) {
return;
}
ButtonBase button = (ButtonBase) node;
if (button.getGraphic() == null) {
return;
}
if (AppVariables.controlDisplayText) {
String name = StyleData.getName();
if (name != null && !name.isEmpty()) {
button.setText(name);
} else {
button.setText(StyleData.getComments());
}
} else {
button.setText(null);
}
} catch (Exception e) {
MyBoxLog.debug(node.getId() + " " + e.toString());
}
}
/*
Color
*/
public static void setConfigStyleColor(BaseController controller, String value) {
AppVariables.ControlColor = getColorStyle(value);
UserConfig.setString("ControlColor", AppVariables.ControlColor.name());
if (AppVariables.ControlColor == StyleColor.Customize) {
FxTask task = new FxTask<Void>(controller) {
@Override
protected boolean handle() {
try {
List<String> iconNames = FxFileTools.getResourceFiles(StyleTools.ButtonsSourcePath + "Red/");
if (iconNames == null || iconNames.isEmpty()) {
return true;
}
String targetPath = AppVariables.MyboxDataPath + "/buttons/customized/";
new File(targetPath).mkdirs();
for (String iconName : iconNames) {
String tname = targetPath + iconName;
if (new File(tname).exists()) {
continue;
}
BufferedImage image = makeIcon(this, StyleColor.Customize, iconName);
if (image != null) {
ImageFileWriters.writeImageFile(this, image, "png", tname);
setInfo(MessageFormat.format(message("FilesGenerated"), tname));
}
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
return true;
}
@Override
protected void whenSucceeded() {
WindowTools.refreshInterfaceAll();
}
};
controller.start(task);
} else {
WindowTools.refreshInterfaceAll();
}
}
/*
Icon
*/
public static String getIconPath() {
try {
StyleColor colorStyle = AppVariables.ControlColor;
if (colorStyle == null) {
AppVariables.ControlColor = StyleColor.Red;
colorStyle = StyleColor.Red;
}
if (colorStyle == StyleColor.Customize) {
String address = AppVariables.MyboxDataPath + "/buttons/customized/";
if (new File(address).exists()) {
return address;
} else {
UserConfig.setString("ControlColor", "red");
AppVariables.ControlColor = StyleColor.Red;
return ButtonsSourcePath + "Red/";
}
} else {
return ButtonsSourcePath + colorStyle.name() + "/";
}
} catch (Exception e) {
return null;
}
}
public static File getIconFile(String name) {
try {
StyleColor colorStyle = AppVariables.ControlColor;
if (colorStyle == null) {
colorStyle = StyleColor.Red;
}
File file = null;
if (colorStyle == StyleColor.Customize) {
file = new File(AppVariables.MyboxDataPath + "/buttons/customized/" + name);
if (!file.exists()) {
colorStyle = StyleColor.Red;
file = null;
}
}
if (file == null) {
file = FxFileTools.getInternalFile(
"/" + ButtonsSourcePath + colorStyle.name() + "/" + name,
"buttons/" + colorStyle.name(),
name);
}
return file;
} catch (Exception e) {
return null;
}
}
public static ImageView getIconImageView(StyleData style) {
try {
if (style == null || style.getIconName() == null || style.getIconName().isEmpty()) {
return null;
}
return getIconImageView(style.getIconName());
} catch (Exception e) {
MyBoxLog.error(e, style.getIconName());
return null;
}
}
public static ImageView getIconImageView(String iconName) {
if (iconName == null || iconName.isBlank()) {
return null;
}
try {
String stylePath = getIconPath();
ImageView view = null;
if (AppVariables.icons40px && iconName.endsWith(".png") && !iconName.endsWith("_40.png")) {
view = getIconImageView(stylePath, iconName.substring(0, iconName.length() - 4) + "_40.png");
}
if (view == null) {
view = getIconImageView(stylePath, iconName);
}
if (view != null) {
view.setFitWidth(AppVariables.iconSize);
view.setFitHeight(AppVariables.iconSize);
}
return view;
} catch (Exception e) {
return null;
}
}
public static ImageView getIconImageView(String stylePath, String iconName) {
try {
if (!stylePath.startsWith(ButtonsSourcePath)) {
File file = new File(stylePath + iconName);
if (!file.exists()) {
return new ImageView(ButtonsSourcePath + iconName);
} else {
return new ImageView(file.toURI().toString());
}
} else {
return new ImageView(stylePath + iconName);
}
} catch (Exception e) {
try {
return new ImageView(ButtonsSourcePath + iconName);
} catch (Exception ex) {
try {
return new ImageView(ButtonsSourcePath + "Red/" + iconName);
} catch (Exception exx) {
return null;
}
}
}
}
public static Image getIconImage(String iconName) {
ImageView view = getIconImageView(iconName);
return view == null ? null : view.getImage();
}
public static Image getSourceImage(String iconName) {
try {
if (iconName == null) {
return null;
}
ImageView view = getIconImageView(ButtonsSourcePath + "Red/", iconName);
return view.getImage();
} catch (Exception e) {
MyBoxLog.error(e, iconName);
return null;
}
}
public static BufferedImage getSourceBufferedImage(String iconName) {
try {
Image image = getSourceImage(iconName);
if (image == null) {
return null;
}
return SwingFXUtils.fromFXImage(image, null);
} catch (Exception e) {
MyBoxLog.error(e, iconName);
return null;
}
}
public static void setIcon(Node node, ImageView imageView) {
try {
if (node == null || imageView == null) {
return;
}
if (node instanceof Labeled) {
if (((Labeled) node).getGraphic() != null) {
if (node.getStyleClass().contains("big")) {
imageView.setFitWidth(AppVariables.iconSize * 2);
imageView.setFitHeight(AppVariables.iconSize * 2);
} else if (node.getStyleClass().contains("halfBig")) {
imageView.setFitWidth(AppVariables.iconSize * 1.5);
imageView.setFitHeight(AppVariables.iconSize * 1.5);
} else {
imageView.setFitWidth(AppVariables.iconSize);
imageView.setFitHeight(AppVariables.iconSize);
}
((Labeled) node).setGraphic(imageView);
}
} else if (node instanceof ImageView) {
ImageView nodev = (ImageView) node;
nodev.setImage(imageView.getImage());
if (node.getStyleClass().contains("big")) {
nodev.setFitWidth(AppVariables.iconSize * 2);
nodev.setFitHeight(AppVariables.iconSize * 2);
} else {
nodev.setFitWidth(AppVariables.iconSize * 1.2);
nodev.setFitHeight(AppVariables.iconSize * 1.2);
}
}
} catch (Exception e) {
MyBoxLog.error(e, node.getId());
}
}
public static StyleColor getColorStyle(String color) {
if (color == null) {
return StyleColor.Red;
}
for (StyleColor style : StyleColor.values()) {
if (style.name().equalsIgnoreCase(color)) {
return style;
}
}
return StyleColor.Red;
}
public static void setStyleColor(Node node) {
StyleData StyleData = getStyleData(node);
setIcon(node, StyleTools.getIconImageView(StyleData));
}
public static BufferedImage makeIcon(FxTask task, StyleColor style, String iconName) {
try {
if (iconName == null) {
return null;
}
if (style == StyleColor.Red) {
return StyleTools.getSourceBufferedImage(iconName);
}
return makeIcon(task, iconName, color(style, true), color(style, false));
} catch (Exception e) {
MyBoxLog.console(e);
return null;
}
}
public static BufferedImage makeIcon(FxTask task, String iconName, Color darkColor, Color lightColor) {
try {
BufferedImage srcImage = StyleTools.getSourceBufferedImage(iconName);
return makeIcon(task, srcImage, darkColor, lightColor);
} catch (Exception e) {
MyBoxLog.console(e);
return null;
}
}
public static BufferedImage makeIcon(FxTask task, BufferedImage srcImage, Color darkColor, Color lightColor) {
try {
if (srcImage == null || darkColor == null || lightColor == null) {
return null;
}
PixelsOperation operation = PixelsOperationFactory.replaceColorOperation(task, srcImage,
color(StyleColor.Red, true), darkColor, 20).setTask(task);
operation = PixelsOperationFactory.replaceColorOperation(task, operation.start(),
color(StyleColor.Red, false), lightColor, 20).setTask(task);
return operation.start();
} catch (Exception e) {
MyBoxLog.console(e);
return null;
}
}
public static Image makeImage(FxTask task, String iconName,
javafx.scene.paint.Color darkColor, javafx.scene.paint.Color lightColor) {
try {
BufferedImage targetImage = makeIcon(task, iconName,
FxColorTools.toAwtColor(darkColor), FxColorTools.toAwtColor(lightColor));
if (targetImage == null) {
return null;
}
return SwingFXUtils.toFXImage(targetImage, null);
} catch (Exception e) {
MyBoxLog.console(e);
return null;
}
}
/*
Tips
*/
public static void setTips(Node node) {
StyleData style = getStyleData(node);
setTips(node, style);
}
public static void setTips(Node node, String tips) {
if (tips == null || tips.isEmpty()) {
return;
}
NodeStyleTools.setTooltip(node, new Tooltip(tips));
}
public static void setTips(Node node, StyleData style) {
if (node == null || style == null) {
return;
}
if (node instanceof Control && ((Control) node).getTooltip() != null) {
return;
}
setTips(node, getTips(node, style));
}
public static String getTips(Node node, StyleData style) {
if (style == null) {
return null;
}
String tips = "";
String name = style.getName();
String comments = style.getComments();
String shortcut = style.getShortcut();
if (comments != null && !comments.isEmpty()) {
tips = comments;
if (shortcut != null && !shortcut.isEmpty()) {
tips += "\n" + shortcut;
}
} else if (name != null && !name.isEmpty()) {
tips = name;
if (shortcut != null && !shortcut.isEmpty()) {
tips += "\n" + shortcut;
}
} else if (shortcut != null && !shortcut.isEmpty()) {
tips = shortcut;
}
if (node instanceof Button && ((Button) node).isDefaultButton()) {
tips += "\nENTER";
}
return tips;
}
public static void setNameIcon(Node node, String name, String iconName) {
setIconName(node, iconName);
StyleData style = getStyleData(node);
if (style != null) {
style.setName(name);
}
setTips(node, style);
}
public static void setName(Node node, String name) {
StyleData style = getStyleData(node);
style.setName(name);
setTips(node, style);
}
public static void setIconTooltips(Node node, String iconName, String tips) {
setIconName(node, iconName);
setTips(node, tips);
}
public static void setIconName(Node node, String iconName) {
setIcon(node, StyleTools.getIconImageView(iconName));
}
/*
contents
*/
public static ContentDisplay getControlContent(String value) {
if (value == null) {
return ContentDisplay.GRAPHIC_ONLY;
}
switch (value.toLowerCase()) {
case "graphic":
return ContentDisplay.GRAPHIC_ONLY;
case "text":
return ContentDisplay.TEXT_ONLY;
case "top":
return ContentDisplay.TOP;
case "left":
return ContentDisplay.LEFT;
case "right":
return ContentDisplay.RIGHT;
case "bottom":
return ContentDisplay.BOTTOM;
case "center":
return ContentDisplay.CENTER;
default:
return ContentDisplay.GRAPHIC_ONLY;
}
}
public static ContentDisplay getConfigControlContent() {
return getControlContent(UserConfig.getString("ControlContent", "image"));
}
}
| 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/fxml/style/StyleButton.java | alpha/MyBox/src/main/java/mara/mybox/fxml/style/StyleButton.java | package mara.mybox.fxml.style;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2021-7-30
* @License Apache License Version 2.0
*/
public class StyleButton {
public static StyleData buttonStyle(String id) {
if (id == null || id.isEmpty()) {
return null;
}
StyleData data = match(id);
if (data != null) {
return data;
}
return startsWith(id);
}
public static StyleData startsWith(String id) {
if (id == null || id.isEmpty()) {
return null;
}
if (id.startsWith("ok")) {
switch (id) {
case "okButton":
return new StyleData("okButton", message("OK"), "F1 / CTRL+E / ALT+E", "iconOK.png");
default:
return new StyleData(id, message("OK"), "", "iconOK.png");
}
}
if (id.startsWith("start")) {
switch (id) {
case "startButton":
return new StyleData(id, message("Start"), "F1 / CTRL+E / ALT+E", "iconStart.png");
default:
return new StyleData(id, message("Start"), "", "iconStart.png");
}
}
if (id.startsWith("save")) {
if (id.startsWith("saveAs")) {
switch (id) {
case "saveAsButton":
return new StyleData(id, message("SaveAs"), "F5 / CTRL+B / ALT+B", "iconSaveAs.png");
default:
return new StyleData(id, message("SaveAs"), "", "iconSaveAs.png");
}
}
switch (id) {
case "saveButton":
return new StyleData(id, message("Save"), "CTRL+S / ALT+S", "iconSave.png");
case "saveTiffButton":
return new StyleData(id, message("SaveAsTiff"), "", "iconTIF.png");
case "savePdfButton":
return new StyleData(id, message("SaveAsPDF"), "", "iconPDF.png");
case "saveScopeButton":
return new StyleData(id, message("SaveScope"), "", "iconSave.png");
default:
return new StyleData(id, message("Save"), "", "iconSave.png");
}
}
if (id.startsWith("cancel")) {
switch (id) {
case "cancelButton":
return new StyleData(id, message("Cancel"), "ESC", "iconCancel.png");
default:
return new StyleData(id, message("Cancel"), "", "iconCancel.png");
}
}
if (id.startsWith("create")) {
switch (id) {
case "createButton":
return new StyleData(id, message("Create"), "CTRL+N", "iconAdd.png");
case "createDataButton":
return new StyleData(id, message("CreateData"), "", "iconAdd.png");
default:
return new StyleData(id, message("Create"), "", "iconAdd.png");
}
}
if (id.startsWith("go")) {
switch (id) {
case "goButton":
return new StyleData(id, message("Go"), "F2 / CTRL+G / ALT+G", "iconGo.png");
default:
return new StyleData(id, message("Go"), "", "iconGo.png");
}
}
if (id.startsWith("newItem")) {
return new StyleData(id, message("Add"), "", "iconNewItem.png");
}
if (id.startsWith("add")) {
switch (id) {
case "addButton":
return new StyleData(id, message("Add"), "CTRL+N / ALT+N", "iconAdd.png");
case "addRowsButton":
return new StyleData(id, message("AddRows"), "CTRL+N / ALT+N", "iconNewItem.png");
case "addFilesButton":
return new StyleData(id, message("AddFiles"), "", "iconSelectFile.png");
case "addDirectoryButton":
return new StyleData(id, message("AddDirectory"), "", "iconSelectPath.png");
case "addMenuButton":
return new StyleData(id, "", "", "iconAdd.png");
default:
return new StyleData(id, message("Add"), "", "iconAdd.png");
}
}
if (id.startsWith("pages")) {
return new StyleData(id, message("Pages"), "", "iconPages.png");
}
if (id.startsWith("makeDirectory")) {
return new StyleData(id, message("MakeDirectory"), "", "iconNewItem.png");
}
if (id.startsWith("clear")) {
switch (id) {
case "clearButton":
return new StyleData(id, message("Clear"), "CTRL+L / ALT+L", "iconClear.png");
default:
return new StyleData(id, message("Clear"), "", "iconClear.png");
}
}
if (id.startsWith("plus")) {
return new StyleData(id, message("Add"), "", "iconPlus.png");
}
if (id.startsWith("query")) {
return new StyleData(id, message("Query"), "", "iconQuery.png");
}
if (id.startsWith("reset")) {
return new StyleData(id, message("Reset"), "", "iconRecover.png");
}
if (id.startsWith("analyse")) {
return new StyleData(id, message("Analyse"), "", "iconAnalyse.png");
}
if (id.startsWith("ocr")) {
return new StyleData(id, message("OCR"), "", "iconAnalyse.png");
}
if (id.startsWith("yes")) {
return new StyleData(id, message("Yes"), "", "iconYes.png");
}
if (id.startsWith("confirm")) {
return new StyleData(id, message("Confirm"), "", "iconYes.png");
}
if (id.startsWith("complete")) {
return new StyleData(id, message("Complete"), "", "iconYes.png");
}
if (id.startsWith("select")) {
if (id.startsWith("selectFile")) {
return new StyleData(id, message("SelectFile"), "", "iconSelectFile.png");
}
if (id.startsWith("selectPath")) {
return new StyleData(id, message("SelectPath"), "", "iconSelectPath.png");
}
if (id.startsWith("selectAll")) {
switch (id) {
case "selectAllButton":
return new StyleData(id, message("SelectAll"), "CTRL+A / ALT+A", "iconSelectAll.png");
default:
return new StyleData(id, message("SelectAll"), "", "iconSelectAll.png");
}
}
if (id.startsWith("selectNone")) {
switch (id) {
case "selectNoneButton":
return new StyleData(id, message("UnselectAll"), "CTRL+O / ALT+O", "iconSelectNone.png");
default:
return new StyleData(id, message("UnselectAll"), "", "iconSelectNone.png");
}
}
if (id.startsWith("selectPixels")) {
return new StyleData(id, message("SelectPixels"), "CTRL+T / ALT+T", "iconSelect.png");
}
if (id.equalsIgnoreCase("selectButton")) {
return new StyleData(id, message("Select"), "CTRL+T / ALT+T", "iconSelect.png");
} else {
return new StyleData(id, message("Select"), "", "iconSelect.png");
}
}
if (id.startsWith("mybox")) {
return new StyleData(id, message("MainPage"), "F8", "iconMyBox.png");
}
if (id.startsWith("download")) {
return new StyleData(id, message("Download"), "", "iconDownload.png");
}
if (id.startsWith("upload")) {
return new StyleData(id, message("Upload"), "", "iconUpload.png");
}
if (id.startsWith("default")) {
return new StyleData(id, message("Default"), "", "iconDefault.png");
}
if (id.startsWith("random")) {
if (id.startsWith("randomColors")) {
return new StyleData(id, message("RandomColors"), "", "iconRandom.png");
} else {
return new StyleData(id, message("Random"), "", "iconRandom.png");
}
}
if (id.startsWith("example")) {
return new StyleData(id, message("Examples"), "", "iconExamples.png");
}
if (id.startsWith("history")) {
return new StyleData(id, message("Histories"), "", "iconHistory.png");
}
if (id.startsWith("sql")) {
return new StyleData(id, "SQL", "", "iconSQL.png");
}
if (id.startsWith("charts")) {
return new StyleData(id, message("Charts"), "", "iconCharts.png");
}
if (id.startsWith("recover")) {
switch (id) {
case "recoverButton":
return new StyleData("recoverButton", message("Recover"), "CTRL+R / ALT+R", "iconRecover.png");
default:
return new StyleData(id, message("Recover"), "", "iconRecover.png");
}
}
if (id.startsWith("zoomIn")) {
switch (id) {
case "zoomInButton":
return new StyleData(id, message("ZoomIn"), "CTRL+3", "iconZoomIn.png");
default:
return new StyleData(id, message("ZoomIn"), "", "iconZoomIn.png");
}
}
if (id.startsWith("zoomOut")) {
switch (id) {
case "zoomOutButton":
return new StyleData(id, message("ZoomOut"), "CTRL+4", "iconZoomOut.png");
default:
return new StyleData(id, message("ZoomOut"), "", "iconZoomOut.png");
}
}
if (id.startsWith("copyToSystemClipboard")) {
return new StyleData(id, message("CopyToSystemClipboard"), "", "iconCopySystem.png");
}
if (id.startsWith("copyToMyBoxClipboard")) {
return new StyleData(id, message("CopyToMyBoxClipboard"), "", "iconCopy.png");
}
if (id.startsWith("CopyToClipboards")) {
return new StyleData(id, message("CopyToClipboards"), "", "iconCopy.png");
}
if (id.startsWith("copy")) {
switch (id) {
case "copyButton":
return new StyleData(id, message("Copy"), "CTRL+C / ALT+C ", "iconCopy.png");
case "copyEnglishButton":
return new StyleData(id, message("CopyEnglish"), "CTRL+E / ALT+E ", "iconCopy.png");
default:
return new StyleData(id, message("Copy"), "", "iconCopy.png");
}
}
if (id.startsWith("paste")) {
switch (id) {
case "pasteButton":
return new StyleData(id, message("Paste"), "CTRL+V / ALT+V", "iconPaste.png");
case "pasteTxtButton":
return new StyleData(id, message("PasteTextAsHtml"), "", "iconPaste.png");
case "pasteContentInSystemClipboardButton":
return new StyleData(id, message("PasteContentInSystemClipboard"), "", "iconPasteSystem.png");
case "pasteContentInDataClipboardButton":
return new StyleData(id, message("PasteContentInMyBoxClipboard"), "", "iconPaste.png");
default:
return new StyleData(id, message("Paste"), "", "iconPaste.png");
}
}
if (id.startsWith("next")) {
switch (id) {
case "nextButton":
return new StyleData(id, message("Next"), "PAGE DOWN", "iconNext.png");
case "nextFileButton":
return new StyleData(id, message("NextFile"), "", "iconNext.png");
default:
return new StyleData(id, message("Next"), "", "iconNext.png");
}
}
if (id.startsWith("previous")) {
switch (id) {
case "previousButton":
return new StyleData(id, message("Previous"), "PAGE UP", "iconPrevious.png");
case "previousFileButton":
return new StyleData(id, message("PreviousFile"), "", "iconPrevious.png");
default:
return new StyleData(id, message("Previous"), "", "iconPrevious.png");
}
}
if (id.startsWith("backward")) {
return new StyleData(id, message("Backward"), "", "iconPrevious.png");
}
if (id.startsWith("forward")) {
return new StyleData(id, message("Forward"), "", "iconNext.png");
}
if (id.startsWith("more")) {
return new StyleData(id, message("More"), "", "iconMore.png");
}
if (id.startsWith("palette")) {
switch (id) {
case "paletteManageButton":
return new StyleData(id, message("ColorPaletteManage"), "", "iconPalette.png");
case "paletteAddInButton":
return new StyleData(id, message("AddInColorPalette"), "", "iconPalette.png");
default:
return new StyleData(id, message("ColorPalette"), "", "iconPalette.png");
}
}
if (id.startsWith("color")) {
switch (id) {
case "colorsButton":
return new StyleData(id, message("Colors"), "", "iconColor.png");
default:
return new StyleData(id, message("Color"), "", "iconColor.png");
}
}
if (id.startsWith("pixels")) {
return new StyleData(id, message("Pixels"), "", "iconMatrix.png");
}
if (id.startsWith("open")) {
if (id.startsWith("openPath") || id.startsWith("openTarget") || id.startsWith("openSource")) {
return new StyleData(id, message("OpenDirectory"), "", "iconOpenPath.png");
}
return new StyleData(id, message("Open"), "", "iconSelectFile.png");
}
if (id.startsWith("delete")) {
switch (id) {
case "deleteButton":
return new StyleData(id, message("Delete"), "DELETE / CTRL+D / ALT+D", "iconDelete.png");
case "deleteRowsButton":
return new StyleData(id, message("DeleteRows"), "DELETE / CTRL+D / ALT+D", "iconDelete.png");
default:
return new StyleData(id, message("Delete"), "", "iconDelete.png");
}
}
if (id.startsWith("input")) {
return new StyleData(id, message("Input"), "", "iconInput.png");
}
if (id.startsWith("suggestion")) {
return new StyleData(id, message("CodeCompletionSuggestions"), "CTRL+1 / ALT+1", "iconInput.png");
}
if (id.startsWith("verify")) {
return new StyleData(id, message("Validate"), "", "iconVerify.png");
}
if (id.startsWith("data")) {
if (id.startsWith("dataManufacture")) {
return new StyleData(id, message("DataManufacture"), "", "iconData.png");
} else if (id.startsWith("database")) {
return new StyleData(id, message("DatabaseTable"), "", "iconDatabase.png");
} else if (id.startsWith("dataDefinition")) {
return new StyleData(id, message("DefineData"), "", "iconMeta.png");
} else if (id.startsWith("dataImport")) {
return new StyleData(id, message("Import"), "", "iconImport.png");
} else if (id.startsWith("dataExport")) {
return new StyleData(id, message("Export"), "", "iconExport.png");
} else if (id.startsWith("dataA")) {
return new StyleData(id, message("SetAsDataA"), "", "iconA.png");
} else if (id.startsWith("dataBB")) {
return new StyleData(id, message("SetAsDataB"), "", "iconB.png");
} else {
return new StyleData(id, message("Data"), "", "iconData.png");
}
}
if (id.startsWith("query")) {
return new StyleData(id, message("Query"), "", "iconData.png");
}
if (id.startsWith("map")) {
return new StyleData(id, message("Map"), "", "iconMap.png");
}
if (id.startsWith("import")) {
return new StyleData(id, message("Import"), "", "iconImport.png");
}
if (id.startsWith("export")) {
return new StyleData(id, message("Export"), "", "iconExport.png");
}
if (id.startsWith("sureButton")) {
return new StyleData(id, message("Sure"), "", "iconYes.png");
}
if (id.startsWith("fill")) {
return new StyleData(id, message("Fill"), "", "iconButterfly.png");
}
if (id.startsWith("cat")) {
return new StyleData(id, message("Meow"), "", "iconCat.png");
}
if (id.startsWith("help")) {
return new StyleData(id, message("HelpMe"), "", "iconClaw.png");
}
if (id.startsWith("edit")) {
if (id.startsWith("editFrames")) {
return new StyleData(id, message("ImagesEditor"), "", "iconThumbsList.png");
}
return new StyleData(id, message("Edit"), "", "iconEdit.png");
}
if (id.startsWith("size")) {
return new StyleData(id, message("Size"), "", "iconSplit.png");
}
if (id.startsWith("equal")) {
return new StyleData(id, message("EqualTo"), "", "iconEqual.png");
}
if (id.startsWith("use")) {
return new StyleData(id, message("Use"), "", "iconYes.png");
}
if (id.startsWith("refresh")) {
return new StyleData(id, message("Refresh"), "", "iconRefresh.png");
}
if (id.startsWith("manufacture")) {
return new StyleData(id, message("Manufacture"), "", "iconEdit.png");
}
if (id.startsWith("run")) {
return new StyleData(id, message("Run"), "", "iconRun.png");
}
if (id.startsWith("info")) {
switch (id) {
case "infoButton":
return new StyleData(id, message("Information"), "CTRL+I", "iconInfo.png");
default:
return new StyleData(id, message("Information"), "", "iconInfo.png");
}
}
if (id.startsWith("view")) {
switch (id) {
case "viewFileButton":
return new StyleData(id, message("Open"), "", "iconView.png");
default:
return new StyleData(id, message("View"), "", "iconView.png");
}
}
if (id.startsWith("html")) {
return new StyleData(id, message("Html"), "", "iconHtml.png");
}
if (id.startsWith("pdf")) {
return new StyleData(id, "PDF", "", "iconPDF.png");
}
if (id.startsWith("link")) {
return new StyleData(id, message("Link"), "", "iconLink.png");
}
if (id.startsWith("stop")) {
return new StyleData(id, message("Stop"), "", "iconStop.png");
}
if (id.startsWith("synchronize")) {
switch (id) {
case "synchronizeButton":
return new StyleData(id, message("SynchronizeChangesToOtherPanes"), "F10", "iconSynchronize.png");
default:
return new StyleData(id, message("SynchronizeChangesToOtherPanes"), "", "iconSynchronize.png");
}
}
if (id.startsWith("function")) {
return new StyleData(id, message("Functions"), "", "iconFunction.png");
}
if (id.startsWith("style")) {
return new StyleData(id, message("Style"), "", "iconStyle.png");
}
if (id.startsWith("paneSize")) {
switch (id) {
case "paneSizeButton":
return new StyleData(id, message("PaneSize"), "CTRL+2", "iconPaneSize.png");
default:
return new StyleData(id, message("PaneSize"), "", "iconPaneSize.png");
}
}
if (id.startsWith("panes")) {
return new StyleData(id, message("Panes"), "", "iconPanes.png");
}
if (id.startsWith("extract")) {
return new StyleData(id, message("Extract"), "", "iconExtract.png");
}
if (id.startsWith("demo")) {
return new StyleData(id, message("Demo"), "", "iconDemo.png");
}
if (id.startsWith("count")) {
return new StyleData(id, message("Count"), "", "iconCalculator.png");
}
if (id.startsWith("delimiter")) {
return new StyleData(id, message("Delimiter"), "", "iconDelimiter.png");
}
if (id.startsWith("comma")) {
return new StyleData(id, message("Comma"), "", "iconDelimiter.png");
}
if (id.startsWith("matrix")) {
if (id.startsWith("matrixA")) {
return new StyleData(id, message("SetAsMatrixA"), "", "iconA.png");
} else if (id.startsWith("matrixB")) {
return new StyleData(id, message("SetAsMatrixB"), "", "iconB.png");
} else {
return new StyleData(id, message("Matrix"), "", "iconMatrix.png");
}
}
if (id.startsWith("tableDefinition")) {
return new StyleData(id, message("TableDefinition"), "", "iconInfo.png");
}
if (id.startsWith("width")) {
return new StyleData(id, message("Width"), "", "iconXRuler.png");
}
if (id.startsWith("preview")) {
switch (id) {
case "previewButton":
return new StyleData(id, message("Preview"), "F3 / CTRL+U / ALT+U", "iconPreview.png");
default:
return new StyleData(id, message("Preview"), "", "iconPreview.png");
}
}
if (id.startsWith("rotateLeft")) {
return new StyleData(id, message("RotateLeft"), "", "iconRotateLeft.png");
}
if (id.startsWith("rotateRight")) {
return new StyleData(id, message("RotateRight"), "", "iconRotateRight.png");
}
if (id.startsWith("turnOver")) {
return new StyleData(id, message("TurnOver"), "", "iconTurnOver.png");
}
if (id.startsWith("rename")) {
return new StyleData(id, message("Rename"), "", "iconInput.png");
}
if (id.startsWith("header")) {
return new StyleData(id, "", "", "iconHeader.png");
}
if (id.startsWith("list")) {
return new StyleData(id, message("List"), "", "iconList.png");
}
if (id.startsWith("codes")) {
return new StyleData(id, message("Codes"), "", "iconMeta.png");
}
if (id.startsWith("fold")) {
return new StyleData(id, message("Fold"), "", "iconMinus.png");
}
if (id.startsWith("unfold")) {
return new StyleData(id, message("Unfold"), "", "iconPlus.png");
}
if (id.startsWith("moveData")) {
return new StyleData(id, message("Move"), "", "iconMove.png");
}
if (id.startsWith("tree")) {
if (id.startsWith("treeLocate")) {
return new StyleData(id, message("Locate"), "", "iconTree.png");
} else {
return new StyleData(id, message("DataTree"), "", "iconTree.png");
}
}
if (id.startsWith("csv")) {
return new StyleData(id, "CSV", "", "iconCSV.png");
}
if (id.startsWith("excel")) {
return new StyleData(id, "Excel", "", "iconExcel.png");
}
if (id.startsWith("ssl")) {
return new StyleData(id, "SSL", "", "iconSSL.png");
}
if (id.startsWith("github")) {
return new StyleData(id, "github", "", "iconGithub.png");
}
if (id.startsWith("txt")) {
return new StyleData(id, message("Texts"), "", "iconTxt.png");
}
if (id.startsWith("clipboard")) {
return new StyleData(id, message("Clipboard"), "", "iconClipboard.png");
}
if (id.startsWith("myBoxClipboard")) {
return new StyleData(id, message("MyBoxClipboard"), "CTRL+M", "iconClipboard.png");
}
if (id.startsWith("systemClipboard")) {
return new StyleData(id, message("SystemClipboard"), "CTRL+J", "iconSystemClipboard.png");
}
if (id.startsWith("loadContentInSystemClipboard")) {
return new StyleData(id, message("LoadContentInSystemClipboard"), "", "iconImageSystem.png");
}
if (id.startsWith("number")) {
return new StyleData(id, "", "", "iconNumber.png");
}
if (id.startsWith("trim")) {
if (id.startsWith("trimData")) {
return new StyleData(id, message("Trim"), "", "iconClean.png");
} else {
return new StyleData(id, "", "", "iconNumber.png");
}
}
if (id.startsWith("lowerLetter")) {
return new StyleData(id, "", "", "iconLowerLetter.png");
}
if (id.startsWith("upperLetter")) {
return new StyleData(id, "", "", "iconUpperLetter.png");
}
if (id.startsWith("character")) {
return new StyleData(id, "", "", "iconCharacter.png");
}
if (id.startsWith("menu")) {
switch (id) {
case "menuButton":
return new StyleData(id, message("ContextMenuTips"), "", "iconMenu.png");
default:
return new StyleData(id, message("ContextMenu"), "", "iconMenu.png");
}
}
if (id.startsWith("close")) {
if (id.startsWith("closePop")) {
return new StyleData(id, message("Close"), "ESC", "iconCancel.png");
}
switch (id) {
case "closeButton":
return new StyleData("closeButton", message("Close"), "", "iconClose.png");
default:
return new StyleData(id, message("Close"), "", "iconClose.png");
}
}
if (id.startsWith("disconnect")) {
return new StyleData(id, message("Disconnect"), "", "iconClose.png");
}
if (id.startsWith("permission")) {
return new StyleData(id, message("Permissions"), "", "iconPermission.png");
}
if (id.startsWith("message")) {
return new StyleData(id, message("SendMessage"), "", "iconMessage.png");
}
if (id.startsWith("pop")) {
switch (id) {
case "popButton":
return new StyleData(id, message("Pop"), "CTRL+P / ALT+P", "iconPop.png");
case "popScopeButton":
return new StyleData(id, message("PopScope"), "", "iconTarget.png");
default:
return new StyleData(id, message("Pop"), "", "iconPop.png");
}
}
if (id.startsWith("play")) {
switch (id) {
case "playButton":
return new StyleData(id, message("Play"), "F1 / CTRL+E / ALT+E", "iconPlay.png");
default:
return new StyleData(id, message("Play"), "", "iconPlay.png");
}
}
if (id.startsWith("sort")) {
return new StyleData(id, message("Sort"), "", "iconSort.png");
}
if (id.startsWith("minus")) {
return new StyleData(id, message("Minus"), "", "iconMinus.png");
}
if (id.startsWith("calculate")) {
return new StyleData(id, message("Calculate"), "", "iconCalculator.png");
}
if (id.startsWith("columnsAdd")) {
return new StyleData(id, message("AddColumns"), "", "iconColumnAdd.png");
}
if (id.startsWith("set")) {
switch (id) {
case "setButton":
return new StyleData(id, message("Set"), "", "iconEqual.png");
case "setAllOrSelectedButton":
return new StyleData(id, message("SetAllOrSelected"), "", "iconEqual.png");
case "setValuesButton":
return new StyleData(id, message("SetValues"), "", "iconEqual.png");
case "settingsClearButton":
return new StyleData(id, message("ClearPersonalSettings"), "", "iconClear.png");
case "settingsOpenButton":
return new StyleData(id, message("OpenDataPath"), "", "iconOpenPath.png");
case "settingsRecentOKButton":
return new StyleData(id, message("OK"), "", "iconOK.png");
case "settingsJVMButton":
return new StyleData(id, message("OK"), "", "iconOK.png");
case "settingsRecentClearButton":
return new StyleData(id, message("Clear"), "", "iconClear.png");
case "settingsChangeRootButton":
return new StyleData(id, message("Change"), "", "iconOK.png");
case "settingsImageHisOKButton":
return new StyleData(id, message("OK"), "", "iconOK.png");
case "settingsImageHisNoButton":
return new StyleData(id, message("NotRecord"), "", "iconCancel.png");
case "settingsImageHisClearButton":
return new StyleData(id, message("Clear"), "", "iconClear.png");
default:
return new StyleData(id, message("Set"), "", "iconEqual.png");
}
}
if (id.startsWith("hex")) {
return new StyleData(id, message("FormattedHexadecimal"), "", "iconHex.png");
}
if (id.startsWith("operation")) {
return new StyleData(id, message("Operations"), "", "iconOperation.png");
}
if (id.startsWith("location")) {
return new StyleData(id, message("Location"), "", "iconLocation.png");
}
if (id.startsWith("locate")) {
return new StyleData(id, message("Locate"), "", "iconLocation.png");
}
if (id.startsWith("imageSize")) {
switch (id) {
case "imageSizeButton":
return new StyleData(id, message("LoadedSize"), "CTRL+1", "iconLoadSize.png");
default:
return new StyleData(id, message("LoadedSize"), "", "iconLoadSize.png");
}
}
if (id.startsWith("validate")) {
return new StyleData(id, message("Validate"), "", "iconAnalyse.png");
}
if (id.startsWith("script")) {
return new StyleData(id, message("Script"), "", "iconScript.png");
}
if (id.startsWith("moveUp")) {
return new StyleData(id, message("MoveUp"), "", "iconUp.png");
}
if (id.startsWith("moveDown")) {
return new StyleData(id, message("MoveDown"), "", "iconDown.png");
}
if (id.startsWith("moveLeft")) {
return new StyleData(id, message("MoveLeft"), "", "iconLeft.png");
}
if (id.startsWith("moveRight")) {
return new StyleData(id, message("MoveRight"), "", "iconRight.png");
}
if (id.startsWith("insert")) {
switch (id) {
case "insertFilesButton":
return new StyleData("insertFilesButton", message("InsertFiles"), "", "iconInsertFile.png");
case "insertDirectoryButton":
return new StyleData("insertDirectoryButton", message("InsertDirectory"), "", "iconInsertPath.png");
default:
return new StyleData(id, message("Insert"), "", "iconInsert.png");
}
}
if (id.startsWith("XYChart")) {
return new StyleData(id, message("XYChart"), "", "iconXYChart.png");
}
if (id.startsWith("jar")) {
return new StyleData(id, message("JarFile"), "", "iconJar.png");
}
if (id.startsWith("options")) {
return new StyleData(id, message("Options"), "", "iconOptions.png");
}
| 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/fxml/style/StyleCheckBox.java | alpha/MyBox/src/main/java/mara/mybox/fxml/style/StyleCheckBox.java | package mara.mybox.fxml.style;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2021-7-30
* @License Apache License Version 2.0
*/
public class StyleCheckBox {
public static StyleData checkBoxStyle(String id) {
if (id == null || id.isEmpty()) {
return null;
}
StyleData data = match(id);
if (data != null) {
return data;
}
return startsWith(id);
}
private static StyleData match(String id) {
switch (id) {
case "popMenuCheck":
return new StyleData(id, message("PopWindowWhenMouseHovering"), "", "iconPop.png");
case "closeNemuCheck":
return new StyleData(id, message("CloseAfterPaste"), "", "iconClose.png");
case "clearInputCheck":
return new StyleData(id, message("ClearAndPaste"), "", "iconClear.png");
case "tableThumbCheck":
return new StyleData("tableThumbCheck", "", message("Thumbnail"), "", "iconThumbsList.png");
case "openCheck":
return new StyleData("openCheck", "", message("OpenWhenComplete"), "", "iconOpenPath.png");
case "thumbCheck":
return new StyleData("thumbCheck", "", message("Thumbnails"), "", "iconBrowse.png");
case "rulerXCheck":
return new StyleData("rulerXCheck", "", message("Rulers"), "", "iconXRuler.png");
case "gridCheck":
return new StyleData(id, message("GridLines"), "", "iconGrid.png");
case "statisticCheck":
return new StyleData("statisticCheck", "", message("Statistic"), "", "iconStatistic.png");
case "transparentBackgroundCheck":
return new StyleData(id, message("TransparentBackground"), "", "iconOpacity.png");
case "transparentCheck":
return new StyleData(id, message("CountTransparent"), "", "iconOpacity.png");
case "displaySizeCheck":
return new StyleData("displaySizeCheck", "", message("DisplaySize"), "", "iconNumber.png");
case "closeAfterCheck":
return new StyleData(id, message("CloseAfterHandled"), "", "iconClose.png");
case "deskewCheck":
return new StyleData("deskewCheck", "", message("Deskew"), "", "iconShear.png");
case "invertCheck":
return new StyleData("invertCheck", "", message("Invert"), "", "iconInvert.png");
case "pickColorCheck":
return new StyleData(id, message("PickColor"), "CTRL+K / ALT+K", "iconPickColor.png");
case "ditherCheck":
return new StyleData(id, message("DitherComments"), "", "");
case "withNamesCheck":
case "sourceWithNamesCheck":
case "targetWithNamesCheck":
return new StyleData(id, message("FirstLineAsNamesComments"), "", "");
case "clearDataWhenLoadImageCheck":
return new StyleData(id, message("ClearDataWhenLoadImage"), "", "iconClear.png");
case "shapeCanMoveCheck":
return new StyleData(id, message("ShapeCanMove"), "", "iconMove.png");
case "onTopCheck":
return new StyleData(id, message("AlwayOnTopComments"), "CTRL+0 / ALT+0", "iconTop.png");
case "synchronizeSwitchCheck":
return new StyleData(id, message("SynchronizeWhenSwitchFormat"), "", "iconSynchronize.png");
case "keepRatioCheck":
return new StyleData(id, message("KeepRatio"), "", "iconAspectRatio.png");
case "scopeExcludeCheck":
return new StyleData(id, message("ScopeExclude"), "", "iconInvert.png");
}
return null;
}
private static StyleData startsWith(String id) {
if (id.startsWith("leftPane")) {
return new StyleData(id, message("ControlLeftPane"), "", "iconDoubleLeft.png");
}
if (id.startsWith("rightPane")) {
return new StyleData(id, message("ControlRightPane"), "", "iconDoubleRight.png");
}
if (id.startsWith("contextMenu")) {
return new StyleData(id, message("ContextMenu"), "", "iconMenu.png");
}
if (id.startsWith("toolbar")) {
return new StyleData(id, message("Toolbar"), "", "iconPanes.png");
}
if (id.startsWith("tips")) {
return new StyleData(id, message("Tips"), "", "iconTips.png");
}
if (id.startsWith("handleTransparent")) {
return new StyleData(id, message("HandleTransparent"), "", "iconOpacity.png");
}
if (id.startsWith("eightNeighbor")) {
return new StyleData(id, message("EightNeighborCheckComments"), "", "");
}
if (id.startsWith("openPath")) {
return new StyleData(id, message("OpenDirectory"), "", "iconOpenPath.png");
}
if (id.startsWith("wrap")) {
return new StyleData(id, message("Wrap"), "", "iconWrap.png");
}
if (id.startsWith("editable")) {
return new StyleData(id, message("Editable"), "", "iconEdit.png");
}
if (id.startsWith("childWindow")) {
return new StyleData(id, message("ChildWindowTips"), "", "iconWindow.png");
}
if (id.startsWith("scope")) {
return new StyleData(id, message("Scope"), "", "iconTarget.png");
}
if (id.startsWith("csv")) {
return new StyleData(id, "CSV", "", "iconCSV.png");
}
if (id.startsWith("excel")) {
return new StyleData(id, "Excel", "", "iconExcel.png");
}
if (id.startsWith("texts")) {
return new StyleData(id, message("Texts"), "", "iconTxt.png");
}
if (id.startsWith("matrix")) {
return new StyleData(id, message("Matrix"), "", "iconMatrix.png");
}
if (id.startsWith("database")) {
return new StyleData(id, message("DatabaseTable"), "", "iconDatabase.png");
}
if (id.startsWith("systemClipboard")) {
return new StyleData(id, message("SystemClipboard"), "", "iconSystemClipboard.png");
}
if (id.startsWith("myBoxClipboard")) {
return new StyleData(id, message("MyBoxClipboard"), "", "iconClipboard.png");
}
if (id.startsWith("html")) {
return new StyleData(id, "Html", "", "iconHtml.png");
}
if (id.startsWith("xml")) {
return new StyleData(id, "XML", "", "iconXML.png");
}
if (id.startsWith("pdf")) {
return new StyleData(id, "PDF", "", "iconPDF.png");
}
if (id.startsWith("json")) {
return new StyleData(id, "json", "", "iconJSON.png");
}
if (id.startsWith("coordinate")) {
return new StyleData(id, message("Coordinate"), "", "iconLocation.png");
}
if (id.startsWith("refreshSwitch")) {
return new StyleData(id, message("RefreshWhenSwitch"), "", "iconRefreshSwitch.png");
}
if (id.startsWith("refreshChange")) {
return new StyleData(id, message("RefreshWhenChange"), "", "iconRefresh.png");
}
if (id.startsWith("nodesList")) {
return new StyleData(id, message("List"), "", "iconList.png");
}
if (id.startsWith("verify")) {
return new StyleData(id, message("Validate"), "", "iconVerify.png");
}
if (id.startsWith("miao")) {
return new StyleData(id, message("Meow"), message("MiaoPrompt"), "", "iconCat.png");
}
if (id.startsWith("format")) {
return new StyleData(id, message("TypesettingWhenWrite"), "", "iconFormat.png");
}
if (id.startsWith("typesetting")) {
return new StyleData(id, message("TypesettingWhenWrite"), "", "iconFormat.png");
}
if (id.startsWith("lostFocusCommit")) {
return new StyleData(id, message("CommitModificationWhenDataCellLoseFocusComments"), "", "iconInput.png");
}
if (id.startsWith("view")) {
return new StyleData(id, message("View"), "", "iconView.png");
}
if (id.startsWith("pop")) {
switch (id) {
case "popAnchorMenuCheck":
return new StyleData(id, message("PopAnchorMenu"), "", "iconShape.png");
case "popLineMenuCheck":
return new StyleData(id, message("PopLineMenu"), "", "iconShape.png");
default:
return new StyleData(id, message("Pop"), "", "iconPop.png");
}
}
if (id.startsWith("anchor")) {
return new StyleData(id, message("ShowAnchors"), "", "iconAnchor.png");
}
if (id.startsWith("addPoint")) {
return new StyleData(id, message("AddPointWhenLeftClick"), "", "iconNewItem.png");
}
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/fxml/style/NodeStyleTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/style/NodeStyleTools.java | package mara.mybox.fxml.style;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Control;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.SplitPane;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TitledPane;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.Pane;
import javafx.scene.text.Font;
import javafx.util.Duration;
import mara.mybox.controller.BaseController;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.value.AppVariables;
import mara.mybox.value.Colors;
/**
* @Author Mara
* @CreateDate 2021-8-5
* @License Apache License Version 2.0
*/
public class NodeStyleTools {
public static String errorDataStyle() {
return "-fx-background-color: #FFF0F5;";
}
public static String attributeTextStyle() {
return "-fx-text-fill: #"
+ Colors.colorValue(AppVariables.ControlColor, true)
+ ";";
}
public static String redTextStyle() {
return "-fx-text-fill: #961c1c;";
}
public static String darkRedTextStyle() {
return "-fx-text-fill: #961c1c; -fx-font-weight: bolder;";
}
public static String linkStyle() {
return "-fx-text-fill: blue;";
}
public static String selectedDataStyle() {
return "-fx-background-color: #0096C9; -fx-text-background-color: white;";
}
public static String selectedRowStyle() {
return "-fx-background-color: lightgray; -fx-text-fill: -fx-selection-bar-text;";
}
public static void applyStyle(Node node) {
try {
if (node == null) {
return;
}
// Base styles are width in first
StyleTools.setStyle(node);
if (node instanceof SplitPane) {
for (Node child : ((SplitPane) node).getItems()) {
applyStyle(child);
}
} else if (node instanceof ScrollPane) {
applyStyle(((ScrollPane) node).getContent());
} else if (node instanceof TitledPane) {
applyStyle(((TitledPane) node).getContent());
} else if (node instanceof TabPane) {
for (Tab tab : ((TabPane) node).getTabs()) {
applyStyle(tab.getContent());
}
} else if (node instanceof Parent) {
for (Node child : ((Parent) node).getChildrenUnmodifiable()) {
applyStyle(child);
}
}
// Special styles are deep in first
Object o = node.getUserData();
if (o != null && o instanceof BaseController) {
BaseController c = (BaseController) o;
c.setControlsStyle();
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void refreshStyle(Parent node) {
try {
if (node == null) {
return;
}
applyStyle(node);
node.applyCss();
node.layout();
} catch (Exception e) {
MyBoxLog.console(e);
}
}
public static boolean setStyle(Pane pane, String nodeId, String style) {
try {
Node node = pane.lookup("#" + nodeId);
return setStyle(node, style);
} catch (Exception e) {
return false;
}
}
public static boolean setStyle(Node node, String style) {
try {
if (node == null) {
return false;
}
if (node instanceof ComboBox) {
ComboBox c = (ComboBox) node;
c.getEditor().setStyle(style);
} else {
node.setStyle(style);
}
return true;
} catch (Exception e) {
return false;
}
}
public static void setTooltip(final Node node, Node tip) {
if (node instanceof Control) {
removeTooltip((Control) node);
}
Tooltip tooltip = new Tooltip();
tooltip.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
tooltip.setGraphic(tip);
tooltip.setShowDelay(Duration.millis(10));
tooltip.setShowDuration(Duration.millis(360000));
tooltip.setHideDelay(Duration.millis(10));
Tooltip.install(node, tooltip);
}
public static void setTooltip(final Node node, String tips) {
setTooltip(node, new Tooltip(tips));
}
public static Tooltip getTooltip(final Node node) {
try {
return (Tooltip) node.getProperties().get("javafx.scene.control.Tooltip");
} catch (Exception e) {
return null;
}
}
public static String getTips(final Node node) {
try {
Tooltip t = getTooltip(node);
if (t == null) {
return null;
}
return t.getText();
} catch (Exception e) {
return null;
}
}
public static void setTooltip(final Node node, final Tooltip tooltip) {
try {
if (node instanceof Control) {
removeTooltip((Control) node);
}
tooltip.setFont(new Font(AppVariables.sceneFontSize));
tooltip.setShowDelay(Duration.millis(10));
tooltip.setShowDuration(Duration.millis(360000));
tooltip.setHideDelay(Duration.millis(10));
Tooltip.install(node, tooltip);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public static void removeTooltip(final Control node) {
Tooltip.uninstall(node, node.getTooltip());
}
public static void removeTooltip(final Node node, final Tooltip tooltip) {
Tooltip.uninstall(node, tooltip);
}
}
| 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/fxml/converter/ShortStringFromatConverter.java | alpha/MyBox/src/main/java/mara/mybox/fxml/converter/ShortStringFromatConverter.java | package mara.mybox.fxml.converter;
import javafx.util.StringConverter;
/**
* @Author Mara
* @CreateDate 2021-11-12
* @License Apache License Version 2.0
*/
public class ShortStringFromatConverter extends StringConverter<Short> {
@Override
public Short fromString(String value) {
try {
return Short.parseShort(value.trim().replaceAll(",", ""));
} catch (Exception e) {
return null;
}
}
@Override
public String toString(Short value) {
try {
return value.toString();
} catch (Exception e) {
return "";
}
}
}
| 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/fxml/converter/EraStringConverter.java | alpha/MyBox/src/main/java/mara/mybox/fxml/converter/EraStringConverter.java | package mara.mybox.fxml.converter;
import javafx.util.StringConverter;
import mara.mybox.data.Era;
import mara.mybox.tools.DateTools;
/**
* @Author Mara
* @CreateDate 2021-10-25
* @License Apache License Version 2.0
*/
public class EraStringConverter extends StringConverter<Era> {
@Override
public Era fromString(String value) {
try {
if (value == null) {
return (null);
}
value = value.trim();
if (value.length() < 1) {
return (null);
}
return new Era(value);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@Override
public String toString(Era value) {
return DateTools.textEra(value);
}
}
| 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/fxml/converter/LocalDateStringConverter.java | alpha/MyBox/src/main/java/mara/mybox/fxml/converter/LocalDateStringConverter.java | package mara.mybox.fxml.converter;
import java.time.LocalDate;
import javafx.util.StringConverter;
import mara.mybox.tools.DateTools;
/**
* @Author Mara
* @CreateDate 2021-10-25
* @License Apache License Version 2.0
*/
public class LocalDateStringConverter extends StringConverter<LocalDate> {
@Override
public LocalDate fromString(String value) {
return DateTools.stringToLocalDate(value);
}
@Override
public String toString(LocalDate value) {
return DateTools.localDateToString(value);
}
}
| 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/fxml/converter/LongStringFromatConverter.java | alpha/MyBox/src/main/java/mara/mybox/fxml/converter/LongStringFromatConverter.java | package mara.mybox.fxml.converter;
import javafx.util.StringConverter;
import mara.mybox.tools.StringTools;
/**
* @Author Mara
* @CreateDate 2021-11-12
* @License Apache License Version 2.0
*/
public class LongStringFromatConverter extends StringConverter<Long> {
@Override
public Long fromString(String value) {
try {
return Long.parseLong(value.trim().replaceAll(",", ""));
} catch (Exception e) {
return null;
}
}
@Override
public String toString(Long value) {
try {
return StringTools.format(value);
} catch (Exception e) {
return "";
}
}
}
| 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/fxml/converter/ColorStringConverter.java | alpha/MyBox/src/main/java/mara/mybox/fxml/converter/ColorStringConverter.java | package mara.mybox.fxml.converter;
import javafx.scene.paint.Color;
import javafx.util.StringConverter;
/**
* @Author Mara
* @CreateDate 2022-1-23
* @License Apache License Version 2.0
*/
public class ColorStringConverter extends StringConverter<Color> {
@Override
public Color fromString(String value) {
try {
return Color.web(value);
} catch (Exception e) {
return null;
}
}
@Override
public String toString(Color value) {
try {
return value.toString();
} catch (Exception e) {
return "";
}
}
}
| 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/fxml/converter/DoubleStringFromatConverter.java | alpha/MyBox/src/main/java/mara/mybox/fxml/converter/DoubleStringFromatConverter.java | package mara.mybox.fxml.converter;
import javafx.util.StringConverter;
/**
* @Author Mara
* @CreateDate 2021-11-12
* @License Apache License Version 2.0
*/
public class DoubleStringFromatConverter extends StringConverter<Double> {
@Override
public Double fromString(String value) {
try {
return Double.valueOf(value.trim().replaceAll(",", ""));
} catch (Exception e) {
return null;
}
}
@Override
public String toString(Double value) {
try {
return value.toString();
} catch (Exception e) {
return "";
}
}
}
| 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/fxml/converter/FloatStringFromatConverter.java | alpha/MyBox/src/main/java/mara/mybox/fxml/converter/FloatStringFromatConverter.java | package mara.mybox.fxml.converter;
import javafx.util.StringConverter;
/**
* @Author Mara
* @CreateDate 2021-11-12
* @License Apache License Version 2.0
*/
public class FloatStringFromatConverter extends StringConverter<Float> {
@Override
public Float fromString(String value) {
try {
return Float.parseFloat(value.trim().replaceAll(",", ""));
} catch (Exception e) {
return null;
}
}
@Override
public String toString(Float value) {
try {
return value.toString();
} catch (Exception e) {
return "";
}
}
}
| 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/fxml/converter/IntegerStringFromatConverter.java | alpha/MyBox/src/main/java/mara/mybox/fxml/converter/IntegerStringFromatConverter.java | package mara.mybox.fxml.converter;
import javafx.util.StringConverter;
import mara.mybox.tools.StringTools;
/**
* @Author Mara
* @CreateDate 2021-11-12
* @License Apache License Version 2.0
*/
public class IntegerStringFromatConverter extends StringConverter<Integer> {
@Override
public Integer fromString(String value) {
try {
return Integer.parseInt(value.trim().replaceAll(",", ""));
} catch (Exception e) {
return null;
}
}
@Override
public String toString(Integer value) {
try {
return StringTools.format(value);
} catch (Exception e) {
return "";
}
}
}
| 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/fxml/chart/ChartTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/chart/ChartTools.java | package mara.mybox.fxml.chart;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javafx.scene.Node;
import javafx.scene.chart.Chart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.PieChart;
import javafx.scene.chart.XYChart;
import javafx.scene.control.Label;
import mara.mybox.fxml.image.FxColorTools;
import mara.mybox.fxml.SquareRootCoordinate;
/**
* @Author Mara
* @CreateDate 2021-7-29
* @License Apache License Version 2.0
*/
public class ChartTools {
public static Chart style(Chart chart, String cssFile) {
chart.getStylesheets().add(Chart.class.getResource(cssFile).toExternalForm());
return chart;
}
public static void setChartCoordinate(NumberAxis numberAxis, XYChartOptions.ChartCoordinate chartCoordinate) {
switch (chartCoordinate) {
case LogarithmicE:
numberAxis.setTickLabelFormatter(new LogarithmicECoordinate());
break;
case Logarithmic10:
numberAxis.setTickLabelFormatter(new Logarithmic10Coordinate());
break;
case SquareRoot:
numberAxis.setTickLabelFormatter(new SquareRootCoordinate());
break;
}
}
public static double realValue(XYChartOptions.ChartCoordinate chartCoordinate, double coordinateValue) {
if (chartCoordinate == null) {
return coordinateValue;
}
switch (chartCoordinate) {
case LogarithmicE:
return Math.pow(Math.E, coordinateValue);
case Logarithmic10:
return Math.pow(10, coordinateValue);
case SquareRoot:
return coordinateValue * coordinateValue;
}
return coordinateValue;
}
public static double coordinateValue(XYChartOptions.ChartCoordinate chartCoordinate, double value) {
if (chartCoordinate == null || value <= 0) {
return value;
}
switch (chartCoordinate) {
case LogarithmicE:
return Math.log(value);
case Logarithmic10:
return Math.log10(value);
case SquareRoot:
return Math.sqrt(value);
}
return value;
}
// This can set more than 8 colors. javafx only supports 8 colors defined in css
// This should be called after data have been assigned to pie
public static void setPieStyle(PieChart pie, boolean showLegend) {
List<String> palette = FxColorTools.randomRGB(pie.getData().size());
setPieStyle(pie, palette, showLegend, 10);
}
public static void setPieStyle(PieChart pie, List<String> palette, boolean showLegend, int fontSize) {
if (pie == null || palette == null || pie.getData() == null || pie.getData().size() > palette.size()) {
return;
}
for (int i = 0; i < pie.getData().size(); i++) {
PieChart.Data data = pie.getData().get(i);
data.getNode().setStyle("-fx-pie-color: " + palette.get(i) + ";");
}
Set<Node> labelItems = pie.lookupAll("chart-pie-label");
for (Node labelItem : labelItems) {
labelItem.setStyle("-fx-font-size: " + fontSize + "fx;");
}
setPieLegend(pie, palette, showLegend);
}
public static void setPieLegend(PieChart pie, List<String> palette, boolean showLegend) {
if (pie == null || palette == null || pie.getData() == null || pie.getData().size() > palette.size()) {
return;
}
pie.setLegendVisible(showLegend);
if (showLegend) {
Set<Node> legendItems = pie.lookupAll("Label.chart-legend-item");
if (legendItems.isEmpty()) {
return;
}
for (Node legendItem : legendItems) {
Label legendLabel = (Label) legendItem;
Node legend = legendLabel.getGraphic();
if (legend != null) {
for (int i = 0; i < pie.getData().size(); i++) {
String name = pie.getData().get(i).getName();
if (name.equals(legendLabel.getText())) {
legend.setStyle("-fx-background-color: " + palette.get(i));
break;
}
}
}
}
}
}
public static void setBarChartStyle(XYChart chart, boolean showLegend) {
List<String> palette = FxColorTools.randomRGB(chart.getData().size());
ChartTools.setBarChartStyle(chart, palette, showLegend);
}
public static void setBarChartStyle(XYChart chart, List<String> palette, boolean showLegend) {
if (chart == null || palette == null) {
return;
}
List<XYChart.Series> seriesList = chart.getData();
if (seriesList == null || seriesList.size() > palette.size()) {
return;
}
for (int i = 0; i < seriesList.size(); i++) {
XYChart.Series series = seriesList.get(i);
if (series.getData() == null) {
continue;
}
for (int j = 0; j < series.getData().size(); j++) {
XYChart.Data item = (XYChart.Data) series.getData().get(j);
if (item.getNode() != null) {
String color = palette.get(i);
item.getNode().setStyle("-fx-bar-fill: " + color + ";");
}
}
}
setLegend(chart, palette, showLegend);
}
public static void setBarChartStyle(XYChart chart, Map<String, String> palette, boolean showLegend) {
if (chart == null || palette == null) {
return;
}
List<XYChart.Series> seriesList = chart.getData();
if (seriesList == null) {
return;
}
for (int i = 0; i < seriesList.size(); i++) {
XYChart.Series series = seriesList.get(i);
if (series.getData() == null) {
continue;
}
String name = series.getName();
String color = palette.get(name);
for (int j = 0; j < series.getData().size(); j++) {
XYChart.Data item = (XYChart.Data) series.getData().get(j);
Node node = item.getNode();
if (node != null) {
node.setStyle("-fx-bar-fill: " + color + ";");
}
}
}
setLegend(chart, palette, showLegend);
}
public static void setLineChartStyle(XYChart chart, int lineWidth, int symbolSize, Map<String, String> palette,
boolean showLegend, boolean dotted) {
if (chart == null || palette == null) {
return;
}
List<XYChart.Series> seriesList = chart.getData();
if (seriesList == null || seriesList.size() > palette.size()) {
return;
}
if (lineWidth < 0) {
lineWidth = 4;
}
for (XYChart.Series series : seriesList) {
Node seriesNode = series.getNode();
if (seriesNode == null) {
continue;
}
String name = series.getName();
String color = palette.get(name);
if (color == null) {
color = FxColorTools.randomRGB();
}
Node node = seriesNode.lookup(".chart-series-line");
if (node != null) {
node.setStyle("-fx-stroke: " + color + "; "
+ "-fx-stroke-width: " + lineWidth + "px;"
+ (dotted ? " -fx-stroke-dash-array: " + lineWidth * 2 + ";" : ""));
}
for (int i = 0; i < series.getData().size(); i++) {
XYChart.Data item = (XYChart.Data) series.getData().get(i);
if (item.getNode() == null) {
continue;
}
node = item.getNode().lookup(".chart-line-symbol");
if (node != null) {
int r = symbolSize / 2;
node.setStyle("-fx-background-color: " + color + ", white;"
+ "-fx-background-radius: " + r + ";"
+ "-fx-padding: " + r + ";");
}
}
}
setLegend(chart, palette, showLegend);
}
public static void setAreaChartStyle(XYChart chart, int lineWidth, int symbolSize, Map<String, String> palette, boolean showLegend) {
if (chart == null || palette == null) {
return;
}
List<XYChart.Series> seriesList = chart.getData();
if (seriesList == null) {
return;
}
if (lineWidth < 0) {
lineWidth = 1;
}
for (XYChart.Series series : seriesList) {
if (series.getData() == null) {
continue;
}
Node seriesNode = series.getNode();
if (seriesNode == null) {
continue;
}
String name = series.getName();
String color = palette.get(name);
if (color == null) {
color = FxColorTools.randomRGB();
}
Node node = seriesNode.lookup(".chart-series-area-line");
if (node != null) {
node.setStyle("-fx-stroke: " + color + "; -fx-stroke-width: " + lineWidth + "px;");
}
node = seriesNode.lookup(".chart-series-area-fill");
if (node != null) {
node.setStyle("-fx-fill: " + color + "44;");
}
for (int i = 0; i < series.getData().size(); i++) {
XYChart.Data item = (XYChart.Data) series.getData().get(i);
if (item.getNode() == null) {
continue;
}
node = item.getNode().lookup(".chart-area-symbol");
if (node != null) {
int r = symbolSize / 2;
node.setStyle("-fx-background-color: " + color + ", white;"
+ "-fx-background-radius: " + r + ";"
+ "-fx-padding: " + r + ";");
}
}
}
setLegend(chart, palette, showLegend);
}
public static void setScatterChartStyle(XYChart chart, int symbolSize, Map<String, String> palette, boolean showLegend) {
if (chart == null || palette == null) {
return;
}
List<XYChart.Series> seriesList = chart.getData();
if (seriesList == null || seriesList.size() > palette.size()) {
return;
}
for (XYChart.Series series : seriesList) {
String name = series.getName();
String color = palette.get(name);
if (color == null) {
color = FxColorTools.randomRGB();
}
for (int i = 0; i < series.getData().size(); i++) {
XYChart.Data item = (XYChart.Data) series.getData().get(i);
if (item.getNode() == null) {
continue;
}
Node node = item.getNode().lookup(".chart-symbol");
if (node != null) {
int r = symbolSize / 2;
node.setStyle("-fx-background-color: " + color + ";"
+ "-fx-background-radius: " + r + ";"
+ "-fx-padding: " + r + ";");
}
}
}
setLegend(chart, palette, showLegend);
}
public static void setBubbleChartStyle(XYChart chart, String bubbleStyle, Map<String, String> palette, boolean showLegend) {
if (chart == null || palette == null) {
return;
}
List<XYChart.Series> seriesList = chart.getData();
if (seriesList == null || seriesList.size() > palette.size()) {
return;
}
for (int s = 0; s < seriesList.size(); s++) {
XYChart.Series series = seriesList.get(s);
String name = series.getName();
String color = palette.get(name);
if (color == null) {
color = FxColorTools.randomRGB();
}
for (int i = 0; i < series.getData().size(); i++) {
XYChart.Data item = (XYChart.Data) series.getData().get(i);
if (item.getNode() == null) {
continue;
}
Node node = item.getNode().lookup(".chart-bubble");
if (node != null) {
String style = "-fx-bubble-fill: " + color + ";";
if (bubbleStyle != null && !bubbleStyle.isBlank()) {
style += " -fx-background-color: " + bubbleStyle + ";";
}
node.setStyle(style);
}
}
}
setLegend(chart, palette, showLegend);
}
public static void setLegend(XYChart chart, Map<String, String> palette, boolean showLegend) {
if (chart == null || palette == null) {
return;
}
List<XYChart.Series> seriesList = chart.getData();
if (seriesList == null) {
return;
}
chart.setLegendVisible(showLegend);
if (showLegend) {
Set<Node> legendItems = chart.lookupAll("Label.chart-legend-item");
if (legendItems.isEmpty()) {
return;
}
for (Node legendItem : legendItems) {
Label legendLabel = (Label) legendItem;
Node legend = legendLabel.getGraphic();
if (legend != null) {
for (int i = 0; i < seriesList.size(); i++) {
String name = seriesList.get(i).getName();
String color = palette.get(name);
if (color != null && name.equals(legendLabel.getText())) {
legend.setStyle("-fx-background-color: " + color);
}
}
}
}
}
}
public static void setLegend(XYChart chart, List<String> palette, boolean showLegend) {
if (chart == null || palette == null) {
return;
}
List<XYChart.Series> seriesList = chart.getData();
if (seriesList == null) {
return;
}
chart.setLegendVisible(showLegend);
if (showLegend) {
Set<Node> legendItems = chart.lookupAll("Label.chart-legend-item");
if (legendItems.isEmpty()) {
return;
}
for (Node legendItem : legendItems) {
Label legendLabel = (Label) legendItem;
Node legend = legendLabel.getGraphic();
if (legend != null) {
for (int i = 0; i < seriesList.size(); i++) {
if (seriesList.get(i).getName().equals(legendLabel.getText())) {
legend.setStyle("-fx-background-color: " + palette.get(i));
break;
}
}
}
}
}
}
}
| 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/fxml/chart/LabeledScatterChart.java | alpha/MyBox/src/main/java/mara/mybox/fxml/chart/LabeledScatterChart.java | package mara.mybox.fxml.chart;
import java.util.List;
import javafx.geometry.Bounds;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.chart.Axis;
import javafx.scene.chart.ScatterChart;
import javafx.scene.chart.XYChart;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.shape.Line;
import mara.mybox.dev.MyBoxLog;
/**
* Reference:
* https://stackoverflow.com/questions/34286062/how-to-clear-text-added-in-a-javafx-barchart/41494789#41494789
* By Roland
*
* @Author Mara
* @CreateDate 2022-1-25
* @License Apache License Version 2.0
*/
public class LabeledScatterChart<X, Y> extends ScatterChart<X, Y> {
protected XYChartMaker chartMaker;
public LabeledScatterChart(Axis xAxis, Axis yAxis) {
super(xAxis, yAxis);
init();
}
public final void init() {
this.setLegendSide(Side.TOP);
this.setMaxWidth(Double.MAX_VALUE);
this.setMaxHeight(Double.MAX_VALUE);
VBox.setVgrow(this, Priority.ALWAYS);
HBox.setHgrow(this, Priority.ALWAYS);
chartMaker = new XYChartMaker<Axis, Axis>();
}
public LabeledScatterChart setMaker(XYChartMaker<X, Y> chartMaker) {
this.chartMaker = chartMaker;
return this;
}
@Override
protected void seriesAdded(Series<X, Y> series, int seriesIndex) {
super.seriesAdded(series, seriesIndex);
chartMaker.makeLabels(series, getPlotChildren());
}
@Override
protected void seriesRemoved(final Series<X, Y> series) {
chartMaker.removeLabels(getPlotChildren());
super.seriesRemoved(series);
}
@Override
protected void layoutPlotChildren() {
super.layoutPlotChildren();
chartMaker.displayLabels();
}
public void drawLine(List<XYChart.Data<X, Y>> data, Line line, boolean pointsVisible) {
try {
if (data == null || line == null) {
return;
}
double startX = Double.MAX_VALUE, startY = Double.MAX_VALUE,
endX = -Double.MAX_VALUE, endY = -Double.MAX_VALUE;
for (int i = 0; i < data.size(); i++) {
Node node = data.get(i).getNode();
Bounds regionBounds = node.getBoundsInParent();
double x = regionBounds.getMinX() + regionBounds.getWidth() / 2;
double y = regionBounds.getMinY() + regionBounds.getHeight() / 2;
if (chartMaker.isXY) {
if (x > endX) {
endX = x;
endY = y;
}
if (x < startX) {
startX = x;
startY = y;
}
} else {
if (y > endY) {
endX = x;
endY = y;
}
if (y < startY) {
startX = x;
startY = y;
}
}
node.setVisible(pointsVisible);
}
if (startX == Double.MAX_VALUE || endX == -Double.MAX_VALUE) {
return;
}
if (!getPlotChildren().contains(line)) {
getPlotChildren().add(line);
}
line.setStartX(startX);
line.setStartY(startY);
line.setEndX(endX);
line.setEndY(endY);
} catch (Exception e) {
MyBoxLog.debug(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/fxml/chart/LabeledBarChart.java | alpha/MyBox/src/main/java/mara/mybox/fxml/chart/LabeledBarChart.java | package mara.mybox.fxml.chart;
import javafx.geometry.Side;
import javafx.scene.chart.Axis;
import javafx.scene.chart.BarChart;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import mara.mybox.fxml.chart.ChartOptions.LabelType;
/**
* Reference:
* https://stackoverflow.com/questions/34286062/how-to-clear-text-added-in-a-javafx-barchart/41494789#41494789
* By Roland
*
* @Author Mara
* @License Apache License Version 2.0
*/
public class LabeledBarChart<X, Y> extends BarChart<X, Y> {
protected XYChartMaker chartMaker;
public LabeledBarChart(Axis xAxis, Axis yAxis) {
super(xAxis, yAxis);
init();
}
public final void init() {
this.setLegendSide(Side.TOP);
this.setMaxWidth(Double.MAX_VALUE);
this.setMaxHeight(Double.MAX_VALUE);
VBox.setVgrow(this, Priority.ALWAYS);
HBox.setHgrow(this, Priority.ALWAYS);
chartMaker = new XYChartMaker<Axis, Axis>();
}
public LabeledBarChart setMaker(XYChartMaker<X, Y> chartMaker) {
this.chartMaker = chartMaker;
return this;
}
@Override
protected void seriesAdded(Series<X, Y> series, int seriesIndex) {
super.seriesAdded(series, seriesIndex);
chartMaker.makeLabels(series, getPlotChildren());
}
@Override
protected void seriesRemoved(final Series<X, Y> series) {
chartMaker.removeLabels(getPlotChildren());
super.seriesRemoved(series);
}
@Override
protected void layoutPlotChildren() {
super.layoutPlotChildren();
chartMaker.displayLabels();
}
public LabeledBarChart<X, Y> setLabelType(LabelType labelType) {
chartMaker.setLabelType(labelType);
return this;
}
public LabeledBarChart<X, Y> setLabelFontSize(int labelFontSize) {
chartMaker.setLabelFontSize(labelFontSize);
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/fxml/chart/PieChartMaker.java | alpha/MyBox/src/main/java/mara/mybox/fxml/chart/PieChartMaker.java | package mara.mybox.fxml.chart;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Side;
import javafx.scene.chart.PieChart;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.image.FxColorTools;
import mara.mybox.fxml.style.NodeStyleTools;
import mara.mybox.tools.DoubleTools;
import mara.mybox.tools.NumberTools;
/**
* @Author Mara
* @CreateDate 2022-5-16
* @License Apache License Version 2.0
*/
public class PieChartMaker extends PieChartOptions {
public PieChartMaker() {
chartType = ChartType.Pie;
}
public PieChartMaker init(String chartName) {
clearChart();
this.chartName = chartName;
initPieOptions();
return this;
}
@Override
public void clearChart() {
super.clearChart();
pieChart = null;
}
public PieChart makeChart() {
try {
clearChart();
chartType = ChartType.Pie;
if (chartName == null) {
return null;
}
initPieChart();
styleChart();
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
return pieChart;
}
public void initPieChart() {
try {
pieChart = new PieChart();
chart = pieChart;
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void writeChart(List<List<String>> data, int catgoryCol, int valueCol, int percentageCol) {
try {
Random random = new Random();
ObservableList<PieChart.Data> pieData = FXCollections.observableArrayList();
pieChart.setData(pieData);
if (legendSide == null) {
pieChart.setLegendSide(Side.TOP);
}
String label;
List<String> paletteList = new ArrayList();
for (List<String> rowData : data) {
String name = rowData.get(catgoryCol);
if (name == null) {
name = "";
}
double d = doubleValue(rowData.get(valueCol));
if (d <= 0 || DoubleTools.invalidDouble(d)) {
continue;
}
double percent = doubleValue(rowData.get(percentageCol));
String value = NumberTools.format(d, scale);
switch (labelType) {
case Category:
label = (displayLabelName ? getCategoryLabel() + ": " : "") + name;
break;
case Value:
label = (displayLabelName ? getValueLabel() + ": " : "") + value + "=" + percent + "%";
break;
case CategoryAndValue:
label = (displayLabelName ? getCategoryLabel() + ": " : "") + name + "\n"
+ (displayLabelName ? getValueLabel() + ": " : "") + value + "=" + percent + "%";
break;
case NotDisplay:
case Point:
case Pop:
default:
label = name;
break;
}
PieChart.Data item = new PieChart.Data(label, d);
pieData.add(item);
if (popLabel()) {
NodeStyleTools.setTooltip(item.getNode(),
getCategoryLabel() + ": " + name + "\n"
+ getValueLabel() + ": " + value + "=" + percent + "%");
}
paletteList.add(FxColorTools.randomRGB(random));
}
pieChart.setLegendVisible(legendSide != null);
pieChart.setLabelsVisible(labelVisible());
pieChart.setClockwise(clockwise);
ChartTools.setPieStyle(pieChart, paletteList, showLegend(), labelFontSize);
} catch (Exception e) {
MyBoxLog.debug(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/fxml/chart/XYZChart.java | alpha/MyBox/src/main/java/mara/mybox/fxml/chart/XYZChart.java | package mara.mybox.fxml.chart;
import java.io.File;
import java.nio.charset.Charset;
import java.util.List;
import mara.mybox.db.data.ColumnDefinition.InvalidAs;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.image.FxColorTools;
import mara.mybox.fxml.FxFileTools;
import mara.mybox.tools.DoubleTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.TextFileTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-9-18
* @License Apache License Version 2.0
*/
public class XYZChart {
protected String title;
protected ColorType colorType;
protected boolean isScatter, darkMode, xCategory, yCategory, zCategory, isOrthographic;
protected int seriesSize, scale;
protected double width, height, pointSize;
protected List<List<String>> data;
protected List<Data2DColumn> columns;
protected File chartFile;
public static enum ColorType {
Column, Random, Gradient
}
public XYZChart() {
init();
}
private void init() {
title = null;
colorType = ColorType.Column;
isScatter = true;
darkMode = xCategory = yCategory = zCategory = isOrthographic = false;
seriesSize = 1;
scale = 8;
width = 800;
height = 600;
pointSize = 10;
data = null;
columns = null;
chartFile = null;
}
public static XYZChart create() {
return new XYZChart();
}
public File makeChart() {
try {
chartFile = null;
if (data == null || data.isEmpty()) {
return null;
}
File echartsFile = FxFileTools.getInternalFile("/js/echarts.min.js", "js", "echarts.min.js");
File echartsGLFile = FxFileTools.getInternalFile("/js/echarts-gl.min.js", "js", "echarts-gl.min.js");
String xName = columns.get(0).getColumnName();
String yName = columns.get(1).getColumnName();
String z1Name = columns.get(2).getColumnName();
String chartName = isScatter ? message("ScatterChart") : message("SurfaceChart");
String[] colors = new String[seriesSize];
String[] symbols = new String[seriesSize];
String html = "<html>\n"
+ " <head>\n"
+ " <meta charset=\"utf-8\" />\n"
+ " <title>" + title + "</title>\n"
+ " <script src=\"" + echartsFile.toURI().toString() + "\"></script>\n"
+ " <script src=\"" + echartsGLFile.toURI().toString() + "\"></script>\n"
+ " </head>\n"
+ " <body style=\"width:" + (width + 50) + "px; margin:0 auto;\">\n"
+ " <h3 align=center>" + title + "</h2>\n"
+ " <h2 align=center>" + chartName + "</h2>\n";
if (isScatter) {
html += " <style type=\"text/css\">\n";
String[] presymbols = {"circle", "triangle", "diamond", "arrow", "rect"};
for (int i = 0; i < seriesSize; i++) {
String color;
if (colorType == ColorType.Column) {
color = FxColorTools.color2css(columns.get(i + 2).getColor());
} else {
color = FxColorTools.randomRGB();
}
colors[i] = color;
String symbol = presymbols[i % presymbols.length];
symbols[i] = symbol;
if ("circle".equals(symbol)) {
html += " .symbol" + i + " {\n"
+ " width: 20px;\n"
+ " height: 20px;\n"
+ " background-color: " + color + ";\n"
+ " border-radius: 50%;\n"
+ " display: inline-block;\n"
+ " }\n";
} else if ("rect".equals(symbol)) {
html += " .symbol" + i + " {\n"
+ " width: 20px;\n"
+ " height: 20px;\n"
+ " background-color: " + color + ";\n"
+ " display: inline-block;\n"
+ " }\n";
} else if ("triangle".equals(symbol)) {
html += " .symbol" + i + " {\n"
+ " width: 0;\n"
+ " height: 0;\n"
+ " border-left: 10px solid transparent;\n"
+ " border-right: 10px solid transparent;\n"
+ " border-bottom: 20px solid " + color + ";\n"
+ " display: inline-block;\n"
+ " }\n";
} else if ("diamond".equals(symbol)) {
html += " .symbol" + i + " {\n"
+ " width: 16px; \n"
+ " height: 16px; \n"
+ " background-color: " + color + "; \n"
+ " transform:rotate(45deg); \n"
+ " display: inline-block;\n"
+ " }\n";
} else if ("arrow".equals(symbol)) {
html += " .symbol" + i + " {\n"
+ " width: 0;\n"
+ " height: 0;\n"
+ " border: 10px solid;\n"
+ " border-color: white white " + color + " white;\n"
+ " display: inline-block;\n"
+ " }\n";
}
}
html += " </style>\n";
html += " <P><div style=\"text-align: center; margin:0 auto;\">\n";
for (int i = 0; i < seriesSize; i++) {
html += " <div class=\"symbol" + i + "\"></div><span> " + columns.get(i + 2).getColumnName() + " </span>\n";
}
html += " </div></P>\n";
}
html += " <div id=\"chart\" style=\"width: " + width + "px;height: " + height + "px;\"></div>\n"
+ " <script type=\"text/javascript\">\n"
+ " var myChart = echarts.init(document.getElementById('chart')"
+ (darkMode ? ", 'dark'" : "") + ");\n";
html += " var srcData = [];\n";
double min = Double.MAX_VALUE, max = -Double.MAX_VALUE;
String s;
double d;
for (List<String> row : data) {
int rowLen = row.size();
if (rowLen < 3) {
continue;
}
String push = " srcData.push([";
s = row.get(0);
if (xCategory) {
push += "'" + s + "'";
} else {
d = DoubleTools.scale(s, InvalidAs.Skip, scale);
if (DoubleTools.invalidDouble(d)) {
continue;
}
push += d;
}
s = row.get(1);
if (yCategory) {
push += ", '" + s + "'";
} else {
d = DoubleTools.scale(s, InvalidAs.Skip, scale);
if (DoubleTools.invalidDouble(d)) {
continue;
}
push += ", " + d;
}
for (int i = 2; i < 2 + seriesSize; i++) {
s = row.get(i);
if (zCategory) {
push += ", '" + s + "'";
} else {
d = DoubleTools.scale(s, InvalidAs.Skip, scale);
if (DoubleTools.invalidDouble(d)) {
push += ", Number.NaN";
} else {
push += ", " + d;
if (d > max) {
max = d;
}
if (d < min) {
min = d;
}
}
}
}
for (int i = 2 + seriesSize; i < rowLen; i++) {
push += ", '" + row.get(i) + "'";
}
html += push + "]);\n";
}
if (min == Double.MAX_VALUE) {
min = -10;
}
if (max == -Double.MAX_VALUE) {
max = 10;
}
html += "\n\n option = {\n";
if (darkMode) {
html += " backgroundColor: '#ffffff',\n";
}
if (colorType == ColorType.Gradient) {
html += " visualMap: {\n"
+ " show: true,\n"
+ " dimension: 2,\n"
+ " min: " + min + ",\n"
+ " max: " + max + ",\n"
+ " inRange: {\n"
+ " color: [\n"
+ " '#313695',\n"
+ " '#4575b4',\n"
+ " '#74add1',\n"
+ " '#abd9e9',\n"
+ " '#e0f3f8',\n"
+ " '#ffffbf',\n"
+ " '#fee090',\n"
+ " '#fdae61',\n"
+ " '#f46d43',\n"
+ " '#d73027',\n"
+ " '#a50026'\n"
+ " ]\n"
+ " }\n"
+ " },\n";
}
String dimensions;
if (isScatter) {
dimensions = "'" + xName + "', '" + yName + "', '" + z1Name + "'";
} else {
dimensions = "'x', 'y', 'z'"; // looks surface ndoes not accpet customized names for xyz. Bug?
}
for (int i = 3; i < columns.size(); i++) {
dimensions += ",'" + columns.get(i).getColumnName() + "'";
}
if (isScatter) {
html += " dataset: {\n"
+ " dimensions: [\n"
+ " " + dimensions + "\n"
+ " ],\n"
+ " source: srcData\n"
+ " },\n";
}
html += " xAxis3D: {\n"
+ " type: '" + (xCategory ? "category" : "value") + "',\n"
+ " name: 'X: " + xName + "'\n"
+ " },\n" + " yAxis3D: {\n"
+ " type: '" + (yCategory ? "category" : "value") + "',\n"
+ " name: 'Y: " + yName + "'\n"
+ " },\n"
+ " zAxis3D: {\n"
+ " type: '" + (zCategory ? "category" : "value") + "',\n"
+ " name: 'Z" + (seriesSize == 1 ? ": " + z1Name : "") + "'\n"
+ " },\n"
+ " grid3D: {\n"
+ " viewControl: {\n"
+ " projection: '" + (isOrthographic ? "orthographic" : "perspective") + "'\n"
+ " }\n"
+ " },\n"
+ " tooltip: {},\n"
+ " series: [\n";
if (isScatter) {
for (int i = 0; i < seriesSize; i++) {
if (i > 0) {
html += " ,\n";
}
Data2DColumn column = columns.get(i + 2);
String zName = column.getColumnName();
html += " {\n"
+ " type: 'scatter3D',\n"
+ " name: '" + zName + "',\n"
+ " symbol: '" + symbols[i] + "',\n"
+ " symbolSize: " + pointSize + ",\n"
+ " itemStyle: {\n"
+ " color: '" + colors[i] + "'\n"
+ " },\n"
+ " encode: {\n"
+ " x: '" + xName + "',\n"
+ " y: '" + yName + "',\n"
+ " z: '" + zName + "'\n"
+ " }\n"
+ " }\n";
}
} else {
Data2DColumn column = columns.get(2);
String zName = column.getColumnName();
String color;
if (colorType == ColorType.Column) {
color = FxColorTools.color2rgb(column.getColor());
} else {
color = FxColorTools.randomRGB();
}
html += " {\n"
+ " type: 'surface',\n"
+ " name: '" + zName + "',\n"
+ " symbolSize: " + pointSize + ",\n"
+ " itemStyle: {\n"
+ " color: '" + color + "'\n"
+ " },\n"
+ " wireframe: {\n"
+ " show: true\n"
+ " },\n"
+ " dimensions: [" + dimensions + "],\n"
+ " data: srcData\n"
+ " }\n";
}
html += " ]\n"
+ " }\n\n"
+ " myChart.setOption(option);\n"
+ " </script>\n"
+ " </body>\n"
+ "</html>";
chartFile = FileTmpTools.generateFile(title, "html");
TextFileTools.writeFile(chartFile, html, Charset.forName("UTF-8"));
return chartFile;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
/*
set
*/
public XYZChart setTitle(String title) {
this.title = title;
return this;
}
public XYZChart setColorType(ColorType colorType) {
this.colorType = colorType;
return this;
}
public XYZChart setIsScatter(boolean isScatter) {
this.isScatter = isScatter;
return this;
}
public XYZChart setDarkMode(boolean darkMode) {
this.darkMode = darkMode;
return this;
}
public XYZChart setxCategory(boolean xCategory) {
this.xCategory = xCategory;
return this;
}
public XYZChart setyCategory(boolean yCategory) {
this.yCategory = yCategory;
return this;
}
public XYZChart setzCategory(boolean zCategory) {
this.zCategory = zCategory;
return this;
}
public XYZChart setIsOrthographic(boolean isOrthographic) {
this.isOrthographic = isOrthographic;
return this;
}
public XYZChart setSeriesSize(int seriesSize) {
this.seriesSize = seriesSize;
return this;
}
public XYZChart setScale(int scale) {
this.scale = scale;
return this;
}
public XYZChart setWidth(double width) {
this.width = width;
return this;
}
public XYZChart setHeight(double height) {
this.height = height;
return this;
}
public XYZChart setPointSize(double pointSize) {
this.pointSize = pointSize;
return this;
}
public XYZChart setData(List<List<String>> data) {
this.data = data;
return this;
}
public XYZChart setColumns(List<Data2DColumn> columns) {
this.columns = columns;
return this;
}
/*
get
*/
public File getChartFile() {
return chartFile;
}
}
| 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/fxml/chart/LabeledAreaChart.java | alpha/MyBox/src/main/java/mara/mybox/fxml/chart/LabeledAreaChart.java | package mara.mybox.fxml.chart;
import javafx.geometry.Side;
import javafx.scene.chart.AreaChart;
import javafx.scene.chart.Axis;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
/**
* Reference:
* https://stackoverflow.com/questions/34286062/how-to-clear-text-added-in-a-javafx-barchart/41494789#41494789
* By Roland
*
* @Author Mara
* @CreateDate 2022-1-25
* @License Apache License Version 2.0
*/
public class LabeledAreaChart<X, Y> extends AreaChart<X, Y> {
protected XYChartMaker<X, Y> chartMaker;
public LabeledAreaChart(Axis xAxis, Axis yAxis) {
super(xAxis, yAxis);
init();
}
public final void init() {
this.setLegendSide(Side.TOP);
this.setMaxWidth(Double.MAX_VALUE);
this.setMaxHeight(Double.MAX_VALUE);
VBox.setVgrow(this, Priority.ALWAYS);
HBox.setHgrow(this, Priority.ALWAYS);
chartMaker = new XYChartMaker<>();
}
public LabeledAreaChart setMaker(XYChartMaker<X, Y> chartMaker) {
this.chartMaker = chartMaker;
setCreateSymbols(chartMaker.displayLabel());
return this;
}
@Override
protected void seriesAdded(Series<X, Y> series, int seriesIndex) {
super.seriesAdded(series, seriesIndex);
chartMaker.makeLabels(series, getPlotChildren());
}
@Override
protected void seriesRemoved(final Series<X, Y> series) {
chartMaker.removeLabels(getPlotChildren());
super.seriesRemoved(series);
}
@Override
protected void layoutPlotChildren() {
super.layoutPlotChildren();
chartMaker.displayLabels();
}
}
| 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/fxml/chart/LabeledBubbleChart.java | alpha/MyBox/src/main/java/mara/mybox/fxml/chart/LabeledBubbleChart.java | package mara.mybox.fxml.chart;
import javafx.geometry.Side;
import javafx.scene.chart.Axis;
import javafx.scene.chart.BubbleChart;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
/**
* Reference:
* https://stackoverflow.com/questions/34286062/how-to-clear-text-added-in-a-javafx-barchart/41494789#41494789
* By Roland
*
* @Author Mara
* @CreateDate 2022-1-25
* @License Apache License Version 2.0
*/
public class LabeledBubbleChart<X, Y> extends BubbleChart<X, Y> {
protected XYChartMaker chartMaker;
public LabeledBubbleChart(Axis xAxis, Axis yAxis) {
super(xAxis, yAxis);
init();
}
public final void init() {
this.setLegendSide(Side.TOP);
this.setMaxWidth(Double.MAX_VALUE);
this.setMaxHeight(Double.MAX_VALUE);
VBox.setVgrow(this, Priority.ALWAYS);
HBox.setHgrow(this, Priority.ALWAYS);
chartMaker = new XYChartMaker<>();
}
public LabeledBubbleChart setMaker(XYChartMaker<X, Y> chartMaker) {
this.chartMaker = chartMaker;
return this;
}
@Override
protected void seriesAdded(Series<X, Y> series, int seriesIndex) {
super.seriesAdded(series, seriesIndex);
chartMaker.makeLabels(series, getPlotChildren());
}
@Override
protected void seriesRemoved(final Series<X, Y> series) {
chartMaker.removeLabels(getPlotChildren());
super.seriesRemoved(series);
}
@Override
protected void layoutPlotChildren() {
super.layoutPlotChildren();
chartMaker.displayLabels();
}
}
| 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/fxml/chart/LogarithmicECoordinate.java | alpha/MyBox/src/main/java/mara/mybox/fxml/chart/LogarithmicECoordinate.java | package mara.mybox.fxml.chart;
import javafx.util.StringConverter;
import mara.mybox.tools.StringTools;
/**
* @Author Mara
* @CreateDate 2020-05-16
* @License Apache License Version 2.0
*/
public class LogarithmicECoordinate extends StringConverter<Number> {
@Override
public String toString(Number value) {
return StringTools.format(Math.pow(Math.E, value.doubleValue()));
}
@Override
public Number fromString(String string) {
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/fxml/chart/ResidualChart.java | alpha/MyBox/src/main/java/mara/mybox/fxml/chart/ResidualChart.java | package mara.mybox.fxml.chart;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javafx.application.Platform;
import javafx.scene.chart.Axis;
import javafx.scene.chart.XYChart;
import javafx.scene.shape.Line;
import javafx.scene.text.Text;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2022-5-10
* @License Apache License Version 2.0
*/
public class ResidualChart<X, Y> extends LabeledScatterChart<X, Y> {
protected Line upperLine, lowerLine;
protected Text text;
protected String info;
public ResidualChart(Axis xAxis, Axis yAxis) {
super(xAxis, yAxis);
init();
upperLine = new Line();
lowerLine = new Line();
text = new Text();
}
public synchronized void displayControls(int dataSize) {
if (dataSize < 3) {
getPlotChildren().removeAll(upperLine, lowerLine, text);
return;
}
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
Platform.runLater(() -> {
if (getData() != null && dataSize == getData().size()) {
t.cancel();
makeControls();
}
});
Platform.requestNextPulse();
}
}, 100, 100);
}
public void makeControls() {
try {
getPlotChildren().removeAll(upperLine, lowerLine, text);
List<XYChart.Series<X, Y>> seriesList = this.getData();
if (seriesList == null || seriesList.size() < 3) {
return;
}
String prefix = "-fx-stroke-dash-array: " + chartMaker.getLineWidth() * 2
+ "; -fx-stroke-width:" + chartMaker.getLineWidth() + "px; -fx-stroke:";
upperLine.setStyle(prefix + chartMaker.getPalette().get(seriesList.get(1).getName()));
drawLine(seriesList.get(1).getData(), upperLine, false);
lowerLine.setStyle(prefix + chartMaker.getPalette().get(seriesList.get(2).getName()));
drawLine(seriesList.get(2).getData(), lowerLine, false);
text.setStyle("-fx-font-size:" + chartMaker.getLabelFontSize() + "px; -fx-text-fill: black;");
text.setText(info);
getPlotChildren().add(text);
text.setLayoutX(10);
text.setLayoutY(10);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public ResidualChart setInfo(String info) {
this.info = info;
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/fxml/chart/SimpleRegressionChart.java | alpha/MyBox/src/main/java/mara/mybox/fxml/chart/SimpleRegressionChart.java | package mara.mybox.fxml.chart;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javafx.application.Platform;
import javafx.scene.chart.Axis;
import javafx.scene.chart.XYChart;
import javafx.scene.shape.Line;
import javafx.scene.text.Text;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2022-5-2
* @License Apache License Version 2.0
*/
public class SimpleRegressionChart<X, Y> extends LabeledScatterChart<X, Y> {
protected Line regressionLine;
protected Text text;
protected boolean displayText, displayFittedPoints, displayFittedLine;
protected String model;
public SimpleRegressionChart(Axis xAxis, Axis yAxis) {
super(xAxis, yAxis);
init();
regressionLine = new Line();
text = new Text();
}
public synchronized void displayControls() {
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
Platform.runLater(() -> {
if (getData() != null && 2 == getData().size()) {
t.cancel();
makeControls();
}
});
Platform.requestNextPulse();
}
}, 100, 100);
}
public void makeControls() {
try {
getPlotChildren().removeAll(regressionLine, text);
List<XYChart.Series<X, Y>> seriesList = this.getData();
if (seriesList == null) {
return;
}
getPlotChildren().removeAll(regressionLine, text);
regressionLine.setStyle("-fx-stroke-width:" + chartMaker.getLineWidth()
+ "px; -fx-stroke:" + chartMaker.getPalette().get(seriesList.get(1).getName()));
drawLine(seriesList.get(1).getData(), regressionLine, displayFittedPoints);
regressionLine.setVisible(displayFittedLine);
text.setStyle("-fx-font-size:" + chartMaker.getLabelFontSize() + "px; -fx-text-fill: black;");
text.setText(model);
getPlotChildren().add(text);
if (regressionLine.getStartY() > 60) {
text.setLayoutX(10);
text.setLayoutY(10);
} else {
text.setLayoutX(10);
text.setLayoutY(text.getParent().getBoundsInParent().getHeight() - text.getBoundsInParent().getHeight() - 10);
}
text.setVisible(displayText);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void displayFittedPoints(boolean display) {
try {
displayFittedPoints = display;
List<XYChart.Series<X, Y>> seriesList = this.getData();
if (seriesList == null) {
return;
}
List<XYChart.Data<X, Y>> data1 = seriesList.get(1).getData();
for (int i = 0; i < data1.size(); i++) {
data1.get(i).getNode().setVisible(display);
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void displayFittedLine(boolean display) {
try {
displayFittedLine = display;
regressionLine.setVisible(display);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void displayText(boolean display) {
try {
displayText = display;
text.setVisible(display);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
/*
get/set
*/
public SimpleRegressionChart<X, Y> setModel(String model) {
this.model = model;
return this;
}
public SimpleRegressionChart<X, Y> setDisplayFittedPoints(boolean displayFittedPoints) {
this.displayFittedPoints = displayFittedPoints;
return this;
}
public SimpleRegressionChart<X, Y> setDisplayFittedLine(boolean displayFittedLine) {
this.displayFittedLine = displayFittedLine;
return this;
}
public SimpleRegressionChart<X, Y> setDisplayText(boolean displayText) {
this.displayText = displayText;
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/fxml/chart/LabeledStackedAreaChart.java | alpha/MyBox/src/main/java/mara/mybox/fxml/chart/LabeledStackedAreaChart.java | package mara.mybox.fxml.chart;
import javafx.geometry.Side;
import javafx.scene.chart.Axis;
import javafx.scene.chart.StackedAreaChart;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import mara.mybox.dev.MyBoxLog;
/**
* Reference:
* https://stackoverflow.com/questions/34286062/how-to-clear-text-added-in-a-javafx-barchart/41494789#41494789
* By Roland
*
* @Author Mara
* @CreateDate 2022-1-25
* @License Apache License Version 2.0
*/
public class LabeledStackedAreaChart<X, Y> extends StackedAreaChart<X, Y> {
protected XYChartMaker chartMaker;
public LabeledStackedAreaChart(Axis xAxis, Axis yAxis) {
super(xAxis, yAxis);
init();
}
public final void init() {
this.setLegendSide(Side.TOP);
this.setMaxWidth(Double.MAX_VALUE);
this.setMaxHeight(Double.MAX_VALUE);
VBox.setVgrow(this, Priority.ALWAYS);
HBox.setHgrow(this, Priority.ALWAYS);
chartMaker = new XYChartMaker<Axis, Axis>();
}
public LabeledStackedAreaChart setMaker(XYChartMaker<X, Y> chartMaker) {
this.chartMaker = chartMaker;
setCreateSymbols(chartMaker.displayLabel());
return this;
}
@Override
protected void seriesAdded(Series<X, Y> series, int seriesIndex) {
super.seriesAdded(series, seriesIndex);
chartMaker.makeLabels(series, getPlotChildren());
}
@Override
protected void seriesRemoved(final Series<X, Y> series) {
chartMaker.removeLabels(getPlotChildren());
super.seriesRemoved(series);
}
@Override
protected void layoutPlotChildren() {
try {
super.layoutPlotChildren();
chartMaker.displayLabels();
} catch (Exception e) {
MyBoxLog.debug(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/fxml/chart/PieChartOptions.java | alpha/MyBox/src/main/java/mara/mybox/fxml/chart/PieChartOptions.java | package mara.mybox.fxml.chart;
import java.util.Map;
import javafx.scene.Node;
import javafx.scene.chart.PieChart;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2022-5-13
* @License Apache License Version 2.0
*/
public class PieChartOptions extends ChartOptions {
protected PieChart pieChart;
protected boolean clockwise;
public PieChartOptions() {
chartType = ChartType.Pie;
}
public final void initPieOptions() {
try {
if (chartName == null) {
return;
}
initChartOptions();
clockwise = UserConfig.getBoolean(chartName + "Clockwise", false);
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
/*
get/set
*/
public PieChart getPieChart() {
return pieChart;
}
public void setPieChart(PieChart pieChart) {
this.pieChart = pieChart;
}
public Map<Node, Node> getNodeLabels() {
return nodeLabels;
}
public void setNodeLabels(Map<Node, Node> nodeLabels) {
this.nodeLabels = nodeLabels;
}
public boolean isClockwise() {
return clockwise;
}
public void setClockwise(boolean clockwise) {
this.clockwise = clockwise;
UserConfig.setBoolean(chartName + "Clockwise", clockwise);
if (pieChart != null) {
pieChart.setClockwise(clockwise);
}
}
}
| 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/fxml/chart/Logarithmic10Coordinate.java | alpha/MyBox/src/main/java/mara/mybox/fxml/chart/Logarithmic10Coordinate.java | package mara.mybox.fxml.chart;
import javafx.util.StringConverter;
import mara.mybox.tools.StringTools;
/**
* @Author Mara
* @CreateDate 2020-05-16
* @License Apache License Version 2.0
*/
public class Logarithmic10Coordinate extends StringConverter<Number> {
@Override
public String toString(Number value) {
return StringTools.format(Math.pow(10, value.doubleValue()));
}
@Override
public Number fromString(String string) {
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/fxml/chart/XYChartOptions.java | alpha/MyBox/src/main/java/mara/mybox/fxml/chart/XYChartOptions.java | package mara.mybox.fxml.chart;
import java.sql.Connection;
import javafx.geometry.Side;
import javafx.scene.chart.Axis;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
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 2022-5-13
* @License Apache License Version 2.0
*/
public class XYChartOptions<X, Y> extends ChartOptions<X, Y> {
protected XYChart xyChart;
protected LabeledLineChart lineChart;
protected LabeledBarChart barChart;
protected LabeledStackedBarChart stackedBarChart;
protected LabeledScatterChart scatterChart;
protected LabeledAreaChart areaChart;
protected LabeledStackedAreaChart stackedAreaChart;
protected LabeledBubbleChart bubbleChart;
protected BoxWhiskerChart boxWhiskerChart;
protected SimpleRegressionChart simpleRegressionChart;
protected ResidualChart residualChart;
protected CategoryAxis categoryStringAxis;
protected NumberAxis categoryNumberAxis, valueAxis;
protected Axis xAxis, yAxis, categoryAxis;
protected ChartCoordinate categoryCoordinate, numberCoordinate, sizeCoordinate,
xCoordinate, yCoordinate;
protected int lineWidth, symbolSize, categoryFontSize, categoryMargin, categoryTickRotation,
numberFontSize, numberTickRotation;
protected boolean isXY, categoryIsNumbers,
displayCategoryMark, displayCategoryTick, displayNumberMark, displayNumberTick,
altRowsFill, altColumnsFill, displayVlines, displayHlines, displayVZero, displayHZero,
dotted;
protected LabelLocation labelLocation;
protected Side categorySide, numberSide;
protected Sort sort;
protected double barGap, categoryGap;
protected String bubbleStyle;
public static enum LabelLocation {
Above, Below, Center
}
public static enum ChartCoordinate {
Cartesian, LogarithmicE, Logarithmic10, SquareRoot
}
public static enum Sort {
None, X, Y
}
public static final String DefaultBubbleStyle
= "radial-gradient(center 50% 50%, radius 50%, transparent 0%, transparent 90%, derive(-fx-bubble-fill,0%) 100%)";
public XYChartOptions() {
}
public XYChartOptions initXYChartOptions() {
if (chartName == null) {
return this;
}
initChartOptions();
try (Connection conn = DerbyBase.getConnection()) {
isXY = UserConfig.getBoolean(conn, chartName + "XY", true);
switch (chartType) {
case Bubble:
categoryIsNumbers = true;
labelLocation = LabelLocation.Center;
break;
case SimpleRegressionChart:
case ResidualChart:
categoryIsNumbers = true;
labelLocation = LabelLocation.Above;
break;
case Bar:
case StackedBar:
case Area:
case StackedArea:
categoryIsNumbers = false;
labelLocation = LabelLocation.Above;
break;
default:
categoryIsNumbers = UserConfig.getBoolean(conn, chartName + "CategoryIsNumbers", false);
labelLocation = LabelLocation.Below;
break;
}
displayCategoryMark = UserConfig.getBoolean(conn, chartName + "DisplayCategoryMark", true);
displayCategoryTick = UserConfig.getBoolean(conn, chartName + "DisplayCategoryTick", true);
displayNumberMark = UserConfig.getBoolean(conn, chartName + "DisplayNumberMark", true);
displayNumberTick = UserConfig.getBoolean(conn, chartName + "DisplayNumberTick", true);
plotAnimated = UserConfig.getBoolean(conn, chartName + "PlotAnimated", false);
altRowsFill = UserConfig.getBoolean(conn, chartName + "AltRowsFill", false);
altColumnsFill = UserConfig.getBoolean(conn, chartName + "AltColumnsFill", false);
displayVlines = UserConfig.getBoolean(conn, chartName + "DisplayVlines", true);
displayHlines = UserConfig.getBoolean(conn, chartName + "DisplayHlines", true);
displayVZero = UserConfig.getBoolean(conn, chartName + "DisplayVZero", true);
displayHZero = UserConfig.getBoolean(conn, chartName + "DisplayHZero", true);
dotted = UserConfig.getBoolean(conn, chartName + "Dotted", false);
categoryFontSize = UserConfig.getInt(conn, chartName + "CategoryFontSize", 10);
categoryMargin = UserConfig.getInt(conn, chartName + "CategoryMargin", 2);
categoryTickRotation = UserConfig.getInt(conn, chartName + "CategoryTickRotation", 90);
numberFontSize = UserConfig.getInt(conn, chartName + "NumberFontSize", 10);
numberTickRotation = UserConfig.getInt(conn, chartName + "NumberTickRotation", 0);
lineWidth = UserConfig.getInt(conn, chartName + "LineWidth", 2);
symbolSize = UserConfig.getInt(conn, chartName + "SymbolSize", 10);
barGap = UserConfig.getDouble(conn, chartName + "BarGap", 2d);
categoryGap = chartType == ChartType.StackedBar ? 1
: UserConfig.getDouble(conn, chartName + "CategoryBarGap", 1d);
bubbleStyle = UserConfig.getString(conn, chartName + "BubbleStyle", DefaultBubbleStyle);
String saved = UserConfig.getString(conn, chartName + "LabelLocation", labelLocation.name());
if (saved != null) {
for (LabelLocation type : LabelLocation.values()) {
if (type.name().equals(saved)) {
labelLocation = type;
break;
}
}
}
categorySide = Side.BOTTOM;
saved = UserConfig.getString(conn, chartName + "CategorySide", "BOTTOM");
if (saved != null) {
for (Side value : Side.values()) {
if (value.name().equals(saved)) {
categorySide = value;
break;
}
}
}
numberSide = Side.LEFT;
saved = UserConfig.getString(conn, chartName + "NumberSide", "LEFT");
if (saved != null) {
for (Side value : Side.values()) {
if (value.name().equals(saved)) {
numberSide = value;
break;
}
}
}
categoryCoordinate = ChartCoordinate.Cartesian;
saved = UserConfig.getString(conn, chartName + "CategoryCoordinate", "Cartesian");
if (saved != null) {
for (ChartCoordinate value : ChartCoordinate.values()) {
if (value.name().equals(saved)) {
categoryCoordinate = value;
break;
}
}
}
numberCoordinate = ChartCoordinate.Cartesian;
saved = UserConfig.getString(conn, chartName + "NumberCoordinate", "Cartesian");
if (saved != null) {
for (ChartCoordinate value : ChartCoordinate.values()) {
if (value.name().equals(saved)) {
numberCoordinate = value;
break;
}
}
}
sizeCoordinate = ChartCoordinate.Cartesian;
saved = UserConfig.getString(conn, chartName + "SizeCoordinate", "Cartesian");
if (saved != null) {
for (ChartCoordinate value : ChartCoordinate.values()) {
if (value.name().equals(saved)) {
sizeCoordinate = value;
break;
}
}
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
return this;
}
/*
get/set
*/
public ChartCoordinate getCategoryCoordinate() {
categoryCoordinate = categoryCoordinate == null ? ChartCoordinate.Cartesian : categoryCoordinate;
return categoryCoordinate;
}
public void setCategoryCoordinate(ChartCoordinate categoryCoordinate) {
this.categoryCoordinate = categoryCoordinate;
UserConfig.setString(chartName + "CategoryCoordinate", getCategoryCoordinate().name());
}
public ChartCoordinate getNumberCoordinate() {
numberCoordinate = numberCoordinate == null ? ChartCoordinate.Cartesian : numberCoordinate;
return numberCoordinate;
}
public void setNumberCoordinate(ChartCoordinate numberCoordinate) {
this.numberCoordinate = numberCoordinate;
UserConfig.setString(chartName + "NumberCoordinate", getNumberCoordinate().name());
}
public ChartCoordinate getSizeCoordinate() {
sizeCoordinate = sizeCoordinate == null ? ChartCoordinate.Cartesian : sizeCoordinate;
return sizeCoordinate;
}
public void setSizeCoordinate(ChartCoordinate sizeCoordinate) {
this.sizeCoordinate = sizeCoordinate;
UserConfig.setString(chartName + "SizeCoordinate", getSizeCoordinate().name());
}
public ChartCoordinate getxCoordinate() {
return xCoordinate;
}
public void setxCoordinate(ChartCoordinate xCoordinate) {
this.xCoordinate = xCoordinate;
}
public ChartCoordinate getyCoordinate() {
return yCoordinate;
}
public void setyCoordinate(ChartCoordinate yCoordinate) {
this.yCoordinate = yCoordinate;
}
public int getLineWidth() {
if (lineWidth <= 0) {
lineWidth = 2;
}
return lineWidth;
}
public void setLineWidth(int lineWidth) {
this.lineWidth = lineWidth;
UserConfig.setInt(chartName + "LineWidth", getLineWidth());
}
public int getSymbolSize() {
if (symbolSize <= 0) {
symbolSize = 10;
}
return symbolSize;
}
public void setSymbolSize(int symbolSize) {
this.symbolSize = symbolSize;
UserConfig.setInt(chartName + "SymbolSize", getSymbolSize());
}
@Override
public XYChartOptions setCategoryLabel(String categoryLabel) {
this.categoryLabel = categoryLabel;
if (categoryAxis != null) {
categoryAxis.setLabel((displayLabelName ? message("Category") + ": " : "") + categoryLabel);
}
return this;
}
public int getCategoryFontSize() {
categoryFontSize = categoryFontSize < 0 ? 10 : categoryFontSize;
return categoryFontSize;
}
public void setCategoryFontSize(int categoryFontSize) {
this.categoryFontSize = categoryFontSize;
UserConfig.setInt(chartName + "CategoryFontSize", getCategoryFontSize());
if (categoryAxis != null) {
categoryAxis.setStyle("-fx-font-size: " + this.categoryFontSize + "px;");
}
}
public int getCategoryMargin() {
categoryMargin = categoryMargin < 0 ? 0 : categoryMargin;
return categoryMargin;
}
public void setCategoryMargin(int categoryMargin) {
this.categoryMargin = categoryMargin;
UserConfig.setInt(chartName + "CategoryMargin", getCategoryMargin());
if (categoryStringAxis != null) {
categoryStringAxis.setStartMargin(this.categoryMargin);
categoryStringAxis.setEndMargin(this.categoryMargin);
}
}
public int getCategoryTickRotation() {
categoryTickRotation = categoryTickRotation < 0 ? 90 : categoryTickRotation;
return categoryTickRotation;
}
public void setCategoryTickRotation(int categoryTickRotation) {
this.categoryTickRotation = categoryTickRotation;
UserConfig.setInt(chartName + "CategoryTickRotation", getCategoryTickRotation());
if (categoryAxis != null) {
categoryAxis.setTickLabelRotation(this.categoryTickRotation);
}
}
@Override
public XYChartOptions setValueLabel(String valueLabel) {
this.valueLabel = valueLabel;
if (valueAxis != null) {
valueAxis.setLabel((displayLabelName ? message("Value") + ": " : "") + valueLabel);
}
return this;
}
public int getNumberFontSize() {
numberFontSize = numberFontSize < 0 ? 10 : numberFontSize;
return numberFontSize;
}
public void setNumberFontSize(int numberFontSize) {
this.numberFontSize = numberFontSize;
UserConfig.setInt(chartName + "NumberFontSize", getNumberFontSize());
if (valueAxis != null) {
valueAxis.setStyle("-fx-font-size: " + this.numberFontSize + "px;");
}
}
public int getNumberTickRotation() {
numberTickRotation = numberTickRotation < 0 ? 0 : numberTickRotation;
return numberTickRotation;
}
public void setNumberTickRotation(int numberTickRotation) {
this.numberTickRotation = numberTickRotation;
UserConfig.setInt(chartName + "NumberTickRotation", getNumberTickRotation());
if (valueAxis != null) {
valueAxis.setTickLabelRotation(this.numberTickRotation);
}
}
@Override
public void setTickFontSize(int tickFontSize) {
super.setTickFontSize(tickFontSize);
if (categoryAxis != null) {
categoryAxis.setStyle("-fx-font-size: " + categoryFontSize
+ "px; -fx-tick-label-font-size: " + this.tickFontSize + "px; ");
}
if (valueAxis != null) {
valueAxis.setStyle("-fx-font-size: " + numberFontSize
+ "px; -fx-tick-label-font-size: " + this.tickFontSize + "px; ");
}
}
public boolean isIsXY() {
return isXY;
}
public void setIsXY(boolean isXY) {
this.isXY = isXY;
UserConfig.setBoolean(chartName + "XY", isXY);
}
public boolean isCategoryIsNumbers() {
return categoryIsNumbers;
}
public XYChartOptions setCategoryIsNumbers(boolean categoryIsNumbers) {
this.categoryIsNumbers = categoryIsNumbers;
return this;
}
public boolean isDisplayCategoryMark() {
return displayCategoryMark;
}
public void setDisplayCategoryMark(boolean displayCategoryMark) {
this.displayCategoryMark = displayCategoryMark;
UserConfig.setBoolean(chartName + "DisplayCategoryMark", displayCategoryMark);
if (categoryAxis != null) {
categoryAxis.setTickMarkVisible(displayCategoryMark);
}
}
public boolean isDisplayCategoryTick() {
return displayCategoryTick;
}
public void setDisplayCategoryTick(boolean displayCategoryTick) {
this.displayCategoryTick = displayCategoryTick;
UserConfig.setBoolean(chartName + "DisplayCategoryTick", displayCategoryTick);
if (categoryAxis != null) {
categoryAxis.setTickLabelsVisible(displayCategoryTick);
}
}
public boolean isDisplayNumberMark() {
return displayNumberMark;
}
public void setDisplayNumberMark(boolean displayNumberMark) {
this.displayNumberMark = displayNumberMark;
UserConfig.setBoolean(chartName + "DisplayNumberMark", displayNumberTick);
if (valueAxis != null) {
valueAxis.setTickMarkVisible(displayNumberMark);
}
}
public boolean isDisplayNumberTick() {
return displayNumberTick;
}
public void setDisplayNumberTick(boolean displayNumberTick) {
this.displayNumberTick = displayNumberTick;
UserConfig.setBoolean(chartName + "DisplayNumberTick", displayNumberTick);
if (valueAxis != null) {
valueAxis.setTickLabelsVisible(displayNumberTick);
}
}
public boolean isAltRowsFill() {
return altRowsFill;
}
public void setAltRowsFill(boolean altRowsFill) {
this.altRowsFill = altRowsFill;
UserConfig.setBoolean(chartName + "AltRowsFill", altRowsFill);
if (xyChart != null) {
xyChart.setAlternativeRowFillVisible(altRowsFill);
}
}
public boolean isAltColumnsFill() {
return altColumnsFill;
}
public void setAltColumnsFill(boolean altColumnsFill) {
this.altColumnsFill = altColumnsFill;
UserConfig.setBoolean(chartName + "AltColumnsFill", altColumnsFill);
if (xyChart != null) {
xyChart.setAlternativeColumnFillVisible(altColumnsFill);
}
}
public boolean isDisplayVlines() {
return displayVlines;
}
public void setDisplayVlines(boolean displayVlines) {
this.displayVlines = displayVlines;
UserConfig.setBoolean(chartName + "DisplayVlines", displayVlines);
if (xyChart != null) {
xyChart.setVerticalGridLinesVisible(displayVlines);
}
}
public boolean isDisplayHlines() {
return displayHlines;
}
public void setDisplayHlines(boolean displayHlines) {
this.displayHlines = displayHlines;
UserConfig.setBoolean(chartName + "DisplayHlines", displayHlines);
if (xyChart != null) {
xyChart.setHorizontalGridLinesVisible(displayHlines);
}
}
public boolean isDisplayVZero() {
return displayVZero;
}
public void setDisplayVZero(boolean displayVZero) {
this.displayVZero = displayVZero;
UserConfig.setBoolean(chartName + "DisplayVZero", displayVZero);
if (xyChart != null) {
xyChart.setVerticalZeroLineVisible(displayVZero);
}
}
public boolean isDisplayHZero() {
return displayHZero;
}
public void setDisplayHZero(boolean displayHZero) {
this.displayHZero = displayHZero;
UserConfig.setBoolean(chartName + "DisplayHZero", displayHZero);
if (xyChart != null) {
xyChart.setHorizontalZeroLineVisible(displayHZero);
}
}
public LabelLocation getLabelLocation() {
labelLocation = labelLocation == null ? LabelLocation.Center : labelLocation;
return labelLocation;
}
public void setLabelLocation(LabelLocation labelLocation) {
this.labelLocation = labelLocation;
UserConfig.setString(chartName + "LabelLocation", getLabelLocation().name());
}
public Side getCategorySide() {
categorySide = categorySide == null ? Side.BOTTOM : categorySide;
return categorySide;
}
public void setCategorySide(Side categorySide) {
this.categorySide = categorySide;
UserConfig.setString(chartName + "CategorySide", getCategorySide().name());
if (categoryAxis != null) {
categoryAxis.setSide(this.categorySide);
}
}
public Side getNumberSide() {
numberSide = numberSide == null ? Side.LEFT : numberSide;
return numberSide;
}
public void setNumberSide(Side numberSide) {
this.numberSide = numberSide;
UserConfig.setString(chartName + "NumberSide", getNumberSide().name());
if (valueAxis != null) {
valueAxis.setSide(this.numberSide);
}
}
public double getBarGap() {
barGap = barGap < 0 ? 0 : barGap;
return barGap;
}
public void setBarGap(double barGap) {
this.barGap = barGap;
UserConfig.setDouble(chartName + "BarGap", getBarGap());
}
public double getCategoryGap() {
categoryGap = categoryGap < 0 ? 1 : categoryGap;
return categoryGap;
}
public void setCategoryGap(double categoryGap) {
this.categoryGap = categoryGap;
UserConfig.setDouble(chartName + "CategoryBarGap", getCategoryGap());
}
public XYChart getXyChart() {
return xyChart;
}
public void setXyChart(XYChart xyChart) {
this.xyChart = xyChart;
}
public CategoryAxis getCategoryStringAxis() {
return categoryStringAxis;
}
public void setCategoryStringAxis(CategoryAxis categoryStringAxis) {
this.categoryStringAxis = categoryStringAxis;
}
public NumberAxis getCategoryNumberAxis() {
return categoryNumberAxis;
}
public void setCategoryNumberAxis(NumberAxis categoryNumberAxis) {
this.categoryNumberAxis = categoryNumberAxis;
}
public NumberAxis getValueAxis() {
return valueAxis;
}
public void setValueAxis(NumberAxis valueAxis) {
this.valueAxis = valueAxis;
}
public Axis getxAxis() {
return xAxis;
}
public void setxAxis(Axis xAxis) {
this.xAxis = xAxis;
}
public Axis getyAxis() {
return yAxis;
}
public void setyAxis(Axis yAxis) {
this.yAxis = yAxis;
}
public Axis getCategoryAxis() {
return categoryAxis;
}
public void setCategoryAxis(Axis categoryAxis) {
this.categoryAxis = categoryAxis;
}
public String getBubbleStyle() {
bubbleStyle = bubbleStyle == null || bubbleStyle.isBlank() ? DefaultBubbleStyle : bubbleStyle;
return bubbleStyle;
}
public void setBubbleStyle(String bubbleStyle) {
this.bubbleStyle = bubbleStyle;
UserConfig.setString(chartName + "BubbleStyle", bubbleStyle);
if (bubbleChart != null) {
ChartTools.setBubbleChartStyle(bubbleChart, getBubbleStyle(), palette, legendSide != null);
}
}
public boolean isDotted() {
return dotted;
}
public XYChartOptions<X, Y> setDotted(boolean dotted) {
this.dotted = dotted;
UserConfig.setBoolean(chartName + "Dotted", dotted);
return this;
}
public LabeledLineChart getLineChart() {
return lineChart;
}
public void setLineChart(LabeledLineChart lineChart) {
this.lineChart = lineChart;
}
public LabeledBarChart getBarChart() {
return barChart;
}
public void setBarChart(LabeledBarChart barChart) {
this.barChart = barChart;
}
public LabeledStackedBarChart getStackedBarChart() {
return stackedBarChart;
}
public void setStackedBarChart(LabeledStackedBarChart stackedBarChart) {
this.stackedBarChart = stackedBarChart;
}
public LabeledScatterChart getScatterChart() {
return scatterChart;
}
public void setScatterChart(LabeledScatterChart scatterChart) {
this.scatterChart = scatterChart;
}
public LabeledAreaChart getAreaChart() {
return areaChart;
}
public void setAreaChart(LabeledAreaChart areaChart) {
this.areaChart = areaChart;
}
public LabeledStackedAreaChart getStackedAreaChart() {
return stackedAreaChart;
}
public void setStackedAreaChart(LabeledStackedAreaChart stackedAreaChart) {
this.stackedAreaChart = stackedAreaChart;
}
public LabeledBubbleChart getBubbleChart() {
return bubbleChart;
}
public void setBubbleChart(LabeledBubbleChart bubbleChart) {
this.bubbleChart = bubbleChart;
}
public BoxWhiskerChart getBoxWhiskerChart() {
return boxWhiskerChart;
}
public void setBoxWhiskerChart(BoxWhiskerChart boxWhiskerChart) {
this.boxWhiskerChart = boxWhiskerChart;
}
public SimpleRegressionChart getSimpleRegressionChart() {
return simpleRegressionChart;
}
public void setSimpleRegressionChart(SimpleRegressionChart simpleRegressionChart) {
this.simpleRegressionChart = simpleRegressionChart;
}
public ResidualChart getResidualChart() {
return residualChart;
}
public void setResidualChart(ResidualChart residualChart) {
this.residualChart = residualChart;
}
public Sort getSort() {
return sort;
}
public void setSort(Sort sort) {
this.sort = sort;
}
}
| 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/fxml/chart/XYChartMaker.java | alpha/MyBox/src/main/java/mara/mybox/fxml/chart/XYChartMaker.java | package mara.mybox.fxml.chart;
import java.util.List;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import mara.mybox.db.data.ColumnDefinition.InvalidAs;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.LocateTools;
import mara.mybox.fxml.style.NodeStyleTools;
import mara.mybox.tools.DoubleTools;
import mara.mybox.tools.NumberTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-5-16
* @License Apache License Version 2.0
*/
public class XYChartMaker<X, Y> extends XYChartOptions<X, Y> {
public XYChartMaker() {
}
public XYChartMaker init(ChartType chartType, String chartName) {
clearChart();
this.chartType = chartType;
this.chartName = chartName;
initXYChartOptions();
return this;
}
/*
make chart
*/
public final XYChart makeChart() {
try {
clearChart();
if (chartType == null || chartName == null) {
return null;
}
initAxis();
switch (chartType) {
case Bar:
makeBarChart();
break;
case StackedBar:
makeStackedBarChart();
break;
case Line:
makeLineChart();
break;
case Scatter:
makeScatterChart();
break;
case Area:
makeAreaChart();
break;
case StackedArea:
makeStackedAreaChart();
break;
case Bubble:
makeBubbleChart();
break;
case BoxWhiskerChart:
makeBoxWhiskerChart();
break;
case SimpleRegressionChart:
makeSimpleRegressionChart();
break;
case ResidualChart:
makeResidualChart();
break;
default:
break;
}
if (xyChart == null) {
return null;
}
initXYChart();
styleChart();
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
return xyChart;
}
@Override
public void clearChart() {
super.clearChart();
xyChart = null;
lineChart = null;
barChart = null;
stackedBarChart = null;
areaChart = null;
stackedAreaChart = null;
bubbleChart = null;
scatterChart = null;
boxWhiskerChart = null;
simpleRegressionChart = null;
residualChart = null;
categoryStringAxis = null;
categoryNumberAxis = null;
valueAxis = null;
xAxis = null;
yAxis = null;
categoryAxis = null;
}
public void initAxis() {
try {
if (categoryIsNumbers) {
categoryNumberAxis = new NumberAxis();
categoryAxis = categoryNumberAxis;
ChartTools.setChartCoordinate(categoryNumberAxis, categoryCoordinate);
} else {
categoryStringAxis = new CategoryAxis();
categoryAxis = categoryStringAxis;
categoryStringAxis.setGapStartAndEnd(true);
}
categoryAxis.setLabel((displayLabelName ? message("Category") + ": " : "") + getCategoryLabel());
categoryAxis.setSide(categorySide);
categoryAxis.setTickLabelsVisible(displayCategoryTick);
categoryAxis.setTickMarkVisible(displayCategoryMark);
categoryAxis.setTickLabelRotation(categoryTickRotation);
categoryAxis.setAnimated(false);
categoryAxis.setStyle("-fx-font-size: " + categoryFontSize
+ "px; -fx-tick-label-font-size: " + tickFontSize + "px; ");
valueAxis = new NumberAxis();
valueAxis.setLabel((displayLabelName ? message("Value") + ": " : "") + getValueLabel());
valueAxis.setSide(numberSide);
valueAxis.setTickLabelsVisible(displayNumberTick);
valueAxis.setTickMarkVisible(displayNumberMark);
valueAxis.setTickLabelRotation(numberTickRotation);
ChartTools.setChartCoordinate(valueAxis, numberCoordinate);
valueAxis.setStyle("-fx-font-size: " + numberFontSize
+ "px; -fx-tick-label-font-size: " + tickFontSize + "px; ");
if (isXY) {
xAxis = categoryAxis;
yAxis = valueAxis;
xCoordinate = categoryCoordinate;
yCoordinate = numberCoordinate;
} else {
xAxis = valueAxis;
yAxis = categoryAxis;
xCoordinate = numberCoordinate;
yCoordinate = categoryCoordinate;
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void initXYChart() {
try {
if (xyChart == null) {
return;
}
xyChart.setAlternativeRowFillVisible(altRowsFill);
xyChart.setAlternativeColumnFillVisible(altColumnsFill);
xyChart.setVerticalGridLinesVisible(displayVlines);
xyChart.setHorizontalGridLinesVisible(displayHlines);
xyChart.setVerticalZeroLineVisible(displayVZero);
xyChart.setHorizontalZeroLineVisible(displayHZero);
if (legendSide == null) {
xyChart.setLegendVisible(false);
} else {
xyChart.setLegendVisible(true);
xyChart.setLegendSide(legendSide);
}
xyChart.getXAxis().setAnimated(false); // If not, the axis becomes messed
chart = xyChart;
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public boolean makeLineChart() {
try {
lineChart = new LabeledLineChart(xAxis, yAxis).setMaker(this);
if (sort == Sort.X) {
lineChart.setAxisSortingPolicy(LineChart.SortingPolicy.X_AXIS);
} else if (sort == Sort.Y) {
lineChart.setAxisSortingPolicy(LineChart.SortingPolicy.Y_AXIS);
} else {
lineChart.setAxisSortingPolicy(LineChart.SortingPolicy.NONE);
}
xyChart = lineChart;
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public boolean makeBarChart() {
try {
barChart = new LabeledBarChart(xAxis, yAxis).setMaker(this);
barChart.setBarGap(barGap);
barChart.setCategoryGap(categoryGap);
xyChart = barChart;
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public boolean makeStackedBarChart() {
try {
stackedBarChart = new LabeledStackedBarChart(xAxis, yAxis).setMaker(this);
stackedBarChart.setCategoryGap(categoryGap);
xyChart = stackedBarChart;
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public boolean makeScatterChart() {
try {
scatterChart = new LabeledScatterChart(xAxis, yAxis).setMaker(this);
xyChart = scatterChart;
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public boolean makeAreaChart() {
try {
areaChart = new LabeledAreaChart(xAxis, yAxis).setMaker(this);
xyChart = areaChart;
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public boolean makeStackedAreaChart() {
try {
stackedAreaChart = new LabeledStackedAreaChart(xAxis, yAxis).setMaker(this);
xyChart = stackedAreaChart;
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public boolean makeBubbleChart() {
try {
bubbleChart = new LabeledBubbleChart(xAxis, yAxis).setMaker(this);
xyChart = bubbleChart;
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public boolean makeBoxWhiskerChart() {
try {
boxWhiskerChart = new BoxWhiskerChart(xAxis, yAxis);
boxWhiskerChart.setMaker(this);
xyChart = boxWhiskerChart;
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public boolean makeSimpleRegressionChart() {
try {
simpleRegressionChart = new SimpleRegressionChart(xAxis, yAxis);
simpleRegressionChart.setMaker(this);
xyChart = simpleRegressionChart;
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public boolean makeResidualChart() {
try {
residualChart = new ResidualChart(xAxis, yAxis);
residualChart.setMaker(this);
xyChart = residualChart;
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public void writeXYChart(List<Data2DColumn> columns, List<List<String>> data,
int categoryIndex, List<Integer> valueIndices) {
try {
if (columns == null || data == null || categoryIndex < 0
|| valueIndices == null || valueIndices.isEmpty()) {
return;
}
if (chartType == ChartType.Bubble) {
writeBubbleChart(columns, data, categoryIndex, valueIndices.get(0),
valueIndices.subList(1, valueIndices.size()));
return;
}
xyChart.getData().clear();
XYChart.Data xyData;
int index = 0;
for (int colIndex : valueIndices) {
Data2DColumn column = columns.get(colIndex);
String colName = column.getColumnName();
XYChart.Series series = new XYChart.Series();
series.setName(colName);
double numberValue;
for (List<String> rowData : data) {
String category = rowData.get(categoryIndex);
if (category == null) {
category = "";
}
numberValue = scaleValue(rowData.get(colIndex));
if (DoubleTools.invalidDouble(numberValue)) {
if (invalidAs == InvalidAs.Zero) {
numberValue = 0;
} else {
continue;
}
}
numberValue = ChartTools.coordinateValue(numberCoordinate, numberValue);
if (isXY) {
if (xyChart.getXAxis() instanceof NumberAxis) {
double categoryValue = scaleValue(category);
if (DoubleTools.invalidDouble(categoryValue)) {
if (invalidAs == InvalidAs.Zero) {
categoryValue = 0;
} else {
continue;
}
}
xyData = new XYChart.Data(categoryValue, numberValue);
} else {
xyData = new XYChart.Data(category, numberValue);
}
} else {
if (xyChart.getYAxis() instanceof NumberAxis) {
double categoryValue = scaleValue(category);
if (DoubleTools.invalidDouble(categoryValue)) {
if (invalidAs == InvalidAs.Zero) {
categoryValue = 0;
} else {
continue;
}
}
xyData = new XYChart.Data(numberValue, categoryValue);
} else {
xyData = new XYChart.Data(numberValue, category);
}
}
series.getData().add(xyData);
}
xyChart.getData().add(index++, series);
}
setChartStyle();
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void writeBubbleChart(List<Data2DColumn> columns, List<List<String>> data,
int catgoryCol, int numberCol, List<Integer> sizeCols) {
try {
if (columns == null || data == null || catgoryCol < 0
|| numberCol < 0 || sizeCols == null || sizeCols.isEmpty()) {
return;
}
xyChart.getData().clear();
XYChart.Data xyData;
int index = 0;
for (int col : sizeCols) {
Data2DColumn column = columns.get(col);
String colName = column.getColumnName();
XYChart.Series series = new XYChart.Series();
series.setName(colName);
double categoryValue, categoryCoordinateValue, numberValue, numberCoordinateValue,
sizeValue, sizeCoordinateValue;
for (List<String> rowData : data) {
categoryValue = scaleValue(rowData.get(catgoryCol));
categoryCoordinateValue = ChartTools.coordinateValue(categoryCoordinate, categoryValue);
numberValue = scaleValue(rowData.get(numberCol));
numberCoordinateValue = ChartTools.coordinateValue(numberCoordinate, numberValue);
sizeValue = scaleValue(rowData.get(col));
if (sizeValue <= 0) {
continue;
}
sizeCoordinateValue = ChartTools.coordinateValue(sizeCoordinate, sizeValue);
if (isXY) {
xyData = new XYChart.Data(categoryCoordinateValue, numberCoordinateValue);
} else {
xyData = new XYChart.Data(numberCoordinateValue, categoryCoordinateValue);
}
xyData.setExtraValue(sizeCoordinateValue);
series.getData().add(xyData);
}
xyChart.getData().add(index++, series);
}
setChartStyle();
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
/*
style
*/
public void setChartStyle() {
if (xyChart == null) {
return;
}
if (barChart != null) {
ChartTools.setBarChartStyle(barChart, palette, legendSide != null);
} else if (stackedBarChart != null) {
ChartTools.setBarChartStyle(stackedBarChart, palette, legendSide != null);
} else if (lineChart != null) {
ChartTools.setLineChartStyle(lineChart, lineWidth, symbolSize, palette, legendSide != null, dotted);
} else if (areaChart != null) {
ChartTools.setAreaChartStyle(areaChart, lineWidth, symbolSize, palette, legendSide != null);
} else if (stackedAreaChart != null) {
ChartTools.setAreaChartStyle(stackedAreaChart, lineWidth, symbolSize, palette, legendSide != null);
} else if (scatterChart != null) {
ChartTools.setScatterChartStyle(scatterChart, symbolSize, palette, legendSide != null);
} else if (bubbleChart != null) {
ChartTools.setBubbleChartStyle(bubbleChart, bubbleStyle, palette, legendSide != null);
} else if (boxWhiskerChart != null) {
ChartTools.setLineChartStyle(boxWhiskerChart, lineWidth, symbolSize, palette, legendSide != null, dotted);
} else if (simpleRegressionChart != null) {
ChartTools.setScatterChartStyle(simpleRegressionChart, symbolSize, palette, legendSide != null);
} else if (residualChart != null) {
ChartTools.setScatterChartStyle(residualChart, symbolSize, palette, legendSide != null);
}
}
/*
labels
*/
protected void makeLabels(XYChart.Series<X, Y> series, ObservableList<Node> nodes) {
if (labelType == null || xyChart == null) {
return;
}
try {
for (int s = 0; s < series.getData().size(); s++) {
XYChart.Data<X, Y> item = series.getData().get(s);
Node label = makeLabel(series.getName(), item);
if (label != null) {
label.setStyle("-fx-font-size: " + labelFontSize + "px; -fx-text-fill: black;");
nodeLabels.put(item.getNode(), label);
nodes.add(label);
}
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
private Node makeLabel(String numberName, XYChart.Data item) {
if (item == null || item.getNode() == null) {
return null;
}
try {
String categoryName, category, number, extra, categoryDis, numberDis, extraDis;
if (isXY) {
categoryName = xyChart.getXAxis().getLabel();
category = item.getXValue() == null ? "" : item.getXValue().toString();
if (categoryIsNumbers) {
categoryDis = NumberTools.format(ChartTools.realValue(xCoordinate, Double.parseDouble(category)), scale);
} else {
categoryDis = category;
}
number = item.getYValue() == null ? "" : item.getYValue().toString();
numberDis = NumberTools.format(ChartTools.realValue(yCoordinate, Double.parseDouble(number)), scale);
} else {
categoryName = xyChart.getYAxis().getLabel();
category = item.getYValue() == null ? "" : item.getYValue().toString();
if (categoryIsNumbers) {
categoryDis = NumberTools.format(ChartTools.realValue(yCoordinate, Double.parseDouble(category)), scale);
} else {
categoryDis = category;
}
number = item.getXValue() == null ? "" : item.getXValue().toString();
numberDis = NumberTools.format(ChartTools.realValue(xCoordinate, Double.parseDouble(number)), scale);
}
if (item.getExtraValue() != null) {
double d = (double) item.getExtraValue();
extra = "\n" + (displayLabelName ? message("Size") + ": " : "") + NumberTools.format(d, scale);
extraDis = "\n" + (displayLabelName ? message("Size") + ": " : "")
+ NumberTools.format(ChartTools.realValue(sizeCoordinate, d), scale);
} else {
extra = "";
extraDis = "";
}
if (popLabel || labelType == LabelType.Pop) {
NodeStyleTools.setTooltip(item.getNode(),
categoryName + ": " + categoryDis + "\n"
+ numberName + ": " + numberDis + extraDis);
}
if (labelType == null || labelType == LabelType.NotDisplay) {
return null;
}
String display = null;
switch (labelType) {
case Category:
display = (displayLabelName ? categoryName + ": " : "") + categoryDis;
break;
case Value:
display = (displayLabelName ? numberName + ": " : "") + numberDis + extraDis;
break;
case CategoryAndValue:
display = (displayLabelName ? categoryName + ": " : "") + categoryDis + "\n"
+ (displayLabelName ? numberName + ": " : "") + numberDis + extraDis;
break;
}
if (display != null && !display.isBlank()) {
Text text = new Text(display);
text.setTextAlignment(TextAlignment.CENTER);
return text;
} else {
return null;
}
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
protected void displayLabels() {
if (nodeLabels == null
|| labelType == null || labelLocation == null
|| labelType == LabelType.NotDisplay || labelType == LabelType.Pop) {
return;
}
for (Node node : nodeLabels.keySet()) {
Node text = nodeLabels.get(node);
switch (labelLocation) {
case Below:
LocateTools.belowCenter(text, node);
break;
case Above:
LocateTools.aboveCenter(text, node);
break;
case Center:
LocateTools.center(text, node);
break;
}
}
}
protected void removeLabels(ObservableList<Node> nodes) {
if (nodeLabels == null
|| labelType == null || labelType == LabelType.NotDisplay || labelType == LabelType.Pop) {
return;
}
for (Node node : nodeLabels.keySet()) {
Node text = nodeLabels.get(node);
nodes.remove(text);
}
nodeLabels.clear();
}
}
| 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/fxml/chart/ChartOptions.java | alpha/MyBox/src/main/java/mara/mybox/fxml/chart/ChartOptions.java | package mara.mybox.fxml.chart;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.chart.Chart;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import mara.mybox.db.data.ColumnDefinition.InvalidAs;
import mara.mybox.db.DerbyBase;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.DoubleTools;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2022-5-11
* @License Apache License Version 2.0
*/
public class ChartOptions<X, Y> {
protected String chartName;
protected ChartType chartType;
protected Chart chart;
protected LabelType labelType;
protected String defaultChartTitle, defaultCategoryLabel, defaultValueLabel,
chartTitle, categoryLabel, valueLabel;
protected int scale, labelFontSize, titleFontSize, tickFontSize;
protected boolean popLabel, displayLabelName, plotAnimated;
protected Side titleSide, legendSide;
protected InvalidAs invalidAs;
protected Map<Node, Node> nodeLabels = new HashMap<>();
protected Map<String, String> palette;
public static enum ChartType {
Bar, StackedBar, Line, Bubble, Scatter, Area, StackedArea, Pie,
BoxWhiskerChart, SimpleRegressionChart, ResidualChart
}
public static enum LabelType {
NotDisplay, CategoryAndValue, Value, Category, Pop, Point
}
public ChartOptions() {
}
public ChartOptions(String chartName) {
this.chartName = chartName;
}
public void clearChart() {
chart = null;
invalidAs = null;
}
public final void initChartOptions() {
clearChart();
if (chartName == null) {
return;
}
try ( Connection conn = DerbyBase.getConnection()) {
popLabel = UserConfig.getBoolean(conn, chartName + "PopLabel", true);
displayLabelName = UserConfig.getBoolean(conn, chartName + "DisplayLabelName", false);
scale = UserConfig.getInt(conn, chartName + "Scale", 2);
labelFontSize = UserConfig.getInt(conn, chartName + "LabelFontSize", 10);
titleFontSize = UserConfig.getInt(conn, chartName + "TitleFontSize", 12);
tickFontSize = UserConfig.getInt(conn, chartName + "TickFontSize", 10);
if (chartType == ChartType.BoxWhiskerChart
|| chartType == ChartType.Scatter
|| chartType == ChartType.SimpleRegressionChart
|| chartType == ChartType.ResidualChart) {
labelType = LabelType.Point;
} else {
labelType = LabelType.NotDisplay;
String saved = UserConfig.getString(conn, chartName + "LabelType", "NotDisplay");
if (saved != null) {
for (LabelType type : LabelType.values()) {
if (type.name().equals(saved)) {
labelType = type;
break;
}
}
}
}
titleSide = Side.TOP;
String saved = UserConfig.getString(conn, chartName + "TitleSide", "TOP");
if (saved != null) {
for (Side value : Side.values()) {
if (value.name().equals(saved)) {
titleSide = value;
break;
}
}
}
legendSide = Side.TOP;
saved = UserConfig.getString(conn, chartName + "LegendSide", "TOP");
if (saved != null) {
if ("NotDisplay".equals(saved)) {
legendSide = null;
} else {
for (Side value : Side.values()) {
if (value.name().equals(saved)) {
legendSide = value;
break;
}
}
}
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public Chart drawChart() {
return chart;
}
public void styleChart() {
try {
if (chart == null) {
return;
}
chart.setStyle("-fx-font-size: " + titleFontSize
+ "px; -fx-tick-label-font-size: " + tickFontSize + "px; ");
chart.setTitle(getChartTitle());
chart.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
VBox.setVgrow(chart, Priority.ALWAYS);
HBox.setHgrow(chart, Priority.ALWAYS);
chart.setAnimated(plotAnimated);
chart.setTitleSide(titleSide);
chart.setLegendSide(legendSide);
AnchorPane.setTopAnchor(chart, 2d);
AnchorPane.setBottomAnchor(chart, 2d);
AnchorPane.setLeftAnchor(chart, 2d);
AnchorPane.setRightAnchor(chart, 2d);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public boolean displayLabel() {
return labelType != null && labelType != LabelType.NotDisplay;
}
public boolean popLabel() {
return popLabel || labelType == LabelType.Pop;
}
public boolean labelVisible() {
return labelType == LabelType.Category
|| labelType == LabelType.Value
|| labelType == LabelType.CategoryAndValue;
}
public boolean showLegend() {
return legendSide != null;
}
public double doubleValue(String v) {
return DoubleTools.toDouble(v, invalidAs);
}
public double scaleValue(String v) {
return DoubleTools.scale(v, invalidAs, scale);
}
protected void setLabelsStyle() {
if (nodeLabels == null) {
return;
}
for (Node node : nodeLabels.values()) {
node.setStyle("-fx-font-size: " + labelFontSize + "px; -fx-text-fill: black;");;
}
}
/*
get/set
*/
public String getChartName() {
return chartName;
}
public ChartOptions setChartName(String chartName) {
this.chartName = chartName;
return this;
}
public ChartType getChartType() {
return chartType;
}
public ChartOptions setChartType(ChartType chartType) {
this.chartType = chartType;
return this;
}
public Chart getChart() {
return chart;
}
public void setChart(Chart chart) {
this.chart = chart;
}
public LabelType getLabelType() {
labelType = labelType == null ? LabelType.Point : labelType;
return labelType;
}
public ChartOptions setLabelType(LabelType labelType) {
this.labelType = labelType;
UserConfig.setString(chartName + "LabelType", getLabelType().name());
return this;
}
public String getChartTitle() {
chartTitle = chartTitle == null ? defaultChartTitle : chartTitle;
return chartTitle;
}
public ChartOptions setChartTitle(String chartTitle) {
this.chartTitle = chartTitle;
if (chart != null) {
chart.setTitle(this.chartTitle);
}
return this;
}
public boolean isPlotAnimated() {
return plotAnimated;
}
public void setPlotAnimated(boolean plotAnimated) {
this.plotAnimated = plotAnimated;
UserConfig.setBoolean(chartName + "PlotAnimated", plotAnimated);
if (chart != null) {
chart.setAnimated(plotAnimated);
}
}
public int getTitleFontSize() {
titleFontSize = titleFontSize <= 0 ? 12 : titleFontSize;
return titleFontSize;
}
public void setTitleFontSize(int titleFontSize) {
this.titleFontSize = titleFontSize;
UserConfig.setInt(chartName + "TitleFontSize", getTitleFontSize());
if (chart != null) {
chart.setStyle("-fx-font-size: " + this.titleFontSize
+ "px; -fx-tick-label-font-size: " + tickFontSize + "px; ");
}
}
public int getTickFontSize() {
tickFontSize = tickFontSize <= 0 ? 10 : tickFontSize;
return tickFontSize;
}
public void setTickFontSize(int tickFontSize) {
this.tickFontSize = tickFontSize;
UserConfig.setInt(chartName + "TickFontSize", getTickFontSize());
if (chart != null) {
chart.setStyle("-fx-font-size: " + titleFontSize
+ "px; -fx-tick-label-font-size: " + this.tickFontSize + "px; ");
}
}
public Side getTitleSide() {
titleSide = titleSide == null ? Side.TOP : titleSide;
return titleSide;
}
public void setTitleSide(Side titleSide) {
this.titleSide = titleSide;
UserConfig.setString(chartName + "TitleSide", getTitleSide().name());
if (chart != null) {
chart.setTitleSide(this.titleSide);
}
}
public Side getLegendSide() {
return legendSide;
}
public void setLegendSide(Side legendSide) {
this.legendSide = legendSide;
UserConfig.setString(chartName + "LegendSide", legendSide == null ? "NotDisplay" : getLegendSide().name());
if (chart != null) {
if (legendSide == null) {
chart.setLegendVisible(false);
} else {
chart.setLegendVisible(true);
chart.setLegendSide(legendSide);
}
}
}
public boolean isPopLabel() {
return popLabel;
}
public void setPopLabel(boolean popLabel) {
this.popLabel = popLabel;
}
public boolean isDisplayLabelName() {
return displayLabelName;
}
public void setDisplayLabelName(boolean displayLabelName) {
this.displayLabelName = displayLabelName;
UserConfig.setBoolean(chartName + "DisplayLabelName", displayLabelName);
}
public int getScale() {
scale = scale < 0 ? 2 : scale;
return scale;
}
public void setScale(int scale) {
this.scale = scale;
UserConfig.setInt(chartName + "Scale", getScale());
}
public Map<String, String> getPalette() {
return palette;
}
public ChartOptions setPalette(Map<String, String> palette) {
this.palette = palette;
return this;
}
public int getLabelFontSize() {
labelFontSize = labelFontSize <= 0 ? 10 : labelFontSize;
return labelFontSize;
}
public void setLabelFontSize(int labelFontSize) {
this.labelFontSize = labelFontSize;
UserConfig.setInt(chartName + "LabelFontSize", getLabelFontSize());
setLabelsStyle();
}
public String getCategoryLabel() {
categoryLabel = categoryLabel == null ? getDefaultCategoryLabel() : categoryLabel;
return categoryLabel;
}
public ChartOptions setCategoryLabel(String categoryLabel) {
this.categoryLabel = categoryLabel;
return this;
}
public String getDefaultChartTitle() {
return defaultChartTitle;
}
public ChartOptions setDefaultChartTitle(String defaultChartTitle) {
this.defaultChartTitle = defaultChartTitle;
this.chartTitle = defaultChartTitle;
return this;
}
public String getDefaultCategoryLabel() {
defaultCategoryLabel = defaultCategoryLabel == null ? message("Category") : defaultCategoryLabel;
return defaultCategoryLabel;
}
public ChartOptions setDefaultCategoryLabel(String defaultCategoryLabel) {
this.defaultCategoryLabel = defaultCategoryLabel;
setCategoryLabel(defaultCategoryLabel);
return this;
}
public String getValueLabel() {
valueLabel = valueLabel == null ? getDefaultValueLabel() : valueLabel;
return valueLabel;
}
public ChartOptions setValueLabel(String valueLabel) {
this.valueLabel = valueLabel;
return this;
}
public String getDefaultValueLabel() {
defaultValueLabel = defaultValueLabel == null ? message("Value") : defaultValueLabel;
return defaultValueLabel;
}
public ChartOptions setDefaultValueLabel(String defaultValueLabel) {
this.defaultValueLabel = defaultValueLabel;
setValueLabel(defaultValueLabel);
return this;
}
public ChartOptions setInvalidAs(InvalidAs invalidAs) {
this.invalidAs = invalidAs;
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/fxml/chart/LabeledStackedBarChart.java | alpha/MyBox/src/main/java/mara/mybox/fxml/chart/LabeledStackedBarChart.java | package mara.mybox.fxml.chart;
import javafx.geometry.Side;
import javafx.scene.chart.Axis;
import javafx.scene.chart.StackedBarChart;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import mara.mybox.dev.MyBoxLog;
/**
* Reference:
* https://stackoverflow.com/questions/34286062/how-to-clear-text-added-in-a-javafx-barchart/41494789#41494789
* By Roland
*
* @Author Mara
* @CreateDate 2022-1-25
* @License Apache License Version 2.0
*/
public class LabeledStackedBarChart<X, Y> extends StackedBarChart<X, Y> {
protected XYChartMaker chartMaker;
public LabeledStackedBarChart(Axis xAxis, Axis yAxis) {
super(xAxis, yAxis);
init();
}
public final void init() {
this.setLegendSide(Side.TOP);
this.setMaxWidth(Double.MAX_VALUE);
this.setMaxHeight(Double.MAX_VALUE);
VBox.setVgrow(this, Priority.ALWAYS);
HBox.setHgrow(this, Priority.ALWAYS);
chartMaker = new XYChartMaker<Axis, Axis>();
}
public LabeledStackedBarChart setMaker(XYChartMaker<X, Y> chartMaker) {
this.chartMaker = chartMaker;
return this;
}
@Override
protected void seriesAdded(Series<X, Y> series, int seriesIndex) {
super.seriesAdded(series, seriesIndex);
chartMaker.makeLabels(series, getPlotChildren());
}
@Override
protected void seriesRemoved(final Series<X, Y> series) {
chartMaker.removeLabels(getPlotChildren());
super.seriesRemoved(series);
}
@Override
protected void layoutPlotChildren() {
try {
super.layoutPlotChildren();
chartMaker.displayLabels();
} catch (Exception e) {
MyBoxLog.debug(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/fxml/chart/BoxWhiskerChart.java | alpha/MyBox/src/main/java/mara/mybox/fxml/chart/BoxWhiskerChart.java | package mara.mybox.fxml.chart;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import javafx.application.Platform;
import javafx.geometry.Bounds;
import javafx.scene.chart.Axis;
import javafx.scene.chart.XYChart;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.shape.Rectangle;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2022-4-27
* @License Apache License Version 2.0
*/
public class BoxWhiskerChart<X, Y> extends LabeledLineChart<X, Y> {
protected Rectangle[] boxs;
protected Line[] vLines, minLines, maxLines, medianLines, meanLines,
uMidOutlierLines, uExOutlierLines, lMidOutlierLines, lExOutlierLines;
protected int boxWidth, dataSize, currentSeriesSize;
protected boolean handleOutliers, handleMean;
public BoxWhiskerChart(Axis xAxis, Axis yAxis) {
super(xAxis, yAxis);
init();
currentSeriesSize = 0;
}
public int currentSeriesSize() {
currentSeriesSize = getData() == null ? 0 : getData().size();
return currentSeriesSize;
}
public int expectedSeriesSize() {
int seriesSize = 5;
if (handleMean) {
seriesSize++;
}
if (handleOutliers) {
seriesSize += 4;
}
return seriesSize;
}
@Override
protected void layoutPlotChildren() {
super.layoutPlotChildren();
currentSeriesSize();
}
private void clearMain() {
try {
if (boxs != null) {
for (Rectangle rect : boxs) {
getPlotChildren().remove(rect);
}
boxs = null;
}
if (vLines != null) {
for (Line line : vLines) {
getPlotChildren().remove(line);
}
vLines = null;
}
if (minLines != null) {
for (Line line : minLines) {
getPlotChildren().remove(line);
}
minLines = null;
}
if (maxLines != null) {
for (Line line : maxLines) {
getPlotChildren().remove(line);
}
maxLines = null;
}
if (medianLines != null) {
for (Line line : medianLines) {
getPlotChildren().remove(line);
}
medianLines = null;
}
} catch (Exception e) {
}
}
private void clearMean() {
try {
if (meanLines != null) {
for (Line line : meanLines) {
getPlotChildren().remove(line);
}
meanLines = null;
}
} catch (Exception e) {
}
}
private void clearOutliers() {
try {
if (uMidOutlierLines != null) {
for (Line line : uMidOutlierLines) {
getPlotChildren().remove(line);
}
uMidOutlierLines = null;
}
if (uExOutlierLines != null) {
for (Line line : uExOutlierLines) {
getPlotChildren().remove(line);
}
uExOutlierLines = null;
}
if (lMidOutlierLines != null) {
for (Line line : lMidOutlierLines) {
getPlotChildren().remove(line);
}
lMidOutlierLines = null;
}
if (lExOutlierLines != null) {
for (Line line : lExOutlierLines) {
getPlotChildren().remove(line);
}
lExOutlierLines = null;
}
} catch (Exception e) {
}
}
private void makeMain() {
try {
clearMain();
if (!chartMaker.displayLabel()) {
return;
}
List<XYChart.Series<X, Y>> seriesList = this.getData();
int startIndex = handleMean ? 1 : 0;
if (seriesList == null || seriesList.size() < 5 + startIndex) {
return;
}
dataSize = seriesList.get(startIndex + 0).getData().size();
boxs = new Rectangle[dataSize];
vLines = new Line[dataSize];
minLines = new Line[dataSize];
maxLines = new Line[dataSize];
medianLines = new Line[dataSize];
if (boxWidth <= 0) {
boxWidth = 40;
}
List<XYChart.Data<X, Y>> data0 = seriesList.get(startIndex + 0).getData();
List<XYChart.Data<X, Y>> data1 = seriesList.get(startIndex + 1).getData();
List<XYChart.Data<X, Y>> data2 = seriesList.get(startIndex + 2).getData();
List<XYChart.Data<X, Y>> data3 = seriesList.get(startIndex + 3).getData();
List<XYChart.Data<X, Y>> data4 = seriesList.get(startIndex + 4).getData();
Map<String, String> palette = chartMaker.getPalette();
String color0 = palette.get(seriesList.get(startIndex + 0).getName());
String color2 = palette.get(seriesList.get(startIndex + 2).getName());
String color4 = palette.get(seriesList.get(startIndex + 4).getName());
for (int i = 0; i < dataSize; i++) {
Bounds regionBounds4 = data4.get(i).getNode().getBoundsInParent();
Bounds regionBounds3 = data3.get(i).getNode().getBoundsInParent();
Bounds regionBounds2 = data2.get(i).getNode().getBoundsInParent();
Bounds regionBounds1 = data1.get(i).getNode().getBoundsInParent();
Bounds regionBounds0 = data0.get(i).getNode().getBoundsInParent();
vLines[i] = new Line();
getPlotChildren().add(vLines[i]);
vLines[i].setStyle("-fx-stroke-dash-array: 4;-fx-stroke-width:1px; -fx-stroke:black;");
maxLines[i] = new Line();
getPlotChildren().add(maxLines[i]);
maxLines[i].setStyle("-fx-stroke-width:2px;-fx-stroke:" + color4);
medianLines[i] = new Line();
getPlotChildren().add(medianLines[i]);
medianLines[i].setStyle("-fx-stroke-width:2px;-fx-stroke:" + color2);
minLines[i] = new Line();
getPlotChildren().add(minLines[i]);
minLines[i].setStyle("-fx-stroke-width:2px;-fx-stroke:" + color0);
boxs[i] = new Rectangle();
boxs[i].setWidth(boxWidth);
boxs[i].setFill(Color.TRANSPARENT);
boxs[i].setStyle("-fx-stroke-width:1px; -fx-stroke:black;");
getPlotChildren().add(boxs[i]);
if (chartMaker.isXY) {
double y4 = regionBounds4.getMinY() + regionBounds4.getHeight() / 2;
double y3 = regionBounds3.getMinY() + regionBounds3.getHeight() / 2;
double y2 = regionBounds2.getMinY() + regionBounds2.getHeight() / 2;
double y1 = regionBounds1.getMinY() + regionBounds1.getHeight() / 2;
double y0 = regionBounds0.getMinY() + regionBounds0.getHeight() / 2;
double x = regionBounds3.getMinX() + regionBounds3.getWidth() / 2;
double leftX = x - boxWidth / 2;
double rightX = x + boxWidth / 2;
boxs[i].setLayoutX(leftX);
boxs[i].setLayoutY(y3);
boxs[i].setWidth(boxWidth);
boxs[i].setHeight(y1 - y3);
vLines[i].setStartX(x);
vLines[i].setStartY(y4);
vLines[i].setEndX(x);
vLines[i].setEndY(y0);
maxLines[i].setStartX(leftX);
maxLines[i].setStartY(y4);
maxLines[i].setEndX(rightX);
maxLines[i].setEndY(y4);
medianLines[i].setStartX(leftX);
medianLines[i].setStartY(y2);
medianLines[i].setEndX(rightX);
medianLines[i].setEndY(y2);
minLines[i].setStartX(leftX);
minLines[i].setStartY(y0);
minLines[i].setEndX(rightX);
minLines[i].setEndY(y0);
} else {
double x4 = regionBounds4.getMinX() + regionBounds4.getWidth() / 2;
double x3 = regionBounds3.getMinX() + regionBounds3.getWidth() / 2;
double x2 = regionBounds2.getMinX() + regionBounds2.getWidth() / 2;
double x1 = regionBounds1.getMinX() + regionBounds1.getWidth() / 2;
double x0 = regionBounds0.getMinX() + regionBounds0.getWidth() / 2;
double y = regionBounds3.getMinY() + regionBounds3.getHeight() / 2;
double topY = y - boxWidth / 2;
double bottomY = y + boxWidth / 2;
boxs[i].setLayoutX(x1);
boxs[i].setLayoutY(topY);
boxs[i].setHeight(boxWidth);
boxs[i].setWidth(x3 - x1);
vLines[i].setStartX(x0);
vLines[i].setStartY(y);
vLines[i].setEndX(x4);
vLines[i].setEndY(y);
maxLines[i].setStartX(x4);
maxLines[i].setStartY(topY);
maxLines[i].setEndX(x4);
maxLines[i].setEndY(bottomY);
medianLines[i].setStartX(x2);
medianLines[i].setStartY(topY);
medianLines[i].setEndX(x2);
medianLines[i].setEndY(bottomY);
minLines[i].setStartX(x0);
minLines[i].setStartY(topY);
minLines[i].setEndX(x0);
minLines[i].setEndY(bottomY);
}
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
private void makeMean() {
try {
clearMean();
if (!chartMaker.displayLabel()) {
return;
}
List<XYChart.Series<X, Y>> seriesList = this.getData();
if (seriesList == null || seriesList.size() < 1) {
return;
}
dataSize = seriesList.get(0).getData().size();
meanLines = new Line[dataSize];
if (boxWidth <= 0) {
boxWidth = 40;
}
Map<String, String> palette = chartMaker.getPalette();
String colorMean = palette.get(seriesList.get(0).getName());
List<XYChart.Data<X, Y>> data0 = seriesList.get(0).getData();
for (int i = 0; i < dataSize; i++) {
Bounds regionBoundsMean = data0.get(i).getNode().getBoundsInParent();
meanLines[i] = new Line();
getPlotChildren().add(meanLines[i]);
meanLines[i].setStyle("-fx-stroke-width:2px;-fx-stroke:" + colorMean);
if (chartMaker.isXY) {
double yMean = regionBoundsMean.getMinY() + regionBoundsMean.getHeight() / 2;
double x = regionBoundsMean.getMinX() + regionBoundsMean.getWidth() / 2;
double leftX = x - boxWidth / 2;
double rightX = x + boxWidth / 2;
meanLines[i].setStartX(leftX);
meanLines[i].setStartY(yMean);
meanLines[i].setEndX(rightX);
meanLines[i].setEndY(yMean);
} else {
double xMean = regionBoundsMean.getMinX() + regionBoundsMean.getWidth() / 2;
double y = regionBoundsMean.getMinY() + regionBoundsMean.getHeight() / 2;
double topY = y - boxWidth / 2;
double bottomY = y + boxWidth / 2;
meanLines[i].setStartX(xMean);
meanLines[i].setStartY(topY);
meanLines[i].setEndX(xMean);
meanLines[i].setEndY(bottomY);
}
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
private void makeOutliers() {
try {
clearOutliers();
if (!chartMaker.displayLabel()) {
return;
}
List<XYChart.Series<X, Y>> seriesList = this.getData();
int startIndex = handleMean ? 1 : 0;
if (seriesList == null || seriesList.size() < 9 + startIndex) {
return;
}
dataSize = seriesList.get(startIndex + 5).getData().size();
uMidOutlierLines = new Line[dataSize];
uExOutlierLines = new Line[dataSize];
lMidOutlierLines = new Line[dataSize];
lExOutlierLines = new Line[dataSize];
if (boxWidth <= 0) {
boxWidth = 40;
}
List<XYChart.Data<X, Y>> data0 = seriesList.get(startIndex + 0).getData();
List<XYChart.Data<X, Y>> data4 = seriesList.get(startIndex + 4).getData();
List<XYChart.Data<X, Y>> data5 = seriesList.get(startIndex + 5).getData();
List<XYChart.Data<X, Y>> data6 = seriesList.get(startIndex + 6).getData();
List<XYChart.Data<X, Y>> data7 = seriesList.get(startIndex + 7).getData();
List<XYChart.Data<X, Y>> data8 = seriesList.get(startIndex + 8).getData();
Map<String, String> palette = chartMaker.getPalette();
String color5 = palette.get(seriesList.get(startIndex + 5).getName());
String color6 = palette.get(seriesList.get(startIndex + 6).getName());
String color7 = palette.get(seriesList.get(startIndex + 7).getName());
String color8 = palette.get(seriesList.get(startIndex + 8).getName());
String stylePrefix = "-fx-stroke-dash-array: 2;-fx-stroke-width:1px;-fx-stroke:";
for (int i = 0; i < dataSize; i++) {
Bounds regionBounds0 = data0.get(i).getNode().getBoundsInParent();
Bounds regionBounds4 = data4.get(i).getNode().getBoundsInParent();
Bounds regionBounds5 = data5.get(i).getNode().getBoundsInParent();
Bounds regionBounds6 = data6.get(i).getNode().getBoundsInParent();
Bounds regionBounds7 = data7.get(i).getNode().getBoundsInParent();
Bounds regionBounds8 = data8.get(i).getNode().getBoundsInParent();
uExOutlierLines[i] = new Line();
getPlotChildren().add(uExOutlierLines[i]);
uExOutlierLines[i].setStyle(stylePrefix + color8);
uMidOutlierLines[i] = new Line();
getPlotChildren().add(uMidOutlierLines[i]);
uMidOutlierLines[i].setStyle(stylePrefix + color7);
lMidOutlierLines[i] = new Line();
getPlotChildren().add(lMidOutlierLines[i]);
lMidOutlierLines[i].setStyle(stylePrefix + color6);
lExOutlierLines[i] = new Line();
getPlotChildren().add(lExOutlierLines[i]);
lExOutlierLines[i].setStyle(stylePrefix + color5);
vLines[i] = new Line();
getPlotChildren().add(vLines[i]);
vLines[i].setStyle("-fx-stroke-dash-array: 4;-fx-stroke-width:1px; -fx-stroke:black;");
if (chartMaker.isXY) {
double y0 = regionBounds0.getMinY() + regionBounds0.getHeight() / 2;
double y4 = regionBounds4.getMinY() + regionBounds4.getHeight() / 2;
double y5 = regionBounds5.getMinY() + regionBounds5.getHeight() / 2;
double y6 = regionBounds6.getMinY() + regionBounds6.getHeight() / 2;
double y7 = regionBounds7.getMinY() + regionBounds7.getHeight() / 2;
double y8 = regionBounds8.getMinY() + regionBounds8.getHeight() / 2;
double x = regionBounds5.getMinX() + regionBounds5.getWidth() / 2;
double leftX = x - boxWidth / 2;
double rightX = x + boxWidth / 2;
uExOutlierLines[i].setStartX(leftX);
uExOutlierLines[i].setStartY(y8);
uExOutlierLines[i].setEndX(rightX);
uExOutlierLines[i].setEndY(y8);
uMidOutlierLines[i].setStartX(leftX);
uMidOutlierLines[i].setStartY(y7);
uMidOutlierLines[i].setEndX(rightX);
uMidOutlierLines[i].setEndY(y7);
lMidOutlierLines[i].setStartX(leftX);
lMidOutlierLines[i].setStartY(y6);
lMidOutlierLines[i].setEndX(rightX);
lMidOutlierLines[i].setEndY(y6);
lExOutlierLines[i].setStartX(leftX);
lExOutlierLines[i].setStartY(y5);
lExOutlierLines[i].setEndX(rightX);
lExOutlierLines[i].setEndY(y5);
vLines[i].setStartX(x);
vLines[i].setStartY(Math.min(y8, y4));
vLines[i].setEndX(x);
vLines[i].setEndY(Math.max(y5, y0));
} else {
double x0 = regionBounds0.getMinX() + regionBounds0.getWidth() / 2;
double x4 = regionBounds4.getMinX() + regionBounds4.getWidth() / 2;
double x5 = regionBounds5.getMinX() + regionBounds5.getWidth() / 2;
double x6 = regionBounds6.getMinX() + regionBounds6.getWidth() / 2;
double x7 = regionBounds7.getMinX() + regionBounds7.getWidth() / 2;
double x8 = regionBounds8.getMinX() + regionBounds8.getWidth() / 2;
double y = regionBounds5.getMinY() + regionBounds5.getHeight() / 2;
double topY = y - boxWidth / 2;
double bottomY = y + boxWidth / 2;
uExOutlierLines[i].setStartX(x8);
uExOutlierLines[i].setStartY(topY);
uExOutlierLines[i].setEndX(x8);
uExOutlierLines[i].setEndY(bottomY);
uMidOutlierLines[i].setStartX(x7);
uMidOutlierLines[i].setStartY(topY);
uMidOutlierLines[i].setEndX(x7);
uMidOutlierLines[i].setEndY(bottomY);
lMidOutlierLines[i].setStartX(x6);
lMidOutlierLines[i].setStartY(topY);
lMidOutlierLines[i].setEndX(x6);
lMidOutlierLines[i].setEndY(bottomY);
lExOutlierLines[i].setStartX(x5);
lExOutlierLines[i].setStartY(topY);
lExOutlierLines[i].setEndX(x5);
lExOutlierLines[i].setEndY(bottomY);
vLines[i].setStartX(Math.min(x8, x4));
vLines[i].setStartY(y);
vLines[i].setEndX(Math.max(x5, x0));
vLines[i].setEndY(y);
}
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
private synchronized void makeBoxWhisker() {
makeMain();
if (handleMean) {
makeMean();
}
if (handleOutliers) {
makeOutliers();
}
}
public synchronized void displayBoxWhisker() {
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
Platform.runLater(() -> {
if (getData() != null && expectedSeriesSize() == currentSeriesSize()) {
t.cancel();
makeBoxWhisker();
}
});
Platform.requestNextPulse();
}
}, 100, 100);
}
/*
get/set
*/
public int getBoxWidth() {
boxWidth = boxWidth < 0 ? 40 : boxWidth;
return boxWidth;
}
public BoxWhiskerChart<X, Y> setBoxWidth(int boxWidth) {
this.boxWidth = boxWidth;
UserConfig.setInt("BoxWhiskerChartBoxWidth", getBoxWidth());
return this;
}
public boolean isHandleOutliers() {
return handleOutliers;
}
public BoxWhiskerChart<X, Y> setHandleOutliers(boolean handleOutliers) {
this.handleOutliers = handleOutliers;
UserConfig.setBoolean("BoxWhiskerChartHandleOutliers", handleOutliers);
return this;
}
public boolean isHandleMean() {
return handleMean;
}
public BoxWhiskerChart<X, Y> setHandleMean(boolean handleMean) {
this.handleMean = handleMean;
UserConfig.setBoolean("BoxWhiskerChartHandleMean", handleMean);
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/fxml/chart/LabeledLineChart.java | alpha/MyBox/src/main/java/mara/mybox/fxml/chart/LabeledLineChart.java | package mara.mybox.fxml.chart;
import javafx.geometry.Side;
import javafx.scene.chart.Axis;
import javafx.scene.chart.LineChart;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
/**
* Reference:
* https://stackoverflow.com/questions/34286062/how-to-clear-text-added-in-a-javafx-barchart/41494789#41494789
* By Roland
*
* @Author Mara
* @CreateDate 2022-1-24
* @License Apache License Version 2.0
*/
public class LabeledLineChart<X, Y> extends LineChart<X, Y> {
protected XYChartMaker chartMaker;
public LabeledLineChart(Axis xAxis, Axis yAxis) {
super(xAxis, yAxis);
init();
}
public final void init() {
this.setLegendSide(Side.TOP);
this.setMaxWidth(Double.MAX_VALUE);
this.setMaxHeight(Double.MAX_VALUE);
VBox.setVgrow(this, Priority.ALWAYS);
HBox.setHgrow(this, Priority.ALWAYS);
chartMaker = new XYChartMaker<Axis, Axis>();
}
public LabeledLineChart setMaker(XYChartMaker<X, Y> chartMaker) {
this.chartMaker = chartMaker;
setCreateSymbols(chartMaker.displayLabel());
return this;
}
@Override
protected void seriesAdded(Series<X, Y> series, int seriesIndex) {
super.seriesAdded(series, seriesIndex);
chartMaker.makeLabels(series, getPlotChildren());
}
@Override
protected void seriesRemoved(final Series<X, Y> series) {
chartMaker.removeLabels(getPlotChildren());
super.seriesRemoved(series);
}
@Override
protected void layoutPlotChildren() {
super.layoutPlotChildren();
chartMaker.displayLabels();
}
}
| 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/fxml/menu/FileToolsMenu.java | alpha/MyBox/src/main/java/mara/mybox/fxml/menu/FileToolsMenu.java | package mara.mybox.fxml.menu;
import java.util.ArrayList;
import java.util.Arrays;
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.BaseController;
import mara.mybox.value.Fxmls;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2025-12-9
* @License Apache License Version 2.0
*/
public class FileToolsMenu {
public static List<MenuItem> menusList(BaseController controller) {
MenuItem filesArrangement = new MenuItem(Languages.message("FilesArrangement"));
filesArrangement.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FilesArrangementFxml);
});
MenuItem dirSynchronize = new MenuItem(Languages.message("DirectorySynchronize"));
dirSynchronize.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.DirectorySynchronizeFxml);
});
MenuItem filesRename = new MenuItem(Languages.message("FilesRename"));
filesRename.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FilesRenameFxml);
});
MenuItem fileCut = new MenuItem(Languages.message("FileCut"));
fileCut.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FileCutFxml);
});
MenuItem filesMerge = new MenuItem(Languages.message("FilesMerge"));
filesMerge.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FilesMergeFxml);
});
MenuItem filesCopy = new MenuItem(Languages.message("FilesCopy"));
filesCopy.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FilesCopyFxml);
});
MenuItem filesMove = new MenuItem(Languages.message("FilesMove"));
filesMove.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FilesMoveFxml);
});
MenuItem filesFind = new MenuItem(Languages.message("FilesFind"));
filesFind.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FilesFindFxml);
});
MenuItem filesCompare = new MenuItem(Languages.message("FilesCompare"));
filesCompare.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FilesCompareFxml);
});
MenuItem filesRedundancy = new MenuItem(Languages.message("FilesRedundancy"));
filesRedundancy.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FilesRedundancyFxml);
});
MenuItem filesDelete = new MenuItem(Languages.message("FilesDelete"));
filesDelete.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FilesDeleteFxml);
});
MenuItem DeleteEmptyDirectories = new MenuItem(Languages.message("DeleteEmptyDirectories"));
DeleteEmptyDirectories.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FilesDeleteEmptyDirFxml);
});
MenuItem DeleteJavaTemporaryPathFiles = new MenuItem(Languages.message("DeleteJavaIOTemporaryPathFiles"));
DeleteJavaTemporaryPathFiles.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FilesDeleteJavaTempFxml);
});
MenuItem DeleteNestedDirectories = new MenuItem(Languages.message("DeleteNestedDirectories"));
DeleteNestedDirectories.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FilesDeleteNestedDirFxml);
});
Menu fileDeleteMenu = new Menu(Languages.message("Delete"));
fileDeleteMenu.getItems().addAll(
DeleteJavaTemporaryPathFiles, DeleteEmptyDirectories, filesDelete, DeleteNestedDirectories
);
MenuItem filesArchiveCompress = new MenuItem(Languages.message("FilesArchiveCompress"));
filesArchiveCompress.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FilesArchiveCompressFxml);
});
MenuItem filesCompress = new MenuItem(Languages.message("FilesCompressBatch"));
filesCompress.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FilesCompressBatchFxml);
});
MenuItem filesDecompressUnarchive = new MenuItem(Languages.message("FileDecompressUnarchive"));
filesDecompressUnarchive.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FileDecompressUnarchiveFxml);
});
MenuItem filesDecompressUnarchiveBatch = new MenuItem(Languages.message("FilesDecompressUnarchiveBatch"));
filesDecompressUnarchiveBatch.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FilesDecompressUnarchiveBatchFxml);
});
Menu archiveCompressMenu = new Menu(Languages.message("FilesArchiveCompress"));
archiveCompressMenu.getItems().addAll(
filesDecompressUnarchive, filesDecompressUnarchiveBatch,
filesArchiveCompress, filesCompress
);
List<MenuItem> items = new ArrayList<>();
items.addAll(Arrays.asList(filesArrangement, dirSynchronize, new SeparatorMenuItem(),
archiveCompressMenu, new SeparatorMenuItem(),
fileCut, filesMerge, new SeparatorMenuItem(),
filesFind, filesRedundancy, filesCompare, new SeparatorMenuItem(),
filesRename, filesCopy, filesMove, new SeparatorMenuItem(),
fileDeleteMenu));
return items;
}
}
| 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/fxml/menu/NetworkToolsMenu.java | alpha/MyBox/src/main/java/mara/mybox/fxml/menu/NetworkToolsMenu.java | package mara.mybox.fxml.menu;
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.BaseController;
import mara.mybox.controller.DataTreeController;
import mara.mybox.value.Fxmls;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2025-12-9
* @License Apache License Version 2.0
*/
public class NetworkToolsMenu {
public static List<MenuItem> menusList(BaseController controller) {
MenuItem weiboSnap = new MenuItem(message("WeiboSnap"));
weiboSnap.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.WeiboSnapFxml);
});
MenuItem webBrowserHtml = new MenuItem(message("WebBrowser"));
webBrowserHtml.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.WebBrowserFxml);
});
MenuItem WebFavorites = new MenuItem(message("WebFavorites"));
WebFavorites.setOnAction((ActionEvent event) -> {
DataTreeController.webFavorite(controller, true);
});
MenuItem WebHistories = new MenuItem(message("WebHistories"));
WebHistories.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.WebHistoriesFxml);
});
MenuItem ConvertUrl = new MenuItem(message("ConvertUrl"));
ConvertUrl.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.NetworkConvertUrlFxml);
});
MenuItem QueryAddress = new MenuItem(message("QueryNetworkAddress"));
QueryAddress.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.NetworkQueryAddressFxml);
});
MenuItem QueryDNSBatch = new MenuItem(message("QueryDNSBatch"));
QueryDNSBatch.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.NetworkQueryDNSBatchFxml);
});
MenuItem DownloadFirstLevelLinks = new MenuItem(message("DownloadHtmls"));
DownloadFirstLevelLinks.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.DownloadFirstLevelLinksFxml);
});
MenuItem RemotePathManage = new MenuItem(message("RemotePathManage"));
RemotePathManage.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.RemotePathManageFxml);
});
MenuItem RemotePathSynchronizeFromLocal = new MenuItem(message("RemotePathSynchronizeFromLocal"));
RemotePathSynchronizeFromLocal.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.RemotePathSynchronizeFromLocalFxml);
});
MenuItem SecurityCertificates = new MenuItem(message("SecurityCertificates"));
SecurityCertificates.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.SecurityCertificatesFxml);
});
List<MenuItem> items = new ArrayList<>();
items.addAll(Arrays.asList(webBrowserHtml, WebFavorites, WebHistories, new SeparatorMenuItem(),
RemotePathManage, RemotePathSynchronizeFromLocal, new SeparatorMenuItem(),
QueryAddress, QueryDNSBatch, ConvertUrl, SecurityCertificates, new SeparatorMenuItem(),
DownloadFirstLevelLinks, weiboSnap));
return items;
}
}
| 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/fxml/menu/DataToolsMenu.java | alpha/MyBox/src/main/java/mara/mybox/fxml/menu/DataToolsMenu.java | package mara.mybox.fxml.menu;
import java.util.ArrayList;
import java.util.Arrays;
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.BaseController;
import mara.mybox.controller.DataInMyBoxClipboardController;
import mara.mybox.controller.DataInSystemClipboardController;
import mara.mybox.controller.DataTreeController;
import mara.mybox.controller.GeographyCodeController;
import mara.mybox.value.Fxmls;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2025-12-9
* @License Apache License Version 2.0
*/
public class DataToolsMenu {
public static List<MenuItem> menusList(BaseController controller) {
MenuItem DataManufacture = new MenuItem(message("DataManufacture"));
DataManufacture.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.Data2DManufactureFxml);
});
MenuItem ManageData = new MenuItem(message("ManageData"));
ManageData.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.Data2DManageFxml);
});
MenuItem SpliceData = new MenuItem(message("SpliceData"));
SpliceData.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.Data2DSpliceFxml);
});
MenuItem RowExpression = new MenuItem(message("RowExpression"));
RowExpression.setOnAction((ActionEvent event) -> {
DataTreeController.rowExpression(controller, true);
});
MenuItem DataColumn = new MenuItem(message("DataColumn"));
DataColumn.setOnAction((ActionEvent event) -> {
DataTreeController.dataColumn(controller, true);
});
MenuItem DataInSystemClipboard = new MenuItem(message("DataInSystemClipboard"));
DataInSystemClipboard.setOnAction((ActionEvent event) -> {
DataInSystemClipboardController.oneOpen();
});
MenuItem DataInMyBoxClipboard = new MenuItem(message("DataInMyBoxClipboard"));
DataInMyBoxClipboard.setOnAction((ActionEvent event) -> {
DataInMyBoxClipboardController c = DataInMyBoxClipboardController.oneOpen();
});
MenuItem ExcelConvert = new MenuItem(message("ExcelConvert"));
ExcelConvert.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.DataFileExcelConvertFxml);
});
MenuItem ExcelMerge = new MenuItem(message("ExcelMerge"));
ExcelMerge.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.DataFileExcelMergeFxml);
});
MenuItem CsvConvert = new MenuItem(message("CsvConvert"));
CsvConvert.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.DataFileCSVConvertFxml);
});
MenuItem CsvMerge = new MenuItem(message("CsvMerge"));
CsvMerge.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.DataFileCSVMergeFxml);
});
MenuItem TextDataConvert = new MenuItem(message("TextDataConvert"));
TextDataConvert.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.DataFileTextConvertFxml);
});
MenuItem TextDataMerge = new MenuItem(message("TextDataMerge"));
TextDataMerge.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.DataFileTextMergeFxml);
});
Menu dataFile = new Menu(message("DataFile"));
dataFile.getItems().addAll(CsvConvert, CsvMerge, new SeparatorMenuItem(),
ExcelConvert, ExcelMerge, new SeparatorMenuItem(),
TextDataConvert, TextDataMerge);
MenuItem GeographyCode = new MenuItem(message("GeographyCode"));
GeographyCode.setOnAction((ActionEvent event) -> {
GeographyCodeController.open(controller, true, true);
});
MenuItem LocationInMap = new MenuItem(message("LocationInMap"));
LocationInMap.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.LocationInMapFxml);
});
MenuItem ConvertCoordinate = new MenuItem(message("ConvertCoordinate"));
ConvertCoordinate.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ConvertCoordinateFxml);
});
Menu Location = new Menu(message("Location"));
Location.getItems().addAll(
GeographyCode, LocationInMap, ConvertCoordinate
);
MenuItem MatricesManage = new MenuItem(message("MatricesManage"));
MatricesManage.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.MatricesManageFxml);
});
MenuItem MatrixUnaryCalculation = new MenuItem(message("MatrixUnaryCalculation"));
MatrixUnaryCalculation.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.MatrixUnaryCalculationFxml);
});
MenuItem MatricesBinaryCalculation = new MenuItem(message("MatricesBinaryCalculation"));
MatricesBinaryCalculation.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.MatricesBinaryCalculationFxml);
});
Menu matrix = new Menu(message("Matrix"));
matrix.getItems().addAll(
MatricesManage, MatrixUnaryCalculation, MatricesBinaryCalculation
);
MenuItem DatabaseSQL = new MenuItem(message("DatabaseSQL"));
DatabaseSQL.setOnAction((ActionEvent event) -> {
DataTreeController.sql(controller, true);
});
MenuItem DatabaseTable = new MenuItem(message("DatabaseTable"));
DatabaseTable.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.DataTablesFxml);
});
MenuItem databaseTableDefinition = new MenuItem(message("TableDefinition"));
databaseTableDefinition.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.DatabaseTableDefinitionFxml);
});
Menu database = new Menu(message("Database"));
database.getItems().addAll(
DatabaseTable, DatabaseSQL, databaseTableDefinition
);
MenuItem jshell = new MenuItem(message("JShell"));
jshell.setOnAction((ActionEvent event) -> {
DataTreeController.jShell(controller, true);
});
MenuItem jexl = new MenuItem(message("JEXL"));
jexl.setOnAction((ActionEvent event) -> {
DataTreeController.jexl(controller, true);
});
MenuItem JavaScript = new MenuItem("JavaScript");
JavaScript.setOnAction((ActionEvent event) -> {
DataTreeController.javascript(controller, true);
});
Menu calculation = new Menu(message("ScriptAndExperssion"));
calculation.getItems().addAll(
JavaScript, jshell, jexl
);
MenuItem MathFunction = new MenuItem(message("MathFunction"));
MathFunction.setOnAction((ActionEvent event) -> {
DataTreeController.mathFunction(controller, true);
});
MenuItem barcodeCreator = new MenuItem(message("BarcodeCreator"));
barcodeCreator.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.BarcodeCreatorFxml);
});
MenuItem barcodeDecoder = new MenuItem(message("BarcodeDecoder"));
barcodeDecoder.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.BarcodeDecoderFxml);
});
MenuItem messageDigest = new MenuItem(message("MessageDigest"));
messageDigest.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.MessageDigestFxml);
});
MenuItem Base64Conversion = new MenuItem(message("Base64Conversion"));
Base64Conversion.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.Base64Fxml);
});
MenuItem TTC2TTF = new MenuItem(message("TTC2TTF"));
TTC2TTF.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FileTTC2TTFFxml);
});
Menu miscellaneousMenu = new Menu(message("Miscellaneous"));
miscellaneousMenu.getItems().addAll(
barcodeCreator, barcodeDecoder, new SeparatorMenuItem(),
messageDigest, Base64Conversion, new SeparatorMenuItem(),
TTC2TTF
);
List<MenuItem> items = new ArrayList<>();
items.addAll(Arrays.asList(
DataManufacture, ManageData, new SeparatorMenuItem(),
dataFile, matrix, database, new SeparatorMenuItem(),
SpliceData, DataColumn, RowExpression,
DataInSystemClipboard, DataInMyBoxClipboard, new SeparatorMenuItem(),
calculation, MathFunction, new SeparatorMenuItem(),
Location, miscellaneousMenu));
return items;
}
}
| 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/fxml/menu/MediaToolsMenu.java | alpha/MyBox/src/main/java/mara/mybox/fxml/menu/MediaToolsMenu.java | package mara.mybox.fxml.menu;
import java.util.ArrayList;
import java.util.Arrays;
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.BaseController;
import mara.mybox.value.Fxmls;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2025-12-9
* @License Apache License Version 2.0
*/
public class MediaToolsMenu {
public static List<MenuItem> menusList(BaseController controller) {
MenuItem mediaPlayer = new MenuItem(Languages.message("MediaPlayer"));
mediaPlayer.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.MediaPlayerFxml);
});
MenuItem mediaLists = new MenuItem(Languages.message("ManageMediaLists"));
mediaLists.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.MediaListFxml);
});
MenuItem FFmpegInformation = new MenuItem(Languages.message("FFmpegInformation"));
FFmpegInformation.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FFmpegInformationFxml);
});
MenuItem FFprobe = new MenuItem(Languages.message("FFmpegProbeMediaInformation"));
FFprobe.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FFmpegProbeMediaInformationFxml);
});
MenuItem FFmpegConversionFiles = new MenuItem(Languages.message("FFmpegConvertMediaFiles"));
FFmpegConversionFiles.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FFmpegConvertMediaFilesFxml);
});
MenuItem FFmpegConversionStreams = new MenuItem(Languages.message("FFmpegConvertMediaStreams"));
FFmpegConversionStreams.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FFmpegConvertMediaStreamsFxml);
});
Menu FFmpegConversionMenu = new Menu(Languages.message("FFmpegConvertMedias"));
FFmpegConversionMenu.getItems().addAll(
FFmpegConversionFiles, FFmpegConversionStreams);
MenuItem FFmpegMergeImages = new MenuItem(Languages.message("FFmpegMergeImagesInformation"));
FFmpegMergeImages.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FFmpegMergeImagesFxml);
});
MenuItem FFmpegMergeImageFiles = new MenuItem(Languages.message("FFmpegMergeImagesFiles"));
FFmpegMergeImageFiles.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FFmpegMergeImageFilesFxml);
});
MenuItem screenRecorder = new MenuItem(Languages.message("FFmpegScreenRecorder"));
screenRecorder.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.FFmpegScreenRecorderFxml);
});
Menu FFmpegMergeMenu = new Menu(Languages.message("FFmpegMergeImages"));
FFmpegMergeMenu.getItems().addAll(
FFmpegMergeImageFiles, FFmpegMergeImages);
MenuItem alarmClock = new MenuItem(Languages.message("AlarmClock"));
alarmClock.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.AlarmClockFxml);
});
MenuItem GameElimniation = new MenuItem(Languages.message("GameElimniation"));
GameElimniation.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.GameElimniationFxml);
});
MenuItem GameMine = new MenuItem(Languages.message("GameMine"));
GameMine.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.GameMineFxml);
});
List<MenuItem> items = new ArrayList<>();
items.addAll(Arrays.asList(mediaPlayer, mediaLists, new SeparatorMenuItem(),
screenRecorder,
FFmpegConversionMenu, FFmpegMergeMenu,
FFprobe, FFmpegInformation, new SeparatorMenuItem(),
// alarmClock, new SeparatorMenuItem(),
GameElimniation, GameMine));
return items;
}
}
| 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/fxml/menu/DevelopmentMenu.java | alpha/MyBox/src/main/java/mara/mybox/fxml/menu/DevelopmentMenu.java | package mara.mybox.fxml.menu;
import java.io.File;
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.BaseController;
import mara.mybox.controller.Data2DManufactureController;
import mara.mybox.controller.DataTreeController;
import mara.mybox.controller.MyBoxDocumentsController;
import mara.mybox.controller.TextPopController;
import mara.mybox.data2d.DataFileCSV;
import mara.mybox.data2d.example.SoftwareTesting;
import mara.mybox.db.table.BaseTableTools;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.SystemTools;
import mara.mybox.value.Fxmls;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2025-12-9
* @License Apache License Version 2.0
*/
public class DevelopmentMenu {
public static List<MenuItem> menusList(BaseController controller) {
MenuItem MyBoxProperties = new MenuItem(message("MyBoxProperties"));
MyBoxProperties.setOnAction((ActionEvent event) -> {
controller.openStage(Fxmls.MyBoxPropertiesFxml);
});
MenuItem MyBoxLogs = new MenuItem(message("MyBoxLogs"));
MyBoxLogs.setOnAction((ActionEvent event) -> {
controller.openStage(Fxmls.MyBoxLogsFxml);
});
MenuItem RunSystemCommand = new MenuItem(message("RunSystemCommand"));
RunSystemCommand.setOnAction((ActionEvent event) -> {
controller.openStage(Fxmls.RunSystemCommandFxml);
});
MenuItem JConsole = new MenuItem(message("JConsole"));
JConsole.setOnAction((ActionEvent event) -> {
try {
String cmd = System.getProperty("java.home") + File.separator + "bin" + File.separator + "jconsole";
if (SystemTools.isWindows()) {
cmd += ".exe";
}
new ProcessBuilder(cmd).start();
} catch (Exception e) {
MyBoxLog.error(e);
}
});
MenuItem MacroCommands = new MenuItem(message("MacroCommands"));
MacroCommands.setOnAction((ActionEvent event) -> {
DataTreeController.macroCommands(controller, false);
});
MenuItem MyBoxTables = new MenuItem(message("MyBoxTables"));
MyBoxTables.setOnAction((ActionEvent event) -> {
controller.openStage(Fxmls.MyBoxTablesFxml);
});
MenuItem ManageLanguages = new MenuItem(message("ManageLanguages"));
ManageLanguages.setOnAction((ActionEvent event) -> {
controller.openStage(Fxmls.MyBoxLanguagesFxml);
});
MenuItem MakeIcons = new MenuItem(message("MakeIcons"));
MakeIcons.setOnAction((ActionEvent event) -> {
controller.openStage(Fxmls.MyBoxIconsFxml);
});
MenuItem MakeDocuments = new MenuItem(message("MakeDocuments"));
MakeDocuments.setOnAction((ActionEvent event) -> {
MyBoxDocumentsController.open();
});
MenuItem AutoTesting = new MenuItem(message("AutoTesting"));
AutoTesting.setOnAction((ActionEvent event) -> {
controller.openStage(Fxmls.AutoTestingCasesFxml);
});
MenuItem AllTableNames = new MenuItem(message("AllTableNames"));
AllTableNames.setOnAction((ActionEvent event) -> {
TextPopController.loadText(BaseTableTools.allTableNames());
});
MenuItem MyBoxBaseVerificationList = new MenuItem(message("MyBoxBaseVerificationList"));
MyBoxBaseVerificationList.setOnAction((ActionEvent event) -> {
DataFileCSV data = SoftwareTesting.MyBoxBaseVerificationList(
controller, Languages.getLangName(), false);
Data2DManufactureController.openDef(data);
});
MenuItem MessageAuthor = new MenuItem(message("MessageAuthor"));
MessageAuthor.setOnAction((ActionEvent event) -> {
controller.openStage(Fxmls.MessageAuthorFxml);
});
List<MenuItem> items = new ArrayList<>();
items.addAll(Arrays.asList(MyBoxProperties, MyBoxLogs, new SeparatorMenuItem(),
RunSystemCommand, JConsole, new SeparatorMenuItem(),
MacroCommands, MyBoxTables, AllTableNames, new SeparatorMenuItem(),
ManageLanguages, MakeIcons, MakeDocuments,
AutoTesting, MyBoxBaseVerificationList));
return items;
}
}
| 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/fxml/menu/ImageToolsMenu.java | alpha/MyBox/src/main/java/mara/mybox/fxml/menu/ImageToolsMenu.java | package mara.mybox.fxml.menu;
import java.util.ArrayList;
import java.util.Arrays;
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.BaseController;
import mara.mybox.controller.ColorsManageController;
import mara.mybox.controller.DataTreeController;
import mara.mybox.controller.ImageInMyBoxClipboardController;
import mara.mybox.controller.ImageInSystemClipboardController;
import mara.mybox.value.Fxmls;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2025-12-9
* @License Apache License Version 2.0
*/
public class ImageToolsMenu {
public static List<MenuItem> menusList(BaseController controller) {
MenuItem EditImage = new MenuItem(message("EditImage"));
EditImage.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageEditorFxml);
});
MenuItem imageScope = new MenuItem(message("ImageScope"));
imageScope.setOnAction((ActionEvent event) -> {
DataTreeController.imageScope(controller, true);
});
MenuItem imageOptions = new MenuItem(message("ImageOptions"));
imageOptions.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageShapeOptionsFxml);
});
MenuItem ManageColors = new MenuItem(message("ManageColors"));
ManageColors.setOnAction((ActionEvent event) -> {
ColorsManageController.oneOpen();
});
MenuItem QueryColor = new MenuItem(message("QueryColor"));
QueryColor.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ColorQueryFxml);
});
MenuItem blendColors = new MenuItem(message("BlendColors"));
blendColors.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ColorsBlendFxml);
});
MenuItem ImagesInMyBoxClipboard = new MenuItem(message("ImagesInMyBoxClipboard"));
ImagesInMyBoxClipboard.setOnAction((ActionEvent event) -> {
ImageInMyBoxClipboardController.oneOpen();
});
MenuItem ImagesInSystemClipboard = new MenuItem(message("ImagesInSystemClipboard"));
ImagesInSystemClipboard.setOnAction((ActionEvent event) -> {
ImageInSystemClipboardController.oneOpen();
});
List<MenuItem> items = new ArrayList<>();
items.addAll(Arrays.asList(
EditImage, imageManufactureMenu(controller), imageBatchMenu(controller), svgMenu(controller),
imageScope, imageOptions, new SeparatorMenuItem(),
ManageColors, QueryColor, blendColors, colorSpaceMenu(controller), new SeparatorMenuItem(),
ImagesInMyBoxClipboard, ImagesInSystemClipboard, miscellaneousMenu(controller)));
return items;
}
public static Menu imageManufactureMenu(BaseController controller) {
MenuItem ImageAnalyse = new MenuItem(message("ImageAnalyse"));
ImageAnalyse.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageAnalyseFxml);
});
MenuItem ImagesEditor = new MenuItem(message("ImagesEditor"));
ImagesEditor.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImagesEditorFxml);
});
MenuItem ImagesSplice = new MenuItem(message("ImagesSplice"));
ImagesSplice.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImagesSpliceFxml);
});
MenuItem ImageSplit = new MenuItem(message("ImageSplit"));
ImageSplit.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageSplitFxml);
});
MenuItem ImageSample = new MenuItem(message("ImageSample"));
ImageSample.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageSampleFxml);
});
MenuItem ImageRepeat = new MenuItem(message("ImageRepeatTile"));
ImageRepeat.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageRepeatFxml);
});
MenuItem ImagesPlay = new MenuItem(message("ImagesPlay"));
ImagesPlay.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImagesPlayFxml);
});
MenuItem imagesBrowser = new MenuItem(message("ImagesBrowser"));
imagesBrowser.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImagesBrowserFxml);
});
MenuItem imageOCR = new MenuItem(message("ImageOCR"));
imageOCR.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageOCRFxml);
});
Menu manufactureMenu = new Menu(message("ImageManufacture"));
manufactureMenu.getItems().addAll(
ImageAnalyse, imageOCR, new SeparatorMenuItem(),
ImageRepeat, ImagesSplice, ImageSplit, ImageSample, new SeparatorMenuItem(),
ImagesPlay, ImagesEditor, imagesBrowser);
return manufactureMenu;
}
public static Menu imageBatchMenu(BaseController controller) {
MenuItem imageAlphaAdd = new MenuItem(message("ImageAlphaAdd"));
imageAlphaAdd.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageAlphaAddBatchFxml);
});
MenuItem imageAlphaExtract = new MenuItem(message("ImageAlphaExtract"));
imageAlphaExtract.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageAlphaExtractBatchFxml);
});
MenuItem SvgFromImage = new MenuItem(message("ImageToSvg"));
SvgFromImage.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.SvgFromImageBatchFxml);
});
MenuItem imageConverterBatch = new MenuItem(message("FormatsConversion"));
imageConverterBatch.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageConverterBatchFxml);
});
MenuItem imageOCRBatch = new MenuItem(message("ImageOCRBatch"));
imageOCRBatch.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageOCRBatchFxml);
});
Menu imageBatchMenu = new Menu(message("ImageBatch"));
imageBatchMenu.getItems().addAll(
imageColorBatchMenu(controller), imagePixelsBatchMenu(controller), imageModifyBatchMenu(controller), new SeparatorMenuItem(),
imageConverterBatch, imageAlphaExtract, imageAlphaAdd, SvgFromImage, imageOCRBatch);
return imageBatchMenu;
}
public static Menu imageColorBatchMenu(BaseController controller) {
MenuItem imageReplaceColorMenu = new MenuItem(message("ReplaceColor"));
imageReplaceColorMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageReplaceColorBatchFxml);
});
MenuItem imageBlendColorMenu = new MenuItem(message("BlendColor"));
imageBlendColorMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageBlendColorBatchFxml);
});
MenuItem imageAdjustColorMenu = new MenuItem(message("AdjustColor"));
imageAdjustColorMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageAdjustColorBatchFxml);
});
MenuItem imageBlackWhiteMenu = new MenuItem(message("BlackOrWhite"));
imageBlackWhiteMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageBlackWhiteBatchFxml);
});
MenuItem imageGreyMenu = new MenuItem(message("Grey"));
imageGreyMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageGreyBatchFxml);
});
MenuItem imageSepiaMenu = new MenuItem(message("Sepia"));
imageSepiaMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageSepiaBatchFxml);
});
MenuItem imageReduceColorsMenu = new MenuItem(message("ReduceColors"));
imageReduceColorsMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageReduceColorsBatchFxml);
});
MenuItem imageThresholdingsMenu = new MenuItem(message("Thresholding"));
imageThresholdingsMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageThresholdingBatchFxml);
});
Menu imageColorBatchMenu = new Menu(message("Color"));
imageColorBatchMenu.getItems().addAll(
imageReplaceColorMenu, imageBlendColorMenu, imageAdjustColorMenu,
imageBlackWhiteMenu, imageGreyMenu, imageSepiaMenu,
imageReduceColorsMenu, imageThresholdingsMenu
);
return imageColorBatchMenu;
}
public static Menu imagePixelsBatchMenu(BaseController controller) {
MenuItem imageMosaicMenu = new MenuItem(message("Mosaic"));
imageMosaicMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageMosaicBatchFxml);
});
MenuItem imageFrostedGlassMenu = new MenuItem(message("FrostedGlass"));
imageFrostedGlassMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageGlassBatchFxml);
});
MenuItem imageShadowMenu = new MenuItem(message("Shadow"));
imageShadowMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageShadowBatchFxml);
});
MenuItem imageSmoothMenu = new MenuItem(message("Smooth"));
imageSmoothMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageSmoothBatchFxml);
});
MenuItem imageSharpenMenu = new MenuItem(message("Sharpen"));
imageSharpenMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageSharpenBatchFxml);
});
MenuItem imageContrastMenu = new MenuItem(message("Contrast"));
imageContrastMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageContrastBatchFxml);
});
MenuItem imageEdgeMenu = new MenuItem(message("EdgeDetection"));
imageEdgeMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageEdgeBatchFxml);
});
MenuItem imageEmbossMenu = new MenuItem(message("Emboss"));
imageEmbossMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageEmbossBatchFxml);
});
MenuItem imageConvolutionMenu = new MenuItem(message("Convolution"));
imageConvolutionMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageConvolutionBatchFxml);
});
Menu imagePixelsMenu = new Menu(message("Pixels"));
imagePixelsMenu.getItems().addAll(
imageMosaicMenu, imageFrostedGlassMenu, imageShadowMenu,
imageSmoothMenu, imageSharpenMenu,
imageContrastMenu, imageEdgeMenu, imageEmbossMenu, imageConvolutionMenu);
return imagePixelsMenu;
}
public static Menu imageModifyBatchMenu(BaseController controller) {
MenuItem imageSizeMenu = new MenuItem(message("Size"));
imageSizeMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageSizeBatchFxml);
});
MenuItem imageCropMenu = new MenuItem(message("Crop"));
imageCropMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageCropBatchFxml);
});
MenuItem imagePasteMenu = new MenuItem(message("Paste"));
imagePasteMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImagePasteBatchFxml);
});
MenuItem imageTextMenu = new MenuItem(message("Text"));
imageTextMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageTextBatchFxml);
});
MenuItem imageRoundMenu = new MenuItem(message("Round"));
imageRoundMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageRoundBatchFxml);
});
MenuItem imageRotateMenu = new MenuItem(message("Rotate"));
imageRotateMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageRotateBatchFxml);
});
MenuItem imageMirrorMenu = new MenuItem(message("Mirror"));
imageMirrorMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageMirrorBatchFxml);
});
MenuItem imageShearMenu = new MenuItem(message("Shear"));
imageShearMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageShearBatchFxml);
});
MenuItem imageMarginsMenu = new MenuItem(message("Margins"));
imageMarginsMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageMarginsBatchFxml);
});
Menu imagePixelsMenu = new Menu(message("Modify"));
imagePixelsMenu.getItems().addAll(
imageSizeMenu, imageMarginsMenu, imageCropMenu, imageRoundMenu,
imageRotateMenu, imageMirrorMenu, imageShearMenu,
imagePasteMenu, imageTextMenu);
return imagePixelsMenu;
}
public static Menu svgMenu(BaseController controller) {
MenuItem EditSVG = new MenuItem(message("SVGEditor"));
EditSVG.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.SvgEditorFxml);
});
MenuItem SvgTypesetting = new MenuItem(message("SvgTypesetting"));
SvgTypesetting.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.SvgTypesettingFxml);
});
MenuItem SvgToImage = new MenuItem(message("SvgToImage"));
SvgToImage.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.SvgToImageFxml);
});
MenuItem SvgToPDF = new MenuItem(message("SvgToPDF"));
SvgToPDF.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.SvgToPDFFxml);
});
MenuItem SvgFromImage = new MenuItem(message("ImageToSvg"));
SvgFromImage.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.SvgFromImageBatchFxml);
});
Menu svgMenu = new Menu(message("SVG"));
svgMenu.getItems().addAll(EditSVG, SvgTypesetting, SvgToImage, SvgToPDF, SvgFromImage);
return svgMenu;
}
public static Menu colorSpaceMenu(BaseController controller) {
MenuItem IccEditor = new MenuItem(message("IccProfileEditor"));
IccEditor.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.IccProfileEditorFxml);
});
MenuItem ChromaticityDiagram = new MenuItem(message("DrawChromaticityDiagram"));
ChromaticityDiagram.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ChromaticityDiagramFxml);
});
MenuItem ChromaticAdaptationMatrix = new MenuItem(message("ChromaticAdaptationMatrix"));
ChromaticAdaptationMatrix.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ChromaticAdaptationMatrixFxml);
});
MenuItem ColorConversion = new MenuItem(message("ColorConversion"));
ColorConversion.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ColorConversionFxml);
});
MenuItem RGBColorSpaces = new MenuItem(message("RGBColorSpaces"));
RGBColorSpaces.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.RGBColorSpacesFxml);
});
MenuItem RGB2XYZConversionMatrix = new MenuItem(message("LinearRGB2XYZMatrix"));
RGB2XYZConversionMatrix.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.RGB2XYZConversionMatrixFxml);
});
MenuItem RGB2RGBConversionMatrix = new MenuItem(message("LinearRGB2RGBMatrix"));
RGB2RGBConversionMatrix.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.RGB2RGBConversionMatrixFxml);
});
MenuItem Illuminants = new MenuItem(message("Illuminants"));
Illuminants.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.IlluminantsFxml);
});
Menu csMenu = new Menu(message("ColorSpace"));
csMenu.getItems().addAll(ChromaticityDiagram, IccEditor,
// ColorConversion,
RGBColorSpaces, RGB2XYZConversionMatrix, RGB2RGBConversionMatrix,
Illuminants, ChromaticAdaptationMatrix);
return csMenu;
}
public static Menu miscellaneousMenu(BaseController controller) {
MenuItem ImageBase64 = new MenuItem(message("ImageBase64"));
ImageBase64.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImageBase64Fxml);
});
MenuItem convolutionKernelManager = new MenuItem(message("ConvolutionKernelManager"));
convolutionKernelManager.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ConvolutionKernelManagerFxml);
});
MenuItem pixelsCalculator = new MenuItem(message("PixelsCalculator"));
pixelsCalculator.setOnAction((ActionEvent event) -> {
controller.openStage(Fxmls.PixelsCalculatorFxml);
});
Menu miscellaneousMenu = new Menu(message("Miscellaneous"));
miscellaneousMenu.getItems().addAll(
ImageBase64, convolutionKernelManager, pixelsCalculator
);
return miscellaneousMenu;
}
}
| 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/fxml/menu/HelpMenu.java | alpha/MyBox/src/main/java/mara/mybox/fxml/menu/HelpMenu.java | package mara.mybox.fxml.menu;
import java.io.File;
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.BaseController;
import mara.mybox.fxml.FxFileTools;
import mara.mybox.fxml.HelpTools;
import mara.mybox.fxml.PopTools;
import mara.mybox.value.AppVariables;
import mara.mybox.value.Fxmls;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2025-12-9
* @License Apache License Version 2.0
*/
public class HelpMenu {
public static List<MenuItem> menusList(BaseController controller) {
MenuItem Overview = new MenuItem(message("Overview"));
Overview.setOnAction((ActionEvent event) -> {
String lang = Languages.embedFileLang();
File file = FxFileTools.getInternalFile("/doc/" + lang + "/MyBox-Overview-" + lang + ".pdf",
"doc", "MyBox-Overview-" + lang + ".pdf");
if (file != null && file.exists()) {
PopTools.browseURI(controller, file.toURI());
}
});
MenuItem Shortcuts = new MenuItem(message("Shortcuts"));
Shortcuts.setOnAction((ActionEvent event) -> {
controller.openStage(Fxmls.ShortcutsFxml);
});
MenuItem FunctionsList = new MenuItem(message("FunctionsList"));
FunctionsList.setOnAction((ActionEvent event) -> {
controller.openStage(Fxmls.FunctionsListFxml);
});
MenuItem InterfaceTips = new MenuItem(message("InterfaceTips"));
InterfaceTips.setOnAction((ActionEvent event) -> {
controller.openHtml(HelpTools.makeInterfaceTips(AppVariables.CurrentLangName));
});
MenuItem AboutTreeInformation = new MenuItem(message("AboutTreeInformation"));
AboutTreeInformation.setOnAction((ActionEvent event) -> {
controller.openHtml(HelpTools.aboutTreeInformation());
});
MenuItem AboutImageScope = new MenuItem(message("AboutImageScope"));
AboutImageScope.setOnAction((ActionEvent event) -> {
controller.openHtml(HelpTools.aboutImageScope());
});
MenuItem AboutData2D = new MenuItem(message("AboutData2D"));
AboutData2D.setOnAction((ActionEvent event) -> {
controller.openHtml(HelpTools.aboutData2D());
});
MenuItem AboutRowExpression = new MenuItem(message("AboutRowExpression"));
AboutRowExpression.setOnAction((ActionEvent event) -> {
controller.openHtml(HelpTools.aboutRowExpression());
});
MenuItem AboutGroupingRows = new MenuItem(message("AboutGroupingRows"));
AboutGroupingRows.setOnAction((ActionEvent event) -> {
controller.openHtml(HelpTools.aboutGroupingRows());
});
MenuItem AboutDataAnalysis = new MenuItem(message("AboutDataAnalysis"));
AboutDataAnalysis.setOnAction((ActionEvent event) -> {
controller.openHtml(HelpTools.aboutDataAnalysis());
});
MenuItem AboutCoordinateSystem = new MenuItem(message("AboutCoordinateSystem"));
AboutCoordinateSystem.setOnAction((ActionEvent event) -> {
controller.openHtml(HelpTools.aboutCoordinateSystem());
});
MenuItem AboutColor = new MenuItem(message("AboutColor"));
AboutColor.setOnAction((ActionEvent event) -> {
controller.openHtml(HelpTools.aboutColor());
});
MenuItem AboutMedia = new MenuItem(message("AboutMedia"));
AboutMedia.setOnAction((ActionEvent event) -> {
controller.openHtml(HelpTools.aboutMedia());
});
MenuItem AboutMacro = new MenuItem(message("AboutMacro"));
AboutMacro.setOnAction((ActionEvent event) -> {
controller.openHtml(HelpTools.aboutMacro());
});
MenuItem SomeLinks = new MenuItem(message("SomeLinks"));
SomeLinks.setOnAction((ActionEvent event) -> {
controller.openHtml(HelpTools.usefulLinks(AppVariables.CurrentLangName));
});
MenuItem imagesStories = new MenuItem(message("StoriesOfImages"));
imagesStories.setOnAction((ActionEvent event) -> {
HelpTools.imageStories(controller);
});
MenuItem ReadMe = new MenuItem(message("ReadMe"));
ReadMe.setOnAction((ActionEvent event) -> {
HelpTools.readMe(controller);
});
List<MenuItem> items = new ArrayList<>();
items.addAll(Arrays.asList(Overview, Shortcuts, FunctionsList, new SeparatorMenuItem(),
InterfaceTips, AboutTreeInformation, AboutImageScope,
AboutData2D, AboutRowExpression, AboutGroupingRows, AboutDataAnalysis,
AboutCoordinateSystem, AboutColor, AboutMedia, AboutMacro,
SomeLinks, imagesStories, ReadMe));
return items;
}
}
| 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/fxml/menu/MenuTools.java | alpha/MyBox/src/main/java/mara/mybox/fxml/menu/MenuTools.java | package mara.mybox.fxml.menu;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.CheckMenuItem;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import mara.mybox.controller.BaseController;
import static mara.mybox.fxml.style.NodeStyleTools.attributeTextStyle;
import mara.mybox.fxml.style.StyleTools;
import mara.mybox.tools.StringTools;
import mara.mybox.value.Fxmls;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2025-12-9
* @License Apache License Version 2.0
*/
public class MenuTools {
public static List<MenuItem> toolsMenu(BaseController controller) {
Menu documentMenu = new Menu(message("Document"));
documentMenu.getItems().addAll(DocumentToolsMenu.menusList(controller));
Menu imageMenu = new Menu(message("Image"));
imageMenu.getItems().addAll(ImageToolsMenu.menusList(controller));
Menu fileMenu = new Menu(message("File"));
fileMenu.getItems().addAll(FileToolsMenu.menusList(controller));
Menu networkMenu = new Menu(message("Network"));
networkMenu.getItems().addAll(NetworkToolsMenu.menusList(controller));
Menu dataMenu = new Menu(message("Data"));
dataMenu.getItems().addAll(DataToolsMenu.menusList(controller));
Menu mediaMenu = new Menu(message("Media"));
mediaMenu.getItems().addAll(MediaToolsMenu.menusList(controller));
MenuItem mainMenu = new MenuItem(message("MainPageShortcut"));
mainMenu.setOnAction((ActionEvent event) -> {
controller.openStage(Fxmls.MyboxFxml);
});
List<MenuItem> items = new ArrayList<>();
items.addAll(Arrays.asList(documentMenu, imageMenu, fileMenu,
networkMenu, dataMenu, mediaMenu, new SeparatorMenuItem(),
mainMenu));
return items;
}
public static CheckMenuItem popCheckMenu(String name) {
if (name == null) {
return null;
}
CheckMenuItem popItem = new CheckMenuItem(message("PopMenuWhenMouseHovering"),
StyleTools.getIconImageView("iconPop.png"));
popItem.setSelected(UserConfig.getBoolean(name + "MenuPopWhenMouseHovering", true));
popItem.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
UserConfig.setBoolean(name + "MenuPopWhenMouseHovering", popItem.isSelected());
}
});
return popItem;
}
public static boolean isPopMenu(String name) {
return isPopMenu(name, true);
}
public static boolean isPopMenu(String name, boolean init) {
if (name == null) {
return false;
}
return UserConfig.getBoolean(name + "MenuPopWhenMouseHovering", init);
}
public static List<MenuItem> initMenu(String name) {
return initMenu(name, true);
}
public static List<MenuItem> initMenu(String name, boolean fix) {
List<MenuItem> items = new ArrayList<>();
if (name == null || name.isBlank()) {
return items;
}
MenuItem menu = new MenuItem(fix ? StringTools.menuPrefix(name) : name);
menu.setStyle(attributeTextStyle());
items.add(menu);
items.add(new SeparatorMenuItem());
return items;
}
}
| 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/fxml/menu/DocumentToolsMenu.java | alpha/MyBox/src/main/java/mara/mybox/fxml/menu/DocumentToolsMenu.java | package mara.mybox.fxml.menu;
import java.util.ArrayList;
import java.util.Arrays;
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.BaseController;
import mara.mybox.controller.DataTreeController;
import mara.mybox.controller.ImagesPlayController;
import mara.mybox.controller.TextInMyBoxClipboardController;
import mara.mybox.controller.TextInSystemClipboardController;
import mara.mybox.value.Fxmls;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2025-12-9
* @License Apache License Version 2.0
*/
public class DocumentToolsMenu {
public static List<MenuItem> menusList(BaseController controller) {
Menu treeMenu = new Menu(message("InformationInTree"));
MenuItem TextTree = new MenuItem(message("TextTree"));
TextTree.setOnAction((ActionEvent event) -> {
DataTreeController.textTree(controller, true);
});
MenuItem HtmlTree = new MenuItem(message("HtmlTree"));
HtmlTree.setOnAction((ActionEvent event) -> {
DataTreeController.htmlTree(controller, true);
});
treeMenu.getItems().addAll(TextTree, HtmlTree);
Menu pdfMenu = new Menu("PDF");
MenuItem pdfView = new MenuItem(message("PdfView"));
pdfView.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.PdfViewFxml);
});
MenuItem PdfPlay = new MenuItem(message("PdfPlay"));
PdfPlay.setOnAction((ActionEvent event) -> {
ImagesPlayController c = (ImagesPlayController) controller.openScene(Fxmls.ImagesPlayFxml);
c.setAsPDF();
});
MenuItem PDFAttributes = new MenuItem(message("PDFAttributes"));
PDFAttributes.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.PdfAttributesFxml);
});
MenuItem PDFAttributesBatch = new MenuItem(message("PDFAttributesBatch"));
PDFAttributesBatch.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.PdfAttributesBatchFxml);
});
MenuItem pdfExtractImagesBatch = new MenuItem(message("PdfExtractImagesBatch"));
pdfExtractImagesBatch.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.PdfExtractImagesBatchFxml);
});
MenuItem pdfExtractTextsBatch = new MenuItem(message("PdfExtractTextsBatch"));
pdfExtractTextsBatch.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.PdfExtractTextsBatchFxml);
});
MenuItem pdfConvertImagesBatch = new MenuItem(message("PdfConvertImagesBatch"));
pdfConvertImagesBatch.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.PdfConvertImagesBatchFxml);
});
MenuItem pdfOcrBatch = new MenuItem(message("PdfOCRBatch"));
pdfOcrBatch.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.PdfOCRBatchFxml);
});
MenuItem pdfConvertHtmlsBatch = new MenuItem(message("PdfConvertHtmlsBatch"));
pdfConvertHtmlsBatch.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.PdfConvertHtmlsBatchFxml);
});
MenuItem imagesCombinePdf = new MenuItem(message("ImagesCombinePdf"));
imagesCombinePdf.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImagesEditorFxml);
});
MenuItem pdfCompressImagesBatch = new MenuItem(message("PdfCompressImagesBatch"));
pdfCompressImagesBatch.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.PdfCompressImagesBatchFxml);
});
MenuItem PdfImagesConvertBatch = new MenuItem(message("PdfImagesConvertBatch"));
PdfImagesConvertBatch.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.PdfImagesConvertBatchFxml);
});
MenuItem pdfMerge = new MenuItem(message("MergePdf"));
pdfMerge.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.PdfMergeFxml);
});
MenuItem PdfSplitBatch = new MenuItem(message("PdfSplitBatch"));
PdfSplitBatch.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.PdfSplitBatchFxml);
});
MenuItem PdfAddWatermarkBatch = new MenuItem(message("PdfAddWatermarkBatch"));
PdfAddWatermarkBatch.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.PdfAddWatermarkBatchFxml);
});
pdfMenu.getItems().addAll(
pdfView, PdfPlay, new SeparatorMenuItem(),
pdfConvertImagesBatch, PdfImagesConvertBatch, pdfConvertHtmlsBatch, pdfCompressImagesBatch, new SeparatorMenuItem(),
pdfExtractImagesBatch, pdfExtractTextsBatch, pdfOcrBatch, PdfAddWatermarkBatch, new SeparatorMenuItem(),
PdfSplitBatch, pdfMerge, imagesCombinePdf, new SeparatorMenuItem(),
PDFAttributes, PDFAttributesBatch
);
Menu textsMenu = new Menu(message("Texts"));
MenuItem textEditer = new MenuItem(message("TextEditer"));
textEditer.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.TextEditorFxml);
});
MenuItem TextConvert = new MenuItem(message("TextConvertSplit"));
TextConvert.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.TextFilesConvertFxml);
});
MenuItem TextMerge = new MenuItem(message("TextFilesMerge"));
TextMerge.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.TextFilesMergeFxml);
});
MenuItem TextFindBatch = new MenuItem(message("TextFindBatch"));
TextFindBatch.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.TextFindBatchFxml);
});
MenuItem TextReplaceBatch = new MenuItem(message("TextReplaceBatch"));
TextReplaceBatch.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.TextReplaceBatchFxml);
});
MenuItem TextFilterBatch = new MenuItem(message("TextFilterBatch"));
TextFilterBatch.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.TextFilterBatchFxml);
});
MenuItem TextToHtml = new MenuItem(message("TextToHtml"));
TextToHtml.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.TextToHtmlFxml);
});
MenuItem TextToPdf = new MenuItem(message("TextToPdf"));
TextToPdf.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.TextToPdfFxml);
});
textsMenu.getItems().addAll(
textEditer, TextFindBatch, TextReplaceBatch, TextFilterBatch, TextConvert, TextMerge, TextToHtml, TextToPdf
);
Menu bytesMenu = new Menu(message("Bytes"));
MenuItem bytesEditer = new MenuItem(message("BytesEditer"));
bytesEditer.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.BytesEditorFxml);
});
MenuItem BytesFindBatch = new MenuItem(message("BytesFindBatch"));
BytesFindBatch.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.BytesFindBatchFxml);
});
bytesMenu.getItems().addAll(
bytesEditer, BytesFindBatch
);
Menu htmlMenu = new Menu(message("Html"));
MenuItem htmlEditor = new MenuItem(message("HtmlEditor"));
htmlEditor.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.HtmlEditorFxml);
});
MenuItem htmlToMarkdown = new MenuItem(message("HtmlToMarkdown"));
htmlToMarkdown.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.HtmlToMarkdownFxml);
});
MenuItem HtmlToText = new MenuItem(message("HtmlToText"));
HtmlToText.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.HtmlToTextFxml);
});
MenuItem HtmlToPdf = new MenuItem(message("HtmlToPdf"));
HtmlToPdf.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.HtmlToPdfFxml);
});
MenuItem HtmlSetCharset = new MenuItem(message("HtmlSetCharset"));
HtmlSetCharset.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.HtmlSetCharsetFxml);
});
MenuItem HtmlSetStyle = new MenuItem(message("HtmlSetStyle"));
HtmlSetStyle.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.HtmlSetStyleFxml);
});
MenuItem HtmlSetEquiv = new MenuItem(message("HtmlSetEquiv"));
HtmlSetStyle.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.HtmlSetEquivFxml);
});
MenuItem HtmlSnap = new MenuItem(message("HtmlSnap"));
HtmlSnap.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.HtmlSnapFxml);
});
MenuItem HtmlTypesetting = new MenuItem(message("HtmlTypesetting"));
HtmlTypesetting.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.HtmlTypesettingFxml);
});
MenuItem WebFind = new MenuItem(message("WebFind"));
WebFind.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.HtmlFindFxml);
});
MenuItem HtmlExtractTables = new MenuItem(message("HtmlExtractTables"));
HtmlExtractTables.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.HtmlExtractTablesFxml);
});
MenuItem WebElements = new MenuItem(message("WebElements"));
WebElements.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.HtmlElementsFxml);
});
MenuItem HtmlMergeAsHtml = new MenuItem(message("HtmlMergeAsHtml"));
HtmlMergeAsHtml.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.HtmlMergeAsHtmlFxml);
});
MenuItem HtmlMergeAsMarkdown = new MenuItem(message("HtmlMergeAsMarkdown"));
HtmlMergeAsMarkdown.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.HtmlMergeAsMarkdownFxml);
});
MenuItem HtmlMergeAsPDF = new MenuItem(message("HtmlMergeAsPDF"));
HtmlMergeAsPDF.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.HtmlMergeAsPDFFxml);
});
MenuItem HtmlMergeAsText = new MenuItem(message("HtmlMergeAsText"));
HtmlMergeAsText.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.HtmlMergeAsTextFxml);
});
MenuItem HtmlFrameset = new MenuItem(message("HtmlFrameset"));
HtmlFrameset.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.HtmlFramesetFxml);
});
htmlMenu.getItems().addAll(
htmlEditor, WebFind, WebElements, HtmlSnap, HtmlExtractTables, new SeparatorMenuItem(),
HtmlTypesetting, htmlToMarkdown, HtmlToText, HtmlToPdf, HtmlSetCharset, HtmlSetStyle, HtmlSetEquiv, new SeparatorMenuItem(),
HtmlMergeAsHtml, HtmlMergeAsMarkdown, HtmlMergeAsPDF, HtmlMergeAsText, HtmlFrameset
);
Menu markdownMenu = new Menu("Markdown");
MenuItem markdownEditor = new MenuItem(message("MarkdownEditer"));
markdownEditor.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.MarkdownEditorFxml);
});
MenuItem markdownOptions = new MenuItem(message("MarkdownOptions"));
markdownOptions.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.MarkdownOptionsFxml);
});
MenuItem MarkdownTypesetting = new MenuItem(message("MarkdownTypesetting"));
MarkdownTypesetting.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.MarkdownTypesettingFxml);
});
MenuItem markdownToHtml = new MenuItem(message("MarkdownToHtml"));
markdownToHtml.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.MarkdownToHtmlFxml);
});
MenuItem MarkdownToText = new MenuItem(message("MarkdownToText"));
MarkdownToText.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.MarkdownToTextFxml);
});
MenuItem MarkdownToPdf = new MenuItem(message("MarkdownToPdf"));
MarkdownToPdf.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.MarkdownToPdfFxml);
});
markdownMenu.getItems().addAll(
markdownEditor, markdownOptions, new SeparatorMenuItem(),
MarkdownTypesetting, markdownToHtml, MarkdownToText, MarkdownToPdf
);
Menu jsonMenu = new Menu("JSON");
MenuItem jsonEditorMenu = new MenuItem(message("JsonEditor"));
jsonEditorMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.JsonEditorFxml);
});
MenuItem jsonTypesettingMenu = new MenuItem(message("JsonTypesetting"));
jsonTypesettingMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.JsonTypesettingFxml);
});
jsonMenu.getItems().addAll(
jsonEditorMenu, jsonTypesettingMenu
);
Menu xmlMenu = new Menu("XML");
MenuItem xmlEditorMenu = new MenuItem(message("XmlEditor"));
xmlEditorMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.XmlEditorFxml);
});
MenuItem xmlTypesettingMenu = new MenuItem(message("XmlTypesetting"));
xmlTypesettingMenu.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.XmlTypesettingFxml);
});
xmlMenu.getItems().addAll(
xmlEditorMenu, xmlTypesettingMenu
);
Menu msMenu = new Menu(message("MicrosoftDocumentFormats"));
MenuItem ExtractTextsFromMS = new MenuItem(message("ExtractTextsFromMS"));
ExtractTextsFromMS.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ExtractTextsFromMSFxml);
});
MenuItem WordView = new MenuItem(message("WordView"));
WordView.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.WordViewFxml);
});
MenuItem WordToHtml = new MenuItem(message("WordToHtml"));
WordToHtml.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.WordToHtmlFxml);
});
MenuItem WordToPdf = new MenuItem(message("WordToPdf"));
WordToPdf.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.WordToPdfFxml);
});
MenuItem PptView = new MenuItem(message("PptView"));
PptView.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.PptViewFxml);
});
MenuItem PptToImages = new MenuItem(message("PptToImages"));
PptToImages.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.PptToImagesFxml);
});
MenuItem PptToPdf = new MenuItem(message("PptToPdf"));
PptToPdf.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.PptToPdfFxml);
});
MenuItem PptExtract = new MenuItem(message("PptExtract"));
PptExtract.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.PptExtractFxml);
});
MenuItem PptxMerge = new MenuItem(message("PptxMerge"));
PptxMerge.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.PptxMergeFxml);
});
MenuItem PptSplit = new MenuItem(message("PptSplit"));
PptSplit.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.PptSplitFxml);
});
MenuItem imagesCombinePPT = new MenuItem(message("ImagesCombinePPT"));
imagesCombinePPT.setOnAction((ActionEvent event) -> {
controller.openScene(Fxmls.ImagesEditorFxml);
});
MenuItem PptPlay = new MenuItem(message("PptPlay"));
PptPlay.setOnAction((ActionEvent event) -> {
ImagesPlayController c = (ImagesPlayController) controller.openScene(Fxmls.ImagesPlayFxml);
c.setAsPPT();
});
MenuItem TextInMyBoxClipboard = new MenuItem(message("TextInMyBoxClipboard"));
TextInMyBoxClipboard.setOnAction((ActionEvent event) -> {
TextInMyBoxClipboardController.oneOpen();
});
MenuItem TextInSystemClipboard = new MenuItem(message("TextInSystemClipboard"));
TextInSystemClipboard.setOnAction((ActionEvent event) -> {
TextInSystemClipboardController.oneOpen();
});
msMenu.getItems().addAll(
WordView, WordToHtml, WordToPdf, new SeparatorMenuItem(),
PptView, PptToImages, PptToPdf, PptExtract, PptSplit, PptxMerge, imagesCombinePPT, PptPlay, new SeparatorMenuItem(),
ExtractTextsFromMS
);
List<MenuItem> items = new ArrayList<>();
items.addAll(Arrays.asList(treeMenu, new SeparatorMenuItem(),
pdfMenu, markdownMenu, jsonMenu, xmlMenu, htmlMenu, textsMenu, msMenu, bytesMenu, new SeparatorMenuItem(),
TextInMyBoxClipboard, TextInSystemClipboard));
return items;
}
}
| 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/calculation/DoubleStatistic.java | alpha/MyBox/src/main/java/mara/mybox/calculation/DoubleStatistic.java | package mara.mybox.calculation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mara.mybox.calculation.DescriptiveStatistic.StatisticType;
import mara.mybox.db.data.ColumnDefinition.InvalidAs;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.DoubleArrayTools;
import mara.mybox.tools.DoubleTools;
import mara.mybox.tools.NumberTools;
import mara.mybox.tools.StringTools;
import mara.mybox.value.AppValues;
import org.apache.commons.math3.stat.descriptive.moment.Skewness;
import org.apache.commons.math3.stat.descriptive.rank.Percentile;
/**
* @Author Mara
* @CreateDate 2021-10-4
* @License Apache License Version 2.0
*/
public class DoubleStatistic {
public String name;
public long count, invalidCount;
public double sum, mean, geometricMean, sumSquares,
populationVariance, sampleVariance, populationStandardDeviation, sampleStandardDeviation, skewness,
minimum, maximum, median, upperQuartile, lowerQuartile, mode,
upperMildOutlierLine, upperExtremeOutlierLine, lowerMildOutlierLine, lowerExtremeOutlierLine,
dTmp;
public Object modeValue, minimumValue, maximumValue, medianValue, upperQuartileValue, lowerQuartileValue;
public DescriptiveStatistic options;
public InvalidAs invalidAs;
private double[] doubles, valids;
public DoubleStatistic() {
init();
}
public DoubleStatistic(double[] values) {
initOptions(null);
calculate(values);
}
public DoubleStatistic(double[] values, DescriptiveStatistic inOptions) {
initOptions(inOptions);
calculate(values);
}
public DoubleStatistic(String[] values, DescriptiveStatistic inOptions) {
calculate(values, inOptions);
}
private void init() {
count = 0;
sum = 0;
mean = 0;
geometricMean = 1;
sumSquares = 0;
populationVariance = Double.NaN;
sampleVariance = Double.NaN;
populationStandardDeviation = Double.NaN;
sampleStandardDeviation = Double.NaN;
skewness = Double.NaN;
maximum = -Double.MAX_VALUE;
minimum = Double.MAX_VALUE;
median = Double.NaN;
mode = Double.NaN;
upperQuartile = Double.NaN;
lowerQuartile = Double.NaN;
upperMildOutlierLine = Double.NaN;
upperExtremeOutlierLine = Double.NaN;
lowerMildOutlierLine = Double.NaN;
lowerExtremeOutlierLine = Double.NaN;
modeValue = null;
dTmp = 0;
invalidAs = InvalidAs.Zero;
invalidCount = 0;
options = null;
doubles = null;
valids = null;
}
private void initOptions(DescriptiveStatistic inOptions) {
init();
if (inOptions == null) {
options = DescriptiveStatistic.all(true);
} else {
options = inOptions;
}
invalidAs = options.invalidAs;
}
public final void calculate(String[] values, DescriptiveStatistic inOptions) {
initOptions(inOptions);
if (options.include(StatisticType.Mode)) {
modeValue = modeObject(values);
try {
mode = Double.parseDouble(modeValue + "");
} catch (Exception e) {
mode = Double.NaN;
}
}
calculate(toDoubleArray(values));
}
private void calculate(double[] values) {
try {
if (values == null) {
return;
}
doubles = values;
calculateBase();
calculateVariance();
calculatePercentile();
calculateSkewness();
if (modeValue == null) {
calculateMode();
}
} catch (Exception e) {
MyBoxLog.error(e);
}
}
private void calculateBase() {
try {
if (doubles == null || options == null) {
return;
}
sum = 0;
count = 0;
invalidCount = 0;
double total = doubles.length;
if (total == 0) {
return;
}
List<Double> validList = new ArrayList<>();
for (int i = 0; i < total; ++i) {
double v = doubles[i];
if (Double.isNaN(v)) {
switch (invalidAs) {
case Zero:
v = 0;
break;
default:
invalidCount++;
continue;
}
}
count++;
validList.add(v);
sum += v;
if (options.include(StatisticType.MaximumQ4) && v > maximum) {
maximum = v;
}
if (options.include(StatisticType.MinimumQ0) && v < minimum) {
minimum = v;
}
if (options.include(StatisticType.GeometricMean)) {
geometricMean = geometricMean * v;
}
if (options.include(StatisticType.SumOfSquares)) {
sumSquares += v * v;
}
}
if (count == 0) {
mean = Double.NaN;
sum = Double.NaN;
geometricMean = Double.NaN;
sumSquares = Double.NaN;
valids = null;
} else {
mean = sum / count;
if (options.include(StatisticType.GeometricMean)) {
geometricMean = Math.pow(geometricMean, 1d / count);
}
valids = new double[validList.size()];
int index = 0;
for (double d : validList) {
valids[index++] = d;
}
}
if (maximum == -Double.MAX_VALUE) {
maximum = Double.NaN;
}
if (minimum == Double.MAX_VALUE) {
minimum = Double.NaN;
}
} catch (Exception e) {
MyBoxLog.error(e);
}
}
private void calculateVariance() {
try {
if (valids == null || count <= 0 || options == null || count <= 0) {
return;
}
if (!options.needVariance()) {
return;
}
dTmp = 0;
for (int i = 0; i < count; ++i) {
double v = valids[i];
double p = v - mean;
double p2 = p * p;
dTmp += p2;
}
populationVariance = dTmp / count;
sampleVariance = count < 2 ? Double.NaN : dTmp / (count - 1);
if (options.include(StatisticType.PopulationStandardDeviation)) {
populationStandardDeviation = Math.sqrt(populationVariance);
}
if (options.include(StatisticType.SampleStandardDeviation)) {
sampleStandardDeviation = Math.sqrt(sampleVariance);
}
} catch (Exception e) {
MyBoxLog.error(e);
}
}
private void calculatePercentile() {
try {
if (valids == null || count <= 0 || options == null) {
return;
}
if (!options.needPercentile()) {
return;
}
Percentile percentile = new Percentile();
percentile.setData(valids);
if (options.include(StatisticType.Median)) {
median = percentile.evaluate(50);
medianValue = median;
}
boolean needOutlier = options.needOutlier();
if (options.include(StatisticType.UpperQuartile) || needOutlier) {
upperQuartile = percentile.evaluate(75);
upperQuartileValue = upperQuartile;
}
if (options.include(StatisticType.LowerQuartile) || needOutlier) {
lowerQuartile = percentile.evaluate(25);
lowerQuartileValue = lowerQuartile;
}
if (needOutlier) {
double qi = upperQuartile - lowerQuartile;
if (options.include(StatisticType.UpperExtremeOutlierLine)) {
upperExtremeOutlierLine = upperQuartile + 3 * qi;
}
if (options.include(StatisticType.UpperMildOutlierLine)) {
upperMildOutlierLine = upperQuartile + 1.5 * qi;
}
if (options.include(StatisticType.LowerExtremeOutlierLine)) {
lowerExtremeOutlierLine = lowerQuartile - 3 * qi;
}
if (options.include(StatisticType.LowerMildOutlierLine)) {
lowerMildOutlierLine = lowerQuartile - 1.5 * qi;
}
}
} catch (Exception e) {
MyBoxLog.error(e);
}
}
private void calculateSkewness() {
try {
if (valids == null || count <= 0 || options == null || count <= 0) {
return;
}
if (!options.include(StatisticType.Skewness)) {
return;
}
skewness = new Skewness().evaluate(valids);
} catch (Exception e) {
MyBoxLog.error(e);
}
}
private void calculateMode() {
try {
if (options == null || valids == null || count <= 0) {
return;
}
if (!options.include(StatisticType.Mode)) {
return;
}
mode = mode(valids);
modeValue = mode;
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public List<String> toStringList() {
if (options == null) {
return null;
}
int scale = options.getScale();
List<String> list = new ArrayList<>();
for (StatisticType type : options.types) {
switch (type) {
case Count:
list.add(StringTools.format(count));
break;
case Sum:
list.add(NumberTools.format(sum, scale));
break;
case Mean:
list.add(NumberTools.format(mean, scale));
break;
case MaximumQ4:
list.add(NumberTools.format(maximum, scale));
break;
case MinimumQ0:
list.add(NumberTools.format(minimum, scale));
break;
case GeometricMean:
list.add(NumberTools.format(geometricMean, scale));
break;
case SumOfSquares:
list.add(NumberTools.format(sumSquares, scale));
break;
case PopulationVariance:
list.add(NumberTools.format(populationVariance, scale));
break;
case SampleVariance:
list.add(NumberTools.format(sampleVariance, scale));
break;
case PopulationStandardDeviation:
list.add(NumberTools.format(populationStandardDeviation, scale));
break;
case SampleStandardDeviation:
list.add(NumberTools.format(sampleStandardDeviation, scale));
break;
case Skewness:
list.add(NumberTools.format(skewness, scale));
break;
case Median:
list.add(NumberTools.format(median, scale));
break;
case UpperQuartile:
list.add(NumberTools.format(upperQuartile, scale));
break;
case LowerQuartile:
list.add(NumberTools.format(lowerQuartile, scale));
break;
case UpperExtremeOutlierLine:
list.add(NumberTools.format(upperExtremeOutlierLine, scale));
break;
case UpperMildOutlierLine:
list.add(NumberTools.format(upperMildOutlierLine, scale));
break;
case LowerMildOutlierLine:
list.add(NumberTools.format(lowerMildOutlierLine, scale));
break;
case LowerExtremeOutlierLine:
list.add(NumberTools.format(lowerExtremeOutlierLine, scale));
break;
case Mode:
if (modeValue == null) {
list.add(null);
} else {
try {
list.add(NumberTools.format((double) modeValue, scale));
} catch (Exception e) {
list.add(modeValue.toString());
}
}
break;
}
}
return list;
}
public final double[] toDoubleArray(String[] strings) {
if (strings == null) {
return null;
}
doubles = new double[strings.length];
for (int i = 0; i < strings.length; i++) {
doubles[i] = DoubleTools.toDouble(strings[i], invalidAs);
}
return doubles;
}
public double value(StatisticType type) {
if (type == null) {
return Double.NaN;
}
switch (type) {
case Count:
return count;
case Sum:
return sum;
case Mean:
return mean;
case MaximumQ4:
return maximum;
case MinimumQ0:
return minimum;
case GeometricMean:
return geometricMean;
case SumOfSquares:
return sumSquares;
case PopulationVariance:
return populationVariance;
case SampleVariance:
return sampleVariance;
case PopulationStandardDeviation:
return populationStandardDeviation;
case SampleStandardDeviation:
return sampleStandardDeviation;
case Skewness:
return skewness;
case Median:
return median;
case UpperQuartile:
return upperQuartile;
case LowerQuartile:
return lowerQuartile;
case UpperExtremeOutlierLine:
return upperExtremeOutlierLine;
case UpperMildOutlierLine:
return upperMildOutlierLine;
case LowerMildOutlierLine:
return lowerMildOutlierLine;
case LowerExtremeOutlierLine:
return lowerExtremeOutlierLine;
case Mode:
return mode;
}
return Double.NaN;
}
/*
static methods
*/
public static double sum(double[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidDouble;
}
double sum = 0;
for (int i = 0; i < values.length; ++i) {
sum += values[i];
}
return sum;
}
public static double maximum(double[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidDouble;
}
double max = -Double.MAX_VALUE;
for (int i = 0; i < values.length; ++i) {
if (values[i] > max) {
max = values[i];
}
}
return max;
}
public static double minimum(double[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidDouble;
}
double min = Double.MAX_VALUE;
for (int i = 0; i < values.length; ++i) {
if (values[i] < min) {
min = values[i];
}
}
return min;
}
public static double mean(double[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidDouble;
}
return sum(values) / values.length;
}
public static double mode(double[] values) {
try {
if (values == null || values.length == 0) {
return Double.NaN;
}
Object[] objects = new Object[values.length];
for (int i = 0; i < values.length; i++) {
objects[i] = values[i];
}
Object mode = modeObject(objects);
return mode != null ? (double) mode : Double.NaN;
} catch (Exception e) {
return Double.NaN;
}
}
public static Object modeObject(Object[] values) {
Object mode = null;
try {
if (values == null || values.length == 0) {
return mode;
}
Map<Object, Integer> number = new HashMap<>();
for (Object value : values) {
if (number.containsKey(value)) {
number.put(value, number.get(value) + 1);
} else {
number.put(value, 1);
}
}
double num = 0;
for (Object value : number.keySet()) {
if (num < number.get(value)) {
mode = value;
}
}
} catch (Exception e) {
}
return mode;
}
public static double median(double[] values) {
try {
if (values == null) {
return AppValues.InvalidDouble;
}
int len = values.length;
if (len == 0) {
return AppValues.InvalidDouble;
} else if (len == 1) {
return values[0];
}
double[] sorted = DoubleArrayTools.sortArray(values);
if (len == 2) {
return (sorted[0] + sorted[1]) / 2;
} else if (len % 2 == 0) {
return (sorted[len / 2] + sorted[len / 2 + 1]) / 2;
} else {
return sorted[len / 2];
}
} catch (Exception e) {
return AppValues.InvalidDouble;
}
}
public static double variance(double[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidDouble;
}
double mean = mean(values);
return variance(values, mean);
}
public static double variance(double[] values, double mean) {
if (values == null || values.length == 0) {
return AppValues.InvalidDouble;
}
double variance = 0;
for (int i = 0; i < values.length; ++i) {
variance += Math.pow(values[i] - mean, 2);
}
variance = Math.sqrt(variance / values.length);
return variance;
}
public static double skewness(double[] values, double mean) {
if (values == null || values.length == 0) {
return AppValues.InvalidDouble;
}
double skewness = 0;
for (int i = 0; i < values.length; ++i) {
skewness += Math.pow(values[i] - mean, 3);
}
skewness = Math.cbrt(skewness / values.length);
return skewness;
}
/*
get/set
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSum() {
return sum;
}
public void setSum(double sum) {
this.sum = sum;
}
public double getMean() {
return mean;
}
public void setMean(double mean) {
this.mean = mean;
}
public double getPopulationVariance() {
return populationVariance;
}
public void setPopulationVariance(double populationVariance) {
this.populationVariance = populationVariance;
}
public double getSkewness() {
return skewness;
}
public void setSkewness(double skewness) {
this.skewness = skewness;
}
public double getMinimum() {
return minimum;
}
public void setMinimum(double minimum) {
this.minimum = minimum;
}
public double getMaximum() {
return maximum;
}
public void setMaximum(double maximum) {
this.maximum = maximum;
}
public Object getModeValue() {
return modeValue;
}
public void setModeValue(Object modeValue) {
this.modeValue = modeValue;
}
public double getMedian() {
return median;
}
public void setMedian(double median) {
this.median = median;
}
public long getCount() {
return count;
}
public void setCount(long count) {
this.count = count;
}
public double getGeometricMean() {
return geometricMean;
}
public void setGeometricMean(double geometricMean) {
this.geometricMean = geometricMean;
}
public double getSumSquares() {
return sumSquares;
}
public void setSumSquares(double sumSquares) {
this.sumSquares = sumSquares;
}
public double getSampleVariance() {
return sampleVariance;
}
public void setSampleVariance(double sampleVariance) {
this.sampleVariance = sampleVariance;
}
public double getPopulationStandardDeviation() {
return populationStandardDeviation;
}
public void setPopulationStandardDeviation(double populationStandardDeviation) {
this.populationStandardDeviation = populationStandardDeviation;
}
public double getSampleStandardDeviation() {
return sampleStandardDeviation;
}
public void setSampleStandardDeviation(double sampleStandardDeviation) {
this.sampleStandardDeviation = sampleStandardDeviation;
}
public double getUpperQuartile() {
return upperQuartile;
}
public void setUpperQuartile(double upperQuartile) {
this.upperQuartile = upperQuartile;
}
public double getLowerQuartile() {
return lowerQuartile;
}
public void setLowerQuartile(double lowerQuartile) {
this.lowerQuartile = lowerQuartile;
}
public double getUpperMildOutlierLine() {
return upperMildOutlierLine;
}
public void setUpperMildOutlierLine(double upperMildOutlierLine) {
this.upperMildOutlierLine = upperMildOutlierLine;
}
public double getUpperExtremeOutlierLine() {
return upperExtremeOutlierLine;
}
public void setUpperExtremeOutlierLine(double upperExtremeOutlierLine) {
this.upperExtremeOutlierLine = upperExtremeOutlierLine;
}
public double getLowerMildOutlierLine() {
return lowerMildOutlierLine;
}
public void setLowerMildOutlierLine(double lowerMildOutlierLine) {
this.lowerMildOutlierLine = lowerMildOutlierLine;
}
public double getLowerExtremeOutlierLine() {
return lowerExtremeOutlierLine;
}
public void setLowerExtremeOutlierLine(double lowerExtremeOutlierLine) {
this.lowerExtremeOutlierLine = lowerExtremeOutlierLine;
}
public double getMode() {
return mode;
}
public void setMode(double mode) {
this.mode = mode;
}
public Object getMinimumValue() {
return minimumValue;
}
public void setMinimumValue(Object minimumValue) {
this.minimumValue = minimumValue;
}
public Object getMaximumValue() {
return maximumValue;
}
public void setMaximumValue(Object maximumValue) {
this.maximumValue = maximumValue;
}
public Object getMedianValue() {
return medianValue;
}
public void setMedianValue(Object medianValue) {
this.medianValue = medianValue;
}
public Object getUpperQuartileValue() {
return upperQuartileValue;
}
public void setUpperQuartileValue(Object upperQuartileValue) {
this.upperQuartileValue = upperQuartileValue;
}
public Object getLowerQuartileValue() {
return lowerQuartileValue;
}
public void setLowerQuartileValue(Object lowerQuartileValue) {
this.lowerQuartileValue = lowerQuartileValue;
}
public double getdTmp() {
return dTmp;
}
public void setdTmp(double dTmp) {
this.dTmp = dTmp;
}
public DescriptiveStatistic getOptions() {
return options;
}
public DoubleStatistic setOptions(DescriptiveStatistic options) {
this.options = options;
return this;
}
public DoubleStatistic setValues(double[] values) {
this.doubles = values;
return this;
}
public long getInvalidCount() {
return invalidCount;
}
public DoubleStatistic setInvalidCount(long invalidCount) {
this.invalidCount = invalidCount;
return this;
}
public InvalidAs getInvalidAs() {
return invalidAs;
}
public DoubleStatistic setInvalidAs(InvalidAs invalidAs) {
this.invalidAs = invalidAs;
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/calculation/OLSLinearRegression.java | alpha/MyBox/src/main/java/mara/mybox/calculation/OLSLinearRegression.java | package mara.mybox.calculation;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.ColumnDefinition.InvalidAs;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.fxml.FxTask;
import mara.mybox.tools.DoubleTools;
import static mara.mybox.value.Languages.message;
import org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression;
/**
* @Author Mara
* @CreateDate 2022-8-18
* @License Apache License Version 2.0
*/
public class OLSLinearRegression extends OLSMultipleLinearRegression {
public String yName;
public List<String> xNames;
public int n, k;
public int scale = 8;
public double intercept, rSqure, adjustedRSqure, standardError, variance;
public double[][] x;
public double[] y, coefficients;
public InvalidAs invalidAs;
protected FxTask<Void> task;
public OLSLinearRegression(boolean includeIntercept) {
super();
this.setNoIntercept(!includeIntercept);
}
public boolean calculate(String[] sy, String[][] sx) {
try {
n = sy.length;
k = sx[0].length;
Normalization normalization = Normalization.create()
.setA(Normalization.Algorithm.ZScore)
.setInvalidAs(invalidAs);
sy = normalization.setSourceVector(sy).calculate();
sx = normalization.setSourceMatrix(sx).columnsNormalize();
y = new double[n];
x = new double[n][k];
for (int i = 0; i < n; i++) {
y[i] = DoubleTools.toDouble(sy[i], invalidAs);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < k; j++) {
x[i][j] = DoubleTools.toDouble(sx[i][j], invalidAs);
}
}
newSampleData(y, x);
double[] beta = estimateRegressionParameters();
if (isNoIntercept()) {
intercept = 0;
coefficients = beta;
} else {
intercept = beta[0];
coefficients = new double[beta.length - 1];
for (int i = 1; i < beta.length; i++) {
coefficients[i - 1] = beta[i];
}
}
rSqure = calculateRSquared();
adjustedRSqure = calculateAdjustedRSquared();
standardError = estimateRegressionStandardError();
variance = estimateRegressandVariance();
return true;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
return false;
}
}
public List<Data2DColumn> makeColumns() {
try {
List<Data2DColumn> columns = new ArrayList<>();
columns.add(new Data2DColumn(message("Item"), ColumnDefinition.ColumnType.String));
columns.add(new Data2DColumn(message("DependentVariable") + "_" + yName, ColumnDefinition.ColumnType.Double));
for (String name : xNames) {
columns.add(new Data2DColumn(message("IndependentVariable") + "_" + name, ColumnDefinition.ColumnType.Double));
}
columns.add(new Data2DColumn(message("Residual"), ColumnDefinition.ColumnType.Double));
return columns;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
return null;
}
}
public List<List<String>> makeRegressionData() {
try {
List<List<String>> data = new ArrayList<>();
double[] residuals = estimateResiduals();
List<String> row = new ArrayList<>();
row.add(message("Coefficient"));
row.add("");
for (int j = 0; j < coefficients.length; j++) {
row.add(coefficients[j] + "");
}
row.add("");
data.add(row);
for (int i = 0; i < x.length; i++) {
row = new ArrayList<>();
row.add("" + (i + 1));
row.add(y[i] + "");
for (int j = 0; j < x[i].length; j++) {
row.add(x[i][j] + "");
}
row.add(residuals[i] + "");
data.add(row);
}
return data;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
return null;
}
}
public double[] scaledCoefficients() {
if (coefficients == null) {
return null;
}
double[] scaled = new double[coefficients.length];
for (int i = 0; i < coefficients.length; i++) {
double d = coefficients[i];
if (DoubleTools.invalidDouble(d)) {
scaled[i] = Double.NaN;
} else {
scaled[i] = DoubleTools.scale(d, scale);
}
}
return scaled;
}
/*
set
*/
public OLSLinearRegression setyName(String yName) {
this.yName = yName;
return this;
}
public OLSLinearRegression setxNames(List<String> xNames) {
this.xNames = xNames;
return this;
}
public OLSLinearRegression setScale(int scale) {
this.scale = scale;
return this;
}
public OLSLinearRegression setInvalidAs(InvalidAs invalidAs) {
this.invalidAs = invalidAs;
return this;
}
public OLSLinearRegression setTask(FxTask<Void> task) {
this.task = task;
return this;
}
/*
get
*/
public int getN() {
return n;
}
public int getK() {
return k;
}
public double[][] getXValues() {
return x;
}
public double[] getYValues() {
return y;
}
public double getIntercept() {
return intercept;
}
public double[] getCoefficients() {
return coefficients;
}
public double getrSqure() {
return rSqure;
}
public double getAdjustedRSqure() {
return adjustedRSqure;
}
public double getStandardError() {
return standardError;
}
public double getVariance() {
return variance;
}
}
| 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/calculation/ShortStatistic.java | alpha/MyBox/src/main/java/mara/mybox/calculation/ShortStatistic.java | package mara.mybox.calculation;
import java.util.HashMap;
import java.util.Map;
import mara.mybox.tools.ShortTools;
import mara.mybox.value.AppValues;
/**
* @Author Mara
* @CreateDate 2021-10-4
* @License Apache License Version 2.0
*/
public class ShortStatistic {
private String name;
private int count;
private short minimum, maximum, mode, median;
private double sum, mean, variance, skewness;
public ShortStatistic() {
}
public ShortStatistic(short[] values) {
if (values == null || values.length == 0) {
return;
}
count = values.length;
sum = 0;
minimum = Short.MAX_VALUE;
maximum = Short.MIN_VALUE;
for (int i = 0; i < count; ++i) {
short v = values[i];
sum += v;
if (v > maximum) {
maximum = v;
}
if (v < minimum) {
minimum = v;
}
}
mean = sum / values.length;
variance = 0;
skewness = 0;
mode = mode(values);
median = median(values);
for (int i = 0; i < values.length; ++i) {
short v = values[i];
variance += Math.pow(v - mean, 2);
skewness += Math.pow(v - mean, 3);
}
variance = Math.sqrt(variance / count);
skewness = Math.cbrt(skewness / count);
}
/*
static methods
*/
public static double sum(short[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidShort;
}
double sum = 0;
for (int i = 0; i < values.length; ++i) {
sum += values[i];
}
return sum;
}
public static short maximum(short[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidShort;
}
short max = Short.MIN_VALUE;
for (int i = 0; i < values.length; ++i) {
if (values[i] > max) {
max = values[i];
}
}
return max;
}
public static short minimum(short[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidShort;
}
short min = Short.MAX_VALUE;
for (int i = 0; i < values.length; ++i) {
if (values[i] < min) {
min = values[i];
}
}
return min;
}
public static double mean(short[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidShort;
}
return sum(values) / values.length;
}
public static short mode(short[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidShort;
}
short mode = 0;
Map<Short, Integer> number = new HashMap<>();
for (short value : values) {
if (number.containsKey(value)) {
number.put(value, number.get(value) + 1);
} else {
number.put(value, 1);
}
}
short num = 0;
for (short value : number.keySet()) {
if (num < number.get(value)) {
mode = value;
}
}
return mode;
}
public static short median(short[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidShort;
}
short[] sorted = ShortTools.sortArray(values);
int len = sorted.length;
if (len % 2 == 0) {
return (short) ((sorted[len / 2] + sorted[len / 2 + 1]) / 2);
} else {
return sorted[len / 2];
}
}
public static double variance(short[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidShort;
}
double mean = mean(values);
return variance(values, mean);
}
public static double variance(short[] values, double mean) {
if (values == null || values.length == 0) {
return AppValues.InvalidShort;
}
double variance = 0;
for (int i = 0; i < values.length; ++i) {
variance += Math.pow(values[i] - mean, 2);
}
variance = Math.sqrt(variance / values.length);
return variance;
}
public static double skewness(short[] values, double mean) {
if (values == null || values.length == 0) {
return AppValues.InvalidShort;
}
double skewness = 0;
for (int i = 0; i < values.length; ++i) {
skewness += Math.pow(values[i] - mean, 3);
}
skewness = Math.cbrt(skewness / values.length);
return skewness;
}
/*
get/set
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSum() {
return sum;
}
public void setSum(short sum) {
this.sum = sum;
}
public double getMean() {
return mean;
}
public void setMean(short mean) {
this.mean = mean;
}
public double getVariance() {
return variance;
}
public void setVariance(short variance) {
this.variance = variance;
}
public double getSkewness() {
return skewness;
}
public void setSkewness(short skewness) {
this.skewness = skewness;
}
public short getMinimum() {
return minimum;
}
public void setMinimum(short minimum) {
this.minimum = minimum;
}
public short getMaximum() {
return maximum;
}
public void setMaximum(short maximum) {
this.maximum = maximum;
}
public short getMode() {
return mode;
}
public void setMode(short mode) {
this.mode = mode;
}
public short getMedian() {
return median;
}
public void setMedian(short median) {
this.median = median;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
| 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/calculation/IntStatistic.java | alpha/MyBox/src/main/java/mara/mybox/calculation/IntStatistic.java | package mara.mybox.calculation;
import java.util.HashMap;
import java.util.Map;
import mara.mybox.tools.DoubleTools;
import mara.mybox.tools.IntTools;
import mara.mybox.value.AppValues;
/**
* @Author Mara
* @CreateDate 2019-2-11 12:53:19
* @License Apache License Version 2.0
*/
public class IntStatistic {
private String name;
private int count;
private long sum;
private int minimum, maximum, mode, median;
private double mean, standardDeviation, skewness;
public IntStatistic() {
}
public IntStatistic(int[] values) {
if (values == null || values.length == 0) {
return;
}
count = values.length;
sum = 0;
minimum = Integer.MAX_VALUE;
maximum = Integer.MIN_VALUE;
for (int i = 0; i < count; ++i) {
int v = values[i];
sum += v;
if (v > maximum) {
maximum = v;
}
if (v < minimum) {
minimum = v;
}
}
mean = sum / values.length;
standardDeviation = 0;
skewness = 0;
mode = mode(values);
median = median(values);
for (int i = 0; i < values.length; ++i) {
double v = values[i] - mean;
double v2 = v * v;
standardDeviation += v2;
skewness += v2 * v;
}
standardDeviation = Math.sqrt(standardDeviation / count);
skewness = Math.cbrt(skewness / count);
}
public IntStatistic(String name, long sum, int mean, int variance, int skewness,
int minimum, int maximum, int[] histogram) {
this.name = name;
this.sum = sum;
this.mean = mean;
this.standardDeviation = variance;
this.skewness = skewness;
this.minimum = minimum;
this.maximum = maximum;
this.mode = maximumIndex(histogram);
this.median = medianIndex(histogram);
}
/*
static methods
*/
public static long sum(int[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidLong;
}
long sum = 0;
for (int i = 0; i < values.length; ++i) {
sum += values[i];
}
return sum;
}
public static int maximum(int[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidInteger;
}
int max = Integer.MIN_VALUE;
for (int i = 0; i < values.length; ++i) {
if (values[i] > max) {
max = values[i];
}
}
return max;
}
public static int minimum(int[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidInteger;
}
int min = Integer.MAX_VALUE;
for (int i = 0; i < values.length; ++i) {
if (values[i] < min) {
min = values[i];
}
}
return min;
}
public static double mean(int[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidDouble;
}
return sum(values) * 1d / values.length;
}
public static int mode(int[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidInteger;
}
int mode = 0;
Map<Integer, Integer> number = new HashMap<>();
for (int value : values) {
if (number.containsKey(value)) {
number.put(value, number.get(value) + 1);
} else {
number.put(value, 1);
}
}
int num = 0;
for (int value : number.keySet()) {
if (num < number.get(value)) {
mode = value;
}
}
return mode;
}
public static int median(int[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidInteger;
}
int[] sorted = IntTools.sortArray(values);
int len = sorted.length;
if (len == 2) {
return (sorted[0] + sorted[1]) / 2;
} else if (len % 2 == 0) {
return (sorted[len / 2] + sorted[len / 2 + 1]) / 2;
} else {
return sorted[len / 2];
}
}
public static double variance(int[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidDouble;
}
double mean = mean(values);
if (DoubleTools.invalidDouble(mean)) {
return AppValues.InvalidDouble;
}
return variance(values, mean);
}
public static double variance(int[] values, double mean) {
if (values == null || values.length == 0) {
return AppValues.InvalidDouble;
}
double variance = 0;
for (int i = 0; i < values.length; ++i) {
variance += Math.pow(values[i] - mean, 2);
}
variance = Math.sqrt(variance / values.length);
return variance;
}
public static double skewness(int[] values, double mean) {
if (values == null || values.length == 0) {
return AppValues.InvalidDouble;
}
double skewness = 0;
for (int i = 0; i < values.length; ++i) {
skewness += Math.pow(values[i] - mean, 3);
}
skewness = Math.cbrt(skewness / values.length);
return skewness;
}
public static int medianIndex(int[] values) {
if (values == null || values.length == 0) {
return -1;
}
int[] sorted = IntTools.sortArray(values);
int mid = sorted[sorted.length / 2];
for (int i = 0; i < values.length; ++i) {
if (values[i] == mid) {
return i;
}
}
return -1;
}
public static int maximumIndex(int[] values) {
if (values == null || values.length == 0) {
return -1;
}
int max = Integer.MIN_VALUE, maxIndex = -1;
for (int i = 0; i < values.length; ++i) {
if (values[i] > max) {
max = values[i];
maxIndex = i;
}
}
return maxIndex;
}
/*
get/set
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getSum() {
return sum;
}
public void setSum(long sum) {
this.sum = sum;
}
public double getMean() {
return mean;
}
public void setMean(double mean) {
this.mean = mean;
}
public double getStandardDeviation() {
return standardDeviation;
}
public void setStandardDeviation(double standardDeviation) {
this.standardDeviation = standardDeviation;
}
public double getSkewness() {
return skewness;
}
public void setSkewness(int skewness) {
this.skewness = skewness;
}
public int getMinimum() {
return minimum;
}
public void setMinimum(int minimum) {
this.minimum = minimum;
}
public int getMaximum() {
return maximum;
}
public void setMaximum(int maximum) {
this.maximum = maximum;
}
public int getMode() {
return mode;
}
public void setMode(int mode) {
this.mode = mode;
}
public int getMedian() {
return median;
}
public void setMedian(int median) {
this.median = median;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
| 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/calculation/SimpleLinearRegression.java | alpha/MyBox/src/main/java/mara/mybox/calculation/SimpleLinearRegression.java | package mara.mybox.calculation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
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.tools.DoubleTools;
import mara.mybox.tools.NumberTools;
import static mara.mybox.value.Languages.message;
import org.apache.commons.math3.stat.regression.SimpleRegression;
/**
* @Author Mara
* @CreateDate 2022-5-4
* @License Apache License Version 2.0
*
* To accumulate the progress based on saved values.
*/
public class SimpleLinearRegression extends SimpleRegression {
protected String xName, yName;
protected List<String> lastData;
protected List<Data2DColumn> columns;
protected int scale = 8;
protected double lastIntercept, lastSlope, lastRSquare, lastR;
public SimpleLinearRegression(boolean includeIntercept, String xName, String yName, int scale) {
super(includeIntercept);
this.xName = xName;
this.yName = yName;
this.scale = scale;
makeColumns();
}
private List<Data2DColumn> makeColumns() {
columns = new ArrayList<>();
columns.add(new Data2DColumn(message("RowNumber"), ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(message("NumberOfObservations"), ColumnDefinition.ColumnType.Long));
columns.add(new Data2DColumn(xName, ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(yName, ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(message("Slope"), ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(message("Intercept"), ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(message("CoefficientOfDetermination"), ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(message("PearsonsR"), ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(message("MeanSquareError"), ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(message("SumSquaredErrors"), ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(message("TotalSumSquares"), ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(message("SumSquaredRegression"), ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(message("StandardErrorOfSlope"), ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(message("SignificanceLevelSlopeCorrelation"), ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(message("HalfWidthConfidenceIntervalOfSlope"), ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn(message("StandardErrorOfIntercept"), ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn("SumOfCrossProducts", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn("XSumSquares", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn("Xbar", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn("SumX", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn("Ybar", ColumnDefinition.ColumnType.Double));
columns.add(new Data2DColumn("SumY", ColumnDefinition.ColumnType.Double));
return columns;
}
public List<String> addData(long rowIndex, final double x, final double y) {
super.addData(x, y);
lastIntercept = getIntercept();
lastSlope = getSlope();
lastRSquare = getRSquare();
lastR = getR();
lastData = new ArrayList<>();
lastData.add(rowIndex + "");
lastData.add(getN() + "");
lastData.add(NumberTools.format(x, scale));
lastData.add(NumberTools.format(y, scale));
lastData.add(NumberTools.format(lastSlope, scale));
lastData.add(NumberTools.format(lastIntercept, scale));
lastData.add(NumberTools.format(lastRSquare, scale));
lastData.add(NumberTools.format(lastR, scale));
lastData.add(NumberTools.format(getMeanSquareError(), scale));
lastData.add(NumberTools.format(getSumSquaredErrors(), scale));
lastData.add(NumberTools.format(getTotalSumSquares(), scale));
lastData.add(NumberTools.format(getRegressionSumSquares(), scale));
lastData.add(NumberTools.format(getSlopeStdErr(), scale));
lastData.add(NumberTools.format(getSignificance(), scale));
lastData.add(NumberTools.format(getSlopeConfidenceInterval(), scale));
lastData.add(NumberTools.format(getInterceptStdErr(), scale));
lastData.add(NumberTools.format(getSumOfCrossProducts(), scale));
lastData.add(NumberTools.format(getSumOfCrossProducts(), scale));
lastData.add(NumberTools.format(getXSumSquares(), scale));
try {
Class superClass = getClass().getSuperclass();
Field xbar = superClass.getDeclaredField("xbar");
xbar.setAccessible(true);
lastData.add(NumberTools.format((double) xbar.get(this), scale));
Field sumX = superClass.getDeclaredField("sumX");
sumX.setAccessible(true);
lastData.add(NumberTools.format((double) sumX.get(this), scale));
Field ybar = superClass.getDeclaredField("ybar");
ybar.setAccessible(true);
lastData.add(NumberTools.format((double) ybar.get(this), scale));
Field sumY = superClass.getDeclaredField("sumY");
sumY.setAccessible(true);
lastData.add(NumberTools.format((double) sumY.get(this), scale));
} catch (Exception e) {
MyBoxLog.console(e);
}
return lastData;
}
// data should have row index as first column
public List<List<String>> addData(List<List<String>> data, InvalidAs invalidAs) {
if (data == null) {
return null;
}
List<List<String>> regressionData = new ArrayList<>();
double x, y;
for (List<String> row : data) {
try {
long index = Long.parseLong(row.get(0));
x = DoubleTools.toDouble(row.get(1), invalidAs);
y = DoubleTools.toDouble(row.get(2), invalidAs);
List<String> resultRow = addData(index, x, y);
regressionData.add(resultRow);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
return regressionData;
}
public String modelDesc() {
return message("IndependentVariable") + ": " + xName + "\n"
+ message("DependentVariable") + ": " + yName + "\n"
+ message("LinearModel") + ": " + getModel() + "\n"
+ message("CoefficientOfDetermination") + ": " + NumberTools.format(lastRSquare, scale) + "\n"
+ message("PearsonsR") + ": " + NumberTools.format(lastR, scale);
}
public String getModel() {
if (Double.isNaN(lastIntercept) || Double.isNaN(lastSlope)
|| Double.isNaN(lastRSquare) || Double.isNaN(lastR)) {
return message("Invalid");
}
return yName + " = "
+ NumberTools.format(lastIntercept, scale) + (lastSlope > 0 ? " + " : " - ")
+ NumberTools.format(Math.abs(lastSlope), scale) + " * " + xName;
}
/*
get/set
*/
public String getxName() {
return xName;
}
public SimpleLinearRegression setxName(String xName) {
this.xName = xName;
return this;
}
public String getyName() {
return yName;
}
public SimpleLinearRegression setyName(String yName) {
this.yName = yName;
return this;
}
public List<String> getLastData() {
return lastData;
}
public List<Data2DColumn> getColumns() {
return columns;
}
public int getScale() {
return scale;
}
public SimpleLinearRegression setScale(int scale) {
this.scale = scale;
return this;
}
public double getLastIntercept() {
return lastIntercept;
}
public void setLastIntercept(double lastIntercept) {
this.lastIntercept = lastIntercept;
}
public double getLastSlope() {
return lastSlope;
}
public void setLastSlope(double lastSlope) {
this.lastSlope = lastSlope;
}
public double getLastRSquare() {
return lastRSquare;
}
public void setLastRSquare(double lastRSquare) {
this.lastRSquare = lastRSquare;
}
public double getLastR() {
return lastR;
}
public void setLastR(double lastR) {
this.lastR = lastR;
}
}
| 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/calculation/ExpressionCalculator.java | alpha/MyBox/src/main/java/mara/mybox/calculation/ExpressionCalculator.java | package mara.mybox.calculation;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import mara.mybox.calculation.DescriptiveStatistic.StatisticType;
import mara.mybox.data.FindReplaceString;
import mara.mybox.data2d.Data2D;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.Data2DColumn;
import static mara.mybox.value.Languages.message;
import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory;
/**
* @Author Mara
* @CreateDate 2022-6-13
* @License Apache License Version 2.0
*/
public class ExpressionCalculator {
public final static String VariablePrefix = "__MyBox_VRB_";
public static ScriptEngine scriptEngine;
public String expression, result, error;
public Map<String, String> variableNames;
public Bindings variableValues;
public FindReplaceString replaceHandler;
public ExpressionCalculator() {
// https://github.com/Mararsh/MyBox/issues/1568
if (scriptEngine == null) {
ScriptEngineManager factory = new ScriptEngineManager(ClassLoader.getSystemClassLoader());
factory.registerEngineName("nashorn", new NashornScriptEngineFactory());
scriptEngine = factory.getEngineByName("nashorn");
}
variableValues = scriptEngine.createBindings();
variableNames = new HashMap<>();
reset();
}
final public void reset() {
expression = null;
result = null;
error = null;
variableNames.clear();
variableValues.clear();
if (replaceHandler == null) {
replaceHandler = createReplaceAll();
}
}
/*
calculate
*/
private boolean executeScript() {
try {
error = null;
result = null;
if (expression == null || expression.isBlank()) {
return true;
}
scriptEngine.setBindings(variableValues, ScriptContext.ENGINE_SCOPE);
Object o = scriptEngine.eval(expression);
if (o != null) {
result = o.toString();
}
// MyBoxLog.console(info());
return true;
} catch (Exception e) {
handleError(e.toString());
return false;
}
}
public String calculate(String script, Map<String, Object> variables) {
reset();
this.expression = script;
if (variables != null) {
for (String v : variables.keySet()) {
variableValues.put(v, variables.get(v));
}
}
if (executeScript()) {
return result;
} else {
return null;
}
}
public boolean condition(String script, Map<String, Object> variables) {
calculate(script, variables);
return "true".equals(result);
}
public void handleError(String e) {
error = e;
// if (e != null && AppValues.Alpha) {
// MyBoxLog.debug(error + "\n" + info());
// }
}
public String info() {
String info = "expression: " + expression;
for (String variable : variableValues.keySet()) {
Object o = variableValues.get(variable);
info += "\nvariable:" + variable + " type:" + o.getClass() + " value:" + o;
}
info += "\nresult: " + result;
info += "\nerror: " + error;
return info;
}
/*
"dataRowNumber" is 1-based
*/
public boolean makeExpression(Data2D data2D,
String script, List<String> rowValues, long dataRowNumber) {
try {
reset();
if (script == null || script.isBlank()
|| rowValues == null || rowValues.isEmpty()
|| data2D == null || !data2D.hasColumns()) {
handleError(message("invalidParameter"));
return false;
}
expression = script;
int index = 1, rowSize = rowValues.size();
String name, stringValue;
Object value;
for (int i = 0; i < data2D.columnsNumber(); i++) {
Data2DColumn column = data2D.getColumns().get(i);
name = column.getColumnName();
stringValue = i < rowSize ? rowValues.get(i) : null;
value = column.fromString(stringValue, ColumnDefinition.InvalidAs.Use);
String placeholder = "#{" + name + "}";
String placeholderQuoted = "'" + placeholder + "'";
String variableName = VariablePrefix + index++;
if (expression.contains(placeholderQuoted)) {
expression = replaceAll(expression, placeholderQuoted, variableName);
}
expression = replaceAll(expression, placeholder, variableName);
variableNames.put(placeholderQuoted, variableName);
variableValues.put(variableName, value);
// MyBoxLog.console(variableName + " " + value);
}
expression = replaceAll(expression, "#{" + message("DataRowNumber") + "}", dataRowNumber + "");
// MyBoxLog.console(info());
return true;
} catch (Exception e) {
handleError(e.toString());
return false;
}
}
/*
first value of "tableRow" should be "dataRowNumber"
"tableRowNumber" is 0-based
*/
public boolean calculateTableRowExpression(Data2D data2D,
String script, List<String> tableRow, long tableRowNumber) {
try {
reset();
if (tableRow == null || tableRow.isEmpty()) {
handleError(message("invalidParameter"));
return false;
}
if (!makeExpression(data2D, script,
tableRow.subList(1, tableRow.size()),
Long.parseLong(tableRow.get(0)))) {
return false;
}
expression = replaceAll(expression, "#{" + message("TableRowNumber") + "}",
(tableRowNumber + 1) + "");
return executeScript();
} catch (Exception e) {
handleError(e.toString());
return false;
}
}
public boolean calculateDataRowExpression(Data2D data2D,
String script, List<String> dataRow, long dataRowNumber) {
try {
reset();
if (script != null && script.contains("#{" + message("TableRowNumber") + "}")) {
handleError(message("NoTableRowNumberWhenAllPages"));
return false;
}
if (!makeExpression(data2D, script, dataRow, dataRowNumber)) {
return false;
}
return executeScript();
} catch (Exception e) {
handleError(e.toString());
return false;
}
}
public boolean validateExpression(Data2D data2D, String script, boolean allPages) {
try {
handleError(null);
if (script == null || script.isBlank()) {
return true;
}
List<String> dummyRow = data2D.dummyRow();
String filledScript = replaceDummyStatistic(data2D, script);
if (allPages) {
return calculateDataRowExpression(data2D, filledScript, dummyRow, 1);
} else {
dummyRow.add(0, "1");
return calculateTableRowExpression(data2D, filledScript, dummyRow, 0);
}
} catch (Exception e) {
handleError(e.toString());
return false;
}
}
public String replaceDummyStatistic(Data2D data2D, String script) {
try {
if (data2D == null || !data2D.hasColumns() || script == null || script.isBlank()) {
return script;
}
String filledScript = script;
for (int i = 0; i < data2D.columnsNumber(); i++) {
Data2DColumn column = data2D.columns.get(i);
String name = column.getColumnName();
for (StatisticType stype : StatisticType.values()) {
filledScript = replaceAll(filledScript, "#{" + name + "-" + message(stype.name()) + "}", "1");
}
}
return filledScript;
} catch (Exception e) {
handleError(e.toString());
return null;
}
}
public String replaceAll(String script, String string, String replaced) {
return replaceHandler.replace(null, script, string, replaced);
}
/*
get
*/
public String getResult() {
return result;
}
public String getError() {
return error;
}
/*
static
*/
public static FindReplaceString createReplaceAll() {
return FindReplaceString.create()
.setOperation(FindReplaceString.Operation.ReplaceAll)
.setIsRegex(false)
.setCaseInsensitive(false)
.setMultiline(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/calculation/FloatStatistic.java | alpha/MyBox/src/main/java/mara/mybox/calculation/FloatStatistic.java | package mara.mybox.calculation;
import java.util.HashMap;
import java.util.Map;
import mara.mybox.tools.FloatTools;
import mara.mybox.value.AppValues;
/**
* @Author Mara
* @CreateDate 2021-10-4
* @License Apache License Version 2.0
*/
public class FloatStatistic {
private String name;
private int count;
private float minimum, maximum, mode, median;
private double sum, mean, variance, skewness;
public FloatStatistic() {
}
public FloatStatistic(float[] values) {
if (values == null || values.length == 0) {
return;
}
count = values.length;
sum = 0;
minimum = Float.MAX_VALUE;
maximum = Float.MIN_VALUE;
for (int i = 0; i < count; ++i) {
float v = values[i];
sum += v;
if (v > maximum) {
maximum = v;
}
if (v < minimum) {
minimum = v;
}
}
mean = sum / values.length;
variance = 0;
skewness = 0;
mode = mode(values);
median = median(values);
for (int i = 0; i < values.length; ++i) {
float v = values[i];
variance += Math.pow(v - mean, 2);
skewness += Math.pow(v - mean, 3);
}
variance = Math.sqrt(variance / count);
skewness = Math.cbrt(skewness / count);
}
/*
static methods
*/
public static double sum(float[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidLong;
}
double sum = 0;
for (int i = 0; i < values.length; ++i) {
sum += values[i];
}
return sum;
}
public static float maximum(float[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidLong;
}
float max = Float.MIN_VALUE;
for (int i = 0; i < values.length; ++i) {
if (values[i] > max) {
max = values[i];
}
}
return max;
}
public static float minimum(float[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidLong;
}
float min = Float.MAX_VALUE;
for (int i = 0; i < values.length; ++i) {
if (values[i] < min) {
min = values[i];
}
}
return min;
}
public static double mean(float[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidLong;
}
return sum(values) / values.length;
}
public static float mode(float[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidLong;
}
float mode = 0;
Map<Float, Integer> number = new HashMap<>();
for (float value : values) {
if (number.containsKey(value)) {
number.put(value, number.get(value) + 1);
} else {
number.put(value, 1);
}
}
float num = 0;
for (float value : number.keySet()) {
if (num < number.get(value)) {
mode = value;
}
}
return mode;
}
public static float median(float[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidLong;
}
float[] sorted = FloatTools.sortArray(values);
int len = sorted.length;
if (len == 2) {
return (sorted[0] + sorted[1]) / 2;
} else if (len % 2 == 0) {
return (sorted[len / 2] + sorted[len / 2 + 1]) / 2;
} else {
return sorted[len / 2];
}
}
public static double variance(float[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidLong;
}
double mean = mean(values);
return variance(values, mean);
}
public static double variance(float[] values, double mean) {
if (values == null || values.length == 0) {
return AppValues.InvalidLong;
}
double variance = 0;
for (int i = 0; i < values.length; ++i) {
variance += Math.pow(values[i] - mean, 2);
}
variance = Math.sqrt(variance / values.length);
return variance;
}
public static double skewness(float[] values, double mean) {
if (values == null || values.length == 0) {
return AppValues.InvalidLong;
}
double skewness = 0;
for (int i = 0; i < values.length; ++i) {
skewness += Math.pow(values[i] - mean, 3);
}
skewness = Math.cbrt(skewness / values.length);
return skewness;
}
/*
get/set
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSum() {
return sum;
}
public void setSum(float sum) {
this.sum = sum;
}
public double getMean() {
return mean;
}
public void setMean(float mean) {
this.mean = mean;
}
public double getVariance() {
return variance;
}
public void setVariance(float variance) {
this.variance = variance;
}
public double getSkewness() {
return skewness;
}
public void setSkewness(float skewness) {
this.skewness = skewness;
}
public float getMinimum() {
return minimum;
}
public void setMinimum(float minimum) {
this.minimum = minimum;
}
public float getMaximum() {
return maximum;
}
public void setMaximum(float maximum) {
this.maximum = maximum;
}
public float getMode() {
return mode;
}
public void setMode(float mode) {
this.mode = mode;
}
public float getMedian() {
return median;
}
public void setMedian(float median) {
this.median = median;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
| 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/calculation/DescriptiveStatistic.java | alpha/MyBox/src/main/java/mara/mybox/calculation/DescriptiveStatistic.java | package mara.mybox.calculation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mara.mybox.controller.BaseData2DTaskController;
import mara.mybox.data2d.Data2D;
import mara.mybox.data2d.DataTable;
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.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.tools.NumberTools;
import mara.mybox.tools.StringTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-4-14
* @License Apache License Version 2.0
*/
public class DescriptiveStatistic {
public List<StatisticType> types = new ArrayList<>();
public int scale;
public InvalidAs invalidAs;
protected BaseData2DTaskController taskController;
protected FxTask<Void> task;
protected Data2D data2D;
protected Map<StatisticType, List<String>> statisticRows;
protected List<List<String>> outputData;
protected List<Data2DColumn> outputColumns;
protected String categoryName;
protected List<String> colsNames, outputNames;
protected List<Integer> colsIndices;
public StatisticObject statisticObject = StatisticObject.Columns;
public enum StatisticType {
Count, Sum, Mean, GeometricMean, SumOfSquares, Skewness, Mode,
PopulationVariance, SampleVariance, PopulationStandardDeviation, SampleStandardDeviation,
MinimumQ0, LowerQuartile, Median, UpperQuartile, MaximumQ4,
LowerExtremeOutlierLine, LowerMildOutlierLine, UpperMildOutlierLine, UpperExtremeOutlierLine
}
public enum StatisticObject {
Columns, Rows, All
}
public static DescriptiveStatistic all(boolean select) {
DescriptiveStatistic s = new DescriptiveStatistic();
s.types.clear();
if (select) {
s.types.addAll(Arrays.asList(StatisticType.values()));
}
return s;
}
public DescriptiveStatistic add(StatisticType type) {
if (!types.contains(type)) {
types.add(type);
}
return this;
}
public DescriptiveStatistic remove(StatisticType type) {
types.remove(type);
return this;
}
public List<String> names() {
List<String> names = new ArrayList<>();
for (StatisticType type : types) {
names.add(message(type.name()));
}
return names;
}
public boolean include(StatisticType type) {
return types.contains(type);
}
public boolean need() {
return !types.isEmpty();
}
public boolean needNonStored() {
return include(StatisticType.MinimumQ0)
|| include(StatisticType.MaximumQ4)
|| include(StatisticType.Mean)
|| include(StatisticType.Sum)
|| include(StatisticType.Count)
|| include(StatisticType.Skewness)
|| include(StatisticType.GeometricMean)
|| include(StatisticType.SumOfSquares)
|| needVariance();
}
public boolean needVariance() {
return include(StatisticType.PopulationVariance)
|| include(StatisticType.SampleVariance)
|| include(StatisticType.PopulationStandardDeviation)
|| include(StatisticType.SampleStandardDeviation);
}
public boolean needStored() {
return needPercentile() || include(StatisticType.Mode);
}
public boolean needPercentile() {
return include(StatisticType.Median)
|| include(StatisticType.UpperQuartile)
|| include(StatisticType.LowerQuartile) || needOutlier();
}
public boolean needOutlier() {
return include(StatisticType.LowerExtremeOutlierLine)
|| include(StatisticType.LowerMildOutlierLine)
|| include(StatisticType.UpperMildOutlierLine)
|| include(StatisticType.UpperExtremeOutlierLine);
}
public boolean prepare() {
try {
switch (statisticObject) {
case Rows:
return prepareByRows();
case All:
return prepareByColumns("", Arrays.asList(message("All")));
default:
return prepareByColumns(message("Column") + "-", colsNames);
}
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
MyBoxLog.error(e);
return false;
}
}
public boolean prepareByColumns(String prefix, List<String> names) {
try {
if (names == null || names.isEmpty() || types.size() < 1) {
taskController.popError(message("SelectToHandle") + " " + prefix);
return false;
}
outputNames = new ArrayList<>();
outputColumns = new ArrayList<>();
String cName = DerbyBase.checkIdentifier(names, prefix + message("Calculation"), false);
outputNames.add(cName);
outputNames.addAll(names);
outputColumns.add(new Data2DColumn(cName, ColumnDefinition.ColumnType.String, 300));
for (String name : names) {
outputColumns.add(new Data2DColumn(name, ColumnDefinition.ColumnType.Double));
}
outputData = new ArrayList<>();
statisticRows = new HashMap<>();
for (StatisticType type : types) {
List<String> row = new ArrayList<>();
row.add(prefix + message(type.name()));
statisticRows.put(type, row);
outputData.add(row);
}
return true;
} catch (Exception e) {
taskController.popError(e.toString());
MyBoxLog.error(e);
return false;
}
}
public boolean prepareByRows() {
try {
if (types.size() < 1) {
taskController.popError(message("SelectToHandle"));
return false;
}
outputNames = new ArrayList<>();
outputColumns = new ArrayList<>();
String cName = categoryName != null ? categoryName : message("SourceRowNumber");
outputNames.add(cName);
outputColumns.add(new Data2DColumn(cName, ColumnDefinition.ColumnType.Long));
String prefix = message("Rows") + "-";
int width = 150;
for (StatisticType type : types) {
cName = prefix + message(type.name());
outputNames.add(cName);
outputColumns.add(new Data2DColumn(cName, ColumnDefinition.ColumnType.Double, width));
}
if (outputNames.size() < 2) {
taskController.popError(message("SelectToHandle"));
return false;
}
return true;
} catch (Exception e) {
taskController.popError(e.toString());
MyBoxLog.error(e);
return false;
}
}
public boolean statisticData(List<List<String>> rows) {
try {
if (rows == null || rows.isEmpty()) {
if (task != null) {
task.setError(message("SelectToHandle"));
}
return false;
}
switch (statisticObject) {
case Rows:
return statisticByRows(rows);
case All:
return statisticByAll(rows);
default:
return statisticByColumns(rows);
}
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
MyBoxLog.error(e);
return false;
}
}
public boolean statisticByColumns(List<List<String>> rows) {
try {
if (rows == null || rows.isEmpty()) {
return false;
}
int rowsNumber = rows.size();
int colsNumber = rows.get(0).size();
for (int c = 0; c < colsNumber; c++) {
String[] colData = new String[rowsNumber];
for (int r = 0; r < rowsNumber; r++) {
colData[r] = rows.get(r).get(c);
}
DoubleStatistic statistic = new DoubleStatistic(colData, this);
statisticByColumnsWrite(statistic);
}
return true;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
MyBoxLog.error(e);
return false;
}
}
public boolean statisticByColumnsWrite(DoubleStatistic statistic) {
if (statistic == null) {
return false;
}
statisticByColumnsWriteWithoutStored(statistic);
statisticByColumnsWriteStored(statistic);
return true;
}
public boolean statisticByColumnsWriteWithoutStored(DoubleStatistic statistic) {
if (statistic == null || statisticRows == null) {
return false;
}
for (StatisticType type : types) {
List<String> row = statisticRows.get(type);
if (row == null) {
continue;
}
switch (type) {
case Count:
row.add(StringTools.format(statistic.getCount()));
break;
case Sum:
row.add(NumberTools.format(statistic.getSum(), scale));
break;
case Mean:
row.add(NumberTools.format(statistic.getMean(), scale));
break;
case GeometricMean:
row.add(NumberTools.format(statistic.getGeometricMean(), scale));
break;
case SumOfSquares:
row.add(NumberTools.format(statistic.getSumSquares(), scale));
break;
case PopulationVariance:
row.add(NumberTools.format(statistic.getPopulationVariance(), scale));
break;
case SampleVariance:
row.add(NumberTools.format(statistic.getSampleVariance(), scale));
break;
case PopulationStandardDeviation:
row.add(NumberTools.format(statistic.getPopulationStandardDeviation(), scale));
break;
case SampleStandardDeviation:
row.add(NumberTools.format(statistic.getSampleStandardDeviation(), scale));
break;
case Skewness:
row.add(NumberTools.format(statistic.getSkewness(), scale));
break;
case MinimumQ0:
row.add(NumberTools.format(statistic.getMinimum(), scale));
break;
case MaximumQ4:
row.add(NumberTools.format(statistic.getMaximum(), scale));
break;
}
}
return true;
}
public boolean statisticByColumnsWriteStored(DoubleStatistic statistic) {
if (statistic == null || statisticRows == null) {
return false;
}
for (StatisticType type : types) {
List<String> row = statisticRows.get(type);
if (row == null) {
continue;
}
Object v;
switch (type) {
case Median:
v = statistic.getMedianValue();
break;
case Mode:
v = statistic.getModeValue();
break;
case LowerQuartile:
v = statistic.getLowerQuartileValue();
break;
case UpperQuartile:
v = statistic.getUpperQuartileValue();
break;
case UpperExtremeOutlierLine:
v = statistic.getUpperExtremeOutlierLine();
break;
case UpperMildOutlierLine:
v = statistic.getUpperMildOutlierLine();
break;
case LowerMildOutlierLine:
v = statistic.getLowerMildOutlierLine();
break;
case LowerExtremeOutlierLine:
v = statistic.getLowerExtremeOutlierLine();
break;
default:
continue;
}
try {
row.add(NumberTools.format((double) v, scale));
} catch (Exception e) {
try {
row.add(v.toString());
} catch (Exception ex) {
row.add("");
}
}
}
return true;
}
public boolean statisticByRows(List<List<String>> rows) {
try {
if (rows == null || rows.isEmpty()) {
return false;
}
outputData = new ArrayList<>();
int rowsNumber = rows.size();
for (int r = 0; r < rowsNumber; r++) {
List<String> rowStatistic = new ArrayList<>();
List<String> row = rows.get(r);
rowStatistic.add(row.get(0));
int colsNumber = row.size();
String[] rowData = new String[colsNumber - 1];
for (int c = 1; c < colsNumber; c++) {
rowData[c - 1] = row.get(c);
}
DoubleStatistic statistic = new DoubleStatistic(rowData, this);
rowStatistic.addAll(statistic.toStringList());
outputData.add(rowStatistic);
}
return true;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
MyBoxLog.error(e);
return false;
}
}
public boolean statisticByAll(List<List<String>> rows) {
try {
if (rows == null || rows.isEmpty()) {
return false;
}
int rowsNumber = rows.size();
int colsNumber = rows.get(0).size();
String[] allData = new String[rowsNumber * colsNumber];
int index = 0;
for (int r = 0; r < rowsNumber; r++) {
for (int c = 0; c < colsNumber; c++) {
allData[index++] = rows.get(r).get(c);
}
}
DoubleStatistic statistic = new DoubleStatistic(allData, this);
statisticByColumnsWrite(statistic);
return true;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
MyBoxLog.error(e);
return false;
}
}
public boolean statisticAllByColumnsWithoutStored() {
DoubleStatistic[] statisticData = data2D.statisticByColumnsWithoutStored(colsIndices, this);
if (statisticData == null) {
return false;
}
for (DoubleStatistic statistic : statisticData) {
statisticByColumnsWriteWithoutStored(statistic);
}
return true;
}
public boolean statisticAllByColumns() {
if (!(data2D instanceof DataTable)) {
return false;
}
try {
DoubleStatistic[] statisticData = data2D.statisticByColumnsWithoutStored(colsIndices, this);
if (statisticData == null) {
return false;
}
DataTable dataTable = (DataTable) data2D;
statisticData = dataTable.statisticByColumnsForStored(colsIndices, this);
if (statisticData == null) {
return false;
}
for (int c : colsIndices) {
Data2DColumn column = data2D.getColumns().get(c);
DoubleStatistic colStatistic = column.getStatistic();
statisticByColumnsWrite(colStatistic);
}
return true;
} catch (Exception e) {
if (task != null) {
task.setError(e.toString());
}
MyBoxLog.error(e);
return false;
}
}
/*
get/set
*/
public StatisticObject getStatisticObject() {
return statisticObject;
}
public DescriptiveStatistic setStatisticObject(StatisticObject statisticObject) {
this.statisticObject = statisticObject;
return this;
}
public int getScale() {
return scale;
}
public DescriptiveStatistic setScale(int scale) {
this.scale = scale;
return this;
}
public BaseData2DTaskController getTaskController() {
return taskController;
}
public DescriptiveStatistic setTaskController(BaseData2DTaskController taskController) {
this.taskController = taskController;
return this;
}
public FxTask<Void> getTask() {
return task;
}
public DescriptiveStatistic setTask(FxTask<Void> task) {
this.task = task;
return this;
}
public Data2D getData2D() {
return data2D;
}
public DescriptiveStatistic setData2D(Data2D data2D) {
this.data2D = data2D;
return this;
}
public List<List<String>> getOutputData() {
return outputData;
}
public DescriptiveStatistic setOutputData(List<List<String>> outputData) {
this.outputData = outputData;
return this;
}
public List<Data2DColumn> getOutputColumns() {
return outputColumns;
}
public DescriptiveStatistic setOutputColumns(List<Data2DColumn> outputColumns) {
this.outputColumns = outputColumns;
return this;
}
public List<String> getOutputNames() {
return outputNames;
}
public DescriptiveStatistic setHandledNames(List<String> handledNames) {
this.outputNames = handledNames;
return this;
}
public List<String> getColsNames() {
return colsNames;
}
public DescriptiveStatistic setColsNames(List<String> colsNames) {
this.colsNames = colsNames;
return this;
}
public List<Integer> getColsIndices() {
return colsIndices;
}
public DescriptiveStatistic setColsIndices(List<Integer> colsIndices) {
this.colsIndices = colsIndices;
return this;
}
public String getCategoryName() {
return categoryName;
}
public DescriptiveStatistic setCategoryName(String categoryName) {
this.categoryName = categoryName;
return this;
}
public InvalidAs getInvalidAs() {
return invalidAs;
}
public DescriptiveStatistic setInvalidAs(InvalidAs invalidAs) {
this.invalidAs = invalidAs;
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/calculation/Normalization.java | alpha/MyBox/src/main/java/mara/mybox/calculation/Normalization.java | package mara.mybox.calculation;
import mara.mybox.db.data.ColumnDefinition.InvalidAs;
import static mara.mybox.db.data.ColumnDefinition.InvalidAs.Zero;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.DoubleTools;
import mara.mybox.tools.StringTools;
import mara.mybox.value.AppValues;
/**
* @Author Mara
* @CreateDate 2022-4-16
* @License Apache License Version 2.0
*/
public class Normalization {
protected double from, to, max, min, sum, mean, variance, width, maxAbs;
protected Algorithm a;
protected String[] sourceVector, resultVector;
protected String[][] sourceMatrix, resultMatrix;
protected Normalization[] values;
protected InvalidAs invalidAs;
public static enum Algorithm {
MinMax, Sum, ZScore, Absoluate
}
public Normalization() {
initParameters();
resetResults();
}
private void initParameters() {
from = 0;
to = 1;
width = 0;
a = Algorithm.MinMax;
sourceVector = null;
sourceMatrix = null;
invalidAs = InvalidAs.Zero;
}
private void resetResults() {
max = min = sum = mean = variance = maxAbs = Double.NaN;
resultVector = null;
}
public Normalization cloneValues() {
try {
Normalization n = new Normalization();
n.a = a;
n.from = from;
n.to = to;
n.max = max;
n.min = min;
n.sum = sum;
n.mean = mean;
n.variance = variance;
n.width = width;
n.maxAbs = maxAbs;
n.invalidAs = invalidAs;
return n;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public String[] calculate() {
try {
resetResults();
if (a == null) {
return null;
}
switch (a) {
case MinMax:
minMax();
break;
case Sum:
sum();
break;
case ZScore:
zscore();
break;
case Absoluate:
absoluate();
break;
}
} catch (Exception e) {
MyBoxLog.error(e);
}
return resultVector;
}
public double[] toDoubles(InvalidAs invalidAs) {
calculate();
if (resultVector == null) {
return null;
}
double[] doubleVector = new double[resultVector.length];
for (int i = 0; i < resultVector.length; i++) {
String s = resultVector[i];
doubleVector[i] = DoubleTools.toDouble(s, invalidAs);
}
return doubleVector;
}
public boolean minMax() {
try {
resetResults();
if (sourceVector == null) {
return false;
}
int len = sourceVector.length;
if (len == 0) {
return false;
}
min = Double.MAX_VALUE;
max = -Double.MAX_VALUE;
for (String s : sourceVector) {
double d = DoubleTools.toDouble(s, invalidAs);
if (DoubleTools.invalidDouble(d)) {
switch (invalidAs) {
case Zero:
d = 0;
break;
default:
continue;
}
}
if (d > max) {
max = d;
}
if (d < min) {
min = d;
}
}
double k = max - min;
if (k == 0) {
k = AppValues.TinyDouble;
}
k = (to - from) / k;
resultVector = new String[len];
for (int i = 0; i < len; i++) {
String s = sourceVector[i];
double d = DoubleTools.toDouble(s, invalidAs);
if (DoubleTools.invalidDouble(d)) {
resultVector[i] = null;
} else {
resultVector[i] = from + k * (d - min) + "";
}
}
return true;
} catch (Exception e) {
MyBoxLog.error(e);
return false;
}
}
public boolean zscore() {
try {
resetResults();
if (sourceVector == null) {
return false;
}
int len = sourceVector.length;
if (len == 0) {
return false;
}
sum = 0;
for (String s : sourceVector) {
double d = DoubleTools.toDouble(s, invalidAs);
if (DoubleTools.invalidDouble(d)) {
continue;
}
sum += d;
}
mean = sum / len;
variance = 0;
for (String s : sourceVector) {
double d = DoubleTools.toDouble(s, invalidAs);
if (DoubleTools.invalidDouble(d)) {
switch (invalidAs) {
case Zero:
d = 0;
break;
default:
continue;
}
}
double v = d - mean;
variance += v * v;
}
variance = Math.sqrt(variance / (len == 1 ? len : len - 1));
if (variance == 0) {
variance = AppValues.TinyDouble;
}
resultVector = new String[len];
for (int i = 0; i < len; i++) {
String s = sourceVector[i];
double d = DoubleTools.toDouble(s, invalidAs);
if (DoubleTools.invalidDouble(d)) {
resultVector[i] = null;
} else {
resultVector[i] = (d - mean) / variance + "";
}
}
return true;
} catch (Exception e) {
MyBoxLog.error(e);
return false;
}
}
public boolean sum() {
try {
resetResults();
if (sourceVector == null) {
return false;
}
int len = sourceVector.length;
if (len == 0) {
return false;
}
sum = 0;
for (String s : sourceVector) {
double d = DoubleTools.toDouble(s, invalidAs);
if (DoubleTools.invalidDouble(d)) {
continue;
}
sum += Math.abs(d);
}
if (sum == 0) {
sum = AppValues.TinyDouble;
}
resultVector = new String[len];
for (int i = 0; i < len; i++) {
String s = sourceVector[i];
double d = DoubleTools.toDouble(s, invalidAs);
if (DoubleTools.invalidDouble(d)) {
resultVector[i] = null;
} else {
resultVector[i] = d / sum + "";
}
}
return true;
} catch (Exception e) {
MyBoxLog.error(e);
return false;
}
}
public boolean absoluate() {
try {
resetResults();
if (sourceVector == null) {
return false;
}
int len = sourceVector.length;
if (len == 0) {
return false;
}
maxAbs = 0;
for (String s : sourceVector) {
double d = DoubleTools.toDouble(s, invalidAs);
if (DoubleTools.invalidDouble(d)) {
continue;
}
double abs = Math.abs(d);
if (abs > maxAbs) {
maxAbs = abs;
}
}
resultVector = new String[len];
for (int i = 0; i < len; i++) {
String s = sourceVector[i];
double d = DoubleTools.toDouble(s, invalidAs);
if (DoubleTools.invalidDouble(d)) {
resultVector[i] = null;
} else if (maxAbs == 0 || width == 0) {
resultVector[i] = "0";
} else {
resultVector[i] = width * d / maxAbs + "";
}
}
return true;
} catch (Exception e) {
MyBoxLog.error(e);
return false;
}
}
public String[][] columnsNormalize() {
try {
if (sourceMatrix == null || sourceMatrix.length == 0 || a == null) {
return null;
}
String[][] orignalSource = sourceMatrix;
sourceMatrix = StringTools.transpose(sourceMatrix);
if (rowsNormalize() == null) {
resetResults();
return null;
}
resultMatrix = StringTools.transpose(resultMatrix);
sourceMatrix = orignalSource;
} catch (Exception e) {
MyBoxLog.error(e);
}
return resultMatrix;
}
public String[][] rowsNormalize() {
try {
if (sourceMatrix == null || sourceMatrix.length == 0 || a == null) {
return null;
}
int rlen = sourceMatrix.length, clen = sourceMatrix[0].length;
resultMatrix = new String[rlen][clen];
values = new Normalization[rlen];
for (int i = 0; i < rlen; i++) {
sourceVector = sourceMatrix[i];
if (calculate() == null) {
resetResults();
return null;
}
resultMatrix[i] = resultVector;
values[i] = this.cloneValues();
}
} catch (Exception e) {
MyBoxLog.error(e);
}
return resultMatrix;
}
public String[][] allNormalize() {
try {
if (sourceMatrix == null || sourceMatrix.length == 0 || a == null) {
return null;
}
int w = sourceMatrix[0].length;
sourceVector = StringTools.matrix2Array(sourceMatrix);
if (calculate() == null) {
resetResults();
return null;
}
resultMatrix = StringTools.array2Matrix(resultVector, w);
} catch (Exception e) {
MyBoxLog.error(e);
}
return resultMatrix;
}
/*
static
*/
public static Normalization create() {
return new Normalization();
}
/*
get/set
*/
public double getFrom() {
return from;
}
public Normalization setFrom(double from) {
this.from = from;
return this;
}
public double getTo() {
return to;
}
public Normalization setTo(double to) {
this.to = to;
return this;
}
public Algorithm getA() {
return a;
}
public Normalization setA(Algorithm a) {
this.a = a;
return this;
}
public double getWidth() {
return width;
}
public Normalization setWidth(double width) {
this.width = width;
return this;
}
public InvalidAs getInvalidAs() {
return invalidAs;
}
public Normalization setInvalidAs(InvalidAs invalidAs) {
this.invalidAs = invalidAs;
return this;
}
public double getMax() {
return max;
}
public Normalization setMax(double max) {
this.max = max;
return this;
}
public double getMin() {
return min;
}
public Normalization setMin(double min) {
this.min = min;
return this;
}
public double getSum() {
return sum;
}
public Normalization setSum(double sum) {
this.sum = sum;
return this;
}
public double getMean() {
return mean;
}
public Normalization setMean(double mean) {
this.mean = mean;
return this;
}
public double getVariance() {
return variance;
}
public Normalization setVariance(double variance) {
this.variance = variance;
return this;
}
public String[] getSourceVector() {
return sourceVector;
}
public Normalization setSourceVector(String[] sourceVector) {
this.sourceVector = sourceVector;
return this;
}
public String[] getResultVector() {
return resultVector;
}
public Normalization setResultVector(String[] resultVector) {
this.resultVector = resultVector;
return this;
}
public String[][] getSourceMatrix() {
return sourceMatrix;
}
public Normalization setSourceMatrix(String[][] sourceMatrix) {
this.sourceMatrix = sourceMatrix;
return this;
}
public String[][] getResultMatrix() {
return resultMatrix;
}
public Normalization setResultMatrix(String[][] resultMatrix) {
this.resultMatrix = resultMatrix;
return this;
}
public double getMaxAbs() {
return maxAbs;
}
public Normalization setMaxAbs(double maxAbs) {
this.maxAbs = maxAbs;
return this;
}
public Normalization[] getValues() {
return values;
}
public Normalization setValues(Normalization[] values) {
this.values = values;
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/calculation/NumberStatistic.java | alpha/MyBox/src/main/java/mara/mybox/calculation/NumberStatistic.java | package mara.mybox.calculation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import mara.mybox.data.IntValue;
import mara.mybox.tools.IntTools;
/**
* @Author Mara
* @CreateDate 2021-10-3
* @License Apache License Version 2.0
*/
public class NumberStatistic {
private String name;
private long sum;
private int mean, variance, skewness, minimum, maximum, mode, median;
public NumberStatistic() {
}
public NumberStatistic(String name, long sum, int mean,
int variance, int skewness, int minimum, int maximum) {
this.name = name;
this.sum = sum;
this.mean = mean;
this.variance = variance;
this.skewness = skewness;
this.minimum = minimum;
this.maximum = maximum;
}
public NumberStatistic(String name, long sum, int mean,
int variance, int skewness, int minimum, int maximum,
int mode, int median) {
this.name = name;
this.sum = sum;
this.mean = mean;
this.variance = variance;
this.skewness = skewness;
this.minimum = minimum;
this.maximum = maximum;
this.mode = mode;
this.median = median;
}
public NumberStatistic(String name, long sum, int mean,
int variance, int skewness, int minimum, int maximum,
int[] histogram) {
this.name = name;
this.sum = sum;
this.mean = mean;
this.variance = variance;
this.skewness = skewness;
this.minimum = minimum;
this.maximum = maximum;
this.mode = maximumIndex(histogram);
this.median = medianIndex(histogram);
}
/*
static methods
*/
public static long sum(int[] values) {
long sum = 0;
for (int i = 0; i < values.length; ++i) {
sum += values[i];
}
return sum;
}
public static int maximum(int[] values) {
if (values == null || values.length == 0) {
return Integer.MIN_VALUE;
}
int max = Integer.MIN_VALUE;
for (int i = 0; i < values.length; ++i) {
if (values[i] > max) {
max = values[i];
}
}
return max;
}
public static int maximumIndex(int[] values) {
if (values == null || values.length == 0) {
return -1;
}
int max = Integer.MIN_VALUE, maxIndex = -1;
for (int i = 0; i < values.length; ++i) {
if (values[i] > max) {
max = values[i];
maxIndex = i;
}
}
return maxIndex;
}
public static int minimum(int[] values) {
if (values == null || values.length == 0) {
return Integer.MAX_VALUE;
}
int min = Integer.MAX_VALUE;
for (int i = 0; i < values.length; ++i) {
if (values[i] < min) {
min = values[i];
}
}
return min;
}
public static long[] sumMaxMin(int[] values) {
long[] s = new long[3];
if (values == null || values.length == 0) {
return s;
}
int sum = 0, min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
for (int i = 0; i < values.length; ++i) {
sum += values[i];
if (values[i] > max) {
max = values[i];
}
if (values[i] < min) {
min = values[i];
}
}
s[0] = sum;
s[1] = min;
s[2] = max;
return s;
}
public static int mean(int[] values) {
if (values == null || values.length == 0) {
return 0;
}
return (int) (sum(values) / values.length);
}
public static int median(int[] values) {
int mid = 0;
if (values == null || values.length == 0) {
return mid;
}
int[] sorted = IntTools.sortArray(values);
if (sorted.length % 2 == 0) {
mid = (sorted[sorted.length / 2] + sorted[sorted.length / 2 - 1]) / 2;
} else {
mid = sorted[sorted.length / 2];
}
return mid;
}
public static int medianIndex(int[] values) {
if (values == null || values.length == 0) {
return -1;
}
int[] sorted = IntTools.sortArray(values);
int mid = sorted[sorted.length / 2];
for (int i = 0; i < values.length; ++i) {
if (values[i] == mid) {
return i;
}
}
return -1;
}
public static int variance(int[] values) {
int mean = mean(values);
return variance(values, mean);
}
public static int variance(int[] values, int mean) {
int variance = 0;
for (int i = 0; i < values.length; ++i) {
variance += Math.pow(values[i] - mean, 2);
}
variance = (int) Math.sqrt(variance / values.length);
return variance;
}
public static int skewness(int[] values, int mean) {
int skewness = 0;
for (int i = 0; i < values.length; ++i) {
skewness += Math.pow(values[i] - mean, 3);
}
skewness = (int) Math.pow(skewness / values.length, 1d / 3);
return skewness;
}
public static IntValue median(List<IntValue> values) {
if (values == null) {
return null;
}
List<IntValue> sorted = new ArrayList<>();
sorted.addAll(values);
Collections.sort(sorted, new Comparator<IntValue>() {
@Override
public int compare(IntValue p1, IntValue p2) {
return p1.getValue() - p2.getValue();
}
});
IntValue mid = new IntValue();
if (sorted.size() % 2 == 0) {
mid.setName(sorted.get(sorted.size() / 2).getName() + " - " + sorted.get(sorted.size() / 2 + 1).getName());
mid.setValue((sorted.get(sorted.size() / 2).getValue() + sorted.get(sorted.size() / 2 + 1).getValue()) / 2);
} else {
mid.setName(sorted.get(sorted.size() / 2).getName());
mid.setValue(sorted.get(sorted.size() / 2).getValue());
}
return mid;
}
/*
get/set
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getSum() {
return sum;
}
public void setSum(long sum) {
this.sum = sum;
}
public int getMean() {
return mean;
}
public void setMean(int mean) {
this.mean = mean;
}
public int getVariance() {
return variance;
}
public void setVariance(int variance) {
this.variance = variance;
}
public int getSkewness() {
return skewness;
}
public void setSkewness(int skewness) {
this.skewness = skewness;
}
public int getMinimum() {
return minimum;
}
public void setMinimum(int minimum) {
this.minimum = minimum;
}
public int getMaximum() {
return maximum;
}
public void setMaximum(int maximum) {
this.maximum = maximum;
}
public int getMode() {
return mode;
}
public void setMode(int mode) {
this.mode = mode;
}
public int getMedian() {
return median;
}
public void setMedian(int median) {
this.median = median;
}
}
| 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/calculation/LongStatistic.java | alpha/MyBox/src/main/java/mara/mybox/calculation/LongStatistic.java | package mara.mybox.calculation;
import java.util.HashMap;
import java.util.Map;
import mara.mybox.tools.LongTools;
import mara.mybox.value.AppValues;
/**
* @Author Mara
* @CreateDate 2021-10-4
* @License Apache License Version 2.0
*/
public class LongStatistic {
private String name;
private int count;
private long minimum, maximum, mode, median;
private double sum, mean, variance, skewness;
public LongStatistic() {
}
public LongStatistic(long[] values) {
if (values == null || values.length == 0) {
return;
}
count = values.length;
sum = 0;
minimum = Long.MAX_VALUE;
maximum = Long.MIN_VALUE;
for (int i = 0; i < count; ++i) {
long v = values[i];
sum += v;
if (v > maximum) {
maximum = v;
}
if (v < minimum) {
minimum = v;
}
}
mean = sum / values.length;
variance = 0;
skewness = 0;
mode = mode(values);
median = median(values);
for (int i = 0; i < values.length; ++i) {
long v = values[i];
variance += Math.pow(v - mean, 2);
skewness += Math.pow(v - mean, 3);
}
variance = Math.sqrt(variance / count);
skewness = Math.cbrt(skewness / count);
}
/*
static methods
*/
public static double sum(long[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidLong;
}
double sum = 0;
for (int i = 0; i < values.length; ++i) {
sum += values[i];
}
return sum;
}
public static long maximum(long[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidLong;
}
long max = Long.MIN_VALUE;
for (int i = 0; i < values.length; ++i) {
if (values[i] > max) {
max = values[i];
}
}
return max;
}
public static long minimum(long[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidLong;
}
long min = Long.MAX_VALUE;
for (int i = 0; i < values.length; ++i) {
if (values[i] < min) {
min = values[i];
}
}
return min;
}
public static double mean(long[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidLong;
}
return sum(values) / values.length;
}
public static long mode(long[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidLong;
}
long mode = 0;
Map<Long, Integer> number = new HashMap<>();
for (long value : values) {
if (number.containsKey(value)) {
number.put(value, number.get(value) + 1);
} else {
number.put(value, 1);
}
}
long num = 0;
for (long value : number.keySet()) {
if (num < number.get(value)) {
mode = value;
}
}
return mode;
}
public static long median(long[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidLong;
}
long[] sorted = LongTools.sortArray(values);
int len = sorted.length;
if (len == 2) {
return (sorted[0] + sorted[1]) / 2;
} else if (len % 2 == 0) {
return (sorted[len / 2] + sorted[len / 2 + 1]) / 2;
} else {
return sorted[len / 2];
}
}
public static double variance(long[] values) {
if (values == null || values.length == 0) {
return AppValues.InvalidLong;
}
double mean = mean(values);
return variance(values, mean);
}
public static double variance(long[] values, double mean) {
if (values == null || values.length == 0) {
return AppValues.InvalidLong;
}
double variance = 0;
for (int i = 0; i < values.length; ++i) {
variance += Math.pow(values[i] - mean, 2);
}
variance = Math.sqrt(variance / values.length);
return variance;
}
public static double skewness(long[] values, double mean) {
if (values == null || values.length == 0) {
return AppValues.InvalidLong;
}
double skewness = 0;
for (int i = 0; i < values.length; ++i) {
skewness += Math.pow(values[i] - mean, 3);
}
skewness = Math.cbrt(skewness / values.length);
return skewness;
}
/*
get/set
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSum() {
return sum;
}
public void setSum(long sum) {
this.sum = sum;
}
public double getMean() {
return mean;
}
public void setMean(long mean) {
this.mean = mean;
}
public double getVariance() {
return variance;
}
public void setVariance(long variance) {
this.variance = variance;
}
public double getSkewness() {
return skewness;
}
public void setSkewness(long skewness) {
this.skewness = skewness;
}
public long getMinimum() {
return minimum;
}
public void setMinimum(long minimum) {
this.minimum = minimum;
}
public long getMaximum() {
return maximum;
}
public void setMaximum(long maximum) {
this.maximum = maximum;
}
public long getMode() {
return mode;
}
public void setMode(long mode) {
this.mode = mode;
}
public long getMedian() {
return median;
}
public void setMedian(long median) {
this.median = median;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
| 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/calculation/MultinomialClassification.java | alpha/MyBox/src/main/java/mara/mybox/calculation/MultinomialClassification.java | package mara.mybox.calculation;
/**
* @Author Mara
* @CreateDate 2022-9-7
* @License Apache License Version 2.0
*/
public class MultinomialClassification {
// https://www.imooc.com/article/18088
public static double[] softMax(double[][] theta, double[] data) {
if (theta == null || data == null) {
return null;
}
int len = data.length;
if (len != theta.length) {
return null;
}
double[] result = new double[len];
double[] v = new double[len];
double sum = 0d;
for (int i = 0; i < len; i++) {
double d = 0d;
for (int j = 0; j < len; j++) {
d += theta[i][j] * data[j];
}
d = Math.pow(Math.E, d);
v[i] = d;
sum += d;
}
for (int i = 0; i < len; i++) {
result[i] = v[i] / sum;
}
return result;
}
}
| 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/calculation/BinaryClassification.java | alpha/MyBox/src/main/java/mara/mybox/calculation/BinaryClassification.java | package mara.mybox.calculation;
/**
* @Author Mara
* @CreateDate 2022-9-7
* @License Apache License Version 2.0
*/
public class BinaryClassification {
public static double sigMoid(double x) {
return 1 / (1 + Math.exp(-x));
}
public static double sigMoidDerivative(double x) {
return sigMoid(x) * (1 - sigMoid(x));
}
}
| 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/db/DerbyBase.java | alpha/MyBox/src/main/java/mara/mybox/db/DerbyBase.java | package mara.mybox.db;
import java.io.File;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import mara.mybox.controller.MyBoxLoadingController;
import mara.mybox.db.table.BaseTable;
import static mara.mybox.db.table.BaseTableTools.internalTables;
import mara.mybox.db.table.TableColor;
import mara.mybox.db.table.TableColorPalette;
import mara.mybox.db.table.TableColorPaletteName;
import mara.mybox.db.table.TableData2DColumn;
import mara.mybox.db.table.TableFileBackup;
import mara.mybox.db.table.TableMyBoxLog;
import mara.mybox.db.table.TableWebHistory;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.ConfigTools;
import mara.mybox.tools.FileDeleteTools;
import mara.mybox.tools.NetworkTools;
import mara.mybox.value.AppValues;
import mara.mybox.value.AppVariables;
import static mara.mybox.value.Languages.message;
import static mara.mybox.value.Languages.sysDefaultLanguage;
import org.apache.derby.drda.NetworkServerControl;
/**
* @Author Mara
* @CreateDate 2018-10-15 9:31:28
* @License Apache License Version 2.0
*/
public class DerbyBase {
public static String mode = "embedded";
public static String host = "localhost";
public static int port = 1527;
public static String driver, protocol;
protected static final String ClientDriver = "org.apache.derby.jdbc.ClientDriver";
protected static final String embeddedDriver = "org.apache.derby.jdbc.EmbeddedDriver";
protected static final String create = ";user=" + AppValues.AppDerbyUser + ";password="
+ AppValues.AppDerbyPassword + ";create=true";
public static final String login = ";user=" + AppValues.AppDerbyUser + ";password="
+ AppValues.AppDerbyPassword + ";create=false";
public static DerbyStatus status;
public static long lastRetry = 0;
public enum DerbyStatus {
Embedded, Nerwork, Starting, NotConnected, EmbeddedFailed, NerworkFailed
}
public static Connection getConnection() {
try {
if (AppVariables.MyBoxDerbyPath == null) {
return null;
}
return DriverManager.getConnection(protocol + dbHome() + login);
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static String dbHome() {
return AppVariables.MyBoxDerbyPath.getAbsolutePath();
}
public static String readMode() {
String value = ConfigTools.readValue("DerbyMode");
String modeValue;
if (value != null) {
modeValue = "client".equals(value.toLowerCase()) ? "client" : "embedded";
} else {
modeValue = "embedded";
}
return modeValue;
}
public static String startDerby() {
try {
if ("client".equals(readMode())) {
return networkMode();
} else {
return embeddedMode();
}
} catch (Exception e) {
MyBoxLog.error(e);
return e.toString();
}
}
public static String embeddedMode() {
try {
if (isServerStarted(port)) {
shutdownDerbyServer();
} else {
// shutdownEmbeddedDerby();
}
Class.forName(embeddedDriver).getDeclaredConstructors()[0].newInstance();
String lang = sysDefaultLanguage();
if (!startEmbededDriver()) {
status = DerbyStatus.NotConnected;
return MessageFormat.format(message(lang, "DerbyNotAvalibale"), AppVariables.MyBoxDerbyPath);
}
driver = embeddedDriver;
protocol = "jdbc:derby:";
MyBoxLog.console("Driver: " + driver);
mode = "embedded";
ConfigTools.writeConfigValue("DerbyMode", mode);
status = DerbyStatus.Embedded;
return message(lang, "DerbyEmbeddedMode");
} catch (Exception e) {
status = DerbyStatus.EmbeddedFailed;
MyBoxLog.error(e);
return e.toString();
}
}
public static boolean startEmbededDriver() {
try (Connection conn = DriverManager.getConnection("jdbc:derby:" + dbHome() + create)) {
return true;
} catch (Exception e) {
status = DerbyStatus.EmbeddedFailed;
MyBoxLog.console(e);
return false;
}
}
// https://db.apache.org/derby/docs/10.17/devguide/rdevcsecure26537.html
public static void shutdownEmbeddedDerby() {
try (Connection conn = DriverManager.getConnection("jdbc:derby:;shutdown=true")) {
} catch (Exception e) {
status = DerbyStatus.NotConnected;
// MyBoxLog.console(e);
}
}
// Derby will run only at localhost.
// To avoid to let user have to configure security and network for it.
public static String networkMode() {
try {
if (status == DerbyStatus.Starting) {
String lang = sysDefaultLanguage();
return message(lang, "BeingStartingDerby");
}
Class.forName(ClientDriver).getDeclaredConstructors()[0].newInstance();
String lang = sysDefaultLanguage();
if (startDerbyServer()) {
driver = ClientDriver;
protocol = "jdbc:derby://" + host + ":" + port + "/";
mode = "client";
status = DerbyStatus.Nerwork;
ConfigTools.writeConfigValue("DerbyMode", mode);
MyBoxLog.console("Driver: " + driver);
return MessageFormat.format(message(lang, "DerbyServerListening"), port + "");
} else if (startEmbededDriver() && status != DerbyStatus.EmbeddedFailed) {
return embeddedMode();
} else {
status = DerbyStatus.NotConnected;
return MessageFormat.format(message(lang, "DerbyNotAvalibale"), AppVariables.MyBoxDerbyPath);
}
} catch (Exception e) {
status = DerbyStatus.NerworkFailed;
MyBoxLog.error(e);
return e.toString();
}
}
public static boolean startDerbyServer() {
try {
boolean portUsed = NetworkTools.isPortUsed(port);
int uPort = port;
if (portUsed) {
if (DerbyBase.isServerStarted(port)) {
MyBoxLog.console("Derby server is already started in port " + port + ".");
return true;
} else {
uPort = NetworkTools.findFreePort(port);
}
}
NetworkServerControl server = new NetworkServerControl(InetAddress.getByName(host),
uPort, AppValues.AppDerbyUser, AppValues.AppDerbyPassword);
status = DerbyStatus.Starting;
server.start(null);
// server.setTraceDirectory("d:/tmp");
server.trace(false);
if (isServerStarted(server)) {
port = uPort;
MyBoxLog.console("Derby server is listening in port " + port + ".");
status = DerbyStatus.Nerwork;
return true;
} else {
status = DerbyStatus.NerworkFailed;
return false;
}
} catch (Exception e) {
status = DerbyStatus.NerworkFailed;
MyBoxLog.error(e);
return false;
}
}
public static boolean shutdownDerbyServer() {
try {
boolean portUsed = NetworkTools.isPortUsed(port);
if (!portUsed) {
return true;
}
NetworkServerControl server = new NetworkServerControl(InetAddress.getByName(host),
port, AppValues.AppDerbyUser, AppValues.AppDerbyPassword);
server.shutdown();
status = DerbyStatus.NotConnected;
return true;
} catch (Exception e) {
MyBoxLog.error(e);
return false;
}
}
public static boolean isServerStarted(int uPort) {
try (Connection conn = DriverManager.getConnection(
"jdbc:derby://" + host + ":" + uPort + "/" + dbHome() + login)) {
port = uPort;
status = DerbyStatus.Nerwork;
return true;
} catch (Exception e) {
// MyBoxLog.console(e);
return false;
}
}
public static boolean isServerStarted(NetworkServerControl server) {
boolean started = false;
int count = 10, wait = 300;
while (!started && (count > 0)) {
try {
count--;
server.ping();
started = true;
} catch (Exception e) {
// MyBoxLog.error(e);
// MyBoxLog.debug(e);
try {
Thread.currentThread().sleep(wait);
} catch (Exception ex) {
}
}
}
return started;
}
public static boolean isStarted() {
return DerbyBase.status == DerbyStatus.Embedded
|| DerbyBase.status == DerbyStatus.Nerwork;
}
// Upper case
public static List<String> allTables(Connection conn) {
try {
List<String> tables = new ArrayList<>();
String sql = "SELECT TABLENAME FROM SYS.SYSTABLES WHERE TABLETYPE='T' ORDER BY TABLENAME";
conn.setAutoCommit(true);
try (Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery(sql)) {
while (resultSet.next()) {
String savedName = resultSet.getString("TABLENAME");
String referredName = fixedIdentifier(savedName);
tables.add(referredName);
}
} catch (Exception e) {
MyBoxLog.error(e, sql);
}
return tables;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static List<String> columns(Connection conn, String tablename) {
try {
List<String> columns = new ArrayList<>();
String sql = "SELECT columnname, columndatatype FROM SYS.SYSTABLES t, SYS.SYSCOLUMNS c "
+ " where t.TABLEID=c.REFERENCEID AND tablename='" + tablename.toUpperCase() + "'"
+ " order by columnnumber";
conn.setAutoCommit(true);
try (Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery(sql)) {
while (resultSet.next()) {
String savedName = resultSet.getString("columnname");
String referredName = fixedIdentifier(savedName);
columns.add(referredName + ", " + resultSet.getString("columndatatype"));
}
} catch (Exception e) {
MyBoxLog.error(e, sql);
}
return columns;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
// lower case
public static List<String> columnNames(Connection conn, String tablename) {
try {
List<String> columns = new ArrayList<>();
String sql = "SELECT columnname FROM SYS.SYSTABLES t, SYS.SYSCOLUMNS c "
+ " where t.TABLEID=c.REFERENCEID AND tablename='" + tablename.toUpperCase() + "'"
+ " order by columnnumber";
conn.setAutoCommit(true);
try (Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery(sql)) {
while (resultSet.next()) {
String savedName = resultSet.getString("columnname");
String referredName = fixedIdentifier(savedName);
columns.add(referredName);
}
} catch (Exception e) {
MyBoxLog.error(e, sql);
}
return columns;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static List<String> indexes(Connection conn) {
try {
List<String> indexes = new ArrayList<>();
String sql = "SELECT CONGLOMERATENAME FROM SYS.SYSCONGLOMERATES";
conn.setAutoCommit(true);
try (Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery(sql)) {
while (resultSet.next()) {
String savedName = resultSet.getString("CONGLOMERATENAME");
String referredName = fixedIdentifier(savedName);
indexes.add(referredName);
}
} catch (Exception e) {
MyBoxLog.console(e, sql);
}
return indexes;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static List<String> views(Connection conn) {
try {
List<String> tables = new ArrayList<>();
String sql = "SELECT TABLENAME FROM SYS.SYSTABLES WHERE TABLETYPE='V'";
conn.setAutoCommit(true);
try (Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery(sql)) {
while (resultSet.next()) {
String savedName = resultSet.getString("TABLENAME");
String referredName = fixedIdentifier(savedName);
tables.add(referredName);
}
} catch (Exception e) {
MyBoxLog.console(e, sql);
}
return tables;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static boolean initTables(MyBoxLoadingController loadingController) {
MyBoxLog.console("Protocol: " + protocol + dbHome());
try (Connection conn = DriverManager.getConnection(protocol + dbHome() + create)) {
initTables(loadingController, conn);
initIndexs(conn);
initViews(conn);
return true;
} catch (Exception e) {
MyBoxLog.console(e);
return false;
}
}
public static boolean initTables(MyBoxLoadingController loadingController, Connection conn) {
try {
List<String> tables = allTables(conn);
MyBoxLog.console("Tables: " + tables.size());
Map<String, BaseTable> internalTables = internalTables();
for (String name : internalTables.keySet()) {
if (tables.contains(name.toLowerCase())
|| name.startsWith("NODE") && name.endsWith("_TAG")) {
continue;
}
internalTables.get(name).createTable(conn);
if (loadingController != null) {
loadingController.info("Created table: " + name);
} else {
MyBoxLog.console("Created table: " + name);
}
}
return true;
} catch (Exception e) {
MyBoxLog.console(e);
return false;
}
}
public static boolean initIndexs(Connection conn) {
try {
List<String> indexes = indexes(conn);
MyBoxLog.debug("Indexes: " + indexes.size());
if (!indexes.contains("MyBox_Log_index".toLowerCase())) {
try (Statement statement = conn.createStatement()) {
statement.executeUpdate(TableMyBoxLog.Create_Index);
} catch (Exception e) {
// MyBoxLog.error(e);
}
}
if (!indexes.contains("File_Backup_index".toLowerCase())) {
try (Statement statement = conn.createStatement()) {
statement.executeUpdate(TableFileBackup.Create_Index);
} catch (Exception e) {
MyBoxLog.error(e);
}
}
if (!indexes.contains("Color_rgba_unique_index".toLowerCase())) {
try (Statement statement = conn.createStatement()) {
statement.executeUpdate(TableColor.Create_RGBA_Unique_Index);
} catch (Exception e) {
MyBoxLog.error(e);
}
}
if (!indexes.contains("Color_Palette_Name_unique_index".toLowerCase())) {
try (Statement statement = conn.createStatement()) {
statement.executeUpdate(TableColorPaletteName.Create_Unique_Index);
} catch (Exception e) {
MyBoxLog.error(e);
}
}
if (!indexes.contains("Web_History_time_index".toLowerCase())) {
try (Statement statement = conn.createStatement()) {
statement.executeUpdate(TableWebHistory.Create_Time_Index);
} catch (Exception e) {
MyBoxLog.error(e);
}
}
return true;
} catch (Exception e) {
MyBoxLog.console(e);
return false;
}
}
public static boolean initViews(Connection conn) {
try {
List<String> views = views(conn);
MyBoxLog.debug("Views: " + views.size());
if (!views.contains("Data2D_Column_View".toLowerCase())) {
try (Statement statement = conn.createStatement()) {
statement.executeUpdate(TableData2DColumn.CreateView);
} catch (Exception e) {
// MyBoxLog.error(e);
}
}
if (!views.contains("Color_Palette_View".toLowerCase())) {
try (Statement statement = conn.createStatement()) {
statement.executeUpdate(TableColorPalette.CreateView);
} catch (Exception e) {
// MyBoxLog.error(e);
}
}
return true;
} catch (Exception e) {
MyBoxLog.console(e);
return false;
}
}
public static int size(String sql) {
try (Connection conn = DerbyBase.getConnection()) {
conn.setReadOnly(true);
return size(conn, sql);
} catch (Exception e) {
MyBoxLog.error(e, sql);
return 0;
}
}
public static int size(Connection conn, String sql) {
int size = 0;
try {
boolean ac = conn.getAutoCommit();
conn.setAutoCommit(true);
try (ResultSet results = conn.createStatement().executeQuery(sql)) {
if (results != null && results.next()) {
size = results.getInt(1);
}
} catch (Exception e) {
MyBoxLog.error(e, sql);
}
conn.setAutoCommit(ac);
} catch (Exception e) {
MyBoxLog.error(e, sql);
return 0;
}
return size;
}
public static boolean isTableEmpty(String tableName) {
try (Connection conn = DerbyBase.getConnection()) {
String sql = "SELECT * FROM " + tableName + " FETCH FIRST ROW ONLY";
conn.setReadOnly(true);
return isEmpty(conn, sql);
} catch (Exception e) {
MyBoxLog.error(e, tableName);
return false;
}
}
public static boolean isEmpty(Connection conn, String sql) {
try {
boolean isEmpty = true;
conn.setAutoCommit(true);
try (ResultSet results = conn.createStatement().executeQuery(sql)) {
isEmpty = results == null || !results.next();
} catch (Exception e) {
MyBoxLog.error(e, sql);
}
return isEmpty;
} catch (Exception e) {
MyBoxLog.error(e, sql);
return false;
}
}
public static ResultSet query(String sql) {
try (Connection conn = DerbyBase.getConnection()) {
conn.setReadOnly(true);
return query(conn, sql);
} catch (Exception e) {
MyBoxLog.error(e, sql);
return null;
}
}
public static ResultSet query(Connection conn, String sql) {
try (Statement statement = conn.createStatement()) {
conn.setAutoCommit(true);
return statement.executeQuery(sql);
} catch (Exception e) {
MyBoxLog.error(e, sql);
return null;
}
}
public static int update(String sql) {
try (Connection conn = DerbyBase.getConnection()) {
return update(conn, sql);
} catch (Exception e) {
MyBoxLog.error(e, sql);
return 0;
}
}
public static int update(Connection conn, String sql) {
try (Statement statement = conn.createStatement()) {
return statement.executeUpdate(sql);
} catch (Exception e) {
MyBoxLog.error(e, sql);
return 0;
}
}
public static int exist(Connection conn, String referredName) {
if (conn == null || referredName == null) {
return -1;
}
try (ResultSet resultSet = conn.getMetaData().getColumns(null, "MARA",
DerbyBase.savedName(referredName), "%")) {
if (resultSet.next()) {
return 1;
} else {
return 0;
}
} catch (Exception e) {
MyBoxLog.debug(e, referredName);
return -2;
}
}
public static String stringValue(String value) {
if (value == null) {
return null;
}
return value.replaceAll("'", "''");
}
// CALL SYSCS_UTIL.SYSCS_EXPORT_TABLE ('MARA', 'LOCATION', 'D:\MyBox\src\main\resources\fetch\db\Location.del_en', null, null, 'UTF-8');
public static void exportData(String table, String file) {
if (file == null) {
return;
}
File f = new File(file);
FileDeleteTools.delete(f);
try (Connection conn = DerbyBase.getConnection();) {
PreparedStatement ps = conn.prepareStatement("CALL SYSCS_UTIL.SYSCS_EXPORT_TABLE (?,?,?,?,?,?)");
ps.setString(1, null);
ps.setString(2, table.toUpperCase());
ps.setString(3, file);
ps.setString(4, null);
ps.setString(5, null);
ps.setString(6, "UTF-8");
ps.execute();
} catch (Exception e) {
MyBoxLog.error(e, file);
}
}
// CALL SYSCS_UTIL.SYSCS_IMPORT_TABLE ('MARA', 'LOCATION', 'D:\MyBox\src\main\resources\fetch\db\Location.del',null, null, 'UTF-8', 1);
public static void importData(String table, String file, boolean replace) {
if (file == null) {
return;
}
File f = new File(file);
if (!f.exists()) {
return;
}
try (Connection conn = DerbyBase.getConnection();) {
PreparedStatement ps = conn.prepareStatement("CALL SYSCS_UTIL.SYSCS_IMPORT_TABLE (?,?,?,?,?,?,?)");
ps.setString(1, null);
ps.setString(2, table.toUpperCase());
ps.setString(3, file);
ps.setString(4, null);
ps.setString(5, null);
ps.setString(6, "UTF-8");
ps.setInt(7, replace ? 1 : 0);
ps.execute();
} catch (Exception e) {
MyBoxLog.error(e, file);
}
}
// https://db.apache.org/derby/docs/10.17/ref/crefsqlj1003454.html#crefsqlj1003454
// https://db.apache.org/derby/docs/10.17/ref/rrefkeywords29722.html
public static String fixedIdentifier(String name) {
if (name == null) {
return null;
}
if (name.startsWith("\"") && name.endsWith("\"")) {
return name;
}
String sname = name.toLowerCase().replaceAll("(", "(").replaceAll(")", ")");
boolean needQuote = false;
for (int i = 0; i < sname.length(); i++) {
char c = sname.charAt(i);
if (c != '_' && !Character.isLetterOrDigit(c)) {
needQuote = true;
break;
}
if (i == 0 && Character.isDigit(c)) {
needQuote = true;
break;
}
}
return needQuote ? "\"" + sname + "\"" : sname;
}
public static String appendIdentifier(String name, String suffix) {
if (name == null || suffix == null || suffix.isBlank()) {
return null;
}
return fixedIdentifier((name + suffix).replaceAll("\"", ""));
}
public static String checkIdentifier(List<String> names, String name, boolean add) {
if (name == null) {
return null;
}
if (names == null) {
names = new ArrayList<>();
}
String tname = name;
int index = 1;
while (names.contains(tname) || names.contains(tname.toUpperCase())) {
tname = DerbyBase.appendIdentifier(name, ++index + "");
}
if (add) {
names.add(tname);
}
return tname;
}
public static String savedName(String referedName) {
if (referedName == null) {
return null;
}
if (referedName.startsWith("\"") && referedName.endsWith("\"")) {
return referedName.substring(1, referedName.length() - 1);
} else {
return referedName.toUpperCase();
}
}
}
| 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/db/DataBase.java | alpha/MyBox/src/main/java/mara/mybox/db/DataBase.java | package mara.mybox.db;
/**
* @Author Mara
* @CreateDate 2022-12-1
* @License Apache License Version 2.0
*/
public class Database {
public static long BatchSize = 500;
}
| 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/db/migration/TableTag.java | alpha/MyBox/src/main/java/mara/mybox/db/migration/TableTag.java | package mara.mybox.db.migration;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.db.DerbyBase;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.ColumnDefinition.ColumnType;
import mara.mybox.db.table.BaseTable;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2021-3-3
* @License Apache License Version 2.0
*/
public class TableTag extends BaseTable<Tag> {
public TableTag() {
tableName = "Tag";
defineColumns();
}
public TableTag(boolean defineColumns) {
tableName = "Tag";
if (defineColumns) {
defineColumns();
}
}
public final TableTag defineColumns() {
addColumn(new ColumnDefinition("tgid", ColumnType.Long, true, true).setAuto(true));
addColumn(new ColumnDefinition("category", ColumnType.String, true).setLength(StringMaxLength).setDefaultValue("Root"));
addColumn(new ColumnDefinition("tag", ColumnType.String, true).setLength(StringMaxLength));
addColumn(new ColumnDefinition("color", ColumnType.Color, true));
orderColumns = "tgid ASC";
return this;
}
public static final String Create_Unique_Index
= "CREATE UNIQUE INDEX Tag_unique_index on Tag ( category, tag )";
public static final String QueryTag
= "SELECT * FROM Tag WHERE category=? AND tag=?";
public static final String QueryCategoryTags
= "SELECT tag FROM Tag WHERE category=? ";
@Override
public boolean setValue(Tag data, String column, Object value) {
if (data == null || column == null) {
return false;
}
return data.setValue(column, value);
}
@Override
public Object getValue(Tag data, String column) {
if (data == null || column == null) {
return null;
}
return data.getValue(column);
}
@Override
public boolean valid(Tag data) {
if (data == null) {
return false;
}
return data.valid();
}
public Tag queryTag(Connection conn, String category, String tag) {
if (conn == null || tag == null) {
return null;
}
try (PreparedStatement statement = conn.prepareStatement(TableTag.QueryTag)) {
statement.setString(1, category);
statement.setString(2, tag);
conn.setAutoCommit(true);
ResultSet results = statement.executeQuery();
if (results.next()) {
return readData(results);
} else {
return null;
}
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public List<String> categoryTags(String category) {
try (Connection conn = DerbyBase.getConnection()) {
return categoryTags(conn, category);
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public List<String> categoryTags(Connection conn, String category) {
List<String> tags = new ArrayList<>();
try (PreparedStatement statement = conn.prepareStatement(QueryCategoryTags)) {
statement.setString(1, category);
ResultSet results = statement.executeQuery();
conn.setAutoCommit(true);
while (results.next()) {
tags.add(results.getString("tag"));
}
} catch (Exception e) {
MyBoxLog.error(e);
}
return tags;
}
public Tag findAndCreate(Connection conn, String category, String name) {
if (conn == null || category == null || name == null) {
return null;
}
try {
Tag tag = queryTag(conn, category, name);
if (tag == null) {
tag = new Tag(category, name);
tag = insertData(conn, tag);
conn.commit();
}
return tag;
} 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/db/migration/DataMigrationFrom68.java | alpha/MyBox/src/main/java/mara/mybox/db/migration/DataMigrationFrom68.java | package mara.mybox.db.migration;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import mara.mybox.controller.MyBoxLoadingController;
import mara.mybox.data2d.DataFileCSV;
import mara.mybox.data2d.DataMatrix;
import mara.mybox.data2d.TmpTable;
import mara.mybox.data2d.tools.Data2DDefinitionTools;
import mara.mybox.db.Database;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.db.data.Data2DDefinition;
import mara.mybox.db.data.DataNode;
import mara.mybox.db.data.DataNodeTag;
import mara.mybox.db.data.DataTag;
import mara.mybox.db.table.BaseNodeTable;
import static mara.mybox.db.table.BaseNodeTable.RootID;
import static mara.mybox.db.table.BaseTable.StringMaxLength;
import mara.mybox.db.table.TableData2DDefinition;
import mara.mybox.db.table.TableDataNodeTag;
import mara.mybox.db.table.TableDataTag;
import mara.mybox.db.table.TableNodeDataColumn;
import mara.mybox.db.table.TableNodeGeographyCode;
import mara.mybox.db.table.TableNodeHtml;
import mara.mybox.db.table.TableNodeImageScope;
import mara.mybox.db.table.TableNodeJEXL;
import mara.mybox.db.table.TableNodeJShell;
import mara.mybox.db.table.TableNodeJavaScript;
import mara.mybox.db.table.TableNodeMathFunction;
import mara.mybox.db.table.TableNodeRowExpression;
import mara.mybox.db.table.TableNodeSQL;
import mara.mybox.db.table.TableNodeText;
import mara.mybox.db.table.TableNodeWebFavorite;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.value.AppVariables;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2020-06-09
* @License Apache License Version 2.0
*/
public class DataMigrationFrom68 {
public static void handleVersions(MyBoxLoadingController controller,
int lastVersion, Connection conn, String lang) {
try {
if (lastVersion < 6008000) {
updateIn68(conn);
}
if (lastVersion < 6008001) {
updateIn681(conn);
}
if (lastVersion < 6008002) {
updateIn682(controller, conn);
}
if (lastVersion < 6008003) {
updateIn683(controller, conn, lang);
}
if (lastVersion < 6008005) {
updateIn685(controller, conn, lang);
}
if (lastVersion < 6008006) {
updateIn686(controller, conn, lang);
}
if (lastVersion < 6008008) {
updateIn688(controller, conn, lang);
}
if (lastVersion < 6009001) {
updateIn691(controller, conn, lang);
}
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public static void updateIn691(MyBoxLoadingController controller,
Connection conn, String lang) {
MyBoxLog.info("Updating tables in 6.9.1...");
if (controller != null) {
controller.info("Updating tables in 6.9.1...");
}
try (Statement statement = conn.createStatement()) {
statement.executeUpdate("ALTER TABLE Convolution_Kernel ADD COLUMN color SMALLINT");
statement.executeUpdate("UPDATE Convolution_Kernel SET color=0 WHERE is_gray=FALSE");
statement.executeUpdate("UPDATE Convolution_Kernel SET color=1 WHERE is_gray=TRUE");
statement.executeUpdate("ALTER TABLE Convolution_Kernel DROP COLUMN is_gray");
} catch (Exception e) {
MyBoxLog.console(e);
}
}
public static void updateIn688(MyBoxLoadingController controller,
Connection conn, String lang) {
MyBoxLog.info("Updating tables in 6.8.8...");
if (controller != null) {
controller.info("Updating tables in 6.8.8...");
}
try (Statement statement = conn.createStatement()) {
statement.executeUpdate("ALTER TABLE Data2D_Column ADD COLUMN label VARCHAR(" + StringMaxLength + ")");
} catch (Exception e) {
MyBoxLog.console(e);
}
}
public static void updateIn686(MyBoxLoadingController controller,
Connection conn, String lang) {
MyBoxLog.info("Updating tables in 6.8.6...");
if (controller != null) {
controller.info("Updating tables in 6.8.6...");
}
try {
conn.setAutoCommit(false);
try (Statement statement = conn.createStatement();
ResultSet defResult = statement.executeQuery("select * from Data2D_Definition WHERE data_type=4");
PreparedStatement rowQuery = conn.prepareStatement("select * from Data2D_Cell WHERE dcdid=? AND row=?")) {
TableData2DDefinition tableData2DDefinition = new TableData2DDefinition();
double value;
String line;
ResultSet rowResult;
double[] row;
Charset charset = Charset.forName("UTF-8");
while (defResult.next()) {
try {
Data2DDefinition def = tableData2DDefinition.readData(defResult);
long dataid = def.getDataID();
long colsNumber = def.getColsNumber();
long rowsNumber = def.getRowsNumber();
String dataname = dataid + "";
File file = DataMatrix.file(dataname);
rowQuery.setLong(1, dataid);
if (controller != null) {
controller.info("Moving matrix:" + file);
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, charset, false))) {
for (int rowID = 0; rowID < rowsNumber; rowID++) {
try {
rowQuery.setLong(2, rowID);
row = new double[(int) colsNumber];
rowResult = rowQuery.executeQuery();
while (rowResult.next()) {
try {
value = Double.parseDouble(rowResult.getString("value").replaceAll(",", ""));
row[(int) rowResult.getLong("col")] = value;
} catch (Exception exx) {
}
}
line = row[0] + "";
for (int c = 1; c < row.length; c++) {
line += DataMatrix.MatrixDelimiter + row[c];
}
writer.write(line + "\n");
} catch (Exception exx) {
}
}
writer.flush();
} catch (Exception ex) {
}
def.setFile(file).setSheet("Double")
.setDataName(dataname)
.setCharset(charset).setHasHeader(false)
.setDelimiter(DataMatrix.MatrixDelimiter);
tableData2DDefinition.updateData(conn, def);
conn.commit();
} catch (Exception e) {
}
}
defResult.close();
} catch (Exception e) {
MyBoxLog.console(e);
}
conn.setAutoCommit(true);
try (Statement statement = conn.createStatement()) {
statement.executeUpdate("ALTER TABLE Data2D_Cell DROP CONSTRAINT Data2D_Cell_fk");
statement.executeUpdate("DROP TABLE Data2D_Cell");
} catch (Exception e) {
MyBoxLog.console(e);
}
try (Statement statement = conn.createStatement()) {
statement.executeUpdate("ALTER TABLE Node_Image_Scope ADD COLUMN color_threshold_tmp DOUBLE");
statement.executeUpdate("UPDATE Node_Image_Scope SET color_threshold_tmp=color_threshold");
statement.executeUpdate("ALTER TABLE Node_Image_Scope DROP COLUMN color_threshold");
statement.executeUpdate("ALTER TABLE Node_Image_Scope ADD COLUMN color_threshold DOUBLE");
statement.executeUpdate("UPDATE Node_Image_Scope SET color_threshold=color_threshold_tmp");
statement.executeUpdate("ALTER TABLE Node_Image_Scope DROP COLUMN color_threshold_tmp");
} catch (Exception e) {
MyBoxLog.console(e);
}
} catch (Exception e) {
MyBoxLog.console(e);
}
}
public static void updateIn685(MyBoxLoadingController controller,
Connection conn, String lang) {
try (Statement exeStatement = conn.createStatement()) {
MyBoxLog.info("Updating tables in 6.8.5...");
if (controller != null) {
controller.info("Updating tables in 6.8.5...");
}
exeStatement.executeUpdate("ALTER TABLE Node_Image_Scope ADD COLUMN shape_type VARCHAR(128)");
exeStatement.executeUpdate("ALTER TABLE Node_Image_Scope ADD COLUMN color_algorithm VARCHAR(128)");
exeStatement.executeUpdate("ALTER TABLE Node_Image_Scope ADD COLUMN shape_excluded BOOLEAN");
exeStatement.executeUpdate("ALTER TABLE Node_Image_Scope ADD COLUMN color_threshold BIGINT");
exeStatement.executeUpdate("ALTER TABLE Node_Image_Scope ADD COLUMN color_weights VARCHAR(" + StringMaxLength + ")");
exeStatement.executeUpdate("ALTER TABLE Node_Image_Scope ADD COLUMN shape_data CLOB");
exeStatement.executeUpdate("UPDATE Node_Image_Scope SET shape_type=scope_type");
exeStatement.executeUpdate("UPDATE Node_Image_Scope SET shape_type='Matting8' WHERE scope_type='Matting'");
exeStatement.executeUpdate("UPDATE Node_Image_Scope SET shape_type='Whole' WHERE scope_type='COLORS'");
exeStatement.executeUpdate("UPDATE Node_Image_Scope SET color_algorithm=color_type");
exeStatement.executeUpdate("UPDATE Node_Image_Scope SET color_algorithm='RGBRoughWeightedEuclidean' "
+ " WHERE color_type='AllColor' OR color_type='Color' ");
exeStatement.executeUpdate("UPDATE Node_Image_Scope SET shape_excluded=area_excluded");
exeStatement.executeUpdate("UPDATE Node_Image_Scope SET color_threshold=color_distance");
exeStatement.executeUpdate("UPDATE Node_Image_Scope SET shape_data=area_data");
exeStatement.executeUpdate("ALTER TABLE Node_Image_Scope DROP COLUMN scope_type");
exeStatement.executeUpdate("ALTER TABLE Node_Image_Scope DROP COLUMN color_type");
exeStatement.executeUpdate("ALTER TABLE Node_Image_Scope DROP COLUMN color_distance");
exeStatement.executeUpdate("ALTER TABLE Node_Image_Scope DROP COLUMN area_excluded");
exeStatement.executeUpdate("ALTER TABLE Node_Image_Scope DROP COLUMN area_data");
File dir = new File(AppVariables.MyboxDataPath + File.separator + "buttons");
File[] list = dir.listFiles();
if (list != null) {
for (File file : list) {
if (file.isDirectory()) {
continue;
}
file.delete();
}
}
} catch (Exception e) {
MyBoxLog.console(e);
}
}
public static void updateIn683(MyBoxLoadingController controller,
Connection conn, String lang) {
try {
MyBoxLog.info("Updating tables in 6.8.3...");
if (controller != null) {
controller.info("Updating tables in 6.8.3...");
}
try (Statement statement = conn.createStatement()) {
String sql = "ALTER TABLE Data2D_Column DROP COLUMN invalid_as";
statement.executeUpdate(sql);
} catch (Exception e) {
MyBoxLog.console(e);
}
TableNodeGeographyCode gcTable = new TableNodeGeographyCode();
String tname = gcTable.getTableName();
if (controller != null) {
controller.info("Moving data: " + gcTable.getTreeName());
}
// for debug.Remove this block later
// try (Statement statement = conn.createStatement()) {
// conn.setAutoCommit(true);
// statement.executeUpdate("DROP TABLE " + tname + "_Node_Tag");
// statement.executeUpdate("DROP TABLE " + tname + "_Tag");
// } catch (Exception e) {
// MyBoxLog.console(e);
// }
// try (Statement statement = conn.createStatement()) {
// statement.executeUpdate("DROP TABLE " + tname);
// } catch (Exception e) {
//// MyBoxLog.console(e);
// }
// try {
// gcTable.createTable(conn);
// } catch (Exception e) {
//// MyBoxLog.console(e);
// }
String tmpTreeTable = TmpTable.TmpTablePrefix + "TREE_Migration683";
try (Statement statement = conn.createStatement()) {
conn.setAutoCommit(true);
statement.executeUpdate("DROP TABLE " + tmpTreeTable);
} catch (Exception e) {
// MyBoxLog.console(e);
}
try (Statement exeStatement = conn.createStatement();
PreparedStatement idQuery = conn.prepareStatement(
"SELECT chinese_name,english_name FROM Geography_Code WHERE gcid=? FETCH FIRST ROW ONLY")) {
idQuery.setMaxRows(1);
conn.setAutoCommit(true);
exeStatement.executeUpdate("CREATE TABLE " + tmpTreeTable
+ " ( old_nodeid BIGINT, old_parentid BIGINT, new_nodeid BIGINT)");
ResultSet result = conn.createStatement().executeQuery(
"SELECT * FROM Geography_Code ORDER BY gcid");
conn.setAutoCommit(false);
long count = 0;
float orderNum = 0;
DataNode node;
String name;
boolean isChinese = Languages.isChinese(lang);
while (result.next()) {
try {
long nodeid = result.getLong("gcid");
long parentid = result.getLong("owner");
String chinese_name = result.getString("chinese_name");
String english_name = result.getString("english_name");
if (isChinese) {
name = chinese_name != null ? chinese_name : english_name;
} else {
name = english_name != null ? english_name : chinese_name;
}
node = DataNode.create()
.setNodeid(-1).setParentid(RootID)
.setOrderNumber(++orderNum)
.setTitle(name);
node.setValue("level", result.getShort("level") - 1);
node.setValue("coordinate_system", result.getShort("coordinate_system"));
node.setValue("longitude", result.getDouble("longitude"));
node.setValue("latitude", result.getDouble("latitude"));
node.setValue("altitude", result.getDouble("altitude"));
node.setValue("precision", result.getDouble("precision"));
node.setValue("chinese_name", chinese_name);
node.setValue("english_name", english_name);
node.setValue("code1", result.getString("code1"));
node.setValue("code1", result.getString("code1"));
node.setValue("code1", result.getString("code1"));
node.setValue("code2", result.getString("code2"));
node.setValue("code3", result.getString("code3"));
node.setValue("code4", result.getString("code4"));
node.setValue("code5", result.getString("code5"));
node.setValue("alias1", result.getString("alias1"));
node.setValue("alias2", result.getString("alias2"));
node.setValue("alias3", result.getString("alias3"));
node.setValue("alias4", result.getString("alias4"));
node.setValue("alias5", result.getString("alias5"));
node.setValue("area", result.getLong("area") + 0d);
node.setValue("population", result.getLong("population"));
node.setValue("description", result.getString("comments"));
node.setValue("continent", updateIn683_queryName(idQuery, result.getLong("continent"), isChinese));
node.setValue("country", updateIn683_queryName(idQuery, result.getLong("country"), isChinese));
node.setValue("province", updateIn683_queryName(idQuery, result.getLong("province"), isChinese));
node.setValue("city", updateIn683_queryName(idQuery, result.getLong("city"), isChinese));
node.setValue("county", updateIn683_queryName(idQuery, result.getLong("county"), isChinese));
node.setValue("town", updateIn683_queryName(idQuery, result.getLong("town"), isChinese));
node.setValue("village", updateIn683_queryName(idQuery, result.getLong("village"), isChinese));
node.setValue("building", updateIn683_queryName(idQuery, result.getLong("building"), isChinese));
node = gcTable.insertData(conn, node);
long newNodeid = node.getNodeid();
if (newNodeid >= 0) {
if (++count % Database.BatchSize == 0) {
conn.commit();
}
exeStatement.executeUpdate("INSERT INTO " + tmpTreeTable + " VALUES ("
+ nodeid + ", " + parentid + ", " + newNodeid + ")");
}
} catch (Exception e) {
MyBoxLog.console(e);
}
}
conn.commit();
if (controller != null) {
controller.info("Saved: " + gcTable.getTreeName() + " count:" + count);
}
result = conn.createStatement().executeQuery("select A.new_nodeid AS nodeid,"
+ " B.new_nodeid AS parentid "
+ " from " + tmpTreeTable + " A, " + tmpTreeTable + " AS B "
+ " WHERE A.old_parentid=B.old_nodeid");
conn.setAutoCommit(false);
count = 0;
while (result.next()) {
try {
long nodeid = result.getLong("nodeid");
long parentid = result.getLong("parentid");
if (nodeid == parentid) {
parentid = RootID;
}
String sql = "UPDATE " + tname + " SET parentid=" + parentid + " WHERE nodeid=" + nodeid;
exeStatement.executeUpdate(sql);
if (++count % Database.BatchSize == 0) {
conn.commit();
}
} catch (Exception e) {
MyBoxLog.console(e);
}
}
conn.commit();
if (controller != null) {
controller.info("Moved: " + gcTable.getTreeName() + " count:" + count);
}
} catch (Exception e) {
MyBoxLog.error(e);
}
try (Statement statement = conn.createStatement()) {
conn.setAutoCommit(true);
statement.executeUpdate("DROP TABLE " + tmpTreeTable);
statement.executeUpdate("DROP TABLE Geography_Code");
} catch (Exception e) {
MyBoxLog.console(e);
}
} catch (Exception e) {
// MyBoxLog.console(e);
}
}
public static String updateIn683_queryName(PreparedStatement idQuery,
long id, boolean isChinese) {
try {
if (idQuery == null || id < 0) {
return null;
}
idQuery.setLong(1, id);
ResultSet idresults = idQuery.executeQuery();
if (idresults == null || !idresults.next()) {
return null;
}
String chinese_name = idresults.getString("chinese_name");
String english_name = idresults.getString("english_name");
if (isChinese) {
return chinese_name != null ? chinese_name : english_name;
} else {
return english_name != null ? english_name : chinese_name;
}
} catch (Exception e) {
return null;
}
}
public static void updateIn682(MyBoxLoadingController controller, Connection conn) {
try {
MyBoxLog.info("Updating tables in 6.8.2...");
if (controller != null) {
controller.info("Updating tables in 6.8.2...");
}
updateIn682_move(controller, conn, new TableNodeHtml(), "Notebook");
updateIn682_move(controller, conn, new TableNodeText(), "InformationInTree");
updateIn682_move(controller, conn, new TableNodeWebFavorite(), "WebFavorite");
updateIn682_move(controller, conn, new TableNodeSQL(), "SQL");
updateIn682_move(controller, conn, new TableNodeMathFunction(), "MathFunction");
updateIn682_move(controller, conn, new TableNodeImageScope(), "ImageScope");
updateIn682_move(controller, conn, new TableNodeJShell(), "JShellCode");
updateIn682_move(controller, conn, new TableNodeJEXL(), "JEXLCode");
updateIn682_move(controller, conn, new TableNodeJavaScript(), "JavaScript");
updateIn682_move(controller, conn, new TableNodeRowExpression(), "RowFilter");
updateIn682_move(controller, conn, new TableNodeDataColumn(), "Data2DDefinition");
try (Statement statement = conn.createStatement()) {
conn.setAutoCommit(true);
statement.executeUpdate("DROP TABLE tree_node_tag");
statement.executeUpdate("DROP TABLE tree_node");
statement.executeUpdate("DROP TABLE tag");
} catch (Exception e) {
MyBoxLog.console(e);
}
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public static void updateIn682_move(MyBoxLoadingController controller, Connection conn,
BaseNodeTable dataTable, String category) {
String tname = dataTable.getTableName();
if (controller != null) {
controller.info("Moving data: " + dataTable.getTreeName());
}
// for debug.Remove this block later
// try (Statement statement = conn.createStatement()) {
// conn.setAutoCommit(true);
// statement.executeUpdate("DROP TABLE " + tname + "_Node_Tag");
// statement.executeUpdate("DROP TABLE " + tname + "_Tag");
// } catch (Exception e) {
// MyBoxLog.console(e);
// }
// try (Statement statement = conn.createStatement()) {
// statement.executeUpdate("DROP TABLE " + tname);
// } catch (Exception e) {
// MyBoxLog.console(e);
// }
// try {
// dataTable.createTable(conn);
// } catch (Exception e) {
// MyBoxLog.console(e);
// }
String tmpTreeTable = TmpTable.TmpTablePrefix + "TREE_Migration682";
String tmpTagTable = TmpTable.TmpTablePrefix + "TAG_Migration682";
try (Statement statement = conn.createStatement()) {
conn.setAutoCommit(true);
statement.executeUpdate("DROP TABLE " + tmpTreeTable);
statement.executeUpdate("DROP TABLE " + tmpTagTable);
} catch (Exception e) {
// MyBoxLog.console(e);
}
try (Statement statement = conn.createStatement()) {
conn.setAutoCommit(true);
statement.executeUpdate("CREATE TABLE " + tmpTreeTable
+ " ( old_nodeid BIGINT, old_parentid BIGINT, new_nodeid BIGINT)");
ResultSet query = conn.createStatement().executeQuery(
"SELECT * FROM tree_node WHERE category='" + category + "' ORDER BY nodeid");
conn.setAutoCommit(false);
long count = 0;
float orderNum = 0;
DataNode node;
DataFileCSV data2D;
while (query.next()) {
try {
String info = query.getString("info");
if ("Node_Data_Column".equals(tname)) {
data2D = Data2DDefinitionTools.fromXML(info);
if (data2D == null) {
continue;
}
node = new DataNode();
} else {
node = fromText(tname, info);
if (node == null) {
continue;
}
data2D = null;
}
long nodeid = query.getLong("nodeid");
long parentid = query.getLong("parentid");
node.setNodeid(-1).setParentid(RootID)
.setOrderNumber(++orderNum)
.setTitle(query.getString("title"));
node = dataTable.insertData(conn, node);
long newNodeid = node.getNodeid();
if (newNodeid >= 0) {
if (++count % Database.BatchSize == 0) {
conn.commit();
}
statement.executeUpdate("INSERT INTO " + tmpTreeTable + " VALUES ("
+ nodeid + ", " + parentid + ", " + newNodeid + ")");
if (data2D != null) {
int corder = 0;
for (Data2DColumn column : data2D.getColumns()) {
DataNode columnNode = TableNodeDataColumn.fromColumn(column);
columnNode.setParentid(newNodeid).setOrderNumber(++corder);
dataTable.insertData(conn, columnNode);
}
}
}
} catch (Exception e) {
MyBoxLog.console(e);
}
}
conn.commit();
if (controller != null) {
controller.info("Saved: " + dataTable.getTreeName() + " count:" + count);
}
query = conn.createStatement().executeQuery("select A.new_nodeid AS nodeid,"
+ " B.new_nodeid AS parentid "
+ " from " + tmpTreeTable + " A, " + tmpTreeTable + " AS B "
+ " WHERE A.old_parentid=B.old_nodeid");
conn.setAutoCommit(false);
count = 0;
while (query.next()) {
try {
long nodeid = query.getLong("nodeid");
long parentid = query.getLong("parentid");
if (nodeid == parentid) {
parentid = RootID;
}
String sql = "UPDATE " + tname + " SET parentid=" + parentid + " WHERE nodeid=" + nodeid;
statement.executeUpdate(sql);
if (++count % Database.BatchSize == 0) {
conn.commit();
}
} catch (Exception e) {
MyBoxLog.console(e);
}
}
conn.commit();
if (controller != null) {
controller.info("Moved: " + dataTable.getTreeName() + " count:" + count);
}
statement.executeUpdate("CREATE TABLE " + tmpTagTable
+ " ( old_tagid BIGINT, new_tagid BIGINT)");
query = conn.createStatement().executeQuery(
"select * from tag where category='" + category + "' ORDER BY tgid ");
conn.setAutoCommit(false);
count = 0;
TableDataTag tableTreeTag = new TableDataTag(dataTable);
while (query.next()) {
try {
DataTag tag = new DataTag()
.setTag(query.getString("tag"))
.setColorString(query.getString("color"));
tag = tableTreeTag.insertData(conn, tag);
statement.executeUpdate("INSERT INTO " + tmpTagTable + " VALUES ("
+ query.getLong("tgid") + ", " + tag.getTagid() + ")");
if (++count % Database.BatchSize == 0) {
conn.commit();
}
} catch (Exception e) {
MyBoxLog.console(e);
}
}
conn.commit();
if (controller != null) {
controller.info("Tags saved: " + dataTable.getTreeName() + " count:" + count);
}
query = conn.createStatement().executeQuery("select C.new_nodeid AS mnodeid, B.new_tagid AS mtagid "
+ " from tree_node_tag A, " + tmpTagTable + " AS B, " + tmpTreeTable + " AS C"
+ " WHERE A.tnodeid=C.old_nodeid AND A.tagid=B.old_tagid ");
conn.setAutoCommit(false);
count = 0;
TableDataNodeTag tableTreeNodeTag = new TableDataNodeTag(dataTable);
while (query.next()) {
try {
DataNodeTag nodeTag = new DataNodeTag()
.setTnodeid(query.getLong("mnodeid"))
.setTtagid(query.getLong("mtagid"));
tableTreeNodeTag.insertData(conn, nodeTag);
if (++count % Database.BatchSize == 0) {
conn.commit();
}
} catch (Exception e) {
MyBoxLog.console(e);
}
}
conn.commit();
conn.setAutoCommit(true);
if (controller != null) {
controller.info("Tags moved: " + dataTable.getTreeName() + " count:" + count);
}
} catch (Exception e) {
MyBoxLog.error(e);
}
try (Statement statement = conn.createStatement()) {
conn.setAutoCommit(true);
statement.executeUpdate("DROP TABLE " + tmpTreeTable);
statement.executeUpdate("DROP TABLE " + tmpTagTable);
} catch (Exception e) {
// MyBoxLog.console(e);
}
}
public static DataNode fromText(String tableName, String text) {
try {
if (tableName == null) {
return null;
}
DataNode node = new DataNode();
if (text == null || text.isBlank()) {
return node;
}
String ValueSeparater = "_:;MyBoxNodeValue;:_";
String MoreSeparater = "MyBoxTreeNodeMore:";
String info = text.trim();
switch (tableName) {
case "Node_Text":
node.setValue("text", info);
break;
case "Node_Html":
node.setValue("html", info);
break;
case "Node_Web_Favorite":
node.setValue("address", null);
| 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/db/migration/InfoNode.java | alpha/MyBox/src/main/java/mara/mybox/db/migration/InfoNode.java | package mara.mybox.db.migration;
import java.io.File;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import mara.mybox.controller.BaseController;
import mara.mybox.data2d.DataFileCSV;
import mara.mybox.data2d.tools.Data2DDefinitionTools;
import mara.mybox.db.data.BaseData;
import mara.mybox.dev.MyBoxLog;
import static mara.mybox.fxml.FxFileTools.getInternalFile;
import mara.mybox.fxml.FxTask;
import mara.mybox.tools.JsonTools;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2021-4-23
* @License Apache License Version 2.0
*/
public class InfoNode extends BaseData {
public static final String RootIdentify = "MyBoxTreeRoot;;;";
public static final String TitleSeparater = " > ";
public static final String IDPrefix = "ID:";
public static final String TimePrefix = "Time:";
public static final String TagsPrefix = "Tags:";
public static final String TagSeparater = ";;;";
public static final String ValueSeparater = "_:;MyBoxNodeValue;:_";
public static final String MoreSeparater = "MyBoxTreeNodeMore:";
public static final String Root = "Root";
public static final String InformationInTree = "InformationInTree";
public static final String Notebook = "Notebook";
public static final String WebFavorite = "WebFavorite";
public static final String SQL = "SQL";
public static final String JShellCode = "JShellCode";
public static final String JEXLCode = "JEXLCode";
public static final String JavaScript = "JavaScript";
public static final String MathFunction = "MathFunction";
public static final String RowFilter = "RowFilter";
public static final String ImageScope = "ImageScope";
public static final String ImageMaterial = "ImageMaterial";
public static final String Data2DDefinition = "Data2DDefinition";
protected long nodeid, parentid;
protected String category, title, info;
protected Date updateTime;
private void init() {
nodeid = -1;
parentid = -2;
category = null;
title = null;
info = null;
updateTime = new Date();
}
public InfoNode() {
init();
}
public InfoNode(InfoNode parent, String title) {
init();
this.parentid = parent.getNodeid();
this.category = parent.getCategory();
this.title = title;
}
@Override
public boolean valid() {
return valid(this);
}
@Override
public boolean setValue(String column, Object value) {
return setValue(this, column, value);
}
@Override
public Object getValue(String column) {
return getValue(this, column);
}
public InfoNode copyIn(InfoNode parent) {
InfoNode node = new InfoNode();
node.setParentid(parent.getNodeid());
node.setCategory(parent.getCategory());
node.setTitle(title);
node.setInfo(info);
return node;
}
public boolean isRoot() {
return parentid == nodeid;
}
public String getValue() {
if (info == null) {
return null;
}
return info.replaceAll(ValueSeparater, " ").trim();
}
public String getIcon() {
if (category == null || !category.equals(InfoNode.WebFavorite)) {
return null;
}
Map<String, String> values = parseInfo(this);
return values.get("Icon");
}
public boolean equal(InfoNode node) {
return equal(this, node);
}
/*
Static methods
*/
public static InfoNode create() {
return new InfoNode();
}
public static boolean setValue(InfoNode data, String column, Object value) {
if (data == null || column == null) {
return false;
}
try {
switch (column) {
case "nodeid":
data.setNodeid(value == null ? -1 : (long) value);
return true;
case "parentid":
data.setParentid(value == null ? -1 : (long) value);
return true;
case "title":
data.setTitle(value == null ? null : (String) value);
return true;
case "info":
data.setInfo(value == null ? null : encodeInfo(data.getCategory(), (String) value));
return true;
case "category":
data.setCategory(value == null ? null : (String) value);
return true;
case "update_time":
data.setUpdateTime(value == null ? null : (Date) value);
return true;
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
return false;
}
public static Object getValue(InfoNode data, String column) {
if (data == null || column == null) {
return null;
}
switch (column) {
case "nodeid":
return data.getNodeid();
case "parentid":
return data.getParentid();
case "title":
return data.getTitle();
case "info":
return encodeInfo(data);
case "category":
return data.getCategory();
case "update_time":
return data.getUpdateTime();
}
return null;
}
public static boolean valid(InfoNode data) {
return data != null && data.getCategory() != null
&& data.getTitle() != null && !data.getTitle().isBlank()
&& !data.getTitle().contains(TitleSeparater);
}
public static File exampleFile(String category) {
if (null == category) {
return null;
} else {
String lang = Languages.embedFileLang();
return getInternalFile("/data/examples/" + category + "_Examples_" + lang + ".txt",
"data", category + "_Examples_" + lang + ".txt", true);
}
}
public static Map<String, String> parseInfo(InfoNode node) {
if (node == null) {
return new LinkedHashMap<>();
}
return parseInfo(node.getCategory(), node.getInfo());
}
public static Map<String, String> parseInfo(String category, String s) {
Map<String, String> values = new LinkedHashMap<>();
try {
if (category == null) {
return values;
}
String info = s == null || s.isBlank() ? null : s.trim();
switch (category) {
case InfoNode.WebFavorite:
values.put("Address", null);
values.put("Icon", null);
if (info != null) {
if (info.contains(ValueSeparater)) {
String[] ss = info.split(ValueSeparater);
if (ss.length > 0) {
values.put("Address", ss[0].trim());
}
if (ss.length > 1) {
values.put("Icon", ss[1].trim());
}
} else if (info.contains(MoreSeparater)) {
String[] ss = info.split(MoreSeparater);
if (ss.length > 0) {
values.put("Address", ss[0].trim());
}
if (ss.length > 1) {
values.put("Icon", ss[1].trim());
}
} else {
values.put("Address", info);
}
}
break;
case InfoNode.Notebook:
values.put("Note", info);
break;
case InfoNode.JShellCode:
values.put("Codes", info);
break;
case InfoNode.SQL:
values.put("SQL", info);
break;
case InfoNode.JavaScript:
values.put("Script", info);
break;
case InfoNode.InformationInTree:
values.put("Info", info);
break;
case InfoNode.JEXLCode:
values.put("Script", null);
values.put("Context", null);
values.put("Parameters", null);
if (info != null) {
String[] ss = null;
if (info.contains(ValueSeparater)) {
ss = info.split(ValueSeparater);
} else if (info.contains(MoreSeparater)) {
ss = info.split(MoreSeparater);
}
if (ss != null) {
if (ss.length > 0) {
values.put("Script", ss[0].trim());
}
if (ss.length > 1) {
values.put("Context", ss[1].trim());
}
if (ss.length > 2) {
values.put("Parameters", ss[2].trim());
}
} else {
values.put("Script", info);
}
}
break;
case InfoNode.RowFilter:
values.put("Script", null);
values.put("Condition", "true");
values.put("Maximum", "-1");
if (info != null) {
if (info.contains(ValueSeparater)) {
String[] ss = info.split(ValueSeparater);
if (ss.length > 0) {
values.put("Script", ss[0].trim());
}
if (ss.length > 1) {
values.put("Condition", ss[1].trim());
}
if (ss.length > 2) {
values.put("Maximum", ss[2].trim());
}
} else if (info.contains(MoreSeparater)) {
String[] ss = info.split(MoreSeparater);
values.put("Script", ss[0].trim());
if (ss.length > 1) {
ss = ss[1].split(";;;");
if (ss.length > 0) {
values.put("Condition", ss[0].trim());
}
if (ss.length > 1) {
values.put("Maximum", ss[1].trim());
}
}
} else {
values.put("Script", info);
}
}
break;
case InfoNode.MathFunction:
values.put("MathFunctionName", null);
values.put("Variables", null);
values.put("Expression", null);
values.put("FunctionDomain", null);
if (info != null) {
if (info.contains(ValueSeparater)) {
String[] ss = info.split(ValueSeparater);
if (ss.length > 0) {
values.put("MathFunctionName", ss[0].trim());
}
if (ss.length > 1) {
values.put("Variables", ss[1].trim());
}
if (ss.length > 2) {
values.put("Expression", ss[2].trim());
}
if (ss.length > 3) {
values.put("FunctionDomain", ss[3].trim());
}
} else {
String prefix = "Names:::";
if (info.startsWith(prefix)) {
info = info.substring(prefix.length());
int pos = info.indexOf("\n");
String names;
if (pos >= 0) {
names = info.substring(0, pos);
info = info.substring(pos);
} else {
names = info;
info = null;
}
pos = names.indexOf(",");
if (pos >= 0) {
values.put("MathFunctionName", names.substring(0, pos));
String vs = names.substring(pos).trim();
if (vs.length() > 0) {
values.put("Variables", vs.substring(1));
}
} else {
values.put("MathFunctionName", names);
}
}
if (info != null && info.contains(MoreSeparater)) {
String[] ss = info.split(MoreSeparater);
values.put("Expression", ss[0].trim());
if (ss.length > 1) {
values.put("FunctionDomain", ss[1].trim());
}
} else {
values.put("Expression", info);
}
}
}
break;
case InfoNode.ImageMaterial:
values.put("Value", info);
break;
case InfoNode.Data2DDefinition:
case InfoNode.ImageScope:
values.put("XML", info);
break;
default:
values.put("Info", info);
break;
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
return values;
}
public static String encodeInfo(InfoNode node) {
if (node == null) {
return null;
}
return encodeInfo(node.getCategory(), node.getInfo());
}
public static String encodeInfo(String category, String s) {
String info = s == null || s.isBlank() ? null : s.trim();
try {
if (category == null || info == null) {
return info;
}
Map<String, String> values = parseInfo(category, info);
if (values == null) {
return info;
}
switch (category) {
case InfoNode.WebFavorite: {
String address = values.get("Address");
String icon = values.get("Icon");
if (icon == null || icon.isBlank()) {
return address == null || address.isBlank() ? null : address.trim();
}
return (address == null ? "" : address.trim()) + ValueSeparater + "\n"
+ icon.trim();
}
case InfoNode.JEXLCode: {
String script = values.get("Script");
String context = values.get("Context");
String parameters = values.get("Parameters");
if ((parameters == null || parameters.isBlank())
&& (context == null || context.isBlank())) {
return script == null || script.isBlank() ? null : script.trim();
}
return (script == null ? "" : script.trim()) + ValueSeparater + "\n"
+ (context == null ? "" : context.trim()) + ValueSeparater + "\n"
+ (parameters == null ? "" : parameters.trim());
}
case InfoNode.RowFilter: {
String script = values.get("Script");
String condition = values.get("Condition");
String max = values.get("Maximum");
if ((condition == null || condition.isBlank())
&& (max == null || max.isBlank())) {
return script == null || script.isBlank() ? null : script.trim();
}
long maxl = -1;
try {
maxl = Long.parseLong(max);
} catch (Exception e) {
}
if ("true".equalsIgnoreCase(condition) && maxl <= 0) {
return script == null || script.isBlank() ? null : script.trim();
}
return (script == null ? "" : script.trim()) + ValueSeparater + "\n"
+ (condition == null ? "" : condition.trim()) + ValueSeparater + "\n"
+ (max == null ? "" : max.trim());
}
case InfoNode.MathFunction: {
String name = values.get("MathFunctionName");
String variables = values.get("Variables");
String exp = values.get("Expression");
String domain = values.get("FunctionDomain");
if ((name == null || name.isBlank())
&& (variables == null || variables.isBlank())
&& (domain == null || domain.isBlank())) {
return exp == null || exp.isBlank() ? null : exp.trim();
}
return (name == null ? "" : name.trim()) + ValueSeparater + "\n"
+ (variables == null ? "" : variables.trim()) + ValueSeparater + "\n"
+ (exp == null ? "" : exp.trim()) + ValueSeparater + "\n"
+ (domain == null ? "" : domain.trim());
}
}
} catch (Exception e) {
MyBoxLog.error(e);
}
return info;
}
public static String majorInfo(InfoNode node) {
try {
if (node == null || node.getCategory() == null) {
return null;
}
Map<String, String> values = parseInfo(node);
if (values == null) {
return node.getInfo();
}
switch (node.getCategory()) {
case InfoNode.WebFavorite: {
String address = values.get("Address");
return address == null || address.isBlank() ? null : address.trim();
}
case InfoNode.JEXLCode: {
String script = values.get("Script");
return script == null || script.isBlank() ? null : script.trim();
}
case InfoNode.RowFilter: {
String script = values.get("Script");
return script == null || script.isBlank() ? null : script.trim();
}
case InfoNode.MathFunction: {
String exp = values.get("Expression");
return exp == null || exp.isBlank() ? null : exp.trim();
}
}
return node.getInfo();
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static String infoXml(String category, String s, String prefix) {
if (s == null || s.isBlank()) {
return "";
}
String xml = "";
switch (category) {
case InfoNode.Data2DDefinition:
case InfoNode.ImageScope: {
xml = s + "\n";
break;
}
default:
Map<String, String> values = parseInfo(category, s);
if (values != null) {
for (String key : values.keySet()) {
String v = values.get(key);
if (v == null || v.isBlank()) {
continue;
}
String name = message(key);
xml += prefix + "<" + name + ">\n"
+ "<![CDATA[" + v + "]]>\n"
+ prefix + "</" + name + ">\n";
}
}
break;
}
return xml;
}
public static String infoJson(FxTask task, BaseController controller,
String category, String s, String prefix) {
if (s == null || s.isBlank()) {
return "";
}
String json = "";
switch (category) {
case InfoNode.Data2DDefinition: {
DataFileCSV csv = Data2DDefinitionTools.fromXML(s);
if (csv != null) {
json = prefix + ",\n"
+ Data2DDefinitionTools.toJSON(csv, true, prefix);
}
break;
}
case InfoNode.ImageScope: {
OldImageScope scope = OldImageScopeTools.fromXML(task, controller, s);
if (scope != null) {
json = prefix + ",\n"
+ OldImageScopeTools.toJSON(scope, prefix);
}
break;
}
default:
Map<String, String> values = parseInfo(category, s);
if (values != null) {
for (String key : values.keySet()) {
String v = values.get(key);
if (v == null || v.isBlank()) {
continue;
}
json += prefix + ",\n"
+ prefix + "\"" + message(key) + "\": " + JsonTools.encode(v);
}
}
break;
}
return json;
}
public static boolean equal(InfoNode node1, InfoNode node2) {
if (node1 == null || node2 == null) {
return false;
}
return node1.getNodeid() == node2.getNodeid();
}
public static boolean isWebFavorite(String category) {
return Languages.matchIgnoreCase(category, InfoNode.WebFavorite);
}
public static boolean isNotes(String category) {
return Languages.matchIgnoreCase(category, InfoNode.Notebook);
}
/*
get/set
*/
public long getNodeid() {
return nodeid;
}
public InfoNode setNodeid(long nodeid) {
this.nodeid = nodeid;
return this;
}
public long getParentid() {
return parentid;
}
public InfoNode setParentid(long parentid) {
this.parentid = parentid;
return this;
}
public String getTitle() {
return title;
}
public InfoNode setTitle(String title) {
this.title = title;
return this;
}
public String getInfo() {
return info;
}
public InfoNode setInfo(String info) {
this.info = info;
return this;
}
public String getCategory() {
return category;
}
public InfoNode setCategory(String category) {
this.category = category;
return this;
}
public Date getUpdateTime() {
return updateTime;
}
public InfoNode setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
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/db/migration/Data2DCell.java | alpha/MyBox/src/main/java/mara/mybox/db/migration/Data2DCell.java | package mara.mybox.db.migration;
import mara.mybox.db.data.BaseData;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2021-10-17
* @License Apache License Version 2.0
*/
public class Data2DCell extends BaseData {
protected long cellID, dataID;
protected long columnID, rowID;
protected String value;
private void init() {
cellID = -1;
dataID = -1;
columnID = -1;
rowID = -1;
value = null;
}
public Data2DCell() {
init();
}
@Override
public boolean valid() {
return valid(this);
}
@Override
public boolean setValue(String column, Object value) {
return setValue(this, column, value);
}
@Override
public Object getValue(String column) {
return getValue(this, column);
}
/*
static methods
*/
public static Data2DCell create() {
return new Data2DCell();
}
public static boolean valid(Data2DCell data) {
return data != null && data.getColumnID() >= 0 && data.getRowID() >= 0;
}
public static boolean setValue(Data2DCell data, String column, Object value) {
if (data == null || column == null) {
return false;
}
try {
switch (column) {
case "dceid":
data.setCellID(value == null ? -1 : (long) value);
return true;
case "dcdid":
data.setDataID(value == null ? -1 : (long) value);
return true;
case "col":
data.setColumnID(value == null ? 3 : (long) value);
return true;
case "row":
data.setRowID(value == null ? 3 : (long) value);
return true;
case "value":
data.setValue(value == null ? null : (String) value);
return true;
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
return false;
}
public static Object getValue(Data2DCell data, String column) {
if (data == null || column == null) {
return null;
}
try {
switch (column) {
case "dceid":
return data.getCellID();
case "dcdid":
return data.getDataID();
case "row":
return data.getRowID();
case "col":
return data.getColumnID();
case "value":
return data.getValue();
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
return null;
}
/*
get/set
*/
public long getCellID() {
return cellID;
}
public Data2DCell setCellID(long dceid) {
this.cellID = dceid;
return this;
}
public long getDataID() {
return dataID;
}
public Data2DCell setDataID(long dataid) {
this.dataID = dataid;
return this;
}
public String getValue() {
return value;
}
public Data2DCell setValue(String value) {
this.value = value;
return this;
}
public long getColumnID() {
return columnID;
}
public Data2DCell setColumnID(long col) {
this.columnID = col;
return this;
}
public long getRowID() {
return rowID;
}
public Data2DCell setRowID(long row) {
this.rowID = row;
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/db/migration/GeographyCodeTools.java | alpha/MyBox/src/main/java/mara/mybox/db/migration/GeographyCodeTools.java | package mara.mybox.db.migration;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilderFactory;
import mara.mybox.controller.LoadingController;
import mara.mybox.db.DerbyBase;
import mara.mybox.db.data.*;
import static mara.mybox.db.migration.GeoCoordinateSystem.Value.GCJ_02;
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.FileTools;
import mara.mybox.tools.HtmlReadTools;
import mara.mybox.tools.TextFileTools;
import mara.mybox.tools.UrlTools;
import mara.mybox.value.AppValues;
import mara.mybox.value.Languages;
import mara.mybox.value.UserConfig;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import thridparty.CoordinateConverter;
/**
* @Author Mara
* @CreateDate 2020-8-11
* @License Apache License Version 2.0
*/
public class GeographyCodeTools {
/*
Query codes by web service
*/
public static GeographyCode geoCode(GeoCoordinateSystem coordinateSystem, String address) {
try {
if (coordinateSystem == null) {
return null;
}
if (coordinateSystem.getValue() == GeoCoordinateSystem.Value.GCJ_02) {
// GaoDe Map only supports info codes of China
String urlString = "https://restapi.amap.com/v3/geocode/geo?address="
+ URLEncoder.encode(address, "UTF-8") + "&output=xml&key="
+ UserConfig.getString("GaoDeMapServiceKey", AppValues.GaoDeMapWebServiceKey);
GeographyCode geographyCode = new GeographyCode();
geographyCode.setChineseName(address);
geographyCode.setCoordinateSystem(coordinateSystem);
return gaodeCode(urlString, geographyCode);
} else if (coordinateSystem.getValue() == GeoCoordinateSystem.Value.CGCS2000) {
// http://api.tianditu.gov.cn/geocoder?ds={"keyWord":"泰山"}&tk=0ddeb917def62b4691500526cc30a9b1
String urlString = "http://api.tianditu.gov.cn/geocoder?ds="
+ URLEncoder.encode("{\"keyWord\":\""
+ address
+ "\"}", "UTF-8") + "&tk="
+ UserConfig.getString("TianDiTuWebKey", AppValues.TianDiTuWebKey);
URL url = UrlTools.url(urlString);
if (url == null) {
return null;
}
File jsonFile = FileTmpTools.getTempFile(".json");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
connection.connect();
try (final BufferedInputStream inStream = new BufferedInputStream(connection.getInputStream());
final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(jsonFile))) {
byte[] buf = new byte[AppValues.IOBufferLength];
int len;
while ((len = inStream.read(buf)) > 0) {
outputStream.write(buf, 0, len);
}
}
String data = TextFileTools.readTexts(null, jsonFile);
double longitude = -200;
double latitude = -200;
String flag = "\"lon\":";
int pos = data.indexOf(flag);
if (pos >= 0) {
String subData = data.substring(pos + flag.length());
flag = ",";
pos = subData.indexOf(flag);
if (pos >= 0) {
try {
longitude = Double.parseDouble(subData.substring(0, pos));
} catch (Exception e) {
}
}
}
flag = "\"lat\":";
pos = data.indexOf(flag);
if (pos >= 0) {
String subData = data.substring(pos + flag.length());
flag = ",";
pos = subData.indexOf(flag);
if (pos >= 0) {
try {
latitude = Double.parseDouble(subData.substring(0, pos));
} catch (Exception e) {
}
}
}
if (validCoordinate(longitude, latitude)) {
return geoCode(coordinateSystem, longitude, latitude, true);
}
}
return null;
} catch (Exception e) {
return null;
}
}
public static GeographyCode geoCode(GeoCoordinateSystem coordinateSystem, double longitude, double latitude, boolean decodeAncestors) {
try {
GeographyCode geographyCode = TableGeographyCode.readCode(coordinateSystem, longitude, latitude, decodeAncestors);
if (geographyCode != null) {
return geographyCode;
}
return geoCode(coordinateSystem, longitude, latitude);
} catch (Exception e) {
return null;
}
}
public static GeographyCode geoCode(GeoCoordinateSystem coordinateSystem, double longitude, double latitude) {
try {
if (coordinateSystem == null) {
return null;
}
if (coordinateSystem.getValue() == GeoCoordinateSystem.Value.GCJ_02) {
String urlString = "https://restapi.amap.com/v3/geocode/regeo?location="
+ longitude + "," + latitude + "&output=xml&key="
+ UserConfig.getString("GaoDeMapServiceKey", AppValues.GaoDeMapWebServiceKey);
GeographyCode geographyCode = new GeographyCode();
geographyCode.setLongitude(longitude);
geographyCode.setLatitude(latitude);
geographyCode.setCoordinateSystem(coordinateSystem);
return gaodeCode(urlString, geographyCode);
} else if (coordinateSystem.getValue() == GeoCoordinateSystem.Value.CGCS2000) {
String urlString = "http://api.tianditu.gov.cn/geocoder?postStr={'lon':"
+ longitude + ",'lat':" + latitude
+ ",'ver':1}&type=geocode&tk="
+ UserConfig.getString("TianDiTuWebKey", AppValues.TianDiTuWebKey);
GeographyCode geographyCode = new GeographyCode();
geographyCode.setLongitude(longitude);
geographyCode.setLatitude(latitude);
geographyCode.setCoordinateSystem(coordinateSystem);
return tiandituCode(urlString, geographyCode);
}
return null;
} catch (Exception e) {
return null;
}
}
//{"result":{"formatted_address":"泰安市泰山区升平街39号(泰山区区政府大院内)泰山区统计局",
// "location":{"lon":117.12899999995,"lat":36.19280999998},
// "addressComponent":{"address":"泰山区升平街39号(泰山区区政府大院内)","city":"泰安市",
// "county_code":"156370902","nation":"中国","poi_position":"西北","county":"泰山区","city_code":"156370900",
// "address_position":"西北","poi":"泰山区统计局","province_code":"156370000","province":"山东省","road":"运粮街",
//"road_distance":65,"poi_distance":10,"address_distance":10}},"msg":"ok","status":"0"}
public static GeographyCode tiandituCode(String urlString, GeographyCode geographyCode) {
try {
URL url = UrlTools.url(urlString);
if (url == null) {
return null;
}
File jsonFile = FileTmpTools.getTempFile(".json");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
connection.connect();
try (final BufferedInputStream inStream = new BufferedInputStream(connection.getInputStream());
final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(jsonFile))) {
byte[] buf = new byte[AppValues.IOBufferLength];
int len;
while ((len = inStream.read(buf)) > 0) {
outputStream.write(buf, 0, len);
}
}
String data = TextFileTools.readTexts(null, jsonFile);
// MyBoxLog.debug(data);
String flag = "\"formatted_address\":\"";
int pos = data.indexOf(flag);
if (pos >= 0) {
String subData = data.substring(pos + flag.length());
flag = "\"";
pos = subData.indexOf(flag);
if (pos >= 0) {
String v = subData.substring(0, pos);
if (geographyCode.getChineseName() == null) {
geographyCode.setChineseName(v);
} else {
geographyCode.setAlias1(v);
}
}
}
flag = "\"lon\":";
pos = data.indexOf(flag);
if (pos >= 0) {
String subData = data.substring(pos + flag.length());
flag = ",";
pos = subData.indexOf(flag);
if (pos >= 0) {
try {
double longitude = Double.parseDouble(subData.substring(0, pos));
geographyCode.setLongitude(longitude);
} catch (Exception e) {
}
}
}
flag = "\"lat\":";
pos = data.indexOf(flag);
if (pos >= 0) {
String subData = data.substring(pos + flag.length());
flag = "}";
pos = subData.indexOf(flag);
if (pos >= 0) {
try {
double latitude = Double.parseDouble(subData.substring(0, pos));
geographyCode.setLatitude(latitude);
} catch (Exception e) {
}
}
}
flag = "\"address\":\"";
pos = data.indexOf(flag);
if (pos >= 0) {
String subData = data.substring(pos + flag.length());
flag = "\"";
pos = subData.indexOf(flag);
if (pos >= 0) {
String name = subData.substring(0, pos);
if (geographyCode.getChineseName() == null) {
geographyCode.setChineseName(name);
} else if (!geographyCode.getChineseName().equals(name)) {
geographyCode.setAlias1(geographyCode.getChineseName());
geographyCode.setChineseName(name);
}
}
}
flag = "\"city\":\"";
pos = data.indexOf(flag);
if (pos >= 0) {
String subData = data.substring(pos + flag.length());
flag = "\"";
pos = subData.indexOf(flag);
if (pos >= 0) {
geographyCode.setCityName(subData.substring(0, pos));
}
}
flag = "\"county_code\":\"";
pos = data.indexOf(flag);
if (pos >= 0) {
String subData = data.substring(pos + flag.length());
flag = "\"";
pos = subData.indexOf(flag);
if (pos >= 0) {
geographyCode.setCode3(subData.substring(0, pos));
}
}
flag = "\"nation\":\"";
pos = data.indexOf(flag);
if (pos >= 0) {
String subData = data.substring(pos + flag.length());
flag = "\"";
pos = subData.indexOf(flag);
if (pos >= 0) {
geographyCode.setCountryName(subData.substring(0, pos));
}
}
flag = "\"county\":\"";
pos = data.indexOf(flag);
if (pos >= 0) {
String subData = data.substring(pos + flag.length());
flag = "\"";
pos = subData.indexOf(flag);
if (pos >= 0) {
geographyCode.setCountyName(subData.substring(0, pos));
}
}
flag = "\"city_code\":\"";
pos = data.indexOf(flag);
if (pos >= 0) {
String subData = data.substring(pos + flag.length());
flag = "\"";
pos = subData.indexOf(flag);
if (pos >= 0) {
geographyCode.setCode2(subData.substring(0, pos));
}
}
flag = "\"poi\":\"";
pos = data.indexOf(flag);
if (pos >= 0) {
String subData = data.substring(pos + flag.length());
flag = "\"";
pos = subData.indexOf(flag);
if (pos >= 0) {
String name = subData.substring(0, pos);
if (geographyCode.getChineseName() == null) {
geographyCode.setChineseName(name);
} else if (!geographyCode.getChineseName().equals(name)) {
if (geographyCode.getAlias1() == null) {
geographyCode.setAlias1(geographyCode.getChineseName());
geographyCode.setChineseName(name);
} else if (!geographyCode.getAlias1().equals(name)) {
if (geographyCode.getAlias2() == null) {
geographyCode.setAlias2(geographyCode.getChineseName());
geographyCode.setChineseName(name);
} else if (!geographyCode.getAlias2().equals(name)) {
if (geographyCode.getAlias3() == null) {
geographyCode.setAlias3(geographyCode.getChineseName());
geographyCode.setChineseName(name);
} else if (!geographyCode.getAlias3().equals(name)) {
if (geographyCode.getAlias4() == null) {
geographyCode.setAlias4(geographyCode.getChineseName());
geographyCode.setChineseName(name);
} else if (!geographyCode.getAlias4().equals(name)) {
geographyCode.setAlias5(geographyCode.getChineseName());
geographyCode.setChineseName(name);
}
}
}
}
}
}
}
flag = "\"province_code\":\"";
pos = data.indexOf(flag);
if (pos >= 0) {
String subData = data.substring(pos + flag.length());
flag = "\"";
pos = subData.indexOf(flag);
if (pos >= 0) {
geographyCode.setCode1(subData.substring(0, pos));
}
}
flag = "\"province\":\"";
pos = data.indexOf(flag);
if (pos >= 0) {
String subData = data.substring(pos + flag.length());
flag = "\"";
pos = subData.indexOf(flag);
if (pos >= 0) {
geographyCode.setProvinceName(subData.substring(0, pos));
}
}
flag = "\"road\":\"";
pos = data.indexOf(flag);
if (pos >= 0) {
String subData = data.substring(pos + flag.length());
flag = "\"";
pos = subData.indexOf(flag);
if (pos >= 0) {
geographyCode.setVillageName(subData.substring(0, pos));
}
}
if (!validCoordinate(geographyCode)) {
return null;
}
return geographyCode;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
// {"status":"1","info":"OK","infocode":"10000","count":"1","geocodes":
// [{"formatted_address":"山东省泰安市泰山区泰山","country":"中国","province":"山东省","citycode":"0538",
//"city":"泰安市","county":"泰山区","township":[],
//"village":{"name":[],"type":[]},
//"building":{"name":[],"type":[]},
//"adcode":"370902","town":[],"number":[],"location":"117.157242,36.164988","levelCode":"兴趣点"}]}
public static GeographyCode gaodeCode(String urlString, GeographyCode geographyCode) {
try {
URL url = UrlTools.url(urlString);
if (url == null) {
return null;
}
File xmlFile = HtmlReadTools.download(null, url.toString());
// MyBoxLog.debug(FileTools.readTexts(xmlFile));
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
NodeList nodes = doc.getElementsByTagName("formatted_address");
if (nodes != null && nodes.getLength() > 0) {
String v = nodes.item(0).getTextContent();
if (geographyCode.getChineseName() == null) {
geographyCode.setChineseName(v);
} else {
geographyCode.setAlias1(v);
}
}
nodes = doc.getElementsByTagName("country");
if (nodes != null && nodes.getLength() > 0) {
geographyCode.setCountryName(nodes.item(0).getTextContent());
}
nodes = doc.getElementsByTagName("province");
if (nodes != null && nodes.getLength() > 0) {
geographyCode.setProvinceName(nodes.item(0).getTextContent());
}
nodes = doc.getElementsByTagName("citycode");
if (nodes != null && nodes.getLength() > 0) {
geographyCode.setCode2(nodes.item(0).getTextContent());
}
nodes = doc.getElementsByTagName("city");
if (nodes != null && nodes.getLength() > 0) {
geographyCode.setCityName(nodes.item(0).getTextContent());
}
nodes = doc.getElementsByTagName("district");
if (nodes != null && nodes.getLength() > 0) {
geographyCode.setCountyName(nodes.item(0).getTextContent());
}
nodes = doc.getElementsByTagName("township");
if (nodes != null && nodes.getLength() > 0) {
geographyCode.setTownName(nodes.item(0).getTextContent());
}
nodes = doc.getElementsByTagName("neighborhood");
if (nodes != null && nodes.getLength() > 0) {
geographyCode.setVillageName(nodes.item(0).getFirstChild().getTextContent());
}
nodes = doc.getElementsByTagName("building");
if (nodes != null && nodes.getLength() > 0) {
geographyCode.setBuildingName(nodes.item(0).getTextContent());
}
nodes = doc.getElementsByTagName("adcode");
if (nodes != null && nodes.getLength() > 0) {
geographyCode.setCode1(nodes.item(0).getTextContent());
}
nodes = doc.getElementsByTagName("streetNumber");
if (nodes != null && nodes.getLength() > 0) {
nodes = nodes.item(0).getChildNodes();
if (nodes != null) {
Map<String, String> values = new HashMap<>();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
values.put(node.getNodeName(), node.getTextContent());
}
String s = "";
String v = values.get("street");
if (v != null) {
s += v;
}
v = values.get("number");
if (v != null) {
s += v;
}
v = values.get("location");
if (v != null) {
s += v;
}
v = values.get("direction");
if (v != null) {
s += v;
}
v = values.get("distance");
if (v != null) {
s += v;
}
if (geographyCode.getBuildingName() == null) {
geographyCode.setBuildingName(s);
} else if (geographyCode.getAlias1() == null) {
geographyCode.setAlias1(s);
}
}
} else {
nodes = doc.getElementsByTagName("street");
if (nodes != null && nodes.getLength() > 0) {
String s = nodes.item(0).getTextContent();
if (geographyCode.getBuildingName() == null) {
geographyCode.setBuildingName(s);
} else if (geographyCode.getAlias1() == null) {
geographyCode.setAlias1(s);
} else if (geographyCode.getAlias2() == null) {
geographyCode.setAlias2(s);
}
}
nodes = doc.getElementsByTagName("number");
if (nodes != null && nodes.getLength() > 0) {
geographyCode.setCode5(nodes.item(0).getTextContent());
}
if (!validCoordinate(geographyCode)) {
nodes = doc.getElementsByTagName("location");
if (nodes != null && nodes.getLength() > 0) {
String[] values = nodes.item(0).getFirstChild().getTextContent().split(",");
geographyCode.setLongitude(Double.parseDouble(values[0].trim()));
geographyCode.setLatitude(Double.parseDouble(values[1].trim()));
} else {
geographyCode.setLongitude(-200);
geographyCode.setLatitude(-200);
}
}
if (geographyCode.getChineseName() == null) {
geographyCode.setChineseName(geographyCode.getLongitude() + "," + geographyCode.getLatitude());
}
nodes = doc.getElementsByTagName("level");
if (nodes != null && nodes.getLength() > 0) {
String v = nodes.item(0).getTextContent();
if (Languages.message("zh", "Country").equals(v)) {
geographyCode.setLevelCode(new GeographyCodeLevel("Country"));
} else if (Languages.message("zh", "Province").equals(v)) {
geographyCode.setLevelCode(new GeographyCodeLevel("Province"));
} else if (Languages.message("zh", "City").equals(v)) {
geographyCode.setLevelCode(new GeographyCodeLevel("City"));
} else if (Languages.message("zh", "County").equals(v)) {
geographyCode.setLevelCode(new GeographyCodeLevel("County"));
} else if (Languages.message("zh", "Town").equals(v)) {
geographyCode.setLevelCode(new GeographyCodeLevel("Town"));
} else if (Languages.message("zh", "Neighborhood").equals(v)) {
geographyCode.setLevelCode(new GeographyCodeLevel("Village"));
} else if (Languages.message("zh", "PointOfInterest").equals(v)) {
geographyCode.setLevelCode(new GeographyCodeLevel("Point Of Interest"));
} else if (Languages.message("zh", "Street").equals(v)) {
geographyCode.setLevelCode(new GeographyCodeLevel("Village"));
} else if (Languages.message("zh", "Building").equals(v)) {
geographyCode.setLevelCode(new GeographyCodeLevel("Building"));
} else {
geographyCode.setLevelCode(new GeographyCodeLevel("Point Of Interest"));
}
}
}
if (!validCoordinate(geographyCode)) {
return null;
}
return geographyCode;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static GeographyCode encode(FxTask task, GeographyCode code) {
if (code == null) {
return null;
}
try (Connection conn = DerbyBase.getConnection();
PreparedStatement geoInsert = conn.prepareStatement(TableGeographyCode.Insert)) {
return encode(task, conn, geoInsert, code, true);
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
return null;
}
public static GeographyCode encode(FxTask task, Connection conn, PreparedStatement geoInsert,
GeographyCode code, boolean decodeAncestors) {
if (code == null) {
return null;
}
try {
Map<String, Object> codeRet = encode(task, conn, geoInsert, code.getLevel(),
code.getLongitude(), code.getLatitude(),
code.getContinentName(), code.getCountryName(),
code.getProvinceName(), code.getCityName(), code.getCountyName(),
code.getTownName(), code.getVillageName(), code.getBuildingName(),
code.getName(), true, decodeAncestors);
conn.commit();
// if (codeRet.get("message") != null) {
// MyBoxLog.error((String) codeRet.get("message"));
// }
if (codeRet.get("code") != null) {
GeographyCode encoded = (GeographyCode) codeRet.get("code");
return encoded;
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
return null;
}
// !! Caller responses for committing the update
public static Map<String, Object> encode(FxTask task, Connection conn, PreparedStatement geoInsert,
int level, double longitude, double latitude, String continent, String country, String province,
String city, String county, String town, String village, String building, String poi,
boolean create, boolean decodeAncestors) {
Map<String, Object> ret = new HashMap<>();
try {
String msg = "";
if (conn == null) {
ret.put("message", "conn is null");
return ret;
}
String sql;
GeographyCode earch = TableGeographyCode.earth(conn);
if (level == 1) {
if (earch == null) {
importPredefined(task, conn, null);
earch = TableGeographyCode.earth(conn);
}
earch.setOwnerCode(earch);
ret.put("code", earch);
return ret;
}
GeographyCode continentCode = null;
if (continent != null) {
continentCode = TableGeographyCode.readCode(conn, 2, continent, decodeAncestors);
if (continentCode == null) {
continentCode = new GeographyCode();
continentCode.setLevelCode(new GeographyCodeLevel("Continent"));
continentCode.setLongitude(longitude);
continentCode.setLatitude(latitude);
continentCode.setChineseName(continent);
continentCode.setEnglishName(continent);
continentCode.setOwnerCode(earch);
msg += "continent :" + continent + ", " + longitude + "," + latitude;
if (create) {
if (!TableGeographyCode.insert(conn, geoInsert, continentCode)) {
continentCode = null;
msg += " is not existed, and failed to create. ";
} else {
msg += " is not existed, and created now.";
ret.put("inserted", "true");
}
} else {
msg += " is not existed, and will not be created.";
}
}
}
if (level == 2) {
ret.put("message", msg);
ret.put("code", continentCode);
return ret;
}
GeographyCode countryCode = null;
if (country != null) {
countryCode = TableGeographyCode.readCode(conn, 3, country, decodeAncestors);
if (countryCode == null) {
countryCode = new GeographyCode();
countryCode.setLevelCode(new GeographyCodeLevel("Country"));
countryCode.setLongitude(longitude);
countryCode.setLatitude(latitude);
countryCode.setChineseName(country);
countryCode.setEnglishName(country);
if (continentCode != null) {
countryCode.setContinent(continentCode.getGcid());
countryCode.setOwner(continentCode.getGcid());
}
msg += "country :" + country + ", " + longitude + "," + latitude;
if (create) {
if (!TableGeographyCode.insert(conn, geoInsert, countryCode)) {
countryCode = null;
msg += " is not existed, and failed to create. ";
} else {
msg += " is not existed, and created now.";
ret.put("inserted", "true");
}
} else {
msg += " is not existed, and will not be created.";
}
}
}
if (level == 3) {
ret.put("message", msg);
ret.put("code", countryCode);
return ret;
}
GeographyCode provinceCode = null;
if (province != null) {
if (countryCode != null && create) {
sql = "SELECT * FROM Geography_Code WHERE " + " level=4 AND country="
+ countryCode.getGcid() + " AND (" + TableGeographyCode.nameEqual(province) + ")";
provinceCode = TableGeographyCode.queryCode(conn, sql, decodeAncestors);
} else {
provinceCode = TableGeographyCode.readCode(conn, 4, province, decodeAncestors);
}
if (provinceCode == null) {
provinceCode = new GeographyCode();
provinceCode.setLevelCode(new GeographyCodeLevel("Province"));
provinceCode.setLongitude(longitude);
provinceCode.setLatitude(latitude);
provinceCode.setChineseName(province);
provinceCode.setEnglishName(province);
if (countryCode != null) {
provinceCode.setContinent(countryCode.getContinent());
| 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/db/migration/DataMigrationBefore65.java | alpha/MyBox/src/main/java/mara/mybox/db/migration/DataMigrationBefore65.java | package mara.mybox.db.migration;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import mara.mybox.db.Database;
import mara.mybox.db.DerbyBase;
import mara.mybox.db.data.ColorData;
import mara.mybox.db.data.ColorPaletteName;
import mara.mybox.db.data.ConvolutionKernel;
import mara.mybox.db.data.ImageClipboard;
import mara.mybox.db.data.ImageEditHistory;
import mara.mybox.db.data.WebHistory;
import mara.mybox.db.table.TableColor;
import mara.mybox.db.table.TableColorPalette;
import mara.mybox.db.table.TableConvolutionKernel;
import mara.mybox.db.table.TableImageClipboard;
import mara.mybox.db.table.TableImageEditHistory;
import mara.mybox.db.table.TableStringValues;
import mara.mybox.db.table.TableWebHistory;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.image.PaletteTools;
import mara.mybox.tools.FileDeleteTools;
import mara.mybox.tools.FileTools;
import mara.mybox.value.AppVariables;
import mara.mybox.value.Languages;
import mara.mybox.value.SystemConfig;
/**
* @Author Mara
* @CreateDate 2020-06-09
* @License Apache License Version 2.0
*/
public class DataMigrationBefore65 {
public static void handleVersions(int lastVersion, Connection conn) {
try {
if (lastVersion < 6002001) {
migrateBefore621(conn);
}
if (lastVersion < 6003000) {
migrateFrom621(conn);
}
if (lastVersion < 6003002) {
migrateFrom63(conn);
}
if (lastVersion < 6003003) {
updateIn632(conn);
}
if (lastVersion < 6003004) {
updateIn633(conn);
}
if (lastVersion < 6003006) {
updateIn636(conn);
}
if (lastVersion < 6003008) {
updateIn638(conn);
}
if (lastVersion < 6004001) {
updateIn641(conn);
}
if (lastVersion < 6004003) {
updateIn643(conn);
}
if (lastVersion < 6004004) {
updateIn644(conn);
}
if (lastVersion < 6004005) {
updateIn645(conn);
}
if (lastVersion < 6004008) {
updateIn648(conn);
}
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public static void updateIn648(Connection conn) {
try {
MyBoxLog.info("Updating tables in 6.4.8...");
try (Statement statement = conn.createStatement()) {
statement.executeUpdate("ALTER TABLE Data_Definition alter column delimiter set data type VARCHAR(128)");
conn.commit();
statement.executeUpdate("ALTER TABLE Data_Column DROP CONSTRAINT Data_Column_dataid_fk");
conn.commit();
statement.executeUpdate("ALTER TABLE Data_Column ADD CONSTRAINT Data_Column_dataid_fk "
+ " FOREIGN KEY ( dataid ) REFERENCES Data_Definition ( dfid ) ON DELETE Cascade");
conn.commit();
} catch (Exception e) {
MyBoxLog.debug(e);
}
conn.setAutoCommit(true);
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public static void updateIn645(Connection conn) {
try {
MyBoxLog.info("Updating tables in 6.4.5...");
String sql = "SELECT * FROM String_Values where key_name='ImageClipboard'";
try (Statement statement = conn.createStatement();
ResultSet results = statement.executeQuery(sql)) {
conn.setAutoCommit(false);
TableImageClipboard tableImageClipboard = new TableImageClipboard();
while (results.next()) {
ImageClipboard clip = new ImageClipboard();
clip.setImageFile(new File(results.getString("string_value")));
clip.setCreateTime(results.getTimestamp("create_time"));
clip.setSource(null);
tableImageClipboard.insertData(conn, clip);
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
conn.commit();
try (Statement statement = conn.createStatement()) {
statement.executeUpdate("DELETE FROM String_Values where key_name='ImageClipboard'");
} catch (Exception e) {
MyBoxLog.debug(e);
}
TableStringValues.add(conn, "InstalledVersions", "6.4.5");
conn.setAutoCommit(true);
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public static void updateIn644(Connection conn) {
try {
MyBoxLog.info("Updating tables in 6.4.4...");
TableWebHistory tableWebHistory = new TableWebHistory();
String sql = "SELECT * FROM Browser_History";
try (Statement statement = conn.createStatement();
ResultSet results = statement.executeQuery(sql)) {
conn.setAutoCommit(false);
while (results.next()) {
WebHistory his = new WebHistory();
his.setAddress(results.getString("address"));
his.setTitle(results.getString("title"));
his.setIcon(results.getString("icon"));
his.setVisitTime(results.getTimestamp("visit_time"));
tableWebHistory.insertData(conn, his);
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
conn.commit();
try (Statement statement = conn.createStatement()) {
statement.executeUpdate("DROP TABLE Browser_History");
} catch (Exception e) {
MyBoxLog.debug(e);
}
TableStringValues.add(conn, "InstalledVersions", "6.4.4");
conn.setAutoCommit(true);
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public static void updateIn643(Connection conn) {
try {
MyBoxLog.info("Updating tables in 6.4.3...");
String sql = "SELECT * FROM Color_Data";
try (Statement statement = conn.createStatement();
ResultSet results = statement.executeQuery(sql)) {
conn.setAutoCommit(false);
ColorPaletteName defaultPalette = PaletteTools.defaultPalette(Languages.getLangName(), conn);
long paletteid = defaultPalette.getCpnid();
TableColorPalette tableColorPalette = new TableColorPalette();
TableColor tableColor = new TableColor();
while (results.next()) {
ColorData color = tableColor.readData(results);
color.setColorValue(results.getInt("color_value"));
tableColor.writeData(conn, color);
double orderNumber = results.getDouble("palette_index");
if (orderNumber > 0) {
color.setOrderNumner((float) orderNumber);
color.setPaletteid(paletteid);
tableColorPalette.findAndCreate(conn, color, true, true);
}
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
conn.commit();
try (Statement statement = conn.createStatement()) {
statement.executeUpdate("DROP TABLE Color_Data");
} catch (Exception e) {
MyBoxLog.debug(e);
}
TableStringValues.add(conn, "InstalledVersions", "6.4.3");
conn.setAutoCommit(true);
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public static void updateIn641(Connection conn) {
try {
MyBoxLog.info("Updating tables in 6.4.1...");
String sql = "SELECT * FROM image_history";
try (Statement statement = conn.createStatement();
ResultSet results = statement.executeQuery(sql)) {
TableImageEditHistory tableImageEditHistory = new TableImageEditHistory();
while (results.next()) {
ImageEditHistory his = new ImageEditHistory();
String image = results.getString("image_location");
if (image == null) {
continue;
}
his.setImageFile(new File(image));
String hisfile = results.getString("history_location");
if (hisfile == null) {
continue;
}
his.setHistoryFile(new File(hisfile));
his.setUpdateType(results.getString("update_type"));
his.setObjectType(results.getString("object_type"));
his.setOpType(results.getString("op_type"));
his.setScopeType(results.getString("scope_type"));
his.setScopeName(results.getString("scope_name"));
his.setOperationTime(results.getTimestamp("operation_time"));
tableImageEditHistory.insertData(conn, his);
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
conn.commit();
try (Statement statement = conn.createStatement()) {
statement.executeUpdate("DROP TABLE image_history");
} catch (Exception e) {
MyBoxLog.debug(e);
}
TableStringValues.add(conn, "InstalledVersions", "6.4.1");
conn.setAutoCommit(true);
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public static void updateIn638(Connection conn) {
try {
MyBoxLog.info("Updating tables in 6.3.8...");
if (AppVariables.MyBoxLanguagesPath.exists() && AppVariables.MyBoxLanguagesPath.isDirectory()) {
File[] files = AppVariables.MyBoxLanguagesPath.listFiles();
if (files != null && files.length > 0) {
MyBoxLog.info("Change language files names...");
for (File file : files) {
String name = file.getName();
if (!file.isFile() || (name.endsWith(".properties") && name.startsWith("Messages_"))) {
continue;
}
FileTools.override(file, Languages.interfaceLanguageFile(name));
}
}
}
TableStringValues.add(conn, "InstalledVersions", "6.3.8");
conn.setAutoCommit(true);
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void updateIn636(Connection conn) {
try {
MyBoxLog.info("Updating tables in 6.3.6...");
File log4j2Path = new File(System.getProperty("user.home") + File.separator + "log4j2");
if (log4j2Path.exists() && log4j2Path.isDirectory()) {
File[] files = log4j2Path.listFiles();
if (files != null && files.length > 0) {
MyBoxLog.info("Clearing MyBox logs generated by log4j2...");
for (File pathFile : files) {
if (pathFile.isFile()) {
if (pathFile.getName().startsWith("MyBox")) {
FileDeleteTools.delete(pathFile);
}
} else if (pathFile.isDirectory()) {
File[] subPaths = pathFile.listFiles();
if (subPaths != null && subPaths.length > 0) {
for (File subPathsFile : subPaths) {
if (subPathsFile.isFile()) {
if (subPathsFile.getName().startsWith("MyBox")) {
FileDeleteTools.delete(subPathsFile);
}
}
}
subPaths = pathFile.listFiles();
if (subPaths != null && subPaths.length == 0) {
FileDeleteTools.deleteDir(pathFile);
}
}
}
}
files = log4j2Path.listFiles();
if (files != null && files.length == 0) {
FileDeleteTools.deleteDir(log4j2Path);
}
}
}
TableStringValues.add(conn, "InstalledVersions", "6.3.6");
conn.setAutoCommit(true);
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void updateIn633(Connection conn) {
try {
MyBoxLog.info("Updating tables in 6.3.3...");
updateGeographyCodeIn633(conn);
updateConvolutionKernelIn633(conn);
TableStringValues.add(conn, "InstalledVersions", "6.3.3");
conn.setAutoCommit(true);
} catch (Exception e) {
// MyBoxLog.debug(e);
}
}
public static boolean updateGeographyCodeIn633(Connection conn) {
try (Statement statement = conn.createStatement()) {
conn.setAutoCommit(true);
String sql = "ALTER TABLE Geography_Code ADD COLUMN gcsource SMALLINT";
statement.executeUpdate(sql);
} catch (Exception e) {
// MyBoxLog.debug(e);
return false;
}
try (Statement statement = conn.createStatement()) {
String sql = "UPDATE Geography_Code SET gcsource=1 WHERE predefined=true";
statement.executeUpdate(sql);
} catch (Exception e) {
}
try (Statement statement = conn.createStatement()) {
String sql = "UPDATE Geography_Code SET gcsource=1 WHERE predefined=1";
statement.executeUpdate(sql);
} catch (Exception e) {
}
try (Statement statement = conn.createStatement()) {
String sql = "UPDATE Geography_Code SET gcsource=2 WHERE predefined=false";
statement.executeUpdate(sql);
} catch (Exception e) {
}
try (Statement statement = conn.createStatement()) {
String sql = "UPDATE Geography_Code SET gcsource=2 WHERE predefined=0";
statement.executeUpdate(sql);
} catch (Exception e) {
}
try (Statement statement = conn.createStatement()) {
String sql = "ALTER TABLE Geography_Code DROP COLUMN predefined";
statement.executeUpdate(sql);
} catch (Exception e) {
}
return true;
}
public static boolean updateConvolutionKernelIn633(Connection conn) {
try (Statement statement = conn.createStatement()) {
conn.setAutoCommit(true);
String sql = "ALTER TABLE Convolution_Kernel ADD COLUMN is_gray BOOLEAN";
statement.executeUpdate(sql);
sql = "ALTER TABLE Convolution_Kernel ADD COLUMN is_invert BOOLEAN";
statement.executeUpdate(sql);
} catch (Exception e) {
// MyBoxLog.debug(e);
return false;
}
try (Statement statement = conn.createStatement()) {
String sql = "UPDATE Convolution_Kernel SET is_gray=true WHERE gray>0";
statement.executeUpdate(sql);
} catch (Exception e) {
}
try (Statement statement = conn.createStatement()) {
String sql = "UPDATE Convolution_Kernel SET is_gray=false WHERE gray<1";
statement.executeUpdate(sql);
} catch (Exception e) {
}
try (Statement statement = conn.createStatement()) {
String sql = "ALTER TABLE Convolution_Kernel DROP COLUMN gray";
statement.executeUpdate(sql);
} catch (Exception e) {
}
return true;
}
public static void updateIn632(Connection conn) {
try {
MyBoxLog.info("Updating tables in 6.3.2...");
updateForeignKeysIn632(conn);
updateGeographyCodeIn632(conn);
TableStringValues.add(conn, "InstalledVersions", "6.3.2");
conn.setAutoCommit(true);
} catch (Exception e) {
// MyBoxLog.debug(e);
}
}
public static void updateForeignKeysIn632(Connection conn) {
try (Statement query = conn.createStatement();
Statement update = conn.createStatement()) {
conn.setAutoCommit(true);
String sql = "SELECT tablename, constraintName FROM SYS.SYSTABLES t, SYS.SYSCONSTRAINTS c where t.TABLEID=c.TABLEID AND type='F'";
try (ResultSet results = query.executeQuery(sql)) {
while (results.next()) {
String tablename = results.getString("tablename");
String constraintName = results.getString("constraintName");
sql = "ALTER TABLE " + tablename + " DROP FOREIGN KEY \"" + constraintName + "\"";
// MyBoxLog.debug(sql);
update.executeUpdate(sql);
}
}
sql = "ALTER TABLE Geography_Code ADD CONSTRAINT Geography_Code_owner_fk FOREIGN KEY (owner)"
+ " REFERENCES GEOGRAPHY_CODE (gcid) ON DELETE RESTRICT ON UPDATE RESTRICT";
update.executeUpdate(sql);
} catch (Exception e) {
// MyBoxLog.debug(e);
}
}
public static void updateGeographyCodeIn632(Connection conn) {
try (Statement statement = conn.createStatement();
PreparedStatement update = conn.prepareStatement(TableGeographyCode.Update)) {
conn.setAutoCommit(false);
try (ResultSet results = statement.executeQuery("SELECT * FROM Geography_Code WHERE gcid < 5000")) {
while (results.next()) {
GeographyCode code = TableGeographyCode.readResults(results);
// MyBoxLog.debug(code.getGcid() + " " + code.getName() + " "
// + code.getLongitude() + " " + code.getLatitude() + " " + code.getCoordinateSystem().intValue());
code = GeographyCodeTools.toCGCS2000(code, true);
// MyBoxLog.debug(code.getLongitude() + " " + code.getLatitude() + " " + code.getCoordinateSystem().intValue());
TableGeographyCode.update(conn, update, code);
}
}
conn.commit();
conn.setAutoCommit(true);
} catch (Exception e) {
// MyBoxLog.debug(e);
}
}
public static void migrateFrom63(Connection conn) {
MyBoxLog.info("Migrate from 6.3...");
try (Statement statement = conn.createStatement()) {
conn.setAutoCommit(true);
String sql = "ALTER TABLE Geography_Code add column altitude DOUBLE ";
statement.executeUpdate(sql);
sql = "ALTER TABLE Geography_Code add column precision DOUBLE";
statement.executeUpdate(sql);
sql = "ALTER TABLE Geography_Code add column owner BIGINT REFERENCES Geography_Code (gcid) ON DELETE CASCADE ON UPDATE RESTRICT";
statement.executeUpdate(sql);
sql = "ALTER TABLE Geography_Code add column coordinate_system SMALLINT";
statement.executeUpdate(sql);
} catch (Exception e) {
// MyBoxLog.debug(e);
return;
}
try (Statement statement = conn.createStatement()) {
conn.setAutoCommit(true);
String sql = "UPDATE Geography_Code SET area=area*1000000";
statement.executeUpdate(sql);
} catch (Exception e) {
// MyBoxLog.debug(e);
return;
}
try (PreparedStatement update = conn.prepareStatement(TableGeographyCode.Update)) {
String sql = "SELECT * FROM Geography_Code";
int count = 0;
conn.setAutoCommit(false);
try (ResultSet results = conn.createStatement().executeQuery(sql)) {
while (results.next()) {
GeographyCode code = TableGeographyCode.readResults(results);
TableGeographyCode.setUpdate(conn, update, code);
update.addBatch();
if (++count % Database.BatchSize == 0) {
update.executeBatch();
conn.commit();
}
}
}
update.executeBatch();
conn.commit();
TableStringValues.add(conn, "InstalledVersions", "6.3.1");
conn.setAutoCommit(true);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public static void migrateFrom621(Connection conn) {
try {
migrateGeographyCodeIn621(conn);
conn.setAutoCommit(true);
TableStringValues.add(conn, "InstalledVersions", "6.3");
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public static void migrateGeographyCodeIn621(Connection conn) {
MyBoxLog.info("Migrate GeographyCode from 6.2.1...");
String sql = "SELECT * FROM Geography_Code ORDER BY level, country, province, city";
List<GeographyCode> codes = new ArrayList<>();
try (Statement statement = conn.createStatement();
ResultSet results = statement.executeQuery(sql)) {
while (results.next()) {
try {
String address = results.getString("address");
if (address == null) {
break;
}
GeographyCode code = new GeographyCode();
String level = results.getString("level");
GeographyCodeLevel levelCode = new GeographyCodeLevel(level);
code.setLevelCode(levelCode);
code.setLongitude(results.getDouble("longitude"));
code.setLatitude(results.getDouble("latitude"));
if (Languages.isChinese()) {
code.setChineseName(address);
} else {
code.setEnglishName(address);
}
code.setCountryName(results.getString("country"));
code.setProvinceName(results.getString("province"));
code.setCityName(results.getString("city"));
code.setCode2(results.getString("citycode"));
code.setCountyName(results.getString("district"));
code.setTownName(results.getString("township"));
code.setVillageName(results.getString("neighborhood"));
code.setBuildingName(results.getString("building"));
code.setCode1(results.getString("administrative_code"));
code.setComments(results.getString("street"));
codes.add(code);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
try (Statement statement = conn.createStatement()) {
statement.executeUpdate("DROP TABLE Geography_Code");
} catch (Exception e) {
MyBoxLog.debug(e);
}
TableGeographyCode tableGeographyCode = new TableGeographyCode();
tableGeographyCode.createTable(conn);
try (Statement statement = conn.createStatement()) {
statement.executeUpdate(TableGeographyCode.Create_Index_levelIndex);
statement.executeUpdate(TableGeographyCode.Create_Index_gcidIndex);
statement.executeUpdate(TableGeographyCode.Create_Index_codeIndex);
} catch (Exception e) {
MyBoxLog.debug(e);
}
GeographyCodeTools.importPredefined(null, conn);
try (PreparedStatement geoInsert = conn.prepareStatement(TableGeographyCode.Insert)) {
conn.setAutoCommit(false);
int count = 0;
for (GeographyCode code : codes) {
Map<String, Object> ret = GeographyCodeTools.encode(null, conn, geoInsert,
code.getLevel(), code.getLongitude(), code.getLatitude(), null,
code.getCountryName(), code.getProvinceName(), code.getCityName(),
code.getCountyName(), code.getTownName(), code.getVillageName(),
null, null, true, false);
if (ret != null && ret.get("code") != null) {
count++;
}
}
conn.commit();
MyBoxLog.debug("Migrated GeographyCode: " + count);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public static boolean migrateBefore621(Connection conn) {
MyBoxLog.info("Migrate before 6.2.1...");
try {
if (!SystemConfig.getBoolean("UpdatedTables4.2", false)) {
MyBoxLog.info("Updating tables in 4.2...");
List<ConvolutionKernel> records = TableConvolutionKernel.read();
TableConvolutionKernel t = new TableConvolutionKernel();
t.dropTable(conn);
t.createTable(conn);
if (TableConvolutionKernel.write(records)) {
SystemConfig.setBoolean("UpdatedTables4.2", true);
}
}
if (!SystemConfig.getBoolean("UpdatedTables5.4", false)) {
MyBoxLog.info("Updating tables in 5.4...");
String sql = "ALTER TABLE User_Conf alter column key_Name set data type VARCHAR(1024)";
DerbyBase.update(conn, sql);
sql = "ALTER TABLE User_Conf alter column default_string_Value set data type VARCHAR(32672)";
DerbyBase.update(conn, sql);
sql = "ALTER TABLE System_Conf alter column key_Name set data type VARCHAR(1024)";
DerbyBase.update(conn, sql);
sql = "ALTER TABLE System_Conf alter column string_Value set data type VARCHAR(32672)";
DerbyBase.update(conn, sql);
sql = "ALTER TABLE System_Conf alter column default_string_Value set data type VARCHAR(32672)";
DerbyBase.update(conn, sql);
sql = "ALTER TABLE image_history add column temp VARCHAR(128)";
DerbyBase.update(conn, sql);
sql = "UPDATE image_history SET temp=CHAR(update_type)";
DerbyBase.update(conn, sql);
sql = "ALTER TABLE image_history drop column update_type";
DerbyBase.update(conn, sql);
sql = "RENAME COLUMN image_history.temp TO update_type";
DerbyBase.update(conn, sql);
sql = "ALTER TABLE image_history add column object_type VARCHAR(128)";
DerbyBase.update(conn, sql);
sql = "ALTER TABLE image_history add column op_type VARCHAR(128)";
DerbyBase.update(conn, sql);
sql = "ALTER TABLE image_history add column scope_type VARCHAR(128)";
DerbyBase.update(conn, sql);
sql = "ALTER TABLE image_history add column scope_name VARCHAR(1024)";
DerbyBase.update(conn, sql);
sql = "DROP TABLE image_init";
DerbyBase.update(conn, sql);
SystemConfig.setBoolean("UpdatedTables5.4", true);
}
if (!SystemConfig.getBoolean("UpdatedTables5.8", false)) {
MyBoxLog.info("Updating tables in 5.8...");
String sql = "ALTER TABLE SRGB add column palette_index INT";
DerbyBase.update(conn, sql);
// List<String> saveColors = TableStringValues.read("ColorPalette");
// if (saveColors != null && !saveColors.isEmpty()) {
// TableColor.setPalette(saveColors);
// }
TableStringValues.clear("ColorPalette");
SystemConfig.setBoolean("UpdatedTables5.8", true);
}
if (!SystemConfig.getBoolean("UpdatedTables5.9", false)) {
MyBoxLog.info("Updating tables in 5.9...");
String sql = "DROP TABLE Browser_URLs";
DerbyBase.update(conn, sql);
SystemConfig.setBoolean("UpdatedTables5.9", true);
}
if (!SystemConfig.getBoolean("UpdatedTables6.1.5", false)) {
MyBoxLog.info("Updating tables in 6.1.5...");
migrateGeographyCode615();
SystemConfig.setBoolean("UpdatedTables6.1.5", true);
}
if (!SystemConfig.getBoolean("UpdatedTables6.2.1", false)) {
MyBoxLog.info("Updating tables in 6.2.1...");
migrateGeographyCode621();
SystemConfig.setBoolean("UpdatedTables6.2.1", true);
}
TableStringValues.add(conn, "InstalledVersions", "6.2.1");
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public static boolean migrateGeographyCode615() {
MyBoxLog.info("migrate GeographyCode 6.1.5...");
try (Connection conn = DerbyBase.getConnection();
Statement statement = conn.createStatement()) {
int size = DerbyBase.size("select count(*) from Geography_Code");
if (size <= 0) {
return true;
}
String sql = "UPDATE Geography_Code SET level='" + Languages.message("City")
+ "' WHERE level IS NULL";
statement.executeUpdate(sql);
return true;
} catch (Exception e) {
// MyBoxLog.debug(e);
return false;
}
}
public static boolean migrateGeographyCode621() {
MyBoxLog.info("migrate GeographyCode 6.2.1...");
try (Connection conn = DerbyBase.getConnection();
Statement statement = conn.createStatement()) {
String sql = "DELETE FROM Geography_Code "
+ " WHERE country='" + Languages.message("Macao")
+ "' OR country='" + Languages.message("Macau") + "'";
statement.executeUpdate(sql);
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/db/migration/TableInfoNode.java | alpha/MyBox/src/main/java/mara/mybox/db/migration/TableInfoNode.java | package mara.mybox.db.migration;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.db.DerbyBase;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.data.ColumnDefinition.ColumnType;
import static mara.mybox.db.migration.InfoNode.TitleSeparater;
import mara.mybox.db.table.BaseTable;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2021-4-23
* @License Apache License Version 2.0
*/
public class TableInfoNode extends BaseTable<InfoNode> {
public TableInfoNode() {
tableName = "Tree_Node";
defineColumns();
}
public TableInfoNode(boolean defineColumns) {
tableName = "Tree_Node";
if (defineColumns) {
defineColumns();
}
}
public final TableInfoNode defineColumns() {
addColumn(new ColumnDefinition("nodeid", ColumnType.Long, true, true).setAuto(true));
addColumn(new ColumnDefinition("category", ColumnType.String, true).setLength(StringMaxLength));
addColumn(new ColumnDefinition("title", ColumnType.String, true).setLength(StringMaxLength));
addColumn(new ColumnDefinition("info", ColumnType.Clob));
addColumn(new ColumnDefinition("update_time", ColumnType.Datetime));
addColumn(new ColumnDefinition("parentid", ColumnType.Long)
.setReferName("Tree_Node_parent_fk").setReferTable("Tree_Node").setReferColumn("nodeid")
.setOnDelete(ColumnDefinition.OnDelete.Cascade)
);
return this;
}
public static final String Create_Parent_Index
= "CREATE INDEX Tree_Node_parent_index on Tree_Node ( parentid )";
public static final String Create_Title_Index
= "CREATE INDEX Tree_Node_title_index on Tree_Node ( parentid, title )";
public static final String QueryID
= "SELECT * FROM Tree_Node WHERE nodeid=?";
public static final String QueryRoot
= "SELECT * FROM Tree_Node WHERE category=? AND nodeid=parentid ORDER BY nodeid ASC";
public static final String QueryChildren
= "SELECT * FROM Tree_Node WHERE parentid=? AND nodeid<>parentid ORDER BY nodeid ASC";
public static final String QueryLastChild
= "SELECT * FROM Tree_Node WHERE parentid=? AND title=? AND nodeid<>parentid ORDER BY nodeid DESC FETCH FIRST ROW ONLY";
public static final String DeleteID
= "DELETE FROM Tree_Node WHERE nodeid=?";
public static final String ChildrenCount
= "SELECT count(nodeid) FROM Tree_Node WHERE parentid=? AND nodeid<>parentid";
public static final String ChildrenEmpty
= "SELECT nodeid FROM Tree_Node WHERE parentid=? AND nodeid<>parentid FETCH FIRST ROW ONLY";
public static final String CategoryCount
= "SELECT count(nodeid) FROM Tree_Node WHERE category=? AND nodeid<>parentid";
public static final String CategoryEmpty
= "SELECT nodeid FROM Tree_Node WHERE category=? AND nodeid<>parentid FETCH FIRST ROW ONLY";
public static final String DeleteParent
= "DELETE FROM Tree_Node WHERE parentid=?";
public static final String DeleteChildren
= "DELETE FROM Tree_Node WHERE parentid=? AND nodeid<>parentid";
@Override
public boolean setValue(InfoNode data, String column, Object value) {
if (data == null || column == null) {
return false;
}
return data.setValue(column, value);
}
@Override
public Object getValue(InfoNode data, String column) {
if (data == null || column == null) {
return null;
}
return data.getValue(column);
}
@Override
public boolean valid(InfoNode data) {
if (data == null) {
return false;
}
return data.valid();
}
public InfoNode find(long id) {
if (id < 0) {
return null;
}
try (Connection conn = DerbyBase.getConnection()) {
return find(conn, id);
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public InfoNode find(Connection conn, long id) {
if (conn == null || id < 0) {
return null;
}
try (PreparedStatement statement = conn.prepareStatement(QueryID)) {
statement.setLong(1, id);
return query(conn, statement);
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public List<InfoNode> findRoots(String category) {
try (Connection conn = DerbyBase.getConnection()) {
return findRoots(conn, category);
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public List<InfoNode> findRoots(Connection conn, String category) {
if (conn == null || category == null) {
return null;
}
try (PreparedStatement statement = conn.prepareStatement(QueryRoot)) {
statement.setString(1, category);
return query(statement);
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public List<InfoNode> children(long parent) {
if (parent < 0) {
return null;
}
try (Connection conn = DerbyBase.getConnection()) {
return children(conn, parent);
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public List<InfoNode> children(Connection conn, long parent) {
if (conn == null || parent < 0) {
return null;
}
try (PreparedStatement statement = conn.prepareStatement(QueryChildren)) {
statement.setLong(1, parent);
return query(statement);
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public List<InfoNode> ancestor(long id) {
if (id <= 0) {
return null;
}
try (Connection conn = DerbyBase.getConnection()) {
return ancestor(conn, id);
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public List<InfoNode> ancestor(Connection conn, long id) {
if (conn == null || id <= 0) {
return null;
}
List<InfoNode> ancestor = null;
InfoNode node = find(conn, id);
if (node == null || node.isRoot()) {
return ancestor;
}
long parentid = node.getParentid();
InfoNode parent = find(conn, parentid);
if (parent != null) {
ancestor = ancestor(conn, parentid);
if (ancestor == null) {
ancestor = new ArrayList<>();
}
ancestor.add(parent);
}
return ancestor;
}
public InfoNode find(long parent, String title) {
if (title == null || title.isBlank()) {
return null;
}
try (Connection conn = DerbyBase.getConnection()) {
return find(conn, parent, title);
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public InfoNode find(Connection conn, long parent, String title) {
if (conn == null || title == null || title.isBlank()) {
return null;
}
try (PreparedStatement statement = conn.prepareStatement(QueryLastChild)) {
statement.setLong(1, parent);
statement.setString(2, title);
return query(conn, statement);
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public InfoNode findAndCreate(long parent, String title) {
if (title == null || title.isBlank()) {
return null;
}
try (Connection conn = DerbyBase.getConnection()) {
return findAndCreate(conn, parent, title);
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public InfoNode findAndCreate(Connection conn, long parent, String title) {
if (conn == null || title == null || title.isBlank()) {
return null;
}
try {
InfoNode node = find(conn, parent, title);
if (node == null) {
InfoNode parentNode = find(conn, parent);
node = new InfoNode(parentNode, title);
node = insertData(conn, node);
conn.commit();
}
return node;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public InfoNode checkBase(Connection conn) {
InfoNode base = find(conn, 1);
if (base == null) {
try {
String sql = "INSERT INTO Tree_Node (nodeid,title,parentid,category) VALUES(1,'base',1, 'Root')";
update(conn, sql);
conn.commit();
sql = "ALTER TABLE Tree_Node ALTER COLUMN nodeid RESTART WITH 2";
update(conn, sql);
conn.commit();
base = find(conn, 1);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
return base;
}
public InfoNode findAndCreateRoot(String category) {
try (Connection conn = DerbyBase.getConnection()) {
return findAndCreateRoot(conn, category);
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public InfoNode findAndCreateRoot(Connection conn, String category) {
List<InfoNode> roots = findAndCreateRoots(conn, category);
if (roots != null && !roots.isEmpty()) {
InfoNode root = roots.get(0);
root.setTitle(message(category));
return root;
} else {
return null;
}
}
public List<InfoNode> findAndCreateRoots(Connection conn, String category) {
if (conn == null) {
return null;
}
List<InfoNode> roots = findRoots(conn, category);
if (roots == null || roots.isEmpty()) {
try {
conn.setAutoCommit(true);
InfoNode base = checkBase(conn);
if (base == null) {
return null;
}
InfoNode root = InfoNode.create().setCategory(category)
.setTitle(message(category)).setParentid(base.getNodeid());
root = insertData(conn, root);
if (root == null) {
return null;
}
root.setParentid(root.getNodeid());
root = updateData(conn, root);
if (root == null) {
return null;
}
roots = new ArrayList<>();
roots.add(root);
} catch (Exception e) {
// MyBoxLog.debug(e);
}
}
return roots;
}
public InfoNode findAndCreateChain(Connection conn, InfoNode categoryRoot, String ownerChain) {
if (conn == null || categoryRoot == null || ownerChain == null || ownerChain.isBlank()) {
return null;
}
try {
long parentid = categoryRoot.getNodeid();
String chain = ownerChain;
if (chain.startsWith(categoryRoot.getTitle() + TitleSeparater)) {
chain = chain.substring((categoryRoot.getTitle() + TitleSeparater).length());
} else if (chain.startsWith(message(categoryRoot.getTitle()) + TitleSeparater)) {
chain = chain.substring((message(categoryRoot.getTitle()) + TitleSeparater).length());
}
String[] nodes = chain.split(TitleSeparater);
InfoNode owner = null;
for (String node : nodes) {
owner = findAndCreate(conn, parentid, node);
if (owner == null) {
return null;
}
parentid = owner.getNodeid();
}
return owner;
} catch (Exception e) {
MyBoxLog.console(e);
return null;
}
}
public List<InfoNode> decentants(Connection conn, long parentid) {
List<InfoNode> allChildren = new ArrayList<>();
List<InfoNode> children = children(conn, parentid);
if (children != null && !children.isEmpty()) {
allChildren.addAll(allChildren);
for (InfoNode child : children) {
children = decentants(conn, child.getNodeid());
if (children != null && !children.isEmpty()) {
allChildren.addAll(allChildren);
}
}
}
return allChildren;
}
public List<InfoNode> decentants(Connection conn, long parentid, long start, long size) {
List<InfoNode> children = new ArrayList<>();
try (PreparedStatement query = conn.prepareStatement(QueryChildren)) {
decentants(conn, query, parentid, start, size, children, 0);
} catch (Exception e) {
MyBoxLog.debug(e);
}
return children;
}
public long decentants(Connection conn, PreparedStatement query,
long parentid, long start, long size, List<InfoNode> nodes, long index) {
if (conn == null || parentid < 1 || nodes == null
|| query == null || start < 0 || size <= 0 || nodes.size() >= size) {
return index;
}
long thisIndex = index;
try {
int thisSize = nodes.size();
boolean ok = false;
query.setLong(1, parentid);
conn.setAutoCommit(true);
try (ResultSet nresults = query.executeQuery()) {
while (nresults.next()) {
InfoNode data = readData(nresults);
if (data != null) {
if (thisIndex >= start) {
nodes.add(data);
thisSize++;
}
thisIndex++;
if (thisSize >= size) {
ok = true;
break;
}
}
}
} catch (Exception e) {
MyBoxLog.debug(e, tableName);
}
if (!ok) {
List<InfoNode> children = children(conn, parentid);
if (children != null) {
for (InfoNode child : children) {
thisIndex = decentants(conn, query, child.getNodeid(), start, size, nodes, thisIndex);
if (nodes.size() >= size) {
break;
}
}
}
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
return thisIndex;
}
public int decentantsSize(Connection conn, long parentid) {
if (conn == null || parentid < 0) {
return 0;
}
int count = 0;
try (PreparedStatement sizeQuery = conn.prepareStatement(ChildrenCount)) {
count = decentantsSize(conn, sizeQuery, parentid);
} catch (Exception e) {
MyBoxLog.debug(e);
}
return count;
}
public int decentantsSize(Connection conn, PreparedStatement sizeQuery, long parentid) {
if (conn == null || sizeQuery == null || parentid < 0) {
return 0;
}
int count = 0;
try {
count = childrenSize(sizeQuery, parentid);
List<InfoNode> children = children(conn, parentid);
if (children != null) {
for (InfoNode child : children) {
count += decentantsSize(conn, sizeQuery, child.getNodeid());
}
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
return count;
}
public int childrenSize(PreparedStatement sizeQuery, long parent) {
if (sizeQuery == null || parent < 0) {
return 0;
}
int size = 0;
try {
sizeQuery.setLong(1, parent);
sizeQuery.getConnection().setAutoCommit(true);
try (ResultSet results = sizeQuery.executeQuery()) {
if (results != null && results.next()) {
size = results.getInt(1);
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
return size;
}
public int childrenSize(long parent) {
if (parent < 0) {
return 0;
}
try (Connection conn = DerbyBase.getConnection()) {
return childrenSize(conn, parent);
} catch (Exception e) {
MyBoxLog.debug(e);
return -1;
}
}
public int childrenSize(Connection conn, long parent) {
if (conn == null || parent < 0) {
return 0;
}
int size = 0;
try (PreparedStatement sizeQuery = conn.prepareStatement(ChildrenCount)) {
size = childrenSize(sizeQuery, parent);
} catch (Exception e) {
MyBoxLog.debug(e);
}
return size;
}
public boolean childrenEmpty(Connection conn, long parent) {
boolean isEmpty = true;
try (PreparedStatement statement = conn.prepareStatement(ChildrenEmpty)) {
statement.setLong(1, parent);
conn.setAutoCommit(true);
try (ResultSet results = statement.executeQuery()) {
isEmpty = results == null || !results.next();
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
return isEmpty;
}
public boolean equalOrDescendant(FxTask<Void> task, Connection conn, InfoNode node1, InfoNode node2) {
if (conn == null || node1 == null || node2 == null) {
if (task != null) {
task.setError(message("InvalidData"));
}
return false;
}
long id1 = node1.getNodeid();
long id2 = node2.getNodeid();
if (id1 == id2) {
return true;
}
InfoNode parent = parent(conn, node1);
if (parent == null || id1 == parent.getNodeid()) {
return false;
}
return equalOrDescendant(task, conn, parent(conn, node1), node2);
}
public InfoNode parent(Connection conn, InfoNode node) {
if (conn == null || node == null) {
return null;
}
return find(conn, node.getParentid());
}
public int categorySize(String category) {
try (Connection conn = DerbyBase.getConnection()) {
return categorySize(conn, category);
} catch (Exception e) {
MyBoxLog.debug(e);
return -1;
}
}
public int categorySize(Connection conn, String category) {
if (conn == null) {
return 0;
}
int size = 0;
try (PreparedStatement statement = conn.prepareStatement(CategoryCount)) {
statement.setString(1, category);
conn.setAutoCommit(true);
try (ResultSet results = statement.executeQuery()) {
if (results != null && results.next()) {
size = results.getInt(1);
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
return size;
}
public boolean categoryEmpty(Connection conn, String category) {
if (conn == null) {
return true;
}
boolean isEmpty = true;
try (PreparedStatement statement = conn.prepareStatement(CategoryEmpty)) {
statement.setString(1, category);
conn.setAutoCommit(true);
try (ResultSet results = statement.executeQuery()) {
isEmpty = results == null || !results.next();
} catch (Exception e) {
MyBoxLog.debug(e);
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
return isEmpty;
}
public int deleteChildren(long parent) {
try (Connection conn = DerbyBase.getConnection()) {
return deleteChildren(conn, parent);
} catch (Exception e) {
MyBoxLog.debug(e);
return -1;
}
}
public int deleteChildren(Connection conn, long parent) {
try (PreparedStatement statement = conn.prepareStatement(DeleteChildren)) {
statement.setLong(1, parent);
return statement.executeUpdate();
} catch (Exception e) {
MyBoxLog.debug(e);
return -1;
}
}
public String tagsCondition(List<Tag> tags) {
if (tags == null || tags.isEmpty()) {
return null;
}
String condition = " nodeid IN ( SELECT tnodeid FROM Tree_Node_Tag WHERE tagid IN ( " + tags.get(0).getTgid();
for (int i = 1; i < tags.size(); ++i) {
condition += ", " + tags.get(i).getTgid();
}
condition += " ) ) ";
return condition;
}
}
| 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/db/migration/DataMigration.java | alpha/MyBox/src/main/java/mara/mybox/db/migration/DataMigration.java | package mara.mybox.db.migration;
import java.io.File;
import java.sql.Connection;
import mara.mybox.controller.MyBoxLoadingController;
import mara.mybox.db.DerbyBase;
import mara.mybox.db.table.TableStringValues;
import mara.mybox.dev.DevTools;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.value.AppValues;
import mara.mybox.value.AppVariables;
import mara.mybox.value.SystemConfig;
/**
* @Author Mara
* @CreateDate 2020-06-09
* @License Apache License Version 2.0
*/
public class DataMigration {
public static boolean checkUpdates(MyBoxLoadingController controller, String lang) {
MyBoxLog.info("CurrentVersion: " + AppValues.AppVersion);
if (controller != null) {
controller.info("CurrentVersion: " + AppValues.AppVersion);
}
try (Connection conn = DerbyBase.getConnection()) {
SystemConfig.setString(conn, "CurrentVersion", AppValues.AppVersion);
int lastVersion = DevTools.lastVersion(conn);
int currentVersion = DevTools.myboxVersion(AppValues.AppVersion);
if (lastVersion != currentVersion
|| SystemConfig.getBoolean("IsAlpha", false) && !AppValues.Alpha) {
reloadInternalResources();
}
SystemConfig.setBoolean(conn, "IsAlpha", AppValues.Alpha);
if (lastVersion == currentVersion) {
return true;
}
MyBoxLog.info("Last version: " + lastVersion + " " + "Current version: " + currentVersion);
if (controller != null) {
controller.info("Last version: " + lastVersion + " " + "Current version: " + currentVersion);
}
if (lastVersion > 0) {
DataMigrationBefore65.handleVersions(lastVersion, conn);
DataMigrationFrom65to67.handleVersions(lastVersion, conn);
DataMigrationFrom68.handleVersions(controller, lastVersion, conn, lang);
}
TableStringValues.add(conn, "InstalledVersions", AppValues.AppVersion);
conn.setAutoCommit(true);
conn.commit();
} catch (Exception e) {
MyBoxLog.debug(e);
}
return true;
}
public static void reloadInternalResources() {
new Thread() {
@Override
public void run() {
try {
MyBoxLog.info("Refresh internal resources...");
File dir = new File(AppVariables.MyboxDataPath + File.separator + "doc");
File[] list = dir.listFiles();
if (list != null) {
for (File file : list) {
if (file.isDirectory()) {
continue;
}
file.delete();
// String name = file.getName().toLowerCase();
// if (name.contains("mybox") || name.contains("readme")) {
// file.delete();
// }
}
}
dir = new File(AppVariables.MyboxDataPath + File.separator + "image");
list = dir.listFiles();
if (list != null) {
for (File file : list) {
if (file.isDirectory()) {
continue;
}
file.delete();
// String name = file.getName();
// if (name.startsWith("icon") && name.endsWith(".png")) {
// file.delete();
// }
}
}
dir = new File(AppVariables.MyboxDataPath + File.separator + "data");
list = dir.listFiles();
if (list != null) {
for (File file : list) {
if (file.isDirectory()) {
continue;
}
file.delete();
// String name = file.getName();
// if (name.endsWith("_Examples_en.txt") && name.endsWith("_Examples_zh.txt")) {
// file.delete();
// }
}
}
dir = new File(AppVariables.MyboxDataPath + File.separator + "js");
list = dir.listFiles();
if (list != null) {
for (File file : list) {
if (file.isDirectory()) {
continue;
}
file.delete();
}
}
MyBoxLog.info("Internal resources refreshed.");
} catch (Exception e) {
MyBoxLog.console(e.toString());
}
}
}.start();
}
public static void alterColumnLength(Connection conn, String tableName, String colName, int length) {
String sql = "ALTER TABLE " + tableName + " alter column " + colName + " set data type VARCHAR(" + length + ")";
DerbyBase.update(conn, sql);
}
}
| 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/db/migration/OldColorMatchTools.java | alpha/MyBox/src/main/java/mara/mybox/db/migration/OldColorMatchTools.java | package mara.mybox.db.migration;
import java.awt.Color;
import mara.mybox.image.tools.ColorConvertTools;
/**
* @Author Mara
* @CreateDate 2018-6-4 16:07:27
* @License Apache License Version 2.0
*/
public class OldColorMatchTools {
// distanceSquare = Math.pow(distance, 2)
public static boolean isColorMatchSquare(Color color1, Color color2, int distanceSquare) {
if (color1 == null || color2 == null) {
return false;
}
if (color1.getRGB() == color2.getRGB()) {
return true;
} else if (distanceSquare == 0 || color1.getRGB() == 0 || color2.getRGB() == 0) {
return false;
}
return calculateColorDistanceSquare(color1, color2) <= distanceSquare;
}
// https://en.wikipedia.org/wiki/Color_difference
public static int calculateColorDistanceSquare(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Integer.MAX_VALUE;
}
int redDiff = color1.getRed() - color2.getRed();
int greenDiff = color1.getGreen() - color2.getGreen();
int blueDiff = color1.getBlue() - color2.getBlue();
return 2 * redDiff * redDiff + 4 * greenDiff * greenDiff + 3 * blueDiff * blueDiff;
}
// Generally not use this value. Use distance square instead.
public static int calculateColorDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Integer.MAX_VALUE;
}
int v = calculateColorDistanceSquare(color1, color2);
return (int) Math.round(Math.sqrt(v));
}
// https://www.compuphase.com/cmetric.htm
// public static int calculateColorDistance2(Color color1, Color color2) {
// int redDiff = color1.getRed() - color2.getRed();
// int greenDiff = color1.getGreen() - color2.getGreen();
// int blueDiff = color1.getBlue() - color2.getBlue();
// int redAvg = (color1.getRed() + color2.getRed()) / 2;
// return Math.round(((512 + redAvg) * redDiff * redDiff) >> 8
// + 4 * greenDiff * greenDiff
// + ((767 - redAvg) * blueDiff * blueDiff) >> 8);
// }
// distance: 0-255
public static boolean isRedMatch(Color color1, Color color2, int distance) {
if (color1 == null || color2 == null) {
return false;
}
return Math.abs(color1.getRed() - color2.getRed()) <= distance;
}
// distance: 0-255
public static boolean isGreenMatch(Color color1, Color color2, int distance) {
if (color1 == null || color2 == null) {
return false;
}
return Math.abs(color1.getGreen() - color2.getGreen()) <= distance;
}
// distance: 0-255
public static boolean isBlueMatch(Color color1, Color color2, int distance) {
if (color1 == null || color2 == null) {
return false;
}
return Math.abs(color1.getBlue() - color2.getBlue()) <= distance;
}
// distance: 0.0-1.0
public static boolean isHueMatch(Color color1, Color color2, float distance) {
if (color1 == null || color2 == null) {
return false;
}
return Math.abs(ColorConvertTools.getHue(color1) - ColorConvertTools.getHue(color2)) <= distance;
}
// distance: 0.0-1.0
public static boolean isSaturationMatch(Color color1, Color color2, float distance) {
if (color1 == null || color2 == null) {
return false;
}
return Math.abs(ColorConvertTools.getSaturation(color1) - ColorConvertTools.getSaturation(color2)) <= distance;
}
// distance: 0.0-1.0
public static boolean isBrightnessMatch(Color color1, Color color2, float distance) {
if (color1 == null || color2 == null) {
return false;
}
return Math.abs(ColorConvertTools.getBrightness(color1) - ColorConvertTools.getBrightness(color2)) <= distance;
}
}
| 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/db/migration/GeographyCodeLevel.java | alpha/MyBox/src/main/java/mara/mybox/db/migration/GeographyCodeLevel.java | package mara.mybox.db.migration;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2020-3-21
* @License Apache License Version 2.0
*/
public class GeographyCodeLevel implements Cloneable {
private static List<GeographyCodeLevel> Levels;
protected short level;
protected String chineseName, englishName, name, key;
public GeographyCodeLevel() {
level = 10;
}
public GeographyCodeLevel(short value) {
level = value > 10 || value < 1 ? 10 : value;
switch (level) {
case 1:
chineseName = "全球";
englishName = "Global";
break;
case 2:
chineseName = "洲";
englishName = "Continent";
break;
case 3:
chineseName = "国家";
englishName = "Country";
break;
case 4:
chineseName = "省";
englishName = "Province";
break;
case 5:
chineseName = "市";
englishName = "City";
break;
case 6:
chineseName = "县";
englishName = "County";
break;
case 7:
chineseName = "镇";
englishName = "Town";
break;
case 8:
chineseName = "村";
englishName = "Village";
break;
case 9:
chineseName = "建筑";
englishName = "Building";
break;
default:
case 10:
chineseName = "兴趣点";
englishName = "Point Of Interest";
break;
}
key = getKey(level);
}
public GeographyCodeLevel(String name) {
switch (name) {
case "全球":
englishName = "Global";
chineseName = name;
level = 1;
break;
case "Global":
englishName = name;
chineseName = "全球";
level = 1;
break;
case "洲":
englishName = "Continent";
chineseName = name;
level = 2;
break;
case "Continent":
englishName = name;
chineseName = "洲";
level = 2;
break;
case "国家":
englishName = "Country";
chineseName = name;
level = 3;
break;
case "Country":
englishName = name;
chineseName = "国家";
level = 3;
break;
case "省":
englishName = "Province";
chineseName = name;
level = 4;
break;
case "Province":
englishName = name;
chineseName = "省";
level = 4;
break;
case "市":
englishName = "City";
chineseName = name;
level = 5;
break;
case "City":
englishName = name;
chineseName = "市";
level = 5;
break;
case "县":
englishName = "County";
chineseName = name;
level = 6;
break;
case "County":
englishName = name;
chineseName = "县";
level = 6;
break;
case "镇":
englishName = "Town";
chineseName = name;
level = 7;
break;
case "Town":
englishName = name;
chineseName = "镇";
level = 7;
break;
case "村":
englishName = "Village";
chineseName = name;
level = 8;
break;
case "Village":
englishName = name;
chineseName = "村";
level = 8;
break;
case "建筑":
englishName = "Building";
chineseName = name;
level = 9;
break;
case "Building":
englishName = name;
chineseName = "建筑";
level = 9;
break;
case "兴趣点":
englishName = "Point Of Interest";
chineseName = name;
level = 10;
break;
case "Point Of Interest":
default:
englishName = name;
chineseName = "兴趣点";
level = 10;
break;
}
key = getKey(level);
}
@Override
public Object clone() throws CloneNotSupportedException {
try {
return super.clone();
} catch (Exception e) {
return null;
}
}
public static GeographyCodeLevel create(short value, String chineseName, String englishName) {
GeographyCodeLevel level = new GeographyCodeLevel();
level.setLevel(value);
level.setChineseName(chineseName);
level.setEnglishName(englishName);
level.getKey();
return level;
}
public static List<GeographyCodeLevel> levels() {
if (Levels != null) {
return Levels;
}
Levels = new ArrayList<>();
Levels.add(new GeographyCodeLevel((short) 1));
Levels.add(new GeographyCodeLevel((short) 2));
Levels.add(new GeographyCodeLevel((short) 3));
Levels.add(new GeographyCodeLevel((short) 4));
Levels.add(new GeographyCodeLevel((short) 5));
Levels.add(new GeographyCodeLevel((short) 6));
Levels.add(new GeographyCodeLevel((short) 7));
Levels.add(new GeographyCodeLevel((short) 8));
Levels.add(new GeographyCodeLevel((short) 9));
Levels.add(new GeographyCodeLevel((short) 10));
return Levels;
}
public static int level(String name) {
GeographyCodeLevel geolevel = new GeographyCodeLevel(name);
return geolevel.level;
}
public static String name(short level) {
GeographyCodeLevel geolevel = new GeographyCodeLevel(level);
return geolevel.getName();
}
public static String getKey(int level) {
String key;
switch (level) {
case 1:
key = null;
break;
case 2:
key = "continent";
break;
case 3:
key = "country";
break;
case 4:
key = "province";
break;
case 5:
key = "city";
break;
case 6:
key = "county";
break;
case 7:
key = "town";
break;
case 8:
key = "village";
break;
case 9:
key = "building";
break;
default:
key = "gcid";
break;
}
return key;
}
public static String messageNames() {
Levels = levels();
String s = "";
for (GeographyCodeLevel item : Levels) {
if (!s.isBlank()) {
s += "\n";
}
s += item.getName();
}
return s;
}
/*
customzied get/set
*/
public String getKey() {
key = getKey(level);
return key;
}
public short getLevel() {
level = level > 10 || level < 1 ? 10 : level;
return level;
}
public String getName() {
return Languages.isChinese() ? chineseName : englishName;
}
/*
get/set
*/
public void setLevel(short level) {
this.level = level;
}
public String getChineseName() {
return chineseName;
}
public void setChineseName(String chineseName) {
this.chineseName = chineseName;
}
public String getEnglishName() {
return englishName;
}
public void setEnglishName(String englishName) {
this.englishName = englishName;
}
public void setName(String name) {
this.name = name;
}
public static List<GeographyCodeLevel> getLevels() {
return Levels;
}
public static void setLevels(List<GeographyCodeLevel> Levels) {
GeographyCodeLevel.Levels = Levels;
}
public void setKey(String key) {
this.key = key;
}
}
| 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.