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/db/migration/OldImageScopeTools.java
alpha/MyBox/src/main/java/mara/mybox/db/migration/OldImageScopeTools.java
package mara.mybox.db.migration; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; import mara.mybox.controller.BaseController; import mara.mybox.data.DoubleCircle; import mara.mybox.data.DoubleEllipse; import mara.mybox.data.DoublePolygon; import mara.mybox.data.DoubleRectangle; import mara.mybox.data.DoubleShape; import mara.mybox.data.IntPoint; import mara.mybox.db.data.DataNode; import mara.mybox.db.migration.OldImageScope.ColorScopeType; import mara.mybox.db.migration.OldImageScope.ScopeType; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.image.file.ImageFileReaders; import mara.mybox.image.file.ImageFileWriters; import mara.mybox.tools.DateTools; import mara.mybox.tools.JsonTools; import mara.mybox.tools.StringTools; import mara.mybox.tools.XmlTools; import static mara.mybox.tools.XmlTools.cdata; import mara.mybox.value.AppPaths; import mara.mybox.value.AppValues; import static mara.mybox.value.Languages.message; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * @Author Mara * @CreateDate 2018-8-1 16:22:41 * @License Apache License Version 2.0 */ public class OldImageScopeTools { public static OldImageScope.ScopeType scopeType(String type) { if (type == null) { return null; } if ("Matting".equalsIgnoreCase(type)) { return OldImageScope.ScopeType.Matting; } if ("Rectangle".equalsIgnoreCase(type) || "RectangleColor".equalsIgnoreCase(type)) { return OldImageScope.ScopeType.Rectangle; } if ("Circle".equalsIgnoreCase(type) || "CircleColor".equalsIgnoreCase(type)) { return OldImageScope.ScopeType.Circle; } if ("Ellipse".equalsIgnoreCase(type) || "EllipseColor".equalsIgnoreCase(type)) { return OldImageScope.ScopeType.Ellipse; } if ("Polygon".equalsIgnoreCase(type) || "PolygonColor".equalsIgnoreCase(type)) { return OldImageScope.ScopeType.Polygon; } if ("Color".equalsIgnoreCase(type)) { return OldImageScope.ScopeType.Colors; } if ("Outline".equalsIgnoreCase(type)) { return OldImageScope.ScopeType.Outline; } return null; } public static void cloneValues(OldImageScope targetScope, OldImageScope sourceScope) { try { targetScope.setFile(sourceScope.getFile()); targetScope.setName(sourceScope.getName()); targetScope.setAreaData(sourceScope.getAreaData()); targetScope.setColorData(sourceScope.getColorData()); targetScope.setOutlineName(sourceScope.getOutlineName()); List<IntPoint> npoints = new ArrayList<>(); if (sourceScope.getPoints() != null) { npoints.addAll(sourceScope.getPoints()); } targetScope.setPoints(npoints); List<Color> ncolors = new ArrayList<>(); if (sourceScope.getColors() != null) { ncolors.addAll(sourceScope.getColors()); } targetScope.setColors(ncolors); targetScope.setRectangle(sourceScope.getRectangle() != null ? sourceScope.getRectangle().copy() : null); targetScope.setCircle(sourceScope.getCircle() != null ? sourceScope.getCircle().copy() : null); targetScope.setEllipse(sourceScope.getEllipse() != null ? sourceScope.getEllipse().copy() : null); targetScope.setPolygon(sourceScope.getPolygon() != null ? sourceScope.getPolygon().copy() : null); targetScope.setColorDistance(sourceScope.getColorDistance()); targetScope.setColorDistanceSquare(sourceScope.getColorDistanceSquare()); targetScope.setHsbDistance(sourceScope.getHsbDistance()); targetScope.setColorExcluded(sourceScope.isColorExcluded()); targetScope.setDistanceSquareRoot(sourceScope.isDistanceSquareRoot()); targetScope.setAreaExcluded(sourceScope.isAreaExcluded()); targetScope.setMaskOpacity(sourceScope.getMaskOpacity()); targetScope.setCreateTime(sourceScope.getCreateTime()); targetScope.setModifyTime(sourceScope.getModifyTime()); targetScope.setOutlineSource(sourceScope.getOutlineSource()); targetScope.setOutline(sourceScope.getOutline()); targetScope.setEightNeighbor(sourceScope.isEightNeighbor()); targetScope.setClip(sourceScope.getClip()); targetScope.setMaskColor(sourceScope.getMaskColor()); targetScope.setMaskOpacity(sourceScope.getMaskOpacity()); } catch (Exception e) { // MyBoxLog.debug(e); } } public static OldImageScope cloneAll(OldImageScope sourceScope) { OldImageScope targetScope = new OldImageScope(); OldImageScopeTools.cloneAll(targetScope, sourceScope); return targetScope; } public static void cloneAll(OldImageScope targetScope, OldImageScope sourceScope) { try { targetScope.setImage(sourceScope.getImage()); targetScope.setScopeType(sourceScope.getScopeType()); targetScope.setColorScopeType(sourceScope.getColorScopeType()); cloneValues(targetScope, sourceScope); } catch (Exception e) { } } public static boolean inShape(DoubleShape shape, boolean areaExcluded, int x, int y) { if (areaExcluded) { return !DoubleShape.contains(shape, x, y); } else { return DoubleShape.contains(shape, x, y); } } public static boolean isColorMatchSquare(List<Color> colors, boolean colorExcluded, int colorDistanceSqure, Color color) { if (colors == null || colors.isEmpty()) { return true; } if (colorExcluded) { for (Color oColor : colors) { if (OldColorMatchTools.isColorMatchSquare(color, oColor, colorDistanceSqure)) { return false; } } return true; } else { for (Color oColor : colors) { if (OldColorMatchTools.isColorMatchSquare(color, oColor, colorDistanceSqure)) { return true; } } return false; } } public static boolean isRedMatch(List<Color> colors, boolean colorExcluded, int colorDistance, Color color) { if (colors == null || colors.isEmpty()) { return true; } if (colorExcluded) { for (Color oColor : colors) { if (OldColorMatchTools.isRedMatch(color, oColor, colorDistance)) { return false; } } return true; } else { for (Color oColor : colors) { if (OldColorMatchTools.isRedMatch(color, oColor, colorDistance)) { return true; } } return false; } } public static boolean isGreenMatch(List<Color> colors, boolean colorExcluded, int colorDistance, Color color) { if (colors == null || colors.isEmpty()) { return true; } if (colorExcluded) { for (Color oColor : colors) { if (OldColorMatchTools.isGreenMatch(color, oColor, colorDistance)) { return false; } } return true; } else { for (Color oColor : colors) { if (OldColorMatchTools.isGreenMatch(color, oColor, colorDistance)) { return true; } } return false; } } public static boolean isBlueMatch(List<Color> colors, boolean colorExcluded, int colorDistance, Color color) { if (colors == null || colors.isEmpty()) { return true; } if (colorExcluded) { for (Color oColor : colors) { if (OldColorMatchTools.isBlueMatch(color, oColor, colorDistance)) { return false; } } return true; } else { for (Color oColor : colors) { if (OldColorMatchTools.isBlueMatch(color, oColor, colorDistance)) { return true; } } return false; } } public static boolean isHueMatch(List<Color> colors, boolean colorExcluded, float hsbDistance, Color color) { if (colors == null || colors.isEmpty()) { return true; } if (colorExcluded) { for (Color oColor : colors) { if (OldColorMatchTools.isHueMatch(color, oColor, hsbDistance)) { return false; } } return true; } else { for (Color oColor : colors) { if (OldColorMatchTools.isHueMatch(color, oColor, hsbDistance)) { return true; } } return false; } } public static boolean isSaturationMatch(List<Color> colors, boolean colorExcluded, float hsbDistance, Color color) { if (colors == null || colors.isEmpty()) { return true; } if (colorExcluded) { for (Color oColor : colors) { if (OldColorMatchTools.isSaturationMatch(color, oColor, hsbDistance)) { return false; } } return true; } else { for (Color oColor : colors) { if (OldColorMatchTools.isSaturationMatch(color, oColor, hsbDistance)) { return true; } } return false; } } public static boolean isBrightnessMatch(List<Color> colors, boolean colorExcluded, float hsbDistance, Color color) { if (colors == null || colors.isEmpty()) { return true; } if (colorExcluded) { for (Color oColor : colors) { if (OldColorMatchTools.isBrightnessMatch(color, oColor, hsbDistance)) { return false; } } return true; } else { for (Color oColor : colors) { if (OldColorMatchTools.isBrightnessMatch(color, oColor, hsbDistance)) { return true; } } return false; } } /* make scope from */ public static OldImageScope fromDataNode(FxTask task, BaseController controller, DataNode node) { try { if (node == null) { return null; } OldImageScope scope = new OldImageScope(); scope.setName(node.getTitle()); scope.setScopeType(OldImageScopeTools.scopeType(node.getStringValue("scope_type"))); scope.setColorScopeType(OldImageScope.ColorScopeType.valueOf(node.getStringValue("color_type"))); scope.setAreaData(node.getStringValue("area_data")); scope.setColorData(node.getStringValue("color_data")); scope.setColorDistance(node.getIntValue("color_data")); scope.setAreaExcluded(node.getBooleanValue("area_excluded")); scope.setColorExcluded(node.getBooleanValue("color_excluded")); scope.setFile(node.getStringValue("background_file")); scope.setOutlineName(node.getStringValue("outline_file")); if (task != null && !task.isWorking()) { return null; } decodeColorData(scope); decodeAreaData(scope); decodeOutline(task, scope); return scope; } catch (Exception e) { // MyBoxLog.error(e); return null; } } public static OldImageScope fromXML(FxTask task, BaseController controller, String s) { try { if (s == null || s.isBlank()) { return null; } Element e = XmlTools.toElement(task, controller, s); if (e == null || (task != null && !task.isWorking())) { return null; } String tag = e.getTagName(); if (!XmlTools.matchXmlTag("ImageScope", tag)) { return null; } NodeList children = e.getChildNodes(); if (children == null) { return null; } OldImageScope scope = new OldImageScope(); for (int dIndex = 0; dIndex < children.getLength(); dIndex++) { if (task != null && !task.isWorking()) { return null; } Node child = children.item(dIndex); if (!(child instanceof Element)) { continue; } tag = child.getNodeName(); if (tag == null || tag.isBlank()) { continue; } if (XmlTools.matchXmlTag("Background", tag)) { scope.setFile(cdata(child)); } else if (XmlTools.matchXmlTag("Name", tag)) { scope.setName(cdata(child)); } else if (XmlTools.matchXmlTag("Outline", tag)) { scope.setOutlineName(cdata(child)); } else { String value = child.getTextContent(); if (value == null || value.isBlank()) { continue; } if (XmlTools.matchXmlTag("ScopeType", tag)) { scope.setScopeType(OldImageScopeTools.scopeType(value)); } else if (XmlTools.matchXmlTag("ScopeColorType", tag)) { scope.setColorScopeType(OldImageScope.ColorScopeType.valueOf(value)); } else if (XmlTools.matchXmlTag("Area", tag)) { scope.setAreaData(value); } else if (XmlTools.matchXmlTag("Colors", tag)) { scope.setColorData(value); } else if (XmlTools.matchXmlTag("ColorDistance", tag)) { try { scope.setColorDistance(Integer.parseInt(value)); } catch (Exception ex) { } } else if (XmlTools.matchXmlTag("AreaExcluded", tag)) { scope.setAreaExcluded(StringTools.isTrue(value)); } else if (XmlTools.matchXmlTag("ColorExcluded", tag)) { scope.setColorExcluded(StringTools.isTrue(value)); } else if (XmlTools.matchXmlTag("CreateTime", tag)) { scope.setCreateTime(DateTools.encodeDate(value)); } else if (XmlTools.matchXmlTag("ModifyTime", tag)) { scope.setModifyTime(DateTools.encodeDate(value)); } } } decodeColorData(scope); decodeAreaData(scope); decodeOutline(task, scope); return scope; } catch (Exception e) { MyBoxLog.error(e); return null; } } /* convert scope to */ public static DataNode toDataNode(DataNode inNode, OldImageScope scope) { try { if (scope == null) { return null; } ScopeType type = scope.getScopeType(); if (type == null) { return null; } DataNode node = inNode; if (node == null) { node = DataNode.create(); } node.setValue("scope_type", type.name()); node.setValue("color_type", scope.getColorScopeType().name()); node.setValue("area_data", OldImageScopeTools.encodeAreaData(scope)); node.setValue("area_excluded", scope.isAreaExcluded()); node.setValue("color_data", OldImageScopeTools.encodeColorData(scope)); node.setValue("color_excluded", scope.isColorExcluded()); node.setValue("color_distance", scope.getColorDistance()); node.setValue("background_file", scope.getFile()); node.setValue("outline_file", OldImageScopeTools.encodeOutline(null, scope)); return node; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String toXML(OldImageScope scope, String inPrefix) { try { if (scope == null || scope.getScopeType() == null) { return null; } ScopeType type = scope.getScopeType(); if (type == null) { return null; } String prefix = inPrefix + AppValues.Indent; StringBuilder s = new StringBuilder(); s.append(prefix).append("<").append(XmlTools.xmlTag("ImageScope")).append(">\n"); s.append(prefix).append("<").append(XmlTools.xmlTag("ScopeType")).append(">") .append(type) .append("</").append(XmlTools.xmlTag("ScopeType")).append(">\n"); String v = scope.getFile(); if (v != null && !v.isBlank()) { s.append(prefix).append("<").append(XmlTools.xmlTag("Background")).append(">") .append("<![CDATA[").append(v).append("]]>") .append("</").append(XmlTools.xmlTag("Background")).append(">\n"); } v = scope.getName(); if (v != null && !v.isBlank()) { s.append(prefix).append("<").append(XmlTools.xmlTag("Name")).append(">") .append("<![CDATA[").append(v).append("]]>") .append("</").append(XmlTools.xmlTag("Name")).append(">\n"); } v = OldImageScopeTools.encodeOutline(null, scope); if (v != null && !v.isBlank()) { s.append(prefix).append("<").append(XmlTools.xmlTag("Outline")).append(">") .append("<![CDATA[").append(v).append("]]>") .append("</").append(XmlTools.xmlTag("Outline")).append(">\n"); } ColorScopeType ctype = scope.getColorScopeType(); if (ctype != null) { s.append(prefix).append("<").append(XmlTools.xmlTag("ScopeColorType")).append(">") .append(ctype) .append("</").append(XmlTools.xmlTag("ScopeColorType")).append(">\n"); } v = OldImageScopeTools.encodeAreaData(scope); if (v != null && !v.isBlank()) { s.append(prefix).append("<").append(XmlTools.xmlTag("Area")).append(">") .append("<![CDATA[").append(v).append("]]>") .append("</").append(XmlTools.xmlTag("Area")).append(">\n"); } v = OldImageScopeTools.encodeColorData(scope); if (v != null && !v.isBlank()) { s.append(prefix).append("<").append(XmlTools.xmlTag("Colors")).append(">") .append("<![CDATA[").append(v).append("]]>") .append("</").append(XmlTools.xmlTag("Colors")).append(">\n"); } if (scope.getColorDistance() > 0) { s.append(prefix).append("<").append(XmlTools.xmlTag("ColorDistance")).append(">") .append(scope.getColorDistance()) .append("</").append(XmlTools.xmlTag("ColorDistance")).append(">\n"); } s.append(prefix).append("<").append(XmlTools.xmlTag("AreaExcluded")).append(">") .append(scope.isAreaExcluded() ? "true" : "false") .append("</").append(XmlTools.xmlTag("AreaExcluded")).append(">\n"); s.append(prefix).append("<").append(XmlTools.xmlTag("ColorExcluded")).append(">") .append(scope.isColorExcluded() ? "true" : "false") .append("</").append(XmlTools.xmlTag("ColorExcluded")).append(">\n"); s.append(prefix).append("<").append(XmlTools.xmlTag("CreateTime")).append(">") .append(DateTools.dateToString(scope.getCreateTime())) .append("</").append(XmlTools.xmlTag("CreateTime")).append(">\n"); s.append(prefix).append("<").append(XmlTools.xmlTag("ModifyTime")).append(">") .append(DateTools.dateToString(scope.getModifyTime())) .append("</").append(XmlTools.xmlTag("ModifyTime")).append(">\n"); s.append(prefix).append("</").append(XmlTools.xmlTag("ImageScope")).append(">\n"); return s.toString(); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String toJSON(OldImageScope scope, String inPrefix) { try { if (scope == null || scope.getScopeType() == null) { return null; } ScopeType type = scope.getScopeType(); if (type == null) { return null; } String prefix = inPrefix + AppValues.Indent; StringBuilder s = new StringBuilder(); s.append(inPrefix).append("\"").append(message("ImageScope")).append("\": {\n"); s.append(prefix).append("\"").append(message("ScopeType")).append("\": ") .append(JsonTools.encode(type.name())).append(",\n"); String v = scope.getFile(); if (v != null && !v.isBlank()) { s.append(prefix).append("\"").append(message("Background")).append("\": ") .append(JsonTools.encode(v)).append(",\n"); } v = scope.getName(); if (v != null && !v.isBlank()) { s.append(prefix).append("\"").append(message("Name")).append("\": ") .append(JsonTools.encode(v)).append(",\n"); } v = OldImageScopeTools.encodeOutline(null, scope); if (v != null && !v.isBlank()) { s.append(prefix).append("\"").append(message("Outline")).append("\": ") .append(JsonTools.encode(v)).append(",\n"); } ColorScopeType ctype = scope.getColorScopeType(); if (ctype != null) { s.append(prefix).append("\"").append(message("ScopeColorType")).append("\": ") .append(JsonTools.encode(ctype.name())).append(",\n"); } v = OldImageScopeTools.encodeAreaData(scope); if (v != null && !v.isBlank()) { s.append(prefix).append("\"").append(message("Area")).append("\": ") .append(JsonTools.encode(v)).append(",\n"); } v = OldImageScopeTools.encodeColorData(scope); if (v != null && !v.isBlank()) { s.append(prefix).append("\"").append(message("Colors")).append("\": ") .append(JsonTools.encode(v)).append(",\n"); } if (scope.getColorDistance() > 0) { s.append(prefix).append("\"").append(message("ColorDistance")).append("\": ") .append(scope.getColorDistance()).append(",\n"); } s.append(prefix).append("\"").append(message("AreaExcluded")).append("\": ") .append(scope.isAreaExcluded() ? "true" : "false").append(",\n"); s.append(prefix).append("\"").append(message("ColorExcluded")).append("\": ") .append(scope.isColorExcluded() ? "true" : "false").append(",\n"); s.append(prefix).append("\"").append(message("CreateTime")).append("\": ") .append(JsonTools.encode(DateTools.dateToString(scope.getCreateTime()))).append(",\n"); s.append(prefix).append("\"").append(message("ModifyTime")).append("\": ") .append(JsonTools.encode(DateTools.dateToString(scope.getModifyTime()))).append("\n"); s.append(inPrefix).append("}\n"); return s.toString(); } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } /* extract value from scope */ public static boolean decodeColorData(OldImageScope scope) { if (scope == null || scope.getScopeType() == null) { return false; } return decodeColorData(scope.getScopeType(), scope.getColorData(), scope); } public static boolean decodeColorData(OldImageScope.ScopeType type, String colorData, OldImageScope scope) { if (type == null || colorData == null || scope == null) { return false; } try { switch (type) { case Colors: case Rectangle: case Circle: case Ellipse: case Polygon: { List<Color> colors = new ArrayList<>(); if (!colorData.isBlank()) { String[] items = colorData.split(OldImageScope.ValueSeparator); for (String item : items) { try { colors.add(new Color(Integer.parseInt(item), true)); } catch (Exception e) { MyBoxLog.error(e); } } } scope.setColors(colors); scope.setColorData(colorData); } } return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean decodeOutline(FxTask task, OldImageScope scope) { if (scope == null || scope.getScopeType() == null) { return false; } return decodeOutline(task, scope.getScopeType(), scope.getOutlineName(), scope); } public static boolean decodeOutline(FxTask task, OldImageScope.ScopeType type, String outline, OldImageScope scope) { if (type == null || outline == null || scope == null) { return false; } if (type != OldImageScope.ScopeType.Outline) { return true; } try { scope.setOutlineName(outline); BufferedImage image = ImageFileReaders.readImage(task, new File(outline)); if (task != null && !task.isWorking()) { return false; } scope.setOutlineSource(image); return image != null; } catch (Exception e) { MyBoxLog.error(e); // MyBoxLog.debug(e); return false; } } public static String encodeColorData(OldImageScope scope) { if (scope == null || scope.getScopeType() == null) { return ""; } String s = ""; try { switch (scope.getScopeType()) { case Colors: case Rectangle: case Circle: case Ellipse: case Polygon: List<Color> colors = scope.getColors(); if (colors != null) { for (Color color : colors) { s += color.getRGB() + OldImageScope.ValueSeparator; } if (s.endsWith(OldImageScope.ValueSeparator)) { s = s.substring(0, s.length() - OldImageScope.ValueSeparator.length()); } } } scope.setColorData(s); } catch (Exception e) { MyBoxLog.error(e); s = ""; } return s; } public static String encodeAreaData(OldImageScope scope) { if (scope == null || scope.getScopeType() == null) { return ""; } String s = ""; try { switch (scope.getScopeType()) { case Matting: { List<IntPoint> points = scope.getPoints(); if (points != null) { for (IntPoint p : points) { s += p.getX() + OldImageScope.ValueSeparator + p.getY() + OldImageScope.ValueSeparator; } if (s.endsWith(OldImageScope.ValueSeparator)) { s = s.substring(0, s.length() - OldImageScope.ValueSeparator.length()); } } } break; case Rectangle: case Outline: DoubleRectangle rect = scope.getRectangle(); if (rect != null) { s = (int) rect.getX() + OldImageScope.ValueSeparator + (int) rect.getY() + OldImageScope.ValueSeparator + (int) rect.getMaxX() + OldImageScope.ValueSeparator + (int) rect.getMaxY(); } break; case Circle: DoubleCircle circle = scope.getCircle(); if (circle != null) { s = (int) circle.getCenterX() + OldImageScope.ValueSeparator + (int) circle.getCenterY() + OldImageScope.ValueSeparator + (int) circle.getRadius(); } break; case Ellipse: DoubleEllipse ellipse = scope.getEllipse(); if (ellipse != null) { s = (int) ellipse.getX() + OldImageScope.ValueSeparator + (int) ellipse.getY() + OldImageScope.ValueSeparator + (int) ellipse.getMaxX() + OldImageScope.ValueSeparator + (int) ellipse.getMaxY(); } break; case Polygon: DoublePolygon polygon = scope.getPolygon(); if (polygon != null) { for (Double d : polygon.getData()) { s += Math.round(d) + OldImageScope.ValueSeparator; } if (s.endsWith(OldImageScope.ValueSeparator)) { s = s.substring(0, s.length() - OldImageScope.ValueSeparator.length()); } } break; } scope.setAreaData(s); } catch (Exception e) { MyBoxLog.error(e); s = ""; } return s; } public static boolean decodeAreaData(OldImageScope scope) { if (scope == null || scope.getScopeType() == null) { return false; } return decodeAreaData(scope.getScopeType(), scope.getAreaData(), scope); } public static boolean decodeAreaData(OldImageScope.ScopeType type, String areaData, OldImageScope scope) { if (type == null || areaData == null || scope == null) { return false; } try { switch (type) { case Matting: { String[] items = areaData.split(OldImageScope.ValueSeparator); for (int i = 0; i < items.length / 2; ++i) { int x = (int) Double.parseDouble(items[i * 2]); int y = (int) Double.parseDouble(items[i * 2 + 1]); scope.addPoint(x, y); } } break; case Rectangle: case Outline: { String[] items = areaData.split(OldImageScope.ValueSeparator); if (items.length == 4) { DoubleRectangle rect = DoubleRectangle.xy12(Double.parseDouble(items[0]), Double.parseDouble(items[1]), Double.parseDouble(items[2]), Double.parseDouble(items[3])); scope.setRectangle(rect); } else { return false; } } break; case Circle: { String[] items = areaData.split(OldImageScope.ValueSeparator); if (items.length == 3) {
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/GeographyCode.java
alpha/MyBox/src/main/java/mara/mybox/db/migration/GeographyCode.java
package mara.mybox.db.migration; import mara.mybox.db.data.*; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.AppValues; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2020-1-20 * @License Apache License Version 2.0 */ public class GeographyCode extends BaseData { protected long gcid, owner, continent, country, province, city, county, town, village, building, area, population; protected short level; protected GeographyCodeLevel levelCode; protected String name, fullName, chineseName, englishName, levelName, code1, code2, code3, code4, code5, alias1, alias2, alias3, alias4, alias5, comments, continentName, countryName, provinceName, cityName, countyName, townName, villageName, buildingName, poiName, label, info, sourceName; protected double longitude, latitude, altitude, precision; protected GeographyCode ownerCode, continentCode, countryCode, provinceCode, cityCode, countyCode, townCode, villageCode, buildingCode; protected GeoCoordinateSystem coordinateSystem; protected AddressSource source; protected int markSize; public static enum AddressLevel { Global, Continent, Country, Province, City, County, Town, Village, Building, InterestOfLocation } public static enum AddressSource { PredefinedData, InputtedData, Geonames, ImportedData, Unknown } public GeographyCode() { gcid = continent = country = province = city = county = village = town = building = area = population = -1; level = 10; levelCode = null; source = AddressSource.InputtedData; longitude = latitude = -200; altitude = precision = AppValues.InvalidDouble; continentCode = null; countryCode = null; provinceCode = null; cityCode = null; countyCode = null; townCode = null; villageCode = null; buildingCode = null; markSize = -1; } @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); } @Override public Object clone() throws CloneNotSupportedException { try { GeographyCode newCode = (GeographyCode) super.clone(); if (levelCode != null) { newCode.setLevelCode((GeographyCodeLevel) levelCode.clone()); } if (coordinateSystem != null) { newCode.setCoordinateSystem((GeoCoordinateSystem) coordinateSystem.clone()); } if (ownerCode != null) { newCode.setOwnerCode((GeographyCode) ownerCode.clone()); } if (continentCode != null) { newCode.setContinentCode((GeographyCode) continentCode.clone()); } if (countryCode != null) { newCode.setCountryCode((GeographyCode) countryCode.clone()); } if (provinceCode != null) { newCode.setProvinceCode((GeographyCode) provinceCode.clone()); } if (cityCode != null) { newCode.setCityCode((GeographyCode) cityCode.clone()); } if (townCode != null) { newCode.setTownCode((GeographyCode) townCode.clone()); } if (villageCode != null) { newCode.setVillageCode((GeographyCode) villageCode.clone()); } if (buildingCode != null) { newCode.setBuildingCode((GeographyCode) buildingCode.clone()); } return newCode; } catch (Exception e) { MyBoxLog.debug(e); return null; } } /* Static methods */ public static GeographyCode create() { return new GeographyCode(); } public static boolean setValue(GeographyCode data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "gcid": data.setGcid(value == null ? -1 : (long) value); return true; case "level": data.setLevel(value == null ? -1 : (short) value); data.setLevelCode(new GeographyCodeLevel(data.getLevel())); return true; case "chinese_name": data.setChineseName(value == null ? null : (String) value); return true; case "english_name": data.setEnglishName(value == null ? null : (String) value); return true; case "longitude": data.setLongitude(value == null ? AppValues.InvalidDouble : (Double) value); return true; case "latitude": data.setLatitude(value == null ? AppValues.InvalidDouble : (double) value); return true; case "altitude": data.setAltitude(value == null ? AppValues.InvalidDouble : (double) value); return true; case "precision": data.setPrecision(value == null ? AppValues.InvalidDouble : (double) value); return true; case "coordinate_system": data.setCoordinateSystem(value == null ? GeoCoordinateSystem.defaultCode() : new GeoCoordinateSystem((short) value)); return true; case "area": data.setArea(value == null ? AppValues.InvalidLong : (long) value); return true; case "population": data.setPopulation(value == null ? AppValues.InvalidLong : (long) value); return true; case "code1": data.setCode1(value == null ? null : (String) value); return true; case "code2": data.setCode2(value == null ? null : (String) value); return true; case "code3": data.setCode3(value == null ? null : (String) value); return true; case "code4": data.setCode4(value == null ? null : (String) value); return true; case "code5": data.setCode5(value == null ? null : (String) value); return true; case "alias1": data.setAlias1(value == null ? null : (String) value); return true; case "alias2": data.setAlias2(value == null ? null : (String) value); return true; case "alias3": data.setAlias3(value == null ? null : (String) value); return true; case "alias4": data.setAlias4(value == null ? null : (String) value); return true; case "alias5": data.setAlias5(value == null ? null : (String) value); return true; case "owner": data.setOwner(value == null ? null : (long) value); return true; case "continent": data.setContinent(value == null ? null : (long) value); return true; case "country": data.setCountry(value == null ? null : (long) value); return true; case "province": data.setProvince(value == null ? null : (long) value); return true; case "city": data.setCity(value == null ? null : (long) value); return true; case "county": data.setCounty(value == null ? null : (long) value); return true; case "town": data.setTown(value == null ? null : (long) value); return true; case "village": data.setVillage(value == null ? null : (long) value); return true; case "building": data.setBuilding(value == null ? null : (long) value); return true; case "comments": data.setComments(value == null ? null : (String) value); return true; case "gcsource": short s = value == null ? -1 : (short) value; data.setSource(source(s)); return true; } } catch (Exception e) { MyBoxLog.debug(e); } return false; } public static Object getValue(GeographyCode data, String column) { if (data == null || column == null) { return null; } switch (column) { case "gcid": return data.getGcid(); case "level": return data.getLevel(); case "longitude": return data.getLongitude(); case "latitude": return data.getLatitude(); case "altitude": return data.getAltitude(); case "precision": return data.getPrecision(); case "coordinate_system": return data.getCoordinateSystem() == null ? GeoCoordinateSystem.defaultCode().shortValue() : data.getCoordinateSystem().shortValue(); case "chinese_name": return data.getChineseName(); case "english_name": return data.getEnglishName(); case "code1": return data.getCode1(); case "code2": return data.getCode2(); case "code3": return data.getCode3(); case "code4": return data.getCode4(); case "code5": return data.getCode5(); case "alias1": return data.getAlias1(); case "alias2": return data.getAlias2(); case "alias3": return data.getAlias3(); case "alias4": return data.getAlias4(); case "alias5": return data.getAlias5(); case "owner": return data.getOwner(); case "continent": return data.getContinent(); case "country": return data.getCountry(); case "province": return data.getProvince(); case "city": return data.getCity(); case "county": return data.getCounty(); case "town": return data.getTown(); case "village": return data.getVillage(); case "building": return data.getBuilding(); case "area": return data.getArea(); case "population": return data.getPopulation(); case "comments": return data.getComments(); case "gcsource": return source(data.getSource()); } return null; } public static boolean valid(GeographyCode data) { return data != null && ((data.getChineseName() != null && !data.getChineseName().isBlank()) || (data.getEnglishName() != null && !data.getEnglishName().isBlank())); } public static String displayColumn(GeographyCode data, ColumnDefinition column, Object value) { if (data == null || column == null || value == null) { return null; } switch (column.getColumnName()) { case "owner": return data.getOwner() + ""; case "gcsource": return data.getSourceName(); case "level": return data.getLevelName(); case "coordinate_system": GeoCoordinateSystem cs = data.getCoordinateSystem(); return cs != null ? cs.name() : null; case "continent": return data.getContinentName(); case "country": return data.getCountryName(); case "province": return data.getProvinceName(); case "city": return data.getCityName(); case "county": return data.getCountyName(); case "town": return data.getTownName(); case "village": return data.getVillageName(); case "building": return data.getBuildingName(); } return column.formatValue(value); } public static String displayDataMore(GeographyCode data, String lineBreak) { if (data == null || lineBreak == null) { return null; } String fullname = data.getFullName(); if (!data.getName().equals(fullname)) { return lineBreak + Languages.message("FullAddress") + ": " + fullname; } else { return ""; } } public String label(String columnName) { if (columnName == null) { return null; } switch (columnName) { case "gcid": return message("ID"); case "level": return message("Level"); case "longitude": return message("Longitude"); case "latitude": return message("Latitude"); case "altitude": return message("Altitude"); case "precision": return message("Precision"); case "coordinate_system": return message("CoordinateSystem"); case "chinese_name": return message("ChineseName"); case "english_name": return message("EnglishName"); case "code1": return message("Code") + "1"; case "code2": return message("Code") + "2"; case "code3": return message("Code") + "3"; case "code4": return message("Code") + "4"; case "code5": return message("Code") + "5"; case "alias1": return message("Alias") + "1"; case "alias2": return message("Alias") + "2"; case "alias3": return message("Alias") + "3"; case "alias4": return message("Alias") + "4"; case "alias5": return message("Alias") + "5"; case "owner": return message("Owner"); case "continent": return message("Continent"); case "country": return message("Country"); case "province": return message("Province"); case "city": return message("City"); case "county": return message("County"); case "town": return message("Town"); case "village": return message("Village"); case "building": return message("Building"); case "area": return message("Area"); case "population": return message("Population"); case "comments": return message("Comments"); case "gcsource": return message("Source"); } return null; } public static boolean isPredefined(GeographyCode data) { return data != null && data.getSource() == AddressSource.PredefinedData; } public static int mapSize(GeographyCode code) { if (code == null) { return 3; } switch (code.getLevel()) { case 3: return 4; case 4: return 6; case 5: return 9; case 6: return 11; case 7: return 13; case 8: return 16; case 9: case 10: return 18; default: return 3; } } public static String name(GeographyCode code) { if (code != null) { if (Languages.isChinese()) { if (code.getChineseName() != null) { return code.getChineseName(); } else { return code.getEnglishName(); } } else { if (code.getEnglishName() != null) { return code.getEnglishName(); } else { return code.getChineseName(); } } } return null; } public static GeographyCode none() { GeographyCode none = new GeographyCode(); none.setName(Languages.message("None")); return none; } public static AddressSource source(short value) { switch (value) { case 1: return AddressSource.InputtedData; case 2: return AddressSource.PredefinedData; case 3: return AddressSource.Geonames; case 4: return AddressSource.ImportedData; default: return AddressSource.Unknown; } } public static short source(AddressSource source) { return sourceValue(source.name()); } public static short sourceValue(String source) { return sourceValue(Languages.getLangName(), source); } public static short sourceValue(String lang, String source) { if (Languages.message(lang, "InputtedData").equals(source) || "InputtedData".equals(source)) { return 1; } else if (Languages.message(lang, "PredefinedData").equals(source) || "PredefinedData".equals(source)) { return 2; } else if ("Geonames".equals(source)) { return 3; } else if (Languages.message(lang, "ImportedData").equals(source) || "ImportedData".equals(source)) { return 4; } else { return 0; } } public static String sourceName(short value) { return source(value).name(); } /* custmized get/set */ public String getName() { name = name(this); if (name == null) { switch (level) { case 1: return Languages.message("Earth"); case 2: return continentName; case 3: return countryName; case 4: return provinceName; case 5: return cityName; case 6: return countyName; case 7: return townName; case 8: return villageName; case 9: return buildingName; case 10: return poiName; } } return name; } public String getFullName() { getName(); if (levelCode == null || getLevel() <= 3) { fullName = name; } else { continentName = getContinentName(); countryName = getCountryName(); provinceName = getProvinceName(); cityName = getCityName(); countyName = getCountyName(); townName = getTownName(); villageName = getVillageName(); buildingName = getBuildingName(); if (Languages.isChinese()) { if (countryName != null) { fullName = countryName; } else { fullName = ""; } if (provinceName != null && !provinceName.isBlank()) { fullName = fullName.isBlank() ? provinceName : fullName + "-" + provinceName; } if (cityName != null && !cityName.isBlank()) { fullName = fullName.isBlank() ? cityName : fullName + "-" + cityName; } if (countyName != null && !countyName.isBlank()) { fullName = fullName.isBlank() ? countyName : fullName + "-" + countyName; } if (townName != null && !townName.isBlank()) { fullName = fullName.isBlank() ? townName : fullName + "-" + townName; } if (villageName != null && !villageName.isBlank()) { fullName = fullName.isBlank() ? villageName : fullName + "-" + villageName; } if (buildingName != null && !buildingName.isBlank()) { fullName = fullName.isBlank() ? buildingName : fullName + "-" + buildingName; } if (name != null && !name.isBlank()) { fullName = fullName.isBlank() ? name : fullName + "-" + name; } } else { if (name != null) { fullName = name; } else { fullName = ""; } if (buildingName != null && !buildingName.isBlank()) { fullName = fullName.isBlank() ? buildingName : fullName + "," + buildingName; } if (villageName != null && !villageName.isBlank()) { fullName = fullName.isBlank() ? villageName : fullName + "," + villageName; } if (townName != null && !townName.isBlank()) { fullName = fullName.isBlank() ? townName : fullName + "," + townName; } if (countyName != null && !countyName.isBlank()) { fullName = fullName.isBlank() ? countyName : fullName + "," + countyName; } if (cityName != null && !cityName.isBlank()) { fullName = fullName.isBlank() ? cityName : fullName + "," + cityName; } if (provinceName != null && !provinceName.isBlank()) { fullName = fullName.isBlank() ? provinceName : fullName + "," + provinceName; } if (countryName != null && !countryName.isBlank()) { fullName = fullName.isBlank() ? countryName : fullName + "," + countryName; } } } return fullName; } public String getContinentName() { if (continentName == null) { if (level == 2) { continentName = getName(); } else if (level > 2 && getContinentCode() != null) { continentName = name(getContinentCode()); } } return continentName; } public String getCountryName() { if (countryName == null) { if (level == 3) { countryName = getName(); } else if (level > 3 && getCountryCode() != null) { countryName = name(getCountryCode()); } } return countryName; } public String getProvinceName() { if (provinceName == null) { if (level == 4) { provinceName = getName(); } else if (level > 4 && getProvinceCode() != null) { provinceName = name(getProvinceCode()); } } return provinceName; } public String getCityName() { if (cityName == null) { if (level == 5) { cityName = getName(); } else if (level > 5 && getCityCode() != null) { cityName = name(getCityCode()); } } return cityName; } public String getCountyName() { if (countyName == null) { if (level == 6) { countyName = getName(); } else if (level > 6 && getCountyCode() != null) { countyName = name(getCountyCode()); } } return countyName; } public String getTownName() { if (townName == null) { if (level == 7) { townName = getName(); } else if (level > 7 && getTownCode() != null) { townName = name(getTownCode()); } } return townName; } public String getVillageName() { if (villageName == null) { if (level == 8) { villageName = getName(); } else if (level > 8 && getVillageCode() != null) { villageName = name(getVillageCode()); } } return villageName; } public String getBuildingName() { if (buildingName == null) { if (level == 9) { buildingName = getName(); } else if (level > 9 && getBuildingCode() != null) { buildingName = name(getBuildingCode()); } } return buildingName; } public String getPoiName() { if (poiName == null) { if (level == 10) { poiName = getName(); } } return poiName; } public long getContinent() { if (continentCode != null) { continent = continentCode.getGcid(); } return continent; } public long getCountry() { if (countryCode != null) { country = countryCode.getGcid(); } return country; } public long getProvince() { if (provinceCode != null) { province = provinceCode.getGcid(); } return province; } public long getCity() { if (cityCode != null) { city = cityCode.getGcid(); } return city; } public long getCounty() { if (countyCode != null) { county = countyCode.getGcid(); } return county; } public long getVillage() { if (villageCode != null) { village = villageCode.getGcid(); } return village; } public long getTown() { if (townCode != null) { town = townCode.getGcid(); } return town; } public long getBuilding() { if (buildingCode != null) { building = buildingCode.getGcid(); } return building; } public GeographyCode getContinentCode() { // if (level > 2 && continentCode == null) { // TableGeographyCode.decodeAncestors(this); // } return continentCode; } public GeographyCode getCountryCode() { // if (level > 3 && countryCode == null) { // TableGeographyCode.decodeAncestors(this); // } return countryCode; } public GeographyCode getProvinceCode() { // if (level > 4 && provinceCode == null) { // TableGeographyCode.decodeAncestors(this); // } return provinceCode; } public GeographyCode getCityCode() { // if (level > 5 && cityCode == null) { // TableGeographyCode.decodeAncestors(this); // } return cityCode; } public GeographyCode getCountyCode() { // if (level > 7 && countyCode == null) { // TableGeographyCode.decodeAncestors(this); // } return countyCode; } public GeographyCode getTownCode() { // if (level > 8 && townCode == null) { // TableGeographyCode.decodeAncestors(this); // } return townCode; } public GeographyCode getVillageCode() { // if (level > 9 && villageCode == null) { // TableGeographyCode.decodeAncestors(this); // } return villageCode; } public GeographyCode getBuildingCode() { // if (level > 9 && buildingCode == null) { // TableGeographyCode.decodeAncestors(this); // } return buildingCode; } public GeographyCodeLevel getLevelCode() { if (levelCode == null) { levelCode = new GeographyCodeLevel(level); } return levelCode; } public short getLevel() { if (levelCode != null) { level = levelCode.getLevel(); } if (level > 10 || level < 1) { level = 10; } return level; } public String getLevelName() { if (getLevelCode() != null) { levelName = levelCode.getName(); } return levelName; } public GeoCoordinateSystem getCoordinateSystem() { if (coordinateSystem == null) { coordinateSystem = GeoCoordinateSystem.defaultCode(); } return coordinateSystem; } public String getSourceName() { sourceName = Languages.message(source.name()); return sourceName; } public void setSource(short value) { this.source = source(value); } public short getSourceValue() { return source(source); } /* get/set */ public long getGcid() { return gcid; } public void setGcid(long gcid) { this.gcid = gcid; } 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 String getCode1() { return code1; } public void setCode1(String code1) { this.code1 = code1; } public String getCode2() { return code2; } public void setCode2(String code2) { this.code2 = code2; } public String getCode3() { return code3; } public void setCode3(String code3) { this.code3 = code3; } public String getAlias1() { return alias1; } public void setAlias1(String alias1) { this.alias1 = alias1; } public String getAlias2() { return alias2; } public void setAlias2(String alias2) { this.alias2 = alias2; } public String getAlias3() { return alias3; } public void setAlias3(String alias3) { this.alias3 = alias3; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } public double getLongitude() { return longitude; } public GeographyCode setLongitude(double longitude) { this.longitude = longitude; return this; } public double getLatitude() { return latitude; } public GeographyCode setLatitude(double latitude) { this.latitude = latitude; return this; } public void setContinent(long continent) { this.continent = continent; } public void setCountry(long country) { this.country = country; } public void setProvince(long province) { this.province = province; } public void setCity(long city) { this.city = city; } public void setCounty(long county) { this.county = county; } public void setVillage(long village) { this.village = village; } public void setTown(long town) { this.town = town; } public void setBuilding(long building) { this.building = building; } public void setCountryName(String countryName) { this.countryName = countryName; } public void setProvinceName(String provinceName) { this.provinceName = provinceName; } public void setCityName(String cityName) { this.cityName = cityName; } public void setCountyName(String countyName) {
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/TableInfoNodeTag.java
alpha/MyBox/src/main/java/mara/mybox/db/migration/TableInfoNodeTag.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 TableInfoNodeTag extends BaseTable<InfoNodeTag> { protected TableInfoNode tableTreeNode; protected TableTag tableTag; public TableInfoNodeTag() { tableName = "Tree_Node_Tag"; defineColumns(); } public TableInfoNodeTag(boolean defineColumns) { tableName = "Tree_Node_Tag"; if (defineColumns) { defineColumns(); } } public final TableInfoNodeTag defineColumns() { addColumn(new ColumnDefinition("ttid", ColumnType.Long, true, true).setAuto(true)); addColumn(new ColumnDefinition("tnodeid", ColumnType.Long) .setReferName("Tree_Node_Tag_Node_fk").setReferTable("Tree_Node").setReferColumn("nodeid") .setOnDelete(ColumnDefinition.OnDelete.Cascade) ); addColumn(new ColumnDefinition("tagid", ColumnType.Long) .setReferName("Tree_Node_Tag_Tag_fk").setReferTable("Tag").setReferColumn("tgid") .setOnDelete(ColumnDefinition.OnDelete.Cascade) ); return this; } public static final String Create_Unique_Index = "CREATE UNIQUE INDEX Tree_Node_Tag_unique_index on Tree_Node_Tag ( tnodeid , tagid )"; public static final String QueryNodeTags = "SELECT * FROM Tree_Node_Tag, Tag WHERE tnodeid=? AND tagid=tgid"; public static final String QueryNodeTag = "SELECT * FROM Tree_Node_Tag, Tag WHERE tnodeid=? AND tagid=?"; public static final String DeleteNodeTags = "DELETE FROM Tree_Node_Tag WHERE tnodeid=?"; public static final String DeleteNodeTag = "DELETE FROM Tree_Node_Tag WHERE tnodeid=? AND tagid=?"; @Override public Object readForeignValue(ResultSet results, String column) { if (results == null || column == null) { return null; } try { if ("tnodeid".equals(column) && results.findColumn("nodeid") > 0) { return getTableTreeNode().readData(results); } if ("tagid".equals(column) && results.findColumn("tgid") > 0) { return getTableTag().readData(results); } } catch (Exception e) { } return null; } @Override public boolean setForeignValue(InfoNodeTag data, String column, Object value) { if (data == null || column == null || value == null) { return true; } if ("tnodeid".equals(column) && value instanceof InfoNode) { data.setNode((InfoNode) value); } if ("tagid".equals(column) && value instanceof Tag) { data.setTag((Tag) value); } return true; } @Override public boolean setValue(InfoNodeTag data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(InfoNodeTag data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(InfoNodeTag data) { if (data == null) { return false; } return data.valid(); } public List<InfoNodeTag> nodeTags(long nodeid) { List<InfoNodeTag> tags = new ArrayList<>(); if (nodeid < 0) { return tags; } try (Connection conn = DerbyBase.getConnection()) { tags = nodeTags(conn, nodeid); } catch (Exception e) { MyBoxLog.error(e); } return tags; } public List<InfoNodeTag> nodeTags(Connection conn, long nodeid) { List<InfoNodeTag> tags = new ArrayList<>(); if (conn == null || nodeid < 0) { return tags; } try (PreparedStatement statement = conn.prepareStatement(QueryNodeTags)) { statement.setLong(1, nodeid); conn.setAutoCommit(true); ResultSet results = statement.executeQuery(); while (results.next()) { InfoNodeTag tag = readData(results); if (tag != null) { tags.add(tag); } } } catch (Exception e) { MyBoxLog.error(e); } return tags; } public InfoNodeTag query(Connection conn, long nodeid, long tagid) { if (conn == null || nodeid < 0 || tagid < 0) { return null; } InfoNodeTag tag = null; try (PreparedStatement statement = conn.prepareStatement(QueryNodeTag)) { statement.setLong(1, nodeid); statement.setLong(2, tagid); conn.setAutoCommit(true); ResultSet results = statement.executeQuery(); if (results.next()) { tag = readData(results); } } catch (Exception e) { MyBoxLog.error(e); } return tag; } public List<String> nodeTagNames(long nodeid) { List<String> tags = new ArrayList<>(); if (nodeid < 0) { return tags; } try (Connection conn = DerbyBase.getConnection()) { tags = nodeTagNames(conn, nodeid); } catch (Exception e) { MyBoxLog.error(e); } return tags; } public List<String> nodeTagNames(Connection conn, long nodeid) { List<String> tags = new ArrayList<>(); if (nodeid < 0) { return tags; } try (PreparedStatement statement = conn.prepareStatement(QueryNodeTags)) { statement.setLong(1, nodeid); ResultSet results = statement.executeQuery(); conn.setAutoCommit(true); while (results.next()) { InfoNodeTag nodeTag = readData(results); if (nodeTag != null) { tags.add(nodeTag.getTag().getTag()); } } } catch (Exception e) { MyBoxLog.error(e); } return tags; } public int addTags(Connection conn, long nodeid, String category, List<String> tags) { if (conn == null || nodeid < 0 || category == null || category.isBlank() || tags == null || tags.isEmpty()) { return -1; } String sql = "INSERT INTO Tree_Node_Tag (tnodeid, tagid) " + "SELECT " + nodeid + ", tgid FROM Tag " + "WHERE category='" + category + "' AND tag IN ("; for (int i = 0; i < tags.size(); i++) { if (i > 0) { sql += ","; } sql += "'" + tags.get(i) + "'"; } sql += ")"; try (PreparedStatement statement = conn.prepareStatement(sql)) { return statement.executeUpdate(); } catch (Exception e) { MyBoxLog.error(e); return -1; } } public int writeTags(Connection conn, long nodeid, String category, List<String> tags) { if (conn == null || nodeid < 0 || category == null || category.isBlank() || tags == null || tags.isEmpty()) { return -1; } int count = 0; try { for (String name : tags) { Tag tag = getTableTag().findAndCreate(conn, category, name); if (tag == null) { continue; } if (query(conn, nodeid, tag.getTgid()) == null) { InfoNodeTag nodeTag = new InfoNodeTag(nodeid, tag.getTgid()); count += insertData(conn, nodeTag) == null ? 0 : 1; } } } catch (Exception e) { MyBoxLog.error(e); return -1; } return count; } public int removeTags(Connection conn, long nodeid, String category, List<String> tags) { if (conn == null || nodeid < 0 || category == null || category.isBlank() || tags == null || tags.isEmpty()) { return -1; } String sql = "DELETE FROM Tree_Node_Tag WHERE tnodeid=" + nodeid + " AND " + "tagid IN (SELECT tgid FROM Tag " + "WHERE category='" + category + "' AND tag IN ("; for (int i = 0; i < tags.size(); i++) { if (i > 0) { sql += ","; } sql += "'" + tags.get(i) + "'"; } sql += " ) )"; try (PreparedStatement statement = conn.prepareStatement(sql)) { return statement.executeUpdate(); } catch (Exception e) { MyBoxLog.error(e); return -1; } } public int removeTags(Connection conn, long nodeid) { if (conn == null || nodeid < 0) { return -1; } try (PreparedStatement statement = conn.prepareStatement(DeleteNodeTags)) { statement.setLong(1, nodeid); return statement.executeUpdate(); } catch (Exception e) { MyBoxLog.error(e); return -1; } } /* get/set */ public TableInfoNode getTableTreeNode() { if (tableTreeNode == null) { tableTreeNode = new TableInfoNode(); } return tableTreeNode; } public void setTableTreeNode(TableInfoNode tableTreeNode) { this.tableTreeNode = tableTreeNode; } public TableTag getTableTag() { if (tableTag == null) { tableTag = new TableTag(); } return tableTag; } public void setTableTag(TableTag tableTag) { this.tableTag = tableTag; } }
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/GeoCoordinateSystem.java
alpha/MyBox/src/main/java/mara/mybox/db/migration/GeoCoordinateSystem.java
package mara.mybox.db.migration; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2020-7-4 * @License Apache License Version 2.0 */ /* http://epsg.io/4490 http://epsg.io/4479 http://epsg.io/4326 http://epsg.io/3857 https://blog.csdn.net/An1090239782/article/details/100572140 https://blog.csdn.net/xcymorningsun/article/details/79254163 https://blog.csdn.net/qq_34149805/article/details/65634252 */ public class GeoCoordinateSystem implements Cloneable { protected Value value; public enum Value { CGCS2000, GCJ_02, WGS_84, BD_09, Mapbar } public GeoCoordinateSystem(Value value) { this.value = value == null ? defaultValue() : value; } public GeoCoordinateSystem(String name) { this.value = defaultValue(); if (name == null) { return; } for (Value item : Value.values()) { if (name.equals(item.name()) || name.equals(message(item.name()))) { this.value = item; return; } } } public GeoCoordinateSystem(short intValue) { try { value = Value.values()[intValue]; } catch (Exception e) { value = defaultValue(); } } public String name() { if (value == null) { value = defaultValue(); } return value.name(); } public String messageName() { return message(name()); } public short shortValue() { if (value == null) { value = defaultValue(); } return (short) value.ordinal(); } public String gaodeConvertService() { if (value == null) { value = defaultValue(); } switch (value) { case CGCS2000: return "gps"; case GCJ_02: return "autonavi"; case WGS_84: return "gps"; case BD_09: return "baidu"; case Mapbar: return "mapbar"; default: return "autonavi"; } } @Override public Object clone() throws CloneNotSupportedException { try { return super.clone(); } catch (Exception e) { return null; } } public static Value defaultValue() { return Value.CGCS2000; } public static GeoCoordinateSystem defaultCode() { return new GeoCoordinateSystem(GeoCoordinateSystem.defaultValue()); } public static GeoCoordinateSystem Mapbar() { return new GeoCoordinateSystem(GeoCoordinateSystem.Value.Mapbar); } public static GeoCoordinateSystem BD09() { return new GeoCoordinateSystem(GeoCoordinateSystem.Value.BD_09); } public static GeoCoordinateSystem CGCS2000() { return new GeoCoordinateSystem(GeoCoordinateSystem.Value.CGCS2000); } public static GeoCoordinateSystem WGS84() { return new GeoCoordinateSystem(GeoCoordinateSystem.Value.WGS_84); } public static GeoCoordinateSystem GCJ02() { return new GeoCoordinateSystem(GeoCoordinateSystem.Value.GCJ_02); } public static short value(String name) { return new GeoCoordinateSystem(name).shortValue(); } public static String name(short value) { return new GeoCoordinateSystem(value).name(); } public static String messageName(short value) { return new GeoCoordinateSystem(value).messageName(); } public static String messageNames() { String s = ""; for (Value v : Value.values()) { if (!s.isBlank()) { s += "\n"; } s += message(v.name()); } return s; } /* get/set */ public Value getValue() { return value; } public void setValue(Value value) { this.value = 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/db/migration/Tag.java
alpha/MyBox/src/main/java/mara/mybox/db/migration/Tag.java
package mara.mybox.db.migration; import javafx.scene.paint.Color; import mara.mybox.db.data.BaseData; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.image.FxColorTools; /** * @Author Mara * @CreateDate 2021-3-20 * @License Apache License Version 2.0 */ public class Tag extends BaseData { protected long tgid; protected String category, tag; protected Color color; private void init() { tgid = -1; category = null; tag = null; color = FxColorTools.randomColor(); } public Tag() { init(); } public Tag(String category, String tag) { init(); this.category = category; this.tag = tag; } @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 Tag create() { return new Tag(); } public static boolean setValue(Tag data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "tgid": data.setTgid(value == null ? -1 : (long) value); return true; case "category": data.setCategory(value == null ? null : (String) value); return true; case "tag": data.setTag(value == null ? null : (String) value); return true; case "color": data.setColor(value == null ? FxColorTools.randomColor() : Color.web((String) value)); return true; } } catch (Exception e) { MyBoxLog.debug(e); } return false; } public static Object getValue(Tag data, String column) { if (data == null || column == null) { return null; } switch (column) { case "tgid": return data.getTgid(); case "category": return data.getCategory(); case "tag": return data.getTag(); case "color": return data.getColor() == null ? FxColorTools.randomColor().toString() : data.getColor().toString(); } return null; } public static boolean valid(Tag data) { return data != null && data.getTag() != null && !data.getTag().isBlank(); } /* get/set */ public long getTgid() { return tgid; } public Tag setTgid(long tgid) { this.tgid = tgid; return this; } public String getTag() { return tag; } public Tag setTag(String tag) { this.tag = tag; return this; } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } }
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/TableData2DCell.java
alpha/MyBox/src/main/java/mara/mybox/db/migration/TableData2DCell.java
package mara.mybox.db.migration; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.table.BaseTable; /** * @Author Mara * @CreateDate 2021-10-17 * @License Apache License Version 2.0 */ public class TableData2DCell extends BaseTable<Data2DCell> { public TableData2DCell() { tableName = "Data2D_Cell"; defineColumns(); } public TableData2DCell(boolean defineColumns) { tableName = "Data2D_Cell"; if (defineColumns) { defineColumns(); } } public final TableData2DCell defineColumns() { addColumn(new ColumnDefinition("dceid", ColumnType.Long, true, true).setAuto(true)); addColumn(new ColumnDefinition("dcdid", ColumnType.Long, true) .setReferName("Data2D_Cell_fk").setReferTable("Data2D_Definition").setReferColumn("d2did") .setOnDelete(ColumnDefinition.OnDelete.Cascade)); addColumn(new ColumnDefinition("row", ColumnType.Long, true).setMinValue(0)); addColumn(new ColumnDefinition("col", ColumnType.Long, true).setMinValue(0)); addColumn(new ColumnDefinition("value", ColumnType.String, true).setLength(StringMaxLength)); return this; } public static final String QueryData = "SELECT * FROM Data2D_Cell WHERE dcdid=?"; public static final String ClearData = "DELETE FROM Data2D_Cell WHERE dcdid=?"; @Override public boolean setValue(Data2DCell data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(Data2DCell data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(Data2DCell data) { if (data == null) { return false; } return data.valid(); } }
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/OldImageScope.java
alpha/MyBox/src/main/java/mara/mybox/db/migration/OldImageScope.java
package mara.mybox.db.migration; import java.awt.Color; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Date; import java.util.List; import javafx.scene.image.Image; import mara.mybox.data.DoubleCircle; import mara.mybox.data.DoubleEllipse; import mara.mybox.data.DoublePolygon; import mara.mybox.data.DoubleRectangle; import mara.mybox.data.IntPoint; import mara.mybox.db.data.BaseData; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.Colors; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2018-8-1 16:22:41 * @License Apache License Version 2.0 */ public class OldImageScope extends BaseData { public static String ValueSeparator = ","; protected String file, name, areaData, colorData, outlineName; protected ScopeType scopeType; protected ColorScopeType colorScopeType; protected List<Color> colors; protected List<IntPoint> points; protected DoubleRectangle rectangle; protected DoubleCircle circle; protected DoubleEllipse ellipse; protected DoublePolygon polygon; protected int colorDistance, colorDistanceSquare; protected float hsbDistance; protected boolean areaExcluded, colorExcluded, eightNeighbor, distanceSquareRoot; protected Image image, clip; protected Color maskColor; protected float maskOpacity; protected Date createTime, modifyTime; protected BufferedImage outlineSource, outline; public static enum ScopeType { Whole, Matting, Rectangle, Circle, Ellipse, Polygon, Colors, Outline } public static enum ColorScopeType { AllColor, Color, Red, Green, Blue, Brightness, Saturation, Hue } public OldImageScope() { init(); } public OldImageScope(Image image) { this.image = image; init(); } public OldImageScope(Image image, ScopeType type) { this.image = image; init(); scopeType = type; } private void init() { scopeType = ScopeType.Whole; colorScopeType = ColorScopeType.AllColor; clearValues(); } @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 final void clearValues() { colors = new ArrayList<>(); points = new ArrayList<>(); colorDistance = 50; colorDistanceSquare = colorDistance * colorDistance; hsbDistance = 0.5f; maskColor = Colors.TRANSPARENT; maskOpacity = 0.5f; areaExcluded = colorExcluded = distanceSquareRoot = false; eightNeighbor = true; rectangle = null; circle = null; ellipse = null; polygon = null; areaData = null; colorData = null; outlineName = null; outlineSource = null; outline = null; } public OldImageScope cloneValues() { return OldImageScopeTools.cloneAll(this); } public boolean isWhole() { return scopeType == null || scopeType == ScopeType.Whole; } public void decode(FxTask task) { if (colorData != null) { OldImageScopeTools.decodeColorData(this); } if (areaData != null) { OldImageScopeTools.decodeAreaData(this); } if (outlineName != null) { OldImageScopeTools.decodeOutline(task, this); } } public void encode(FxTask task) { OldImageScopeTools.encodeColorData(this); OldImageScopeTools.encodeAreaData(this); OldImageScopeTools.encodeOutline(task, this); } public void addPoint(IntPoint point) { if (point == null) { return; } if (points == null) { points = new ArrayList<>(); } if (!points.contains(point)) { points.add(point); } } public void addPoint(int x, int y) { if (x < 0 || y < 0) { return; } IntPoint point = new IntPoint(x, y); addPoint(point); } public void setPoint(int index, int x, int y) { if (x < 0 || y < 0 || points == null || index < 0 || index >= points.size()) { return; } IntPoint point = new IntPoint(x, y); points.set(index, point); } public void deletePoint(int index) { if (points == null || index < 0 || index >= points.size()) { return; } points.remove(index); } public void clearPoints() { points = new ArrayList<>(); } public boolean addColor(Color color) { if (color == null) { return false; } if (colors == null) { colors = new ArrayList<>(); } if (!colors.contains(color)) { colors.add(color); return true; } else { return false; } } public void clearColors() { colors = new ArrayList<>(); } /* SubClass should implement this */ protected boolean inScope(int x, int y, Color color) { return true; } public boolean inColorMatch(Color color1, Color color2) { return true; } /* Static methods */ public static OldImageScope create() { return new OldImageScope(); } public static boolean setValue(OldImageScope data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "image_location": data.setFile(value == null ? null : (String) value); return true; case "name": data.setName(value == null ? null : (String) value); return true; case "scope_type": data.setScopeType(value == null ? null : OldImageScopeTools.scopeType((String) value)); return true; case "color_scope_type": data.setColorScopeType(value == null ? null : ColorScopeType.valueOf((String) value)); return true; case "area_data": data.setAreaData(value == null ? null : (String) value); return true; case "color_data": data.setColorData(value == null ? null : (String) value); return true; case "color_distance": data.setColorDistance(value == null ? 20 : (int) value); return true; case "hsb_distance": data.setHsbDistance(value == null ? 20 : Float.parseFloat(value + "")); return true; case "area_excluded": data.setAreaExcluded(value == null ? false : (int) value > 0); return true; case "color_excluded": data.setColorExcluded(value == null ? false : (int) value > 0); return true; case "outline": data.setOutlineName(value == null ? null : (String) value); return true; case "create_time": data.setCreateTime(value == null ? null : (Date) value); return true; case "modify_time": data.setCreateTime(value == null ? null : (Date) value); return true; } } catch (Exception e) { MyBoxLog.debug(e); } return false; } public static Object getValue(OldImageScope data, String column) { if (data == null || column == null) { return null; } switch (column) { case "image_location": return data.getFile(); case "name": return data.getName(); case "scope_type": return data.getScopeType().name(); case "color_scope_type": return data.getColorScopeType().name(); case "area_data": return data.getAreaData(); case "color_data": return data.getColorData(); case "color_distance": return data.getColorDistance(); case "hsb_distance": return data.getHsbDistance(); case "area_excluded": return data.isAreaExcluded() ? 1 : 0; case "color_excluded": return data.isColorExcluded() ? 1 : 0; case "outline": return data.getOutline(); case "create_time": return data.getCreateTime(); case "modify_time": return data.getModifyTime(); } return null; } public static boolean valid(OldImageScope data) { return data != null && data.getScopeType() != null; } /* customized get/set */ public void setColorDistance(int colorDistance) { this.colorDistance = colorDistance; this.colorDistanceSquare = colorDistance * colorDistance; } public void setColorDistanceSquare(int colorDistanceSquare) { this.colorDistanceSquare = colorDistanceSquare; this.colorDistance = (int) Math.sqrt(colorDistanceSquare); } public String getColorTypeName() { if (colorScopeType == null) { return null; } return message(colorScopeType.name()); } /* get/set */ public List<Color> getColors() { return colors; } public OldImageScope setColors(List<Color> colors) { this.colors = colors; return this; } public DoubleRectangle getRectangle() { return rectangle; } public OldImageScope setRectangle(DoubleRectangle rectangle) { this.rectangle = rectangle; return this; } public DoubleCircle getCircle() { return circle; } public void setCircle(DoubleCircle circle) { this.circle = circle; } public Image getImage() { return image; } public OldImageScope setImage(Image image) { this.image = image; return this; } public int getColorDistance() { return colorDistance; } public float getMaskOpacity() { return maskOpacity; } public OldImageScope setMaskOpacity(float maskOpacity) { this.maskOpacity = maskOpacity; return this; } public Color getMaskColor() { return maskColor; } public OldImageScope setMaskColor(Color maskColor) { this.maskColor = maskColor; return this; } public ScopeType getScopeType() { return scopeType; } public OldImageScope setScopeType(ScopeType scopeType) { this.scopeType = scopeType; return this; } public ColorScopeType getColorScopeType() { return colorScopeType; } public void setColorScopeType(ColorScopeType colorScopeType) { this.colorScopeType = colorScopeType; } public boolean isAreaExcluded() { return areaExcluded; } public OldImageScope setAreaExcluded(boolean areaExcluded) { this.areaExcluded = areaExcluded; return this; } public boolean isColorExcluded() { return colorExcluded; } public OldImageScope setColorExcluded(boolean colorExcluded) { this.colorExcluded = colorExcluded; return this; } public List<IntPoint> getPoints() { return points; } public void setPoints(List<IntPoint> points) { this.points = points; } public int getColorDistanceSquare() { return colorDistanceSquare; } public float getHsbDistance() { return hsbDistance; } public void setHsbDistance(float hsbDistance) { this.hsbDistance = hsbDistance; } public DoubleEllipse getEllipse() { return ellipse; } public void setEllipse(DoubleEllipse ellipse) { this.ellipse = ellipse; } public DoublePolygon getPolygon() { return polygon; } public void setPolygon(DoublePolygon polygon) { this.polygon = polygon; } public String getFile() { return file; } public void setFile(String file) { this.file = file; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getModifyTime() { return modifyTime; } public void setModifyTime(Date modifyTime) { this.modifyTime = modifyTime; } public BufferedImage getOutline() { return outline; } public OldImageScope setOutline(BufferedImage outline) { this.outline = outline; return this; } public BufferedImage getOutlineSource() { return outlineSource; } public OldImageScope setOutlineSource(BufferedImage outlineSource) { this.outlineSource = outlineSource; return this; } public Image getClip() { return clip; } public void setClip(Image clip) { this.clip = clip; } public boolean isEightNeighbor() { return eightNeighbor; } public OldImageScope setEightNeighbor(boolean eightNeighbor) { this.eightNeighbor = eightNeighbor; return this; } public boolean isDistanceSquareRoot() { return distanceSquareRoot; } public void setDistanceSquareRoot(boolean distanceSquareRoot) { this.distanceSquareRoot = distanceSquareRoot; } public String getAreaData() { return areaData; } public void setAreaData(String areaData) { this.areaData = areaData; } public String getColorData() { return colorData; } public void setColorData(String colorData) { this.colorData = colorData; } public String getOutlineName() { return outlineName; } public void setOutlineName(String outlineName) { this.outlineName = outlineName; } }
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/TableGeographyCode.java
alpha/MyBox/src/main/java/mara/mybox/db/migration/TableGeographyCode.java
package mara.mybox.db.migration; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.sql.Types; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import mara.mybox.db.Database; import mara.mybox.db.DerbyBase; import static mara.mybox.db.DerbyBase.stringValue; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.table.BaseTable; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.Languages; /** * @Author Mara * @CreateDate 2020-2-3 * @License Apache License Version 2.0 */ public class TableGeographyCode extends BaseTable<GeographyCode> { /** * One of following can determine an address: 1. gcid. This is accurate * matching. 2. level + chinese_name/english_name/alias + ancestors. This is * accurate matching. 3. level + chinese_name/english_name/alias. This is * fuzzy matching. Duplaited names can happen. * * Notice: coordinate can not determine an address * * Extra information, like higher level attribuets, can avoid wrong matching * due to duplicated names. Example, 2 cities have same name "A" while they * have different country names, then distinct them by appending country * name. * * Should not run batch insert/update of external data because each new data * need compare previous data. External data may include unexpected data * inconsistent. */ public TableGeographyCode() { tableName = "Geography_Code"; defineColumns(); } public TableGeographyCode(boolean defineColumns) { tableName = "Geography_Code"; if (defineColumns) { defineColumns(); } } public final TableGeographyCode defineColumns() { addColumn(new ColumnDefinition("gcid", ColumnType.Long, true, true).setAuto(true).setMinValue((long) 0)); addColumn(new ColumnDefinition("level", ColumnType.Short, true).setMaxValue((short) 10).setMinValue((short) 1)); addColumn(new ColumnDefinition("coordinate_system", ColumnType.Short)); addColumn(new ColumnDefinition("longitude", ColumnType.Double, true).setMaxValue((double) 180).setMinValue((double) -180)); addColumn(new ColumnDefinition("latitude", ColumnType.Double, true).setMaxValue((double) 90).setMinValue((double) -90)); addColumn(new ColumnDefinition("altitude", ColumnType.Double)); addColumn(new ColumnDefinition("precision", ColumnType.Double)); addColumn(new ColumnDefinition("chinese_name", ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("english_name", ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("continent", ColumnType.Long).setMinValue((long) 0)); addColumn(new ColumnDefinition("country", ColumnType.Long).setMinValue((long) 0)); addColumn(new ColumnDefinition("province", ColumnType.Long).setMinValue((long) 0)); addColumn(new ColumnDefinition("city", ColumnType.Long).setMinValue((long) 0)); addColumn(new ColumnDefinition("county", ColumnType.Long).setMinValue((long) 0)); addColumn(new ColumnDefinition("town", ColumnType.Long).setMinValue((long) 0)); addColumn(new ColumnDefinition("village", ColumnType.Long).setMinValue((long) 0)); addColumn(new ColumnDefinition("building", ColumnType.Long).setMinValue((long) 0)); addColumn(new ColumnDefinition("code1", ColumnType.String).setLength(1024)); addColumn(new ColumnDefinition("code2", ColumnType.String).setLength(1024)); addColumn(new ColumnDefinition("code3", ColumnType.String).setLength(1024)); addColumn(new ColumnDefinition("code4", ColumnType.String).setLength(1024)); addColumn(new ColumnDefinition("code5", ColumnType.String).setLength(1024)); addColumn(new ColumnDefinition("alias1", ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("alias2", ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("alias3", ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("alias4", ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("alias5", ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("area", ColumnType.Long).setMinValue((long) 0)); addColumn(new ColumnDefinition("population", ColumnType.Long).setMinValue((long) 0)); addColumn(new ColumnDefinition("owner", ColumnType.Long).setMinValue((long) 0) .setReferName("Geography_Code_owner_fk").setReferTable("Geography_Code").setReferColumn("gcid")); addColumn(new ColumnDefinition("comments", ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("gcsource", ColumnType.Short).setMinValue((short) 0)); return this; } public static long MaxID = -1; public static final String Create_Index_levelIndex = " CREATE INDEX Geography_Code_level_index on Geography_Code ( " + " level, continent, country ,province ,city ,county ,town , village , building " + " )"; public static final String Create_Index_codeIndex = " CREATE INDEX Geography_Code_code_index on Geography_Code ( " + " level, country ,province ,city ,county ,town , village , building " + " )"; public static final String Create_Index_gcidIndex = " CREATE INDEX Geography_Code_gcid_index on Geography_Code ( " + " gcid DESC, level, continent, country ,province ,city ,county ,town , village , building " + " )"; public static final String AllQeury = "SELECT * FROM Geography_Code ORDER BY gcid"; public static final String PageQeury = "SELECT * FROM Geography_Code ORDER BY gcid " + " OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; public static final String GCidQeury = "SELECT * FROM Geography_Code WHERE gcid=?"; public static final String NameEqual = "( chinese_name IS NOT NULL AND LCASE(chinese_name)=? ) OR " + " ( english_name IS NOT NULL AND LCASE(english_name)=? ) OR " + " ( alias1 IS NOT NULL AND LCASE(alias1)=? ) OR " + " ( alias2 IS NOT NULL AND LCASE(alias2)=? ) OR " + " ( alias3 IS NOT NULL AND LCASE(alias3)=? ) OR " + " ( alias4 IS NOT NULL AND LCASE(alias4)=? ) OR " + " ( alias5 IS NOT NULL AND LCASE(alias5)=? )"; public static final String LevelNameEqual = "level=? AND ( " + NameEqual + " )"; public static final String LevelNameQeury = "SELECT * FROM Geography_Code WHERE " + LevelNameEqual; public static final String CoordinateQeury = "SELECT * FROM Geography_Code WHERE coordinate_system=? AND longitude=? AND latitude=?"; public static final String MaxLevelGCidQuery = "SELECT max(gcid) FROM Geography_Code WHERE level=?"; public static final String GCidExistedQuery = "SELECT gcid FROM Geography_Code where gcid=?"; public static final String MaxGCidQuery = "SELECT max(gcid) FROM Geography_Code"; public static final String FirstChildQuery = "SELECT gcid FROM Geography_Code WHERE " + " owner=? OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY"; public static final String ChildrenQuery = "SELECT * FROM Geography_Code WHERE owner=? ORDER BY gcid"; public static final String LevelSizeQuery = "SELECT count(gcid) FROM Geography_Code WHERE level=?"; public static final String Update = "UPDATE Geography_Code SET " + " level=?, longitude=?, latitude=?, gcsource=?, chinese_name=?, english_name=?, " + " code1=?, code2=?, code3=?, code4=?, code5=?,alias1=?, alias2=?, alias3=?, alias4=?, alias5=?, " + " area=?, population=?, comments=?, " + " continent=?, country=?, province=? , city=?, county=?, town=?, village=? , building=?, " + " owner=?, altitude=? , precision=?, coordinate_system=? " + " WHERE gcid=?"; public static final String Insert = "INSERT INTO Geography_Code( " + " gcid, level, gcsource, longitude, latitude, chinese_name, english_name," + " code1, code2, code3, code4, code5, alias1, alias2, alias3, alias4, alias5, " + " area, population, comments," + " continent, country, province, city, county, town, village, building," + " owner, altitude, precision,coordinate_system ) " + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? ) "; public static final String Delete = "DELETE FROM Geography_Code WHERE gcid=?"; @Override public boolean setValue(GeographyCode data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(GeographyCode data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(GeographyCode data) { if (data == null) { return false; } return data.valid(); } private static long generateID(Connection conn) { try (Statement statement = conn.createStatement()) { try (ResultSet results = statement.executeQuery("SELECT max(gcid) FROM Geography_Code")) { if (results.next()) { MaxID = results.getInt(1); } } long gcid = Math.max(2000000, MaxID + 1); MaxID = gcid; String sql = "ALTER TABLE Geography_Code ALTER COLUMN gcid RESTART WITH " + (MaxID + 1); statement.executeUpdate(sql); return gcid; } catch (Exception e) { MyBoxLog.error(e); return -1; } } public static boolean validCoordinate(double longitude, double latitude) { return longitude >= -180 && longitude <= 180 && latitude >= -90 && latitude <= 90; } public static boolean validCoordinate(GeographyCode code) { return code.getLongitude() >= -180 && code.getLongitude() <= 180 && code.getLatitude() >= -90 && code.getLatitude() <= 90; } public static void setNameParameters(PreparedStatement statement, String name, int fromIndex) { if (statement == null || name == null || fromIndex < 0) { return; } try { String lname = name.toLowerCase(); statement.setString(fromIndex + 1, lname); statement.setString(fromIndex + 2, lname); statement.setString(fromIndex + 3, lname); statement.setString(fromIndex + 4, lname); statement.setString(fromIndex + 5, lname); statement.setString(fromIndex + 6, lname); statement.setString(fromIndex + 7, lname); } catch (Exception e) { MyBoxLog.error(e); } } public static String nameEqual(String value) { String v = stringValue(value).toLowerCase(); return " ( chinese_name IS NOT NULL AND LCASE(chinese_name)='" + v + "' ) OR " + " ( english_name IS NOT NULL AND LCASE(english_name)='" + v + "' ) OR " + " ( alias1 IS NOT NULL AND LCASE(alias1)='" + v + "' ) OR " + " ( alias2 IS NOT NULL AND LCASE(alias2)='" + v + "' ) OR " + " ( alias3 IS NOT NULL AND LCASE(alias3)='" + v + "' ) OR " + " ( alias4 IS NOT NULL AND LCASE(alias4)='" + v + "' ) OR " + " ( alias5 IS NOT NULL AND LCASE(alias5)='" + v + "' ) "; } public static String codeEqual(GeographyCode code) { if (code.getGcid() > 0) { return "gcid=" + code.getGcid(); } int level = code.getLevel(); String s = "level=" + level; switch (level) { case 3: break; case 4: s += " AND country=" + code.getCountry(); break; case 5: s += " AND country=" + code.getCountry() + " AND province=" + code.getProvince(); break; case 6: s += " AND country=" + code.getCountry() + " AND province=" + code.getProvince() + " AND city=" + code.getCity(); break; case 7: s += " AND country=" + code.getCountry() + " AND province=" + code.getProvince() + " AND city=" + code.getCity() + " AND county=" + code.getCounty(); break; case 8: s += " AND country=" + code.getCountry() + " AND province=" + code.getProvince() + " AND city=" + code.getCity() + " AND county=" + code.getCounty() + " AND town=" + code.getTown(); break; case 9: s += " AND country=" + code.getCountry() + " AND province=" + code.getProvince() + " AND city=" + code.getCity() + " AND county=" + code.getCounty() + " AND town=" + code.getTown() + " AND village=" + code.getVillage(); break; case 10: default: s += " AND country=" + code.getCountry() + " AND province=" + code.getProvince() + " AND city=" + code.getCity() + " AND county=" + code.getCounty() + " AND town=" + code.getTown() + " AND village=" + code.getVillage() + " AND building=" + code.getBuilding(); break; } if (code.getChineseName() != null) { String name = stringValue(code.getChineseName()).toLowerCase(); s += " AND ( ( chinese_name IS NOT NULL AND LCASE(chinese_name)='" + name + "' ) OR " + " ( alias1 IS NOT NULL AND LCASE(alias1)='" + name + "' ) OR " + " ( alias2 IS NOT NULL AND LCASE(alias2)='" + name + "' ) OR " + " ( alias3 IS NOT NULL AND LCASE(alias3)='" + name + "' ) OR " + " ( alias4 IS NOT NULL AND LCASE(alias4)='" + name + "' ) OR " + " ( alias5 IS NOT NULL AND LCASE(alias5)='" + name + "' ) ) "; } else if (code.getEnglishName() != null) { String name = stringValue(code.getEnglishName()).toLowerCase(); s += " AND ( ( english_name IS NOT NULL AND LCASE(english_name)='" + name + "' ) OR " + " ( alias1 IS NOT NULL AND LCASE(alias1)='" + name + "' ) OR " + " ( alias2 IS NOT NULL AND LCASE(alias2)='" + name + "' ) OR " + " ( alias3 IS NOT NULL AND LCASE(alias3)='" + name + "' ) OR " + " ( alias4 IS NOT NULL AND LCASE(alias4)='" + name + "' ) OR " + " ( alias5 IS NOT NULL AND LCASE(alias5)='" + name + "' ) ) "; } return s; } public static String codeEqual(String value) { String v = stringValue(value).toLowerCase(); return " ( ( code1 IS NOT NULL AND LCASE(code1)='" + v + "' ) OR " + " ( code2 IS NOT NULL AND LCASE(code2)='" + v + "' ) OR " + " ( code3 IS NOT NULL AND LCASE(code3)='" + v + "' ) OR " + " ( code4 IS NOT NULL AND LCASE(code4)='" + v + "' ) OR " + " ( code5 IS NOT NULL AND LCASE(code5)='" + v + "' ) ) "; } public static GeographyCode earth() { try (Connection conn = DerbyBase.getConnection()) { conn.setReadOnly(true); return earth(conn); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static GeographyCode earth(Connection conn) { String sql = "SELECT * FROM Geography_Code WHERE level=1 AND chinese_name='地球'"; return queryCode(conn, sql, false); } public static GeographyCode China() { try (Connection conn = DerbyBase.getConnection()) { conn.setReadOnly(true); return China(conn); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static GeographyCode China(Connection conn) { String sql = "SELECT * FROM Geography_Code WHERE level=3 AND chinese_name='中国'"; return queryCode(conn, sql, false); } public static GeographyCode queryCode(String sql, boolean decodeAncestors) { try (Connection conn = DerbyBase.getConnection()) { conn.setReadOnly(true); return queryCode(conn, sql, decodeAncestors); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static GeographyCode queryCode(Connection conn, String sql, boolean decodeAncestors) { if (conn == null || sql == null) { return null; } try { GeographyCode code; try (Statement statement = conn.createStatement()) { statement.setMaxRows(1); try (ResultSet results = statement.executeQuery(sql)) { if (results.next()) { code = readResults(results); } else { return null; } } } if (decodeAncestors && code != null) { decodeAncestors(conn, code); } return code; } catch (Exception e) { MyBoxLog.error(e); return null; } } // this way is not accurate since multiple addresses can have same coordinate public static GeographyCode readCode(GeoCoordinateSystem coordinateSystem, double longitude, double latitude, boolean decodeAncestors) { if (coordinateSystem == null || !validCoordinate(longitude, latitude)) { return null; } try (Connection conn = DerbyBase.getConnection()) { conn.setReadOnly(true); return readCode(conn, coordinateSystem, longitude, latitude, decodeAncestors); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static GeographyCode readCode(Connection conn, GeoCoordinateSystem coordinateSystem, double longitude, double latitude, boolean decodeAncestors) { if (coordinateSystem == null || !validCoordinate(longitude, latitude)) { return null; } try { GeographyCode code; try (PreparedStatement statement = conn.prepareStatement(CoordinateQeury)) { statement.setShort(1, coordinateSystem.shortValue()); statement.setDouble(2, longitude); statement.setDouble(3, latitude); code = readCode(conn, statement, decodeAncestors); } return code; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static GeographyCode readCode(long gcid, boolean decodeAncestors) { if (gcid <= 0) { return null; } try (Connection conn = DerbyBase.getConnection()) { conn.setReadOnly(true); return readCode(conn, gcid, decodeAncestors); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static GeographyCode readCode(Connection conn, long gcid, boolean decodeAncestors) { if (conn == null || gcid < 0) { return null; } try { GeographyCode code; try (PreparedStatement query = conn.prepareStatement(GCidQeury)) { query.setLong(1, gcid); code = readCode(conn, query, decodeAncestors); } return code; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static GeographyCode readCode(int level, String name, boolean decodeAncestors) { if (level <= 0 || name == null) { return null; } try (Connection conn = DerbyBase.getConnection()) { conn.setReadOnly(true); return readCode(conn, level, name, decodeAncestors); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static GeographyCode readCode(Connection conn, int level, String name, boolean decodeAncestors) { if (level <= 0 || name == null) { return null; } try { GeographyCode code; try (PreparedStatement statement = conn.prepareStatement(LevelNameQeury)) { statement.setInt(1, level); setNameParameters(statement, name, 1); code = readCode(conn, statement, decodeAncestors); } return code; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static GeographyCode readCode(GeographyCode code, boolean decodeAncestors) { if (code == null || !GeographyCode.valid(code)) { return null; } try (Connection conn = DerbyBase.getConnection()) { conn.setReadOnly(true); return readCode(conn, code, decodeAncestors); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static boolean setCodeQueryParameters2(PreparedStatement statement, GeographyCode code) { if (statement == null || code == null) { return false; } try { fixValues(code); int level = code.getLevel(); String name; if (code.getChineseName() != null) { name = stringValue(code.getChineseName()).toLowerCase(); } else if (code.getEnglishName() != null) { name = stringValue(code.getEnglishName()).toLowerCase(); } else { return false; } statement.setShort(1, (short) level); statement.setLong(2, level > 2 ? code.getContinent() : -1); statement.setLong(3, level > 3 ? code.getCountry() : -1); statement.setLong(4, level > 4 ? code.getProvince() : -1); statement.setLong(5, level > 5 ? code.getCity() : -1); statement.setLong(6, level > 6 ? code.getCounty() : -1); statement.setLong(7, level > 7 ? code.getTown() : -1); statement.setLong(8, level > 8 ? code.getVillage() : -1); statement.setString(9, name); statement.setString(10, name); statement.setString(11, name); statement.setString(12, name); statement.setString(13, name); statement.setString(14, name); statement.setString(15, name); MyBoxLog.debug(name); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static GeographyCode readCode(Connection conn, GeographyCode code, boolean decodeAncestors) { if (conn == null || code == null || !GeographyCode.valid(code)) { return null; } try { if (code.getGcid() > 0) { try (PreparedStatement statement = conn.prepareStatement(GCidQeury)) { statement.setLong(1, code.getGcid()); return readCode(conn, statement, decodeAncestors); } } else { int level = code.getLevel(); String condition = "level=" + level; switch (level) { case 3: // condition += " AND continent=" + code.getContinent(); break; case 4: condition += " AND continent=" + code.getContinent() + " AND country=" + code.getCountry(); break; case 5: condition += " AND continent=" + code.getContinent() + " AND country=" + code.getCountry() + " AND province=" + code.getProvince(); break; case 6: condition += " AND continent=" + code.getContinent() + " AND country=" + code.getCountry() + " AND province=" + code.getProvince() + " AND city=" + code.getCity(); break; case 7: condition += " AND country=" + code.getCountry() + " AND province=" + code.getProvince() + " AND city=" + code.getCity() + " AND county=" + code.getCounty(); break; case 8: condition += " AND continent=" + code.getContinent() + " AND country=" + code.getCountry() + " AND province=" + code.getProvince() + " AND city=" + code.getCity() + " AND county=" + code.getCounty() + " AND town=" + code.getTown(); break; case 9: condition += " AND continent=" + code.getContinent() + " AND country=" + code.getCountry() + " AND province=" + code.getProvince() + " AND city=" + code.getCity() + " AND county=" + code.getCounty() + " AND town=" + code.getTown() + " AND village=" + code.getVillage(); break; case 10: default: condition += " AND continent=" + code.getContinent() + " AND country=" + code.getCountry() + " AND province=" + code.getProvince() + " AND city=" + code.getCity() + " AND county=" + code.getCounty() + " AND town=" + code.getTown() + " AND village=" + code.getVillage() + " AND building=" + code.getBuilding(); break; } String nameEqual = ""; if (code.getChineseName() != null) { String name = stringValue(code.getChineseName()).toLowerCase(); nameEqual = " ( chinese_name IS NOT NULL AND LCASE(chinese_name)='" + name + "' ) OR " + " ( alias1 IS NOT NULL AND LCASE(alias1)='" + name + "' ) OR " + " ( alias2 IS NOT NULL AND LCASE(alias2)='" + name + "' ) OR " + " ( alias3 IS NOT NULL AND LCASE(alias3)='" + name + "' ) OR " + " ( alias4 IS NOT NULL AND LCASE(alias4)='" + name + "' ) OR " + " ( alias5 IS NOT NULL AND LCASE(alias5)='" + name + "' ) "; } if (code.getEnglishName() != null) { String name = stringValue(code.getEnglishName()).toLowerCase(); nameEqual = nameEqual.isBlank() ? "" : nameEqual + " OR "; nameEqual += " ( english_name IS NOT NULL AND LCASE(english_name)='" + name + "' ) OR " + " ( alias1 IS NOT NULL AND LCASE(alias1)='" + name + "' ) OR " + " ( alias2 IS NOT NULL AND LCASE(alias2)='" + name + "' ) OR " + " ( alias3 IS NOT NULL AND LCASE(alias3)='" + name + "' ) OR " + " ( alias4 IS NOT NULL AND LCASE(alias4)='" + name + "' ) OR " + " ( alias5 IS NOT NULL AND LCASE(alias5)='" + name + "' ) "; } if (nameEqual.isBlank()) { return null; } String sql = "SELECT * FROM Geography_Code WHERE " + condition + " AND (" + nameEqual + ")"; return queryCode(conn, sql, decodeAncestors); } } catch (Exception e) { MyBoxLog.error(e); return null; } } // Generally, when location full name is need, "decodeAncestors" should be true public static GeographyCode readCode(Connection conn, PreparedStatement query, boolean decodeAncestors) { if (conn == null || query == null) { return null; } try { GeographyCode code; query.setMaxRows(1); conn.setAutoCommit(true); try (ResultSet results = query.executeQuery()) { if (results.next()) { code = readResults(results); } else { return null; } } if (decodeAncestors && code != null) { decodeAncestors(conn, query, code); } return code; } catch (Exception e) { MyBoxLog.error(e); // MyBoxLog.debug(e); return null; } } public static GeographyCode readResults(Connection conn, ResultSet results, boolean decodeAncestors) { if (conn == null || results == null) { return null; } try { GeographyCode code = readResults(results); if (decodeAncestors && code != null) { decodeAncestors(conn, code); } return code; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static GeographyCode decodeAncestors(GeographyCode code) { if (code == null) { return null; } try (Connection conn = DerbyBase.getConnection()) { conn.setReadOnly(true); decodeAncestors(conn, code); } catch (Exception e) { MyBoxLog.error(e); } return code; } public static void decodeAncestors(Connection conn, GeographyCode code) { if (conn == null || code == null) { return; } try (PreparedStatement query = conn.prepareStatement(GCidQeury)) { decodeAncestors(conn, query, code); } catch (Exception e) { MyBoxLog.error(e); } } public static void decodeAncestors(Connection conn, PreparedStatement query, GeographyCode code) { if (conn == null || code == null) { return; } int level = code.getLevel(); if (level < 3 || level > 10) { return; } try { conn.setAutoCommit(true); if (code.getContinent() > 0) { query.setLong(1, code.getContinent()); try (ResultSet cresults = query.executeQuery()) { if (cresults.next()) { code.setContinentCode(readResults(cresults)); } } } if (level < 4) { return; } if (code.getCountry() > 0) { query.setLong(1, code.getCountry()); try (ResultSet cresults = query.executeQuery()) { if (cresults.next()) { code.setCountryCode(readResults(cresults)); } } } if (level < 5) { return; } if (code.getProvince() > 0) {
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/InfoNodeTag.java
alpha/MyBox/src/main/java/mara/mybox/db/migration/InfoNodeTag.java
package mara.mybox.db.migration; import mara.mybox.db.data.BaseData; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2022-3-11 * @License Apache License Version 2.0 */ public class InfoNodeTag extends BaseData { protected long ttid, tnodeid, tagid; protected InfoNode node; protected Tag tag; private void init() { ttid = tnodeid = tagid = -1; node = null; tag = null; } public InfoNodeTag() { init(); } public InfoNodeTag(long tnodeid, long tagid) { init(); this.tnodeid = tnodeid; this.tagid = tagid; } public InfoNodeTag(InfoNode node, Tag tag) { init(); this.node = node; this.tag = tag; this.tnodeid = node == null ? -1 : node.getNodeid(); this.tagid = tag == null ? -1 : tag.getTgid(); } @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 InfoNodeTag create() { return new InfoNodeTag(); } public static boolean setValue(InfoNodeTag data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "ttid": data.setTtid(value == null ? -1 : (long) value); return true; case "tnodeid": data.setTnodeid(value == null ? -1 : (long) value); return true; case "tagid": data.setTagid(value == null ? -1 : (long) value); return true; } } catch (Exception e) { MyBoxLog.debug(e); } return false; } public static Object getValue(InfoNodeTag data, String column) { if (data == null || column == null) { return null; } switch (column) { case "ttid": return data.getTtid(); case "tnodeid": return data.getTnodeid(); case "tagid": return data.getTagid(); } return null; } public static boolean valid(InfoNodeTag data) { return data != null && data.getTnodeid() > 0 && data.getTagid() > 0; } /* get/set */ public long getTtid() { return ttid; } public void setTtid(long ttid) { this.ttid = ttid; } public long getTnodeid() { return tnodeid; } public void setTnodeid(long tnodeid) { this.tnodeid = tnodeid; } public long getTagid() { return tagid; } public void setTagid(long tagid) { this.tagid = tagid; } public InfoNode getNode() { return node; } public void setNode(InfoNode node) { this.node = node; } public Tag getTag() { return tag; } public void setTag(Tag tag) { this.tag = tag; } }
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/DataMigrationFrom65to67.java
alpha/MyBox/src/main/java/mara/mybox/db/migration/DataMigrationFrom65to67.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 javafx.application.Platform; import mara.mybox.data2d.DataTable; import mara.mybox.data2d.tools.Data2DTableTools; import mara.mybox.db.Database; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.Data2DColumn; import mara.mybox.db.data.Data2DDefinition; import mara.mybox.db.data.Data2DRow; import mara.mybox.db.data.Data2DStyle; import mara.mybox.db.data.WebHistory; import static mara.mybox.db.migration.DataMigration.alterColumnLength; import static mara.mybox.db.table.BaseTable.StringMaxLength; import mara.mybox.db.table.TableAlarmClock; import mara.mybox.db.table.TableColorPalette; import mara.mybox.db.table.TableData2D; import mara.mybox.db.table.TableData2DColumn; import mara.mybox.db.table.TableData2DDefinition; import mara.mybox.db.table.TableData2DStyle; import mara.mybox.db.table.TableStringValues; import mara.mybox.db.table.TableWebHistory; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxFileTools; import mara.mybox.fxml.PopTools; import mara.mybox.image.data.ImageAttributes; import mara.mybox.image.tools.ImageConvertTools; import mara.mybox.tools.DateTools; import mara.mybox.tools.FileDeleteTools; import mara.mybox.value.AppPaths; import static mara.mybox.value.Languages.message; import static mara.mybox.value.Languages.sysDefaultLanguage; import mara.mybox.value.TimeFormats; /** * @Author Mara * @CreateDate 2020-06-09 * @License Apache License Version 2.0 */ public class DataMigrationFrom65to67 { public static void handleVersions(int lastVersion, Connection conn) { try { if (lastVersion < 6005001) { updateIn651(conn); } if (lastVersion < 6005002) { updateIn652(conn); } if (lastVersion < 6005003) { updateIn653(conn); } if (lastVersion < 6005004) { updateIn654(conn); } if (lastVersion < 6005005) { updateIn655(conn); } if (lastVersion < 6005006) { updateIn656(conn); } if (lastVersion < 6005007) { updateIn657(conn); } if (lastVersion < 6005008) { updateIn658(conn); } if (lastVersion < 6005009) { updateIn659(conn); } if (lastVersion < 6006000) { updateIn660(conn); } if (lastVersion < 6006001) { updateIn661(conn); } if (lastVersion < 6006002) { updateIn662(conn); } if (lastVersion < 6007000) { updateIn67(conn); } if (lastVersion < 6007001) { updateIn671(conn); } if (lastVersion < 6007003) { updateIn673(conn); } if (lastVersion < 6007007) { updateIn677(conn); } if (lastVersion < 6007008) { updateIn678(conn); } } catch (Exception e) { MyBoxLog.error(e); } } public static void updateIn678(Connection conn) { try (Statement statement = conn.createStatement()) { MyBoxLog.info("Updating tables in 6.7.8..."); conn.setAutoCommit(true); statement.executeUpdate("DROP INDEX Tree_Node_title_index"); statement.executeUpdate(TableInfoNode.Create_Title_Index); } catch (Exception e) { MyBoxLog.error(e); } } public static void updateIn677(Connection conn) { try (Statement statement = conn.createStatement()) { MyBoxLog.info("Updating tables in 6.7.7..."); conn.setAutoCommit(true); statement.executeUpdate("ALTER TABLE Tree_Node ADD COLUMN info CLOB "); TableInfoNode tableTreeNode = new TableInfoNode(); ResultSet query = statement.executeQuery("SELECT * FROM Tree_Node"); while (query.next()) { InfoNode node = tableTreeNode.readData(query); String value = query.getString("value"); String more = query.getString("more"); String info; if (value != null && !value.isBlank()) { info = value.trim() + "\n"; } else { info = ""; } if (more != null && !more.isBlank()) { info += InfoNode.MoreSeparater + "\n" + more.trim(); } node.setInfo(info); tableTreeNode.updateData(conn, node); } statement.executeUpdate("ALTER TABLE Tree_Node DROP COLUMN value"); statement.executeUpdate("ALTER TABLE Tree_Node DROP COLUMN more"); } catch (Exception e) { MyBoxLog.error(e); } } public static void updateIn673(Connection conn) { try (Statement statement = conn.createStatement()) { MyBoxLog.info("Updating tables in 6.7.3..."); conn.setAutoCommit(true); statement.executeUpdate("ALTER TABLE Image_Edit_History ADD COLUMN thumbnail_file VARCHAR(" + StringMaxLength + ")"); } catch (Exception e) { MyBoxLog.error(e); } } public static void updateIn671(Connection conn) { try (Statement statement = conn.createStatement()) { MyBoxLog.info("Updating tables in 6.7.1..."); conn.setAutoCommit(true); statement.executeUpdate("ALTER TABLE Color ADD COLUMN ryb FLOAT "); statement.executeUpdate("ALTER TABLE Color_Palette ADD COLUMN description VARCHAR(" + StringMaxLength + ")"); statement.executeUpdate("ALTER TABLE Color_Palette_Name ADD COLUMN visit_time TIMESTAMP "); statement.executeUpdate("DROP INDEX Color_Palette_unique_index"); statement.executeUpdate("DROP VIEW Color_Palette_View"); statement.executeUpdate(TableColorPalette.CreateView); } catch (Exception e) { MyBoxLog.error(e); } } public static void updateIn67(Connection conn) { try { MyBoxLog.info("Updating tables in 6.7..."); conn.setAutoCommit(true); TableStringValues.clear("GameEliminationImage"); } catch (Exception e) { MyBoxLog.error(e); } } public static void updateIn662(Connection conn) { try (Statement statement = conn.createStatement()) { MyBoxLog.info("Updating tables in 6.6.2..."); conn.setAutoCommit(true); statement.executeUpdate("ALTER TABLE Data2D_Column DROP COLUMN label"); } catch (Exception e) { MyBoxLog.error(e); } } public static void updateIn661(Connection conn) { try (Statement statement = conn.createStatement()) { MyBoxLog.info("Updating tables in 6.6.1..."); conn.setAutoCommit(true); statement.executeUpdate("ALTER TABLE Data2D_Column ADD COLUMN scale INT"); statement.executeUpdate("ALTER TABLE Data2D_Column ADD COLUMN format VARCHAR(" + StringMaxLength + ")"); statement.executeUpdate("ALTER TABLE Data2D_Column ADD COLUMN fix_year BOOLEAN"); statement.executeUpdate("ALTER TABLE Data2D_Column ADD COLUMN century INT"); statement.executeUpdate("ALTER TABLE Data2D_Column ADD COLUMN invalid_as SMALLINT"); statement.executeUpdate("UPDATE Data2D_Column SET column_type=0 WHERE column_type=2"); statement.executeUpdate("UPDATE Data2D_Column SET format='" + TimeFormats.Datetime + "' WHERE time_format < 2 AND column_type < 6"); statement.executeUpdate("UPDATE Data2D_Column SET format='" + TimeFormats.Date + "' WHERE time_format=2 AND column_type < 6"); statement.executeUpdate("UPDATE Data2D_Column SET format='" + TimeFormats.Year + "' WHERE time_format=3 AND column_type < 6"); statement.executeUpdate("UPDATE Data2D_Column SET format='" + TimeFormats.Month + "' WHERE time_format=4 AND column_type < 6"); statement.executeUpdate("UPDATE Data2D_Column SET format='" + TimeFormats.Time + "' WHERE time_format=5 AND column_type < 6"); statement.executeUpdate("UPDATE Data2D_Column SET format='" + TimeFormats.TimeMs + "' WHERE time_format=6 AND column_type < 6"); statement.executeUpdate("UPDATE Data2D_Column SET format='" + TimeFormats.DatetimeMs + "' WHERE time_format=7 AND column_type < 6"); statement.executeUpdate("UPDATE Data2D_Column SET format='" + TimeFormats.Datetime + " Z' WHERE time_format=8 AND column_type < 6"); statement.executeUpdate("UPDATE Data2D_Column SET format='" + TimeFormats.DatetimeMs + " Z' WHERE time_format=9 AND column_type < 6"); statement.executeUpdate("UPDATE Data2D_Column SET format='#,###' WHERE need_format=true AND column_type >= 6 AND column_type <= 10"); statement.executeUpdate("UPDATE Data2D_Column SET format=null WHERE column_type = 1"); statement.executeUpdate("ALTER TABLE Data2D_Column DROP COLUMN need_format"); statement.executeUpdate("ALTER TABLE Data2D_Column DROP COLUMN time_format"); statement.executeUpdate("ALTER TABLE Data2D_Column DROP COLUMN values_list"); updateIn661MoveLocations(conn); updateIn661MoveEpidemicReports(conn); statement.executeUpdate("DELETE FROM VISIT_HISTORY WHERE resource_type=4 AND resource_value='Location Data'"); statement.executeUpdate("DELETE FROM VISIT_HISTORY WHERE resource_type=4 AND resource_value='位置数据'"); statement.executeUpdate("DELETE FROM VISIT_HISTORY WHERE resource_type=4 AND resource_value='Epidemic Report'"); statement.executeUpdate("DELETE FROM VISIT_HISTORY WHERE resource_type=4 AND resource_value='疫情报告'"); Platform.runLater(() -> { if ("zh".equals(sysDefaultLanguage())) { PopTools.alertInformation(null, "功能'位置数据'和'疫情报告'已被移除。\n" + "它们已存在的数据可在菜单'数据 - 数据库 - 数据库表'下访问。"); } else { PopTools.alertInformation(null, "Functions 'Location Data' and 'Epidemic Report' have been removed.\n" + "Their existed data can be accessed under menu 'Data - Database - Database Table'."); } }); } catch (Exception e) { MyBoxLog.error(e); } } public static void updateIn661MoveLocations(Connection conn) { try (Statement statement = conn.createStatement()) { DataTable locations = new DataTable(); String tableName = message("LocationData"); if (DerbyBase.exist(conn, tableName) == 1) { tableName = message("LocationData") + "_" + DateTools.nowString3(); } List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message("DataSet"), ColumnType.String)); columns.add(new Data2DColumn(message("Label"), ColumnType.String)); columns.add(new Data2DColumn(message("Address"), ColumnType.String)); columns.add(new Data2DColumn(message("Longitude"), ColumnType.Longitude)); columns.add(new Data2DColumn(message("Latitude"), ColumnType.Latitude)); columns.add(new Data2DColumn(message("Altitude"), ColumnType.Double)); columns.add(new Data2DColumn(message("Precision"), ColumnType.Double)); columns.add(new Data2DColumn(message("Speed"), ColumnType.Double)); columns.add(new Data2DColumn(message("Direction"), ColumnType.Short)); columns.add(new Data2DColumn(message("CoordinateSystem"), ColumnType.String)); columns.add(new Data2DColumn(message("DataValue"), ColumnType.Double)); columns.add(new Data2DColumn(message("DataSize"), ColumnType.Double)); columns.add(new Data2DColumn(message("StartTime"), ColumnType.Era)); columns.add(new Data2DColumn(message("EndTime"), ColumnType.Era)); columns.add(new Data2DColumn(message("Image"), ColumnType.String)); columns.add(new Data2DColumn(message("Comments"), ColumnType.String)); locations = Data2DTableTools.createTable(null, conn, tableName, columns, null, null, null, false); TableData2D tableLocations = locations.getTableData2D(); long count = 0; try (ResultSet query = statement.executeQuery("SELECT * FROM Location_Data_View"); PreparedStatement insert = conn.prepareStatement(tableLocations.insertStatement())) { conn.setAutoCommit(false); while (query.next()) { try { Data2DRow data2DRow = tableLocations.newRow(); data2DRow.setValue(message("DataSet"), query.getString("data_set")); data2DRow.setValue(message("Label"), query.getString("label")); data2DRow.setValue(message("Address"), query.getString("address")); data2DRow.setValue(message("Longitude"), query.getDouble("longitude")); data2DRow.setValue(message("Latitude"), query.getDouble("latitude")); data2DRow.setValue(message("Altitude"), query.getDouble("altitude")); data2DRow.setValue(message("Precision"), query.getDouble("precision")); data2DRow.setValue(message("Speed"), query.getDouble("speed")); data2DRow.setValue(message("Direction"), query.getShort("direction")); data2DRow.setValue(message("CoordinateSystem"), GeoCoordinateSystem.name(query.getShort("coordinate_system"))); data2DRow.setValue(message("DataValue"), query.getDouble("data_value")); data2DRow.setValue(message("DataSize"), query.getDouble("data_size")); data2DRow.setValue(message("StartTime"), DateTools.datetimeToString(query.getLong("start_time"))); data2DRow.setValue(message("EndTime"), DateTools.datetimeToString(query.getLong("end_time"))); data2DRow.setValue(message("Image"), query.getString("dataset_image")); data2DRow.setValue(message("Comments"), query.getString("location_comments")); tableLocations.insertData(conn, insert, data2DRow); if (++count % Database.BatchSize == 0) { conn.commit(); } } catch (Exception e) { MyBoxLog.console(e); } } conn.commit(); } conn.setAutoCommit(true); statement.executeUpdate("DROP INDEX Dataset_unique_index"); statement.executeUpdate("DROP VIEW Location_Data_View"); statement.executeUpdate("ALTER TABLE Location_Data DROP CONSTRAINT Location_Data_datasetid_fk"); statement.executeUpdate("DROP TABLE Dataset"); statement.executeUpdate("DROP TABLE Location_Data"); } catch (Exception e) { MyBoxLog.error(e); } } public static void updateIn661MoveEpidemicReports(Connection conn) { try (Statement statement = conn.createStatement()) { String tableName = message("EpidemicReport"); if (DerbyBase.exist(conn, tableName) == 1) { tableName = message("EpidemicReport") + "_" + DateTools.nowString3(); } List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message("DataSet"), ColumnType.String)); columns.add(new Data2DColumn(message("Time"), ColumnType.Datetime)); columns.add(new Data2DColumn(message("Address"), ColumnType.String)); columns.add(new Data2DColumn(message("Longitude"), ColumnType.Longitude)); columns.add(new Data2DColumn(message("Latitude"), ColumnType.Latitude)); columns.add(new Data2DColumn(message("Level"), ColumnType.String)); columns.add(new Data2DColumn(message("Continent"), ColumnType.String)); columns.add(new Data2DColumn(message("Country"), ColumnType.String)); columns.add(new Data2DColumn(message("Province"), ColumnType.String)); columns.add(new Data2DColumn(message("CoordinateSystem"), ColumnType.String)); columns.add(new Data2DColumn(message("Confirmed"), ColumnType.Long)); columns.add(new Data2DColumn(message("Healed"), ColumnType.Long)); columns.add(new Data2DColumn(message("Dead"), ColumnType.Long)); columns.add(new Data2DColumn(message("IncreasedConfirmed"), ColumnType.Long)); columns.add(new Data2DColumn(message("IncreasedHealed"), ColumnType.Long)); columns.add(new Data2DColumn(message("IncreasedDead"), ColumnType.Long)); columns.add(new Data2DColumn(message("Source"), ColumnType.String)); // 1:predefined 2:added 3:filled 4:statistic others:unknown columns.add(new Data2DColumn(message("Comments"), ColumnType.String)); DataTable reports = Data2DTableTools.createTable(null, conn, tableName, columns, null, null, null, false); TableData2D tableReports = reports.getTableData2D(); long count = 0; try (ResultSet query = statement.executeQuery("SELECT * FROM Epidemic_Report"); PreparedStatement insert = conn.prepareStatement(tableReports.insertStatement())) { conn.setAutoCommit(false); while (query.next()) { try { Data2DRow data2DRow = tableReports.newRow(); data2DRow.setValue(message("DataSet"), query.getString("data_set")); data2DRow.setValue(message("Time"), query.getTimestamp("time")); long locationid = query.getLong("locationid"); GeographyCode code = TableGeographyCode.readCode(conn, locationid, true); if (code != null) { try { data2DRow.setValue(message("Address"), code.getName()); data2DRow.setValue(message("Longitude"), code.getLongitude()); data2DRow.setValue(message("Latitude"), code.getLatitude()); data2DRow.setValue(message("Level"), code.getLevelName()); data2DRow.setValue(message("CoordinateSystem"), code.getCoordinateSystem().name()); data2DRow.setValue(message("Comments"), code.getFullName()); } catch (Exception e) { MyBoxLog.console(e); } } data2DRow.setValue(message("Confirmed"), query.getLong("confirmed")); data2DRow.setValue(message("Healed"), query.getLong("healed")); data2DRow.setValue(message("Dead"), query.getLong("dead")); data2DRow.setValue(message("IncreasedConfirmed"), query.getLong("increased_confirmed")); data2DRow.setValue(message("IncreasedHealed"), query.getLong("increased_healed")); data2DRow.setValue(message("IncreasedDead"), query.getLong("increased_dead")); short sd = query.getShort("source"); String source; source = switch (sd) { case 1 -> message("PredefinedData"); case 2 -> message("InputtedData"); case 3 -> message("FilledData"); case 4 -> message("StatisticData"); default -> message("Unknown"); }; data2DRow.setValue(message("Source"), source); tableReports.insertData(conn, insert, data2DRow); if (++count % Database.BatchSize == 0) { conn.commit(); } } catch (Exception e) { MyBoxLog.console(e); } } conn.commit(); } conn.setAutoCommit(true); statement.executeUpdate("DROP INDEX Epidemic_Report_DatasetTimeDesc_index"); statement.executeUpdate("DROP INDEX Epidemic_Report_DatasetTimeAsc_index"); statement.executeUpdate("DROP INDEX Epidemic_Report_timeAsc_index"); statement.executeUpdate("DROP VIEW Epidemic_Report_Statistic_View"); statement.executeUpdate("ALTER TABLE Epidemic_Report DROP CONSTRAINT Epidemic_Report_locationid_fk"); statement.executeUpdate("DROP TABLE Epidemic_Report"); } catch (Exception e) { MyBoxLog.error(e); } } public static void updateIn660(Connection conn) { try (Statement statement = conn.createStatement()) { MyBoxLog.info("Updating tables in 6.6..."); conn.setAutoCommit(true); statement.executeUpdate("ALTER TABLE Data2D_Column ADD COLUMN description VARCHAR(" + StringMaxLength + ")"); } catch (Exception e) { MyBoxLog.error(e); } } public static void updateIn659(Connection conn) { try (Statement statement = conn.createStatement()) { MyBoxLog.info("Updating tables in 6.5.9..."); conn.setAutoCommit(true); statement.executeUpdate("ALTER TABLE Data2D_Column ADD COLUMN need_format Boolean"); // Users' data are discarded. Sorry! statement.executeUpdate("DROP TABLE Alarm_Clock"); new TableAlarmClock().createTable(conn); } catch (Exception e) { MyBoxLog.error(e); } } public static void updateIn658(Connection conn) { try (Statement statement = conn.createStatement()) { MyBoxLog.info("Updating tables in 6.5.8..."); conn.setAutoCommit(true); statement.executeUpdate("ALTER TABLE Data2D_Style ADD COLUMN filter VARCHAR(" + StringMaxLength + ")"); statement.executeUpdate("ALTER TABLE Data2D_Style ADD COLUMN filterReversed Boolean"); TableData2DStyle tableData2DStyle = new TableData2DStyle(); ResultSet query = statement.executeQuery("SELECT * FROM Data2D_Style ORDER BY d2id,sequence,d2sid"); while (query.next()) { String rowFilter = query.getString("rowFilter"); Data2DStyle style = tableData2DStyle.readData(query); if (rowFilter != null && !rowFilter.isBlank()) { if (rowFilter.startsWith("Reversed::")) { style.setFilter(rowFilter.substring("Reversed::".length())); style.setMatchFalse(true); } else { style.setFilter(rowFilter); style.setMatchFalse(false); } } // discard data about column filter. Sorry! tableData2DStyle.updateData(conn, style); } statement.executeUpdate("ALTER TABLE Data2D_Style DROP COLUMN rowFilter"); statement.executeUpdate("ALTER TABLE Data2D_Style DROP COLUMN columnFilter"); FxFileTools.getInternalFile("/js/tianditu.html", "js", "tianditu.html", true); } catch (Exception e) { MyBoxLog.error(e); } } public static void updateIn657(Connection conn) { try (Statement statement = conn.createStatement()) { MyBoxLog.info("Updating tables in 6.5.7..."); conn.setAutoCommit(true); statement.executeUpdate("ALTER TABLE Data2D_Style ADD COLUMN rowFilter VARCHAR(" + StringMaxLength + ")"); statement.executeUpdate("UPDATE Data2D_Style SET rowFilter=moreConditions"); statement.executeUpdate("ALTER TABLE Data2D_Style DROP COLUMN moreConditions"); statement.executeUpdate("ALTER TABLE Data2D_Style ADD COLUMN columnFilter VARCHAR(" + StringMaxLength + ")"); statement.executeUpdate("ALTER TABLE Data2D_Style ADD COLUMN abnoramlValues Boolean"); statement.executeUpdate("ALTER TABLE Data2D_Style ADD COLUMN title VARCHAR(" + StringMaxLength + ")"); } catch (Exception e) { MyBoxLog.error(e); } } public static void updateIn656(Connection conn) { try (Statement statement = conn.createStatement()) { MyBoxLog.info("Updating tables in 6.5.6..."); conn.setAutoCommit(true); statement.executeUpdate("DROP INDEX Data2D_Style_unique_index"); statement.executeUpdate("ALTER TABLE Data2D_Style ADD COLUMN rowStart BigInt"); statement.executeUpdate("ALTER TABLE Data2D_Style ADD COLUMN rowEnd BigInt"); statement.executeUpdate("ALTER TABLE Data2D_Style ADD COLUMN columns VARCHAR(" + StringMaxLength + ")"); statement.executeUpdate("ALTER TABLE Data2D_Style ADD COLUMN moreConditions VARCHAR(" + StringMaxLength + ")"); statement.executeUpdate("ALTER TABLE Data2D_Style ADD COLUMN fontColor VARCHAR(64)"); statement.executeUpdate("ALTER TABLE Data2D_Style ADD COLUMN fontSize VARCHAR(64)"); statement.executeUpdate("ALTER TABLE Data2D_Style ADD COLUMN bgColor VARCHAR(64)"); statement.executeUpdate("ALTER TABLE Data2D_Style ADD COLUMN bold Boolean"); statement.executeUpdate("ALTER TABLE Data2D_Style ADD COLUMN moreStyle VARCHAR(" + StringMaxLength + ")"); statement.executeUpdate("ALTER TABLE Data2D_Style ADD COLUMN sequence int"); conn.setAutoCommit(false); TableData2DStyle tableData2DStyle = new TableData2DStyle(); ResultSet query = statement.executeQuery("SELECT * FROM Data2D_Style ORDER BY d2id,colName,row"); long lastD2id = -1, lastRow = -2, rowStart = -1, sequence = 1; String lastColName = null, lastStyle = null; Data2DStyle data2DStyle = Data2DStyle.create() .setRowStart(rowStart).setRowEnd(rowStart); while (query.next()) { long d2id = query.getLong("d2id"); String colName = query.getString("colName"); String style = query.getString("style"); long row = query.getLong("row"); if (lastD2id != d2id || !colName.equals(lastColName) || !style.equals(lastStyle)) { if (data2DStyle.getRowStart() >= 0) { if (lastD2id != d2id) { sequence = 1; } data2DStyle.setStyleID(-1).setRowEnd(lastRow + 1).setSequence(sequence++); tableData2DStyle.insertData(conn, data2DStyle); conn.commit(); } rowStart = row; data2DStyle.setDataID(d2id).setColumns(colName).setMoreStyle(style) .setRowStart(rowStart).setRowEnd(rowStart + 1); } else if (row > lastRow + 1) { data2DStyle.setStyleID(-1).setRowEnd(lastRow + 1).setSequence(sequence++); tableData2DStyle.insertData(conn, data2DStyle); conn.commit(); rowStart = row; data2DStyle.setDataID(d2id).setColumns(colName).setMoreStyle(style) .setRowStart(rowStart).setRowEnd(rowStart + 1); } lastD2id = d2id; lastRow = row; lastColName = colName; lastStyle = style; } if (data2DStyle.getRowStart() >= 0) { data2DStyle.setStyleID(-1).setRowEnd(lastRow + 1).setSequence(sequence++); tableData2DStyle.insertData(conn, data2DStyle); conn.commit(); } conn.setAutoCommit(true); statement.executeUpdate("ALTER TABLE Data2D_Style DROP COLUMN row"); statement.executeUpdate("ALTER TABLE Data2D_Style DROP COLUMN colName"); statement.executeUpdate("ALTER TABLE Data2D_Style DROP COLUMN style"); statement.executeUpdate("DELETE FROM Data2D_Style WHERE columns IS NULL"); } catch (Exception e) { MyBoxLog.error(e); } } public static void updateIn655(Connection conn) { try (Statement statement = conn.createStatement()) { MyBoxLog.info("Updating tables in 6.5.5..."); ImageAttributes attributes = new ImageAttributes() .setImageFormat("png").setColorSpaceName("sRGB") .setAlpha(ImageAttributes.Alpha.Keep).setQuality(100); File iconPath = new File(AppPaths.getIconsPath()); for (File s : iconPath.listFiles()) { String name = s.getAbsolutePath(); if (s.isFile() && name.endsWith(".ico")) { File t = new File(name.substring(0, name.lastIndexOf(".")) + ".png"); ImageConvertTools.convertColorSpace(null, s, attributes, t); if (t.exists()) { FileDeleteTools.delete(s); } } } conn.setAutoCommit(false); // TableTreeNode tableTreeNode = new TableTreeNode(); // ResultSet query = statement.executeQuery("SELECT * FROM Tree_Node " // + "WHERE category='" + InfoNode.WebFavorite + "' AND more is not null"); // while (query.next()) { // InfoNode node = tableTreeNode.readData(query); // String icon = node.getMore(); // if (icon != null && icon.endsWith(".ico")) { // icon = icon.replace(".ico", ".png"); // node.setMore(icon); // tableTreeNode.updateData(conn, node); // } // } // conn.commit(); ResultSet query = statement.executeQuery("SELECT * FROM Web_History " + "WHERE icon is not null"); TableWebHistory tableWebHistory = new TableWebHistory(); while (query.next()) { WebHistory his = tableWebHistory.readData(query); String icon = his.getIcon(); if (icon != null && icon.endsWith(".ico")) { icon = icon.substring(0, icon.lastIndexOf(".")) + ".png"; his.setIcon(icon); tableWebHistory.updateData(conn, his); } } conn.commit(); conn.setAutoCommit(true); } catch (Exception e) { MyBoxLog.error(e); } } public static void updateIn654(Connection conn) { try (Statement statement = conn.createStatement()) { MyBoxLog.info("Updating tables in 6.5.4..."); conn.setAutoCommit(true); statement.executeUpdate("ALTER TABLE Tag ADD COLUMN category VARCHAR(" + StringMaxLength + ") NOT NULL DEFAULT 'Root'"); statement.executeUpdate("ALTER TABLE Tag ADD COLUMN color VARCHAR(" + StringMaxLength + ")"); statement.executeUpdate("DROP INDEX Tag_unique_index"); statement.executeUpdate("CREATE UNIQUE INDEX Tag_unique_index on Tag ( category, tag )"); statement.executeUpdate("UPDATE Tag SET category='" + InfoNode.Notebook + "'");
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/data/ColorPaletteName.java
alpha/MyBox/src/main/java/mara/mybox/db/data/ColorPaletteName.java
package mara.mybox.db.data; import java.util.Date; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2021-3-31 * @License Apache License Version 2.0 */ public class ColorPaletteName extends BaseData { protected long cpnid; protected String name; protected Date visitTime; private void init() { cpnid = -1; name = null; visitTime = new Date(); } public ColorPaletteName() { init(); } public ColorPaletteName(String name) { init(); this.name = name; } @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 ColorPaletteName create() { return new ColorPaletteName(); } public static boolean setValue(ColorPaletteName data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "cpnid": data.setCpnid(value == null ? -1 : (long) value); return true; case "palette_name": data.setName(value == null ? null : (String) value); return true; case "visit_time": data.setVisitTime(value == null ? null : (Date) value); return true; } } catch (Exception e) { MyBoxLog.debug(e); } return false; } public static Object getValue(ColorPaletteName data, String column) { if (data == null || column == null) { return null; } switch (column) { case "cpnid": return data.getCpnid(); case "palette_name": return data.getName(); case "visit_time": return data.getVisitTime(); } return null; } public static boolean valid(ColorPaletteName data) { return data != null && data.getName() != null && !data.getName().isBlank(); } /* get/set */ public long getCpnid() { return cpnid; } public void setCpnid(long cpnid) { this.cpnid = cpnid; } public String getName() { return name; } public ColorPaletteName setName(String name) { this.name = name; return this; } public Date getVisitTime() { return visitTime; } public ColorPaletteName setVisitTime(Date visitTime) { this.visitTime = visitTime; 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/data/Data2DColumn.java
alpha/MyBox/src/main/java/mara/mybox/db/data/Data2DColumn.java
package mara.mybox.db.data; import javafx.scene.control.CheckBox; import mara.mybox.data2d.tools.Data2DColumnTools; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2020-7-12 * @License Apache License Version 2.0 */ public class Data2DColumn extends ColumnDefinition { protected Data2DDefinition data2DDefinition; protected long columnID, dataID; public final void initData2DColumn() { initColumnDefinition(); columnID = -1; dataID = -1; data2DDefinition = null; } public Data2DColumn() { initData2DColumn(); } public Data2DColumn(String name, ColumnType type) { initData2DColumn(); this.columnName = name; this.type = type; } public Data2DColumn(String name, ColumnType type, int width) { initData2DColumn(); this.columnName = name; this.type = type; this.width = width; } public Data2DColumn(String name, ColumnType type, boolean notNull) { initData2DColumn(); this.columnName = name; this.type = type; this.notNull = notNull; } public Data2DColumn(String name, ColumnType type, boolean notNull, boolean isPrimaryKey) { initData2DColumn(); this.columnName = name; this.type = type; this.notNull = notNull; this.isPrimaryKey = isPrimaryKey; } @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); } @Override public Data2DColumn cloneBase() { try { return (Data2DColumn) clone(); } catch (Exception e) { return null; } } @Override public Data2DColumn cloneAll() { try { Data2DColumn newColumn = (Data2DColumn) super.cloneAll(); newColumn.data2DDefinition = data2DDefinition; newColumn.columnID = columnID; newColumn.dataID = dataID; return newColumn; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public Data2DColumn copy() { try { Data2DColumn newColumn = cloneAll(); newColumn.setColumnID(-1).setDataID(-1).setIndex(-1) .setReferTable(null).setReferColumn(null).setReferName(null); return newColumn; } catch (Exception e) { MyBoxLog.debug(e); return null; } } @Override public String info() { return Data2DColumnTools.columnInfo(this); } /* static methods */ public static Data2DColumn create() { return new Data2DColumn(); } public static Object getValue(Data2DColumn data, String column) { if (data == null || column == null) { return null; } switch (column) { case "d2cid": return data.getColumnID(); case "d2id": return data.getDataID(); default: return ColumnDefinition.getValue(data, column); } } public static boolean setValue(Data2DColumn data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "d2cid": data.setColumnID(value == null ? -1 : (long) value); return true; case "d2id": data.setDataID(value == null ? -1 : (long) value); return true; default: return ColumnDefinition.setValue(data, column, value); } } catch (Exception e) { MyBoxLog.debug(e); } return false; } public static boolean matchCheckBox(CheckBox cb, String name) { if (cb == null || name == null) { return false; } if (name.equals(cb.getText())) { return true; } try { Data2DColumn col = (Data2DColumn) cb.getUserData(); return name.equals(col.getColumnName()) || name.equals(col.getLabel()); } catch (Exception e) { return false; } } public static String getCheckBoxColumnName(CheckBox cb) { if (cb == null) { return null; } try { Data2DColumn col = (Data2DColumn) cb.getUserData(); return col.getColumnName(); } catch (Exception e) { } return cb.getText(); } /* get/set */ public Data2DDefinition getData2DDefinition() { return data2DDefinition; } public Data2DColumn setData2DDefinition(Data2DDefinition data2DDefinition) { this.data2DDefinition = data2DDefinition; return this; } public long getColumnID() { return columnID; } public Data2DColumn setColumnID(long d2cid) { this.columnID = d2cid; return this; } public long getDataID() { return dataID; } public Data2DColumn setDataID(long d2id) { this.dataID = d2id; return this; } @Override public Data2DColumn setLabel(String label) { this.label = label; return this; } @Override public Data2DColumn setDescription(String description) { this.description = description; return this; } @Override public Data2DColumn setFormat(String format) { this.format = format; return this; } @Override public Data2DColumn setWidth(int width) { this.width = width; return this; } @Override public Data2DColumn setScale(int scale) { this.scale = scale; return this; } @Override public Data2DColumn setFixTwoDigitYear(boolean fixTwoDigitYear) { this.fixTwoDigitYear = fixTwoDigitYear; 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/data/DataNode.java
alpha/MyBox/src/main/java/mara/mybox/db/data/DataNode.java
package mara.mybox.db.data; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import static mara.mybox.db.table.BaseNodeTable.RootID; import static mara.mybox.value.AppValues.InvalidDouble; import static mara.mybox.value.AppValues.InvalidInteger; import static mara.mybox.value.AppValues.InvalidLong; import static mara.mybox.value.AppValues.InvalidShort; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2021-4-23 * @License Apache License Version 2.0 */ public class DataNode extends BaseData { public static final String TitleSeparater = " > "; public static final String TagsSeparater = ";;;"; public static enum SelectionType { None, Multiple, Single } protected long nodeid, parentid, index, childrenSize; protected String title, hierarchyNumber, chainName; protected float orderNumber; protected Date updateTime; protected Map<String, Object> values; protected final BooleanProperty selected = new SimpleBooleanProperty(false); protected List<DataNode> chainNodes; protected DataNode parentNode; protected List<DataNodeTag> nodeTags; private void init() { nodeid = -1; parentid = RootID; title = null; updateTime = new Date(); orderNumber = 0f; chainNodes = null; parentNode = null; hierarchyNumber = null; chainName = null; index = -1; childrenSize = -1; selected.set(false); } public DataNode() { init(); } public DataNode cloneAll() { try { DataNode node = create() .setNodeid(nodeid) .setParentid(parentid) .setTitle(title) .setOrderNumber(orderNumber) .setUpdateTime(updateTime) .setHierarchyNumber(hierarchyNumber) .setChainNodes(chainNodes) .setParentNode(parentNode) .setChainName(chainName) .setIndex(index) .setChildrenSize(childrenSize); if (values != null) { for (String key : values.keySet()) { node.setValue(key, values.get(key)); } } node.getSelected().set(selected.get()); return node; } catch (Exception e) { return null; } } public String info() { String info = message("ID") + ": " + nodeid + "\n"; info += message("Title") + ": " + title + "\n"; info += message("ParentID") + ": " + parentid + "\n"; info += message("HierarchyNumber") + ": " + hierarchyNumber + "\n"; info += message("ChainName") + ": " + chainName + "\n"; info += message("OrderNumber") + ": " + orderNumber + "\n"; info += message("Values") + ": " + values + "\n"; info += "Ancestors: " + (chainNodes != null ? chainNodes.size() : null) + "\n"; info += "ParentNode: " + (parentNode != null ? parentNode.getTitle() : null) + "\n"; info += "Index: " + index + "\n"; info += message("ChildrenSize") + ": " + childrenSize + "\n"; return info; } @Override public boolean setValue(String column, Object value) { try { switch (column) { case "nodeid": setNodeid(value == null ? -1 : (long) value); return true; case "parentid": setParentid(value == null ? RootID : (long) value); return true; case "title": setTitle(value == null ? null : (String) value); return true; case "order_number": setOrderNumber(value == null ? 0f : (float) value); return true; case "update_time": setUpdateTime(value == null ? new Date() : (Date) value); return true; } if (values == null) { values = new HashMap<>(); } if (value == null) { values.remove(column); } else { values.put(column, value); } return true; } catch (Exception e) { return false; } } @Override public Object getValue(String column) { try { if (column == null) { return null; } switch (column) { case "nodeid": return getNodeid(); case "parentid": return getParentid(); case "title": return getTitle(); case "order_number": return getOrderNumber(); case "update_time": return getUpdateTime(); } return values.get(column); } catch (Exception e) { return null; } } public String getStringValue(String column) { try { Object o = getValue(column); if (o == null) { return null; } return (String) getValue(column); } catch (Exception e) { return null; } } public int getIntValue(String column) { try { Object o = getValue(column); if (o == null) { return InvalidInteger; } return (Integer) getValue(column); } catch (Exception e) { return InvalidInteger; } } public long getLongValue(String column) { try { Object o = getValue(column); if (o == null) { return InvalidLong; } return (Long) getValue(column); } catch (Exception e) { return InvalidLong; } } public short getShortValue(String column) { try { Object o = getValue(column); if (o == null) { return InvalidShort; } return (Short) getValue(column); } catch (Exception e) { return InvalidShort; } } public double getDoubleValue(String column) { try { Object o = getValue(column); if (o == null) { return InvalidDouble; } return (Double) getValue(column); } catch (Exception e) { return InvalidDouble; } } public boolean getBooleanValue(String column) { try { Object o = getValue(column); if (o == null) { return false; } return (Boolean) getValue(column); } catch (Exception e) { return false; } } @Override public boolean valid() { return true; } public boolean isRoot() { return nodeid == RootID; } @Override public boolean equals(Object obj) { try { return ((DataNode) obj).getNodeid() == nodeid; } catch (Exception e) { return false; } } public String shortDescription() { return shortDescription(title); } public String shortDescription(String name) { String s = ""; if (hierarchyNumber != null && !hierarchyNumber.isBlank()) { s += hierarchyNumber + " - "; } if (nodeid > 0) { s += nodeid + " - "; } s += name; return s; } public String getTagNames() { if (nodeTags == null || nodeTags.isEmpty()) { return null; } String names = null, name; for (DataNodeTag nodeTag : nodeTags) { name = nodeTag.getTag().getTag(); if (names == null) { names = name; } else { names += "," + name; } } return names; } /* Static methods */ public static DataNode create() { return new DataNode(); } public static boolean valid(DataNode node) { return node != null; } public static DataNode createChild(DataNode parent) { return create().setParentid(parent.getNodeid()); } public static DataNode createChild(DataNode parent, String title) { return createChild(parent).setTitle(title); } /* get/set */ public long getNodeid() { return nodeid; } public DataNode setNodeid(long nodeid) { this.nodeid = nodeid; return this; } public long getParentid() { return parentid; } public DataNode setParentid(long parentid) { this.parentid = parentid; return this; } public String getTitle() { return title; } public DataNode setTitle(String title) { this.title = title; return this; } public float getOrderNumber() { return orderNumber; } public DataNode setOrderNumber(float orderNumber) { this.orderNumber = orderNumber; return this; } public Date getUpdateTime() { return updateTime; } public DataNode setUpdateTime(Date updateTime) { this.updateTime = updateTime; return this; } public Map<String, Object> getValues() { return values; } public DataNode setValues(Map<String, Object> values) { this.values = values; return this; } public String getHierarchyNumber() { return hierarchyNumber; } public DataNode setHierarchyNumber(String hierarchyNumber) { this.hierarchyNumber = hierarchyNumber; return this; } public BooleanProperty getSelected() { return selected; } public String getChainName() { return chainName; } public DataNode setChainName(String chainName) { this.chainName = chainName; return this; } public List<DataNode> getChainNodes() { return chainNodes; } public DataNode setChainNodes(List<DataNode> nodes) { this.chainNodes = nodes; return this; } public DataNode getParentNode() { return parentNode; } public DataNode setParentNode(DataNode parentNode) { this.parentNode = parentNode; return this; } public long getIndex() { return index; } public DataNode setIndex(long index) { this.index = index; return this; } public long getChildrenSize() { return childrenSize; } public DataNode setChildrenSize(long childrenSize) { this.childrenSize = childrenSize; return this; } public List<DataNodeTag> getNodeTags() { return nodeTags; } public DataNode setNodeTags(List<DataNodeTag> nodeTags) { this.nodeTags = nodeTags; 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/data/VisitHistoryTools.java
alpha/MyBox/src/main/java/mara/mybox/db/data/VisitHistoryTools.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package mara.mybox.db.data; import java.io.File; import java.sql.Connection; import java.util.ArrayList; import java.util.List; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.MenuItem; import javafx.stage.FileChooser; import mara.mybox.controller.BaseController; import mara.mybox.controller.DataTreeController; import static mara.mybox.db.data.VisitHistory.Default_Max_Histories; import mara.mybox.db.data.VisitHistory.FileType; import mara.mybox.db.data.VisitHistory.OperationType; import mara.mybox.db.data.VisitHistory.ResourceType; import mara.mybox.db.table.TableVisitHistory; import mara.mybox.tools.FileNameTools; import mara.mybox.tools.FileTmpTools; import mara.mybox.value.AppVariables; import mara.mybox.value.FileFilters; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * * @author mara */ public class VisitHistoryTools { public static final TableVisitHistory VisitHistories = new TableVisitHistory(); /* base values */ public static String getPathKey(int type) { return "FilePath" + type; } public static String defaultPath(int type) { return FileTmpTools.generatePath(defaultExt(type)); } public static File getSavedPath(int type) { return UserConfig.getPath(getPathKey(type), defaultPath(type)); } public static String defaultExt(int type) { List<FileChooser.ExtensionFilter> filters = getExtensionFilter(type); if (filters == null || filters.isEmpty()) { return null; } String ext = filters.get(0).getExtensions().get(0); if (ext.endsWith("*")) { if (filters.size() > 1) { ext = filters.get(1).getExtensions().get(0); } else { return null; } } return FileNameTools.ext(ext); } public static List<FileChooser.ExtensionFilter> getExtensionFilter(int fileType) { if (fileType == FileType.Image) { return FileFilters.ImageExtensionFilter; } else if (fileType == FileType.PDF) { return FileFilters.PdfExtensionFilter; } else if (fileType == FileType.Text) { return FileFilters.TextExtensionFilter; } else if (fileType == FileType.All) { return FileFilters.AllExtensionFilter; } else if (fileType == FileType.Markdown) { return FileFilters.MarkdownExtensionFilter; } else if (fileType == FileType.Html) { return FileFilters.HtmlExtensionFilter; } else if (fileType == FileType.Gif) { return FileFilters.GifExtensionFilter; } else if (fileType == FileType.Tif) { return FileFilters.TiffExtensionFilter; } else if (fileType == FileType.MultipleFrames) { return FileFilters.MultipleFramesImageExtensionFilter; } else if (fileType == FileType.Media) { return FileFilters.JdkMediaExtensionFilter; } else if (fileType == FileType.Audio) { return FileFilters.SoundExtensionFilter; } else if (fileType == FileType.Icc) { return FileFilters.IccProfileExtensionFilter; } else if (fileType == FileType.Certificate) { return FileFilters.KeyStoreExtensionFilter; } else if (fileType == VisitHistory.FileType.TTC) { return FileFilters.TTCExtensionFilter; } else if (fileType == VisitHistory.FileType.TTF) { return FileFilters.TTFExtensionFilter; } else if (fileType == VisitHistory.FileType.Excel) { return FileFilters.ExcelExtensionFilter; } else if (fileType == VisitHistory.FileType.CSV) { return FileFilters.CsvExtensionFilter; } else if (fileType == VisitHistory.FileType.Sheet) { return FileFilters.SheetExtensionFilter; } else if (fileType == VisitHistory.FileType.Cert) { return FileFilters.CertExtensionFilter; } else if (fileType == VisitHistory.FileType.Word) { return FileFilters.WordExtensionFilter; } else if (fileType == VisitHistory.FileType.WordX) { return FileFilters.WordXExtensionFilter; } else if (fileType == VisitHistory.FileType.WordS) { return FileFilters.WordSExtensionFilter; } else if (fileType == VisitHistory.FileType.PPT) { return FileFilters.PPTExtensionFilter; } else if (fileType == VisitHistory.FileType.PPTX) { return FileFilters.PPTXExtensionFilter; } else if (fileType == VisitHistory.FileType.PPTS) { return FileFilters.PPTSExtensionFilter; } else if (fileType == VisitHistory.FileType.ImagesList) { return FileFilters.ImagesListExtensionFilter; } else if (fileType == VisitHistory.FileType.Jar) { return FileFilters.JarExtensionFilter; } else if (fileType == VisitHistory.FileType.DataFile) { return FileFilters.DataFileExtensionFilter; } else if (fileType == VisitHistory.FileType.JSON) { return FileFilters.JSONExtensionFilter; } else if (fileType == VisitHistory.FileType.XML) { return FileFilters.XMLExtensionFilter; } else if (fileType == VisitHistory.FileType.SVG) { return FileFilters.SVGExtensionFilter; } else if (fileType == VisitHistory.FileType.Javascript) { return FileFilters.JavascriptExtensionFilter; } else { return FileFilters.AllExtensionFilter; } } public static boolean validFile(String name, int resourceType, int fileType) { if (resourceType != ResourceType.File && resourceType != ResourceType.Path) { return true; } if (name == null) { return false; } File file = new File(name); if (!file.exists()) { return false; } if (resourceType == ResourceType.Path) { return true; } String suffix = FileNameTools.ext(file.getName()); if (fileType == FileType.PDF) { if (!suffix.equalsIgnoreCase("pdf")) { return false; } } else if (fileType == FileType.Tif) { if (!suffix.equalsIgnoreCase("tif") && !suffix.equalsIgnoreCase("tiff")) { return false; } } else if (fileType == FileType.Gif) { if (!suffix.equalsIgnoreCase("gif")) { return false; } } else if (fileType == FileType.Html) { if (!suffix.equalsIgnoreCase("html") && !suffix.equalsIgnoreCase("htm")) { return false; } } else if (fileType == FileType.XML) { if (!suffix.equalsIgnoreCase("xml")) { return false; } } else if (fileType == FileType.Markdown) { if (!suffix.equalsIgnoreCase("md")) { return false; } } else if (fileType == FileType.TTC) { if (!suffix.equalsIgnoreCase("ttc")) { return false; } } else if (fileType == FileType.TTF) { if (!suffix.equalsIgnoreCase("ttf")) { return false; } } else if (fileType == FileType.Excel) { if (!suffix.equalsIgnoreCase("xls") && !suffix.equalsIgnoreCase("xlsx")) { return false; } } else if (fileType == FileType.CSV) { if (!suffix.equalsIgnoreCase("csv")) { return false; } } else if (fileType == FileType.Word) { if (!suffix.equalsIgnoreCase("doc")) { return false; } } else if (fileType == FileType.WordX) { if (!suffix.equalsIgnoreCase("docx")) { return false; } } else if (fileType == FileType.WordS) { if (!suffix.equalsIgnoreCase("doc") && !suffix.equalsIgnoreCase("docx")) { return false; } } else if (fileType == FileType.PPT) { if (!suffix.equalsIgnoreCase("ppt")) { return false; } } else if (fileType == FileType.PPTX) { if (!suffix.equalsIgnoreCase("pptx")) { return false; } } else if (fileType == FileType.PPTS) { if (!suffix.equalsIgnoreCase("ppt") && !suffix.equalsIgnoreCase("pptx")) { return false; } } else if (fileType == FileType.SVG) { if (!suffix.equalsIgnoreCase("svg")) { return false; } } return true; } /* Menu */ public static boolean visitMenu(String name, String fxml) { return VisitHistories.update(ResourceType.Menu, FileType.General, OperationType.Access, name, fxml); } public static List<VisitHistory> getRecentMenu() { return VisitHistories.read(ResourceType.Menu, Default_Max_Histories); } public static List<MenuItem> getRecentMenu(BaseController controller, boolean replaceScene) { List<MenuItem> menus = new ArrayList(); List<VisitHistory> his = VisitHistoryTools.getRecentMenu(); if (his == null || his.isEmpty()) { return menus; } List<String> valid = new ArrayList(); for (VisitHistory h : his) { final String fname = h.getResourceValue(); final String fxml = h.getDataMore(); if (fxml.endsWith("/DataTree.fxml")) { if (!valid.contains(fname)) { valid.add(fname); MenuItem menu = new MenuItem(fname); menu.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { if (message("TextTree").equals(fname)) { DataTreeController.textTree(controller, replaceScene); } else if (message("HtmlTree").equals(fname)) { DataTreeController.htmlTree(controller, replaceScene); } else if (message("WebFavorite").equals(fname)) { DataTreeController.webFavorite(controller, replaceScene); } else if (message("DatabaseSQL").equals(fname)) { DataTreeController.sql(controller, replaceScene); } else if (message("MathFunction").equals(fname)) { DataTreeController.mathFunction(controller, replaceScene); } else if (message("ImageScope").equals(fname)) { DataTreeController.imageScope(controller, replaceScene); } else if (message("JShell").equals(fname)) { DataTreeController.jShell(controller, replaceScene); } else if (message("JEXL").equals(fname)) { DataTreeController.jexl(controller, replaceScene); } else if (message("JavaScript").equals(fname)) { DataTreeController.javascript(controller, replaceScene); } else if (message("RowExpression").equals(fname)) { DataTreeController.rowExpression(controller, replaceScene); } else if (message("DataColumn").equals(fname)) { DataTreeController.dataColumn(controller, replaceScene); } else if (message("MacroCommands").equals(fname)) { DataTreeController.macroCommands(controller, replaceScene); } } }); menus.add(menu); } } else { if (!valid.contains(fxml)) { valid.add(fxml); MenuItem menu = new MenuItem(fname); menu.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { if (replaceScene) { controller.loadScene(fxml); } else { controller.openScene(fxml); } } }); menus.add(menu); } } } return menus; } /* Files */ public static boolean readFile(Connection conn, int fileType, String value) { return VisitHistories.update(conn, ResourceType.File, fileType, OperationType.Read, value); } public static boolean writeFile(Connection conn, int fileType, String value) { return VisitHistories.update(conn, ResourceType.File, fileType, OperationType.Write, value); } public static boolean visitStreamMedia(String address) { return VisitHistories.update(ResourceType.URI, FileType.StreamMedia, OperationType.Access, address); } public static List<VisitHistory> getRecentFileRead(int fileType, int count) { if (count <= 0) { return null; } List<VisitHistory> records = VisitHistories.read(ResourceType.File, fileType, OperationType.Read, count); return records; } public static List<VisitHistory> getRecentFileWrite(int fileType, int count) { if (count <= 0) { return null; } List<VisitHistory> records = VisitHistories.read(ResourceType.File, fileType, OperationType.Write, count); return records; } public static List<VisitHistory> getRecentStreamMedia() { if (AppVariables.fileRecentNumber <= 0) { return null; } List<VisitHistory> records = VisitHistories.read(ResourceType.URI, FileType.StreamMedia, AppVariables.fileRecentNumber); return records; } public static List<VisitHistory> getRecentAlphaImages(int number) { if (number <= 0) { return null; } List<VisitHistory> records = VisitHistories.readAlphaImages(number); return records; } /* Paths */ public static boolean readPath(Connection conn, int fileType, String value) { return VisitHistories.update(conn, ResourceType.Path, fileType, OperationType.Read, value); } public static boolean writePath(Connection conn, int fileType, String value) { return VisitHistories.update(conn, ResourceType.Path, fileType, OperationType.Write, value); } public static List<VisitHistory> getRecentPathRead(int fileType) { return getRecentPathRead(fileType, AppVariables.fileRecentNumber); } public static List<VisitHistory> getRecentPathRead(int fileType, int number) { if (number <= 0) { return null; } List<VisitHistory> records = VisitHistories.read(ResourceType.Path, fileType, OperationType.Read, number); return records; } public static List<VisitHistory> getRecentPathWrite(int fileType) { return getRecentPathWrite(fileType, AppVariables.fileRecentNumber); } public static List<VisitHistory> getRecentPathWrite(int fileType, int number) { if (number <= 0) { return null; } List<VisitHistory> records = VisitHistories.read(ResourceType.Path, fileType, OperationType.Write, number); return records; } }
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/data/WebFavorite.java
alpha/MyBox/src/main/java/mara/mybox/db/data/WebFavorite.java
package mara.mybox.db.data; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2024-8-2 * @License Apache License Version 2.0 */ public class WebFavorite extends BaseData { protected long addrid; protected String address, icon; @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 WebFavorite create() { return new WebFavorite(); } public static boolean setValue(WebFavorite data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "addrid": data.setAddrid(value == null ? -1 : (long) value); return true; case "address": data.setAddress(value == null ? null : (String) value); return true; case "icon": data.setIcon(value == null ? null : (String) value); return true; } } catch (Exception e) { MyBoxLog.debug(e); } return false; } public static Object getValue(WebFavorite data, String column) { if (data == null || column == null) { return null; } switch (column) { case "addrid": return data.getAddrid(); case "address": return data.getAddress(); case "icon": return data.getIcon(); } return null; } public static boolean valid(WebFavorite data) { return data != null && data.getAddress() != null && !data.getAddress().isBlank(); } /* get/set */ public long getAddrid() { return addrid; } public void setAddrid(long addrid) { this.addrid = addrid; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } }
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/data/PathConnection.java
alpha/MyBox/src/main/java/mara/mybox/db/data/PathConnection.java
package mara.mybox.db.data; import java.util.Date; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.AESTools; /** * @Author Mara * @CreateDate 2023-3-17 * @License Apache License Version 2.0 */ public class PathConnection extends BaseData { protected long pcnid; protected Type type; protected String title, host, rootpath, path, username, password; protected boolean hostKeyCheck; protected int port, timeout, retry; protected Date modifyTime; public static enum Type { SFTP, HTTPS, HTTP, FTP } public PathConnection() { init(); } final public void init() { pcnid = -1; title = null; host = null; rootpath = null; path = null; username = null; password = null; type = Type.SFTP; port = 22; timeout = 5000; retry = 3; hostKeyCheck = false; modifyTime = new Date(); } @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 PathConnection copy() { try { return (PathConnection) super.clone(); } catch (Exception e) { MyBoxLog.debug(e); return null; } } /* Static methods */ public static PathConnection create() { return new PathConnection(); } public static boolean setValue(PathConnection data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "pcnid": data.setPcnid(value == null ? null : (long) value); return true; case "type": data.setType(value == null ? null : Type.valueOf((String) value)); return true; case "title": data.setTitle(value == null ? null : (String) value); return true; case "host": data.setHost(value == null ? null : (String) value); return true; case "username": data.setUsername(value == null ? null : (String) value); return true; case "password": data.setPassword(value == null ? null : AESTools.decrypt((String) value)); return true; case "rootpath": data.setRootpath(value == null ? null : (String) value); return true; case "path": data.setPath(value == null ? null : (String) value); return true; case "port": data.setPort(value == null ? -1 : (int) value); return true; case "timeout": data.setTimeout(value == null ? 5000 : (int) value); return true; case "retry": data.setRetry(value == null ? 3 : (int) value); return true; case "host_key_check": data.setHostKeyCheck(value == null ? null : (boolean) value); return true; case "modify_time": data.setModifyTime(value == null ? null : (Date) value); return true; } } catch (Exception e) { MyBoxLog.debug(e); } return false; } public static Object getValue(PathConnection data, String column) { if (data == null || column == null) { return null; } switch (column) { case "pcnid": return data.getPcnid(); case "type": Type type = data.getType(); return type == null ? null : type.name(); case "title": return data.getTitle(); case "host": return data.getHost(); case "username": return data.getUsername(); case "password": return AESTools.encrypt(data.getPassword()); case "rootpath": return data.getRootpath(); case "path": return data.getPath(); case "port": return data.getPort(); case "timeout": return data.getTimeout(); case "retry": return data.getRetry(); case "host_key_check": return data.isHostKeyCheck(); case "modify_time": return data.getModifyTime(); } return null; } public static boolean valid(PathConnection data) { return data != null; } /* set */ public void setPcnid(long pcnid) { this.pcnid = pcnid; } public void setType(Type type) { this.type = type; } public void setTitle(String title) { this.title = title; } public void setHost(String host) { this.host = host; } public void setRootpath(String rootpath) { this.rootpath = rootpath; } public void setPath(String path) { this.path = path; } public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = password; } public void setHostKeyCheck(boolean hostKeyCheck) { this.hostKeyCheck = hostKeyCheck; } public void setPort(int port) { this.port = port; } public void setTimeout(int timeout) { this.timeout = timeout; } public void setRetry(int retry) { this.retry = retry; } public void setModifyTime(Date modifyTime) { this.modifyTime = modifyTime; } /* get */ public long getPcnid() { return pcnid; } public Type getType() { return type; } public String getTitle() { return title; } public String getHost() { return host; } public String getRootpath() { return rootpath; } public String getPath() { return path; } public String getUsername() { return username; } public String getPassword() { return password; } public boolean isHostKeyCheck() { return hostKeyCheck; } public int getPort() { return port; } public int getTimeout() { return timeout; } public int getRetry() { return retry; } public Date getModifyTime() { return modifyTime; } }
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/data/AlarmClock.java
alpha/MyBox/src/main/java/mara/mybox/db/data/AlarmClock.java
package mara.mybox.db.data; import java.util.Date; import java.util.HashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.AlarmClockTask; import static mara.mybox.value.AppVariables.ExecutorService; import static mara.mybox.value.AppVariables.ScheduledTasks; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2018-7-13 * @License Apache License Version 2.0 */ public class AlarmClock extends BaseData { public static final String AlarmValueSeprator = "_FG-FG_"; public static final int offset = 1; protected long atid; protected AlarmType alarmType; protected String title, description, sound; protected boolean isActive, isSoundLoop, isSoundContinully; protected int everyValue, soundLoopTimes; protected float volume; protected Date startTime, lastTime, nextTime; public static enum AlarmType { NotRepeat, EveryDay, Weekend, WorkingDays, EverySomeHours, EverySomeMinutes, EverySomeDays, EverySomeSeconds } private void init() { atid = -1; alarmType = null; } public AlarmClock() { 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); } public void calculateNextTime() { if (!isActive || startTime == null) { nextTime = null; return; } Date now = new Date(); if (startTime.after(now)) { nextTime = startTime; } // if (nextTime != null && nextTime.before(now)) { // if (alarmType == AlarmType.NotRepeat) { // nextTime = null; // isActive = false; //// writeAlarmClock(alarm); // return; // } // if (last != null && last.after(now)) { // last = alarm.getLastTime(); // } // long loops = (now.getTime() - last.getTime()) / period(alarm); // next = last + loops * alarm.getPeriod() + alarm.getPeriod(); // } // if (alarm.getAlarmType() == AlarmType.Weekend) { // while (!DateTools.isWeekend(next)) { // next += 24 * 3600000; // } // } // if (alarm.getAlarmType() == AlarmType.WorkingDays) { // while (DateTools.isWeekend(next)) { // next += 24 * 3600000; // } // } // alarm.setNextTime(next); } public String scehduleKey() { return "AlarmClock" + atid; } public int addInSchedule() { try { removeFromSchedule(); if (!isActive) { return 0; } AlarmClockTask task = new AlarmClockTask(this); ScheduledFuture newFuture; if (ExecutorService == null) { ExecutorService = Executors.newScheduledThreadPool(10); } if (alarmType == AlarmType.NotRepeat) { newFuture = ExecutorService.schedule(task, task.getDelay(), TimeUnit.MILLISECONDS); } else { if (task.getPeriod() <= 0) { isActive = false; return 1; } newFuture = ExecutorService.scheduleAtFixedRate(task, task.getDelay(), task.getPeriod(), TimeUnit.MILLISECONDS); } if (ScheduledTasks == null) { ScheduledTasks = new HashMap<>(); } ScheduledTasks.put(scehduleKey(), newFuture); return 0; } catch (Exception e) { MyBoxLog.error(e); return -1; } } public boolean removeFromSchedule() { try { if (ScheduledTasks == null) { return false; } String key = scehduleKey(); ScheduledFuture future = ScheduledTasks.get(key); if (future != null) { future.cancel(true); ScheduledTasks.remove(key); } return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } /* Static methods */ public static AlarmClock create() { return new AlarmClock(); } public static boolean setValue(AlarmClock data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "atid": data.setAtid(value == null ? null : (long) value); return true; case "alarm_type": data.setAlarmType(value == null ? null : AlarmType.values()[(int) value]); return true; case "every_value": data.setEveryValue(value == null ? null : (int) value); return true; case "start_time": data.setStartTime(value == null ? null : (Date) value); return true; case "last_time": data.setLastTime(value == null ? null : (Date) value); return true; case "next_time": data.setNextTime(value == null ? null : (Date) value); return true; case "sound_loop_times": data.setSoundLoopTimes(value == null ? null : (int) value); return true; case "is_sound_loop": data.setIsSoundLoop(value == null ? null : (boolean) value); return true; case "is_sound_continully": data.setIsSoundContinully(value == null ? null : (boolean) value); return true; case "is_active": data.setIsActive(value == null ? null : (boolean) value); return true; case "volume": data.setVolume(value == null ? null : (float) value); return true; case "title": data.setTitle(value == null ? null : (String) value); return true; case "sound": data.setSound(value == null ? null : (String) value); return true; case "description": data.setDescription(value == null ? null : (String) value); return true; } } catch (Exception e) { MyBoxLog.debug(e); } return false; } public static Object getValue(AlarmClock data, String column) { if (data == null || column == null) { return null; } switch (column) { case "atid": return data.getAtid(); case "alarm_type": AlarmType type = data.getAlarmType(); return type == null ? -1 : type.ordinal(); case "every_value": return data.getEveryValue(); case "start_time": return data.getStartTime(); case "last_time": return data.getLastTime(); case "next_time": return data.getNextTime(); case "sound_loop_times": return data.getSoundLoopTimes(); case "is_sound_loop": return data.isIsSoundLoop(); case "is_sound_continully": return data.isIsSoundContinully(); case "is_active": return data.isIsActive(); case "volume": return data.getVolume(); case "title": return data.getTitle(); case "sound": return data.getSound(); case "description": return data.getDescription(); } return null; } public static boolean valid(AlarmClock data) { return data != null && data.getAlarmType() == null; } public static void setExtraValues2(AlarmClock alarm) { if (alarm == null) { return; } // calculateNextTime(alarm); // if (!alarm.isIsActive()) { // alarm.setStatus(message("Inactive")); // } else { // alarm.setStatus(message("Active")); // } // if (alarm.getLastTime() > 0) { // alarm.setLast(DateTools.datetimeToString(alarm.getLastTime())); // } else { // alarm.setLast(""); // } // if (alarm.getNextTime() > 0) { // alarm.setNext(DateTools.datetimeToString(alarm.getNextTime())); // } else { // alarm.setNext(""); // } } public static String typeString(AlarmClock alarm) { AlarmType type = alarm.getAlarmType(); switch (type) { case NotRepeat: return message("NotRepeat"); case EveryDay: return message("EveryDay"); case Weekend: return message("Weekend"); case WorkingDays: return message("WorkingDays"); case EverySomeHours: case EverySomeMinutes: case EverySomeDays: case EverySomeSeconds: return message("Every") + " " + alarm.getEveryValue() + " " + typeUnit(type); } return null; } public static String typeUnit(AlarmType type) { switch (type) { case EverySomeHours: return message("Hours"); case EverySomeMinutes: return message("Minutes"); case EverySomeDays: return message("Days"); case EverySomeSeconds: return message("Seconds"); } return null; } public static long period(AlarmClock alarm) { switch (alarm.getAlarmType()) { case EveryDay: case Weekend: case WorkingDays: case EverySomeDays: return 24 * 3600000; case EverySomeHours: return alarm.getEveryValue() * 3600000; case EverySomeMinutes: return alarm.getEveryValue() * 60000; case EverySomeSeconds: return alarm.getEveryValue() * 1000; } return -1; } public static boolean scheduleAll() { return true; // try ( Connection conn = DerbyBase.getConnection()) { // TableAlarmClock tableAlarmClock = new TableAlarmClock(); // List<AlarmClock> alarms = tableAlarmClock.readAll(conn); // if (alarms == null) { // return true; // } // for (AlarmClock alarm : alarms) { // if (alarm.addInSchedule() > 0) { // tableAlarmClock.writeData(conn, alarm); // } // } // return true; // } catch (Exception e) { // MyBoxLog.error(e); // return false; // } } /* set */ public void setAtid(long atid) { this.atid = atid; } public void setTitle(String title) { this.title = title; } public void setDescription(String description) { this.description = description; } public void setSound(String sound) { this.sound = sound; } public void setIsActive(boolean isActive) { this.isActive = isActive; } public void setIsSoundLoop(boolean isSoundLoop) { this.isSoundLoop = isSoundLoop; } public void setIsSoundContinully(boolean isSoundContinully) { this.isSoundContinully = isSoundContinully; } public void setAlarmType(AlarmType alarmType) { this.alarmType = alarmType; } public void setEveryValue(int everyValue) { this.everyValue = everyValue; } public void setSoundLoopTimes(int soundLoopTimes) { this.soundLoopTimes = soundLoopTimes; } public void setVolume(float volume) { this.volume = volume; } public void setStartTime(Date startTime) { this.startTime = startTime; } public void setLastTime(Date lastTime) { this.lastTime = lastTime; } public void setNextTime(Date nextTime) { this.nextTime = nextTime; } /* get */ public static String getAlarmValueSeprator() { return AlarmValueSeprator; } public static int getOffset() { return offset; } public long getAtid() { return atid; } public String getTitle() { return title; } public String getDescription() { return description; } public String getSound() { return sound; } public boolean isIsActive() { return isActive; } public boolean isIsSoundLoop() { return isSoundLoop; } public boolean isIsSoundContinully() { return isSoundContinully; } public AlarmType getAlarmType() { return alarmType; } public int getEveryValue() { return everyValue; } public int getSoundLoopTimes() { return soundLoopTimes; } public float getVolume() { return volume; } public Date getStartTime() { return startTime; } public Date getLastTime() { return lastTime; } public Date getNextTime() { return nextTime; } }
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/data/MathFunction.java
alpha/MyBox/src/main/java/mara/mybox/db/data/MathFunction.java
package mara.mybox.db.data; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2024-8-2 * @License Apache License Version 2.0 */ public class MathFunction extends BaseData { protected long funcid; protected String name, expression, domain, variables; @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 MathFunction create() { return new MathFunction(); } public static boolean setValue(MathFunction data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "funcid": data.setFuncid(value == null ? -1 : (long) value); return true; case "name": data.setName(value == null ? null : (String) value); return true; case "variables": data.setVariables(value == null ? null : (String) value); return true; case "expression": data.setExpression(value == null ? null : (String) value); return true; case "domain": data.setDomain(value == null ? null : (String) value); return true; } } catch (Exception e) { MyBoxLog.debug(e); } return false; } public static Object getValue(MathFunction data, String column) { if (data == null || column == null) { return null; } switch (column) { case "funcid": return data.getFuncid(); case "name": return data.getName(); case "variables": return data.getVariables(); case "expression": return data.getExpression(); case "domain": return data.getDomain(); } return null; } public static boolean valid(MathFunction data) { return data != null && data.getName() != null && !data.getName().isBlank(); } /* get/set */ public long getFuncid() { return funcid; } public MathFunction setFuncid(long funcid) { this.funcid = funcid; return this; } public String getName() { return name; } public MathFunction setName(String name) { this.name = name; return this; } public String getExpression() { return expression; } public MathFunction setExpression(String expression) { this.expression = expression; return this; } public String getDomain() { return domain; } public MathFunction setDomain(String domain) { this.domain = domain; return this; } public String getVariables() { return variables; } public MathFunction setVariables(String variables) { this.variables = variables; 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/data/DataNodeTools.java
alpha/MyBox/src/main/java/mara/mybox/db/data/DataNodeTools.java
package mara.mybox.db.data; import java.sql.Connection; import java.util.ArrayList; import java.util.List; import javafx.scene.paint.Color; import mara.mybox.controller.BaseController; import static mara.mybox.db.data.DataNode.TagsSeparater; import mara.mybox.db.table.BaseNodeTable; import mara.mybox.db.table.TableDataNodeTag; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.image.FxColorTools; import mara.mybox.tools.DateTools; import mara.mybox.tools.JsonTools; import static mara.mybox.value.AppValues.Indent; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2024-11-1 * @License Apache License Version 2.0 */ public class DataNodeTools { /* static */ public static String htmlControls(boolean isTree) { String codes = " <script>\n" + " function changeVisible(id) {\n" + " var obj = document.getElementById(id);\n" + " var objv = obj.style.display;\n" + " if (objv == 'none') {\n" + " obj.style.display = 'block';\n" + " } else {\n" + " obj.style.display = 'none';\n" + " }\n" + " }\n" + " function setVisible(className, show) {\n" + " var nodes = document.getElementsByClassName(className);  \n" + " if ( show) {\n" + " for (var i = 0 ; i < nodes.length; i++) {\n" + " nodes[i].style.display = '';\n" + " }\n" + " } else {\n" + " for (var i = 0 ; i < nodes.length; i++) {\n" + " nodes[i].style.display = 'none';\n" + " }\n" + " }\n" + " }\n" + " </script>\n\n"; codes += "<DIV>\n<DIV>\n"; if (isTree) { codes += " <INPUT type=\"checkbox\" checked onclick=\"setVisible('Children', this.checked);\">" + message("Unfold") + "</INPUT>\n"; } codes += " <INPUT type=\"checkbox\" checked onclick=\"setVisible('HierarchyNumber', this.checked);\">" + message("HierarchyNumber") + "</INPUT>\n" + " <INPUT type=\"checkbox\" checked onclick=\"setVisible('NodeTag', this.checked);\">" + message("Tags") + "</INPUT>\n" + " <INPUT type=\"checkbox\" checked onclick=\"setVisible('NodeValues', this.checked);\">" + message("Values") + "</INPUT>\n" + " <INPUT type=\"checkbox\" checked onclick=\"setVisible('NodeAttributes', this.checked);\">" + message("Attributes") + "</INPUT>\n" + "</DIV>\n<HR>\n"; return codes; } public static String tagsHtml(List<DataNodeTag> tags, int indent) { if (tags == null || tags.isEmpty()) { return ""; } String indentTag = " ".repeat(indent + 8); String spaceTag = "&nbsp;".repeat(2); String s = indentTag + "<SPAN class=\"NodeTag\">\n"; for (DataNodeTag nodeTag : tags) { s += indentTag + spaceTag + tagHtml(nodeTag); } s += indentTag + "</SPAN>\n"; return s; } public static String tagHtml(DataNodeTag nodeTag) { if (nodeTag == null) { return null; } Color color = nodeTag.getTag().getColor(); if (color == null) { color = FxColorTools.randomColor(); } return "<SPAN style=\"border-radius:4px; padding: 2px; font-size:0.8em; background-color: " + FxColorTools.color2rgb(color) + "; color: " + FxColorTools.color2rgb(FxColorTools.foreColor(color)) + ";\">" + nodeTag.getTag().getTag() + "</SPAN>\n"; } public static String valuesBox(String dataHtml, String prefix, int indent) { if (dataHtml == null || dataHtml.isBlank()) { return ""; } return prefix + "<DIV class=\"NodeValues\"><DIV style=\"padding: 0 0 0 " + indent * 6 + "px;\"><DIV class=\"valueBox\">\n" + prefix + dataHtml + "\n" + prefix + "</DIV></DIV></DIV>\n"; } public static String titleHtml(DataNode node, List<DataNodeTag> tags, String childrenid, String prefixIndent, String spaceIndent) { if (node == null) { return ""; } String title = node.getHierarchyNumber(); if (title != null && !title.isBlank()) { title = "<SPAN class=\"HierarchyNumber\">" + title + "&nbsp;&nbsp;</SPAN>"; } else { title = ""; } if (childrenid != null) { title += "<a href=\"javascript:changeVisible('" + childrenid + "')\">" + node.getTitle() + "</a>"; } else { title += node.getTitle(); } title = prefixIndent + "<DIV style=\"padding: 2px;\">" + spaceIndent + title + "\n"; title += DataNodeTools.tagsHtml(tags, 4); title += prefixIndent + "</DIV>\n"; return title; } public static String attributesHtml(DataNode node, boolean withId, boolean withTime, boolean withOrder, String spaceIndent) { if (node == null) { return ""; } String attributes = ""; if (withId) { if (node.getNodeid() >= 0) { attributes += message("ID") + ":" + node.getNodeid() + " "; } if (node.getParentid() >= 0) { attributes += message("ParentID") + ":" + node.getParentid() + " "; } } if (withOrder) { attributes += message("OrderNumber") + ":" + node.getOrderNumber() + " "; } if (withTime && node.getUpdateTime() != null) { attributes += message("UpdateTime") + ":" + DateTools.datetimeToString(node.getUpdateTime()) + " "; } if (!attributes.isBlank()) { attributes = "<SPAN>" + spaceIndent + "</SPAN>" + "<SPAN style=\"font-size: 0.8em;\">" + attributes.trim() + "</SPAN>\n"; } String cname = node.getChainName(); if (cname != null && !cname.isBlank()) { if (!attributes.isBlank()) { attributes += "<BR>"; } attributes += "<SPAN>" + spaceIndent + "</SPAN>" + "<SPAN style=\"font-size: 0.8em;\">" + message("Parent") + ":" + cname + "</SPAN>\n"; } if (!attributes.isBlank()) { attributes = "<DIV class=\"NodeAttributes\">" + attributes + "</DIV>\n"; } return attributes; } public static String nodeHtml(FxTask task, Connection conn, BaseController controller, BaseNodeTable dataTable, DataNode node) { try { if (conn == null || node == null) { return null; } long nodeid = node.getNodeid(); String indentNode = " ".repeat(4); List<DataNodeTag> tags = new TableDataNodeTag(dataTable).nodeTags(conn, nodeid); String html = titleHtml(node, tags, null, Indent, ""); html += DataNodeTools.valuesBox(dataTable.valuesHtml(task, conn, controller, node), indentNode, 4); html += attributesHtml(node, true, true, true, ""); return html; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String listNodeHtml(FxTask fxTask, Connection conn, BaseController controller, BaseNodeTable nodeTable, DataNode node, List<DataNodeTag> tags, boolean withId, boolean withTime, boolean withOrder, boolean withData) { try { StringBuilder s = new StringBuilder(); String indent2 = Indent + Indent; String spaceNode = "&nbsp;".repeat(4); s.append(indent2).append("<DIV id=\"").append(node.getNodeid()).append("\">\n"); s.append(titleHtml(node, tags, null, indent2, "")); if (withData) { String values = valuesBox(nodeTable.valuesHtml(fxTask, conn, controller, node), indent2, 4); if (!values.isBlank()) { s.append(values); } } String attrs = attributesHtml(node, withId, withTime, withOrder, spaceNode); if (!attrs.isBlank()) { s.append(attrs); } s.append(indent2).append("</DIV><HR>\n\n"); return s.toString(); } catch (Exception e) { if (fxTask != null) { fxTask.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } return null; } } public static String treeNodeHtml(FxTask fxTask, Connection conn, BaseController controller, BaseNodeTable nodeTable, DataNode node, List<DataNodeTag> tags, int indent, boolean withId, boolean withTime, boolean withOrder, boolean withData) { try { StringBuilder s = new StringBuilder(); String indentNode = " ".repeat(indent); String spaceNode = "&nbsp;".repeat(indent); s.append(titleHtml(node, tags, nodeTable.hasChildren(conn, node) ? "children" + node.getNodeid() : null, indentNode, spaceNode)); if (withData) { String values = valuesBox(nodeTable.valuesHtml(fxTask, conn, controller, node), indentNode, indent + 4); if (!values.isBlank()) { s.append(values); } } String attrs = attributesHtml(node, withId, withTime, withOrder, spaceNode + "&nbsp;".repeat(4)); if (!attrs.isBlank()) { s.append(indentNode).append(Indent).append(attrs); } return s.toString(); } catch (Exception e) { if (fxTask != null) { fxTask.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } return null; } } public static String toXML(FxTask fxTask, Connection conn, BaseController controller, BaseNodeTable dataTable, DataNode node, List<DataNodeTag> tags, String prefix, boolean withId, boolean withTime, boolean withOrder, boolean withData, boolean formatData) { try { StringBuilder s = new StringBuilder(); String prefix2 = prefix + Indent; String prefix3 = prefix2 + Indent; s.append(prefix).append("<NodeAttributes>\n"); if (withId) { if (node.getNodeid() >= 0) { s.append(prefix2).append("<nodeid>").append(node.getNodeid()).append("</nodeid>\n"); } if (node.getParentid() >= 0) { s.append(prefix2).append("<parentid>").append(node.getParentid()).append("</parentid>\n"); } } String cname = node.getChainName(); if (cname != null && !cname.isBlank()) { s.append(prefix2).append("<parent_name>\n"); s.append(prefix3).append("<![CDATA[").append(cname).append("]]>\n"); s.append(prefix2).append("</parent_name>\n"); } String hierarchyNumber = node.getHierarchyNumber(); if (hierarchyNumber != null && !hierarchyNumber.isBlank()) { s.append(prefix2).append("<hierarchy_number>").append(hierarchyNumber).append("</hierarchy_number>\n"); } if (node.getTitle() != null) { s.append(prefix2).append("<title>\n"); s.append(prefix3).append("<![CDATA[").append(node.getTitle()).append("]]>\n"); s.append(prefix2).append("</title>\n"); } if (withOrder) { s.append(prefix2).append("<order_number>").append(node.getOrderNumber()).append("</order_number>\n"); } if (withTime && node.getUpdateTime() != null) { s.append(prefix2).append("<update_time>") .append(DateTools.datetimeToString(node.getUpdateTime())) .append("</update_time>\n"); } if (withData) { String valuesXml = dataTable.valuesXml(prefix2, node, formatData); if (valuesXml != null && !valuesXml.isBlank()) { s.append(valuesXml); } } s.append(prefix).append("</NodeAttributes>\n"); if (tags != null && !tags.isEmpty()) { for (DataNodeTag tag : tags) { s.append(prefix).append("<NodeTag>\n"); s.append(prefix2).append("<![CDATA[").append(tag.getTag().getTag()).append("]]>\n"); s.append(prefix).append("</NodeTag>\n"); } } return s.toString(); } catch (Exception e) { if (fxTask != null) { fxTask.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } return null; } } public static String toJson(FxTask fxTask, Connection conn, BaseController controller, BaseNodeTable dataTable, DataNode node, List<DataNodeTag> tags, String prefix, boolean withId, boolean withTime, boolean withOrder, boolean withData, boolean formatData) { try { StringBuilder s = new StringBuilder(); if (withId) { if (node.getNodeid() >= 0) { s.append(prefix) .append("\"").append(message("ID")).append("\": ") .append(node.getNodeid()); } if (node.getParentid() >= 0) { if (!s.isEmpty()) { s.append(",\n"); } s.append(prefix) .append("\"").append(message("ParentID")).append("\": ") .append(node.getParentid()); } } String cname = node.getChainName(); if (cname != null && !cname.isBlank()) { if (!s.isEmpty()) { s.append(",\n"); } s.append(prefix) .append("\"").append(message("Parent")).append("\": ") .append(JsonTools.encode(cname)); } String hierarchyNumber = node.getHierarchyNumber(); if (hierarchyNumber != null && !hierarchyNumber.isBlank()) { if (!s.isEmpty()) { s.append(",\n"); } s.append(prefix) .append("\"").append(message("HierarchyNumber")).append("\": \"") .append(hierarchyNumber).append("\""); } if (!s.isEmpty()) { s.append(",\n"); } s.append(prefix) .append("\"").append(message("Title")).append("\": ") .append(JsonTools.encode(node.getTitle())); if (withOrder) { s.append(",\n"); s.append(prefix) .append("\"").append(message("OrderNumber")).append("\": \"") .append(node.getOrderNumber()).append("\""); } if (withTime && node.getUpdateTime() != null) { s.append(",\n"); s.append(prefix) .append("\"").append(message("UpdateTime")).append("\": \"") .append(node.getUpdateTime()).append("\""); } if (tags != null && !tags.isEmpty()) { String t = null; for (DataNodeTag tag : tags) { String v = tag.getTag().getTag(); v = JsonTools.encode(v); if (t == null) { t = v; } else { t += "," + v; } } s.append(",\n"); s.append(prefix) .append("\"").append(message("Tags")).append("\": ") .append("[").append(t).append("]"); } if (withData) { String valuesJson = dataTable.valuesJson(prefix, node, formatData); if (valuesJson != null && !valuesJson.isBlank()) { s.append(",\n").append(valuesJson); } } return s.toString(); } catch (Exception e) { if (fxTask != null) { fxTask.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } return null; } } public static List<String> toCsv(FxTask fxTask, Connection conn, BaseController controller, BaseNodeTable dataTable, DataNode node, List<DataNodeTag> tags, boolean withId, boolean withTime, boolean withOrder, boolean withData, boolean formatData) { try { List<String> row = new ArrayList<>(); if (withId) { row.add(node.getNodeid() + ""); row.add(node.getParentid() + ""); } String cname = node.getChainName(); if (cname != null) { row.add(cname); } String hie = node.getHierarchyNumber(); if (hie != null) { row.add(hie); } row.add(node.getTitle()); if (withOrder) { row.add(node.getOrderNumber() + ""); } if (withTime && node.getUpdateTime() != null) { row.add(node.getUpdateTime() + ""); } if (tags != null) { String t = null; for (DataNodeTag tag : tags) { String v = tag.getTag().getTag(); if (t == null) { t = v; } else { t += TagsSeparater + v; } } row.add(t); } if (withData) { for (String name : dataTable.dataColumnNames()) { Object value = node.getValue(name); ColumnDefinition column = dataTable.column(name); String sValue = dataTable.exportValue(column, value, formatData); row.add(sValue); } } return row; } catch (Exception e) { if (fxTask != null) { fxTask.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } 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/data/Data2DDefinition.java
alpha/MyBox/src/main/java/mara/mybox/db/data/Data2DDefinition.java
package mara.mybox.db.data; import java.io.File; import java.nio.charset.Charset; import java.util.Date; import mara.mybox.controller.BaseController; import mara.mybox.controller.Data2DManageController; import mara.mybox.controller.Data2DManufactureController; import mara.mybox.controller.DataInMyBoxClipboardController; import mara.mybox.controller.MatricesManageController; import mara.mybox.controller.MyBoxTablesController; import mara.mybox.data.Pagination; import mara.mybox.data2d.tools.Data2DDefinitionTools; import mara.mybox.db.table.BaseTableTools; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.FileNameTools; import mara.mybox.tools.FileTools; import mara.mybox.value.AppVariables; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2021-11-2 * @License Apache License Version 2.0 */ public class Data2DDefinition extends BaseData { public long dataID; public DataType dataType; public String dataName, sheet, delimiter, comments; public File file; public Charset charset; public boolean hasHeader; public Pagination pagination; public long colsNumber; public short scale; public int maxRandom; public Date modifyTime; public static enum DataType { Texts, CSV, Excel, MyBoxClipboard, Matrix, DatabaseTable, InternalTable } public Data2DDefinition() { pagination = new Pagination(Pagination.ObjectType.Table); resetDefinition(); } @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 boolean equals(Data2DDefinition def) { return def != null && dataID == def.getDataID(); } public Data2DDefinition cloneTo() { try { Data2DDefinition newData = new Data2DDefinition(); newData.cloneFrom(this); return newData; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public Data2DDefinition cloneFrom(Data2DDefinition d) { try { if (d == null) { return null; } dataID = d.getDataID(); dataType = d.getType(); copyAllAttributes(d); } catch (Exception e) { MyBoxLog.debug(e); } return this; } public void copyAllAttributes(Data2DDefinition d) { try { copyFileAttributes(d); copyDataAttributes(d); } catch (Exception e) { MyBoxLog.debug(e); } } public void copyFileAttributes(Data2DDefinition d) { try { if (d == null) { return; } file = d.getFile(); sheet = d.getSheet(); modifyTime = d.getModifyTime(); delimiter = d.getDelimiter(); charset = d.getCharset(); hasHeader = d.isHasHeader(); comments = d.getComments(); } catch (Exception e) { MyBoxLog.debug(e); } } public void copyDataAttributes(Data2DDefinition d) { try { if (d == null) { return; } dataName = d.getDataName(); scale = d.getScale(); maxRandom = d.getMaxRandom(); colsNumber = d.getColsNumber(); pagination.copyFrom(d.pagination); comments = d.getComments(); } catch (Exception e) { MyBoxLog.debug(e); } } public String info() { return Data2DDefinitionTools.defInfo(this); } public final void resetDefinition() { dataID = -1; file = null; if (!isMatrix()) { sheet = null; hasHeader = true; charset = null; delimiter = null; } dataName = null; colsNumber = -1; scale = 2; maxRandom = 1000; modifyTime = new Date(); comments = null; pagination.reset(); } public boolean isValidDefinition() { return valid(this); } public boolean hasData() { if (isDataFile()) { return FileTools.hasData(file); } else if (isTable()) { return sheet != null; } else { return true; } } public Data2DDefinition setCharsetName(String charsetName) { try { charset = Charset.forName(charsetName); } catch (Exception e) { } return this; } public String getTypeName() { return message(dataType.name()); } public String getFileName() { if (file != null) { return file.getAbsolutePath(); } else { return null; } } public boolean isExcel() { return dataType == DataType.Excel; } public boolean isCSV() { return dataType == DataType.CSV; } public boolean isTexts() { return dataType == DataType.Texts; } public boolean isMatrix() { return dataType == DataType.Matrix; } public boolean isClipboard() { return dataType == DataType.MyBoxClipboard; } public boolean isUserTable() { return dataType == DataType.DatabaseTable; } public boolean isInternalTable() { return dataType == DataType.InternalTable || (dataType == DataType.DatabaseTable && BaseTableTools.isInternalTable(sheet)); } public boolean isTable() { return dataType == DataType.DatabaseTable || dataType == DataType.InternalTable; } public boolean isDataFile() { return dataType == DataType.CSV || dataType == DataType.Excel || dataType == DataType.Texts || dataType == DataType.Matrix; } public boolean isTextFile() { return file != null && file.exists() && (dataType == DataType.CSV || dataType == DataType.MyBoxClipboard || dataType == DataType.Texts || dataType == DataType.Matrix); } public boolean hasComments() { return comments != null && !comments.isBlank(); } public String getTitle() { String name; if (isDataFile() && file != null) { name = file.getAbsolutePath(); if (isExcel()) { name += " - " + sheet; } } else if (this.isTable()) { name = sheet; } else { name = dataName; } if (name == null && dataID < 0) { name = message("NewData"); } return name; } public String getName() { if (dataName != null && !dataName.isBlank()) { return dataName; } else { return shortName(); } } public String shortName() { if (file != null) { return FileNameTools.prefix(file.getName()) + (sheet != null ? "_" + sheet : ""); } else if (sheet != null) { return sheet; } else if (dataName != null) { return dataName; } else { return ""; } } public String labelName() { String name = getTitle(); name = getTypeName() + (dataID >= 0 ? " - " + dataID : "") + (name != null ? " - " + name : ""); return name; } public String printName() { String title = getTitle(); if (dataName != null && !dataName.isBlank() && !title.equals(dataName)) { return title + "\n" + dataName; } else { return title; } } public boolean validValue(String value) { if (value == null || dataType != DataType.Texts) { return true; } return !value.contains("\n") && !value.contains(delimiter); } public boolean alwayRejectInvalid() { return dataType == DataType.Matrix || dataType == DataType.DatabaseTable || dataType == DataType.InternalTable; } public boolean rejectInvalidWhenEdit() { return alwayRejectInvalid() || AppVariables.rejectInvalidValueWhenEdit; } public boolean rejectInvalidWhenSave() { return alwayRejectInvalid() || AppVariables.rejectInvalidValueWhenSave; } /* static methods */ public static Data2DDefinition create() { return new Data2DDefinition(); } public static boolean valid(Data2DDefinition data) { return data != null && data.getType() != null; } public static Object getValue(Data2DDefinition data, String column) { if (data == null || column == null) { return null; } switch (column) { case "d2did": return data.getDataID(); case "data_type": return type(data.getType()); case "data_name": return data.getDataName(); case "file": return data.getFile() == null ? null : data.getFile().getAbsolutePath(); case "sheet": return data.getSheet(); case "charset": return data.getCharset() == null ? Charset.defaultCharset().name() : data.getCharset().name(); case "delimiter": return data.getDelimiter(); case "has_header": return data.isHasHeader(); case "columns_number": return data.getColsNumber(); case "rows_number": return data.getRowsNumber(); case "scale": return data.getScale(); case "max_random": return data.getMaxRandom(); case "modify_time": return data.getModifyTime(); case "comments": return data.getComments(); } return null; } public static boolean setValue(Data2DDefinition data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "d2did": data.setDataID(value == null ? -1 : (long) value); return true; case "data_type": data.setType(value == null ? DataType.Texts : type((short) value)); return true; case "data_name": data.setDataName(value == null ? null : (String) value); return true; case "file": data.setFile(value == null ? null : new File((String) value)); return true; case "sheet": data.setSheet(value == null ? null : (String) value); return true; case "charset": data.setCharset(value == null ? null : Charset.forName((String) value)); return true; case "delimiter": data.setDelimiter(value == null ? null : (String) value); return true; case "has_header": data.setHasHeader(value == null ? false : (boolean) value); return true; case "columns_number": data.setColsNumber(value == null ? -1 : (long) value); return true; case "rows_number": data.setRowsNumber(value == null ? -1 : (long) value); return true; case "scale": data.setScale(value == null ? 2 : (short) value); return true; case "max_random": data.setMaxRandom(value == null ? 100 : (int) value); return true; case "modify_time": data.setModifyTime(value == null ? null : (Date) value); return true; case "comments": data.setComments(value == null ? null : (String) value); return true; } } catch (Exception e) { MyBoxLog.debug(e.toString(), column + " " + value); } return false; } public static short type(DataType type) { if (type == null) { return 0; } return (short) (type.ordinal()); } public static DataType type(short type) { DataType[] types = DataType.values(); if (type < 0 || type > types.length) { return DataType.Texts; } return types[type]; } public static DataType type(File file) { if (file == null) { return null; } String suffix = FileNameTools.ext(file.getAbsolutePath()); if (suffix == null) { return null; } switch (suffix) { case "xlsx": case "xls": return DataType.Excel; case "csv": return DataType.CSV; } // if (file.getAbsolutePath().startsWith(AppPaths.getMatrixPath() + File.separator)) { // return DataType.Matrix; // } return DataType.Texts; } public static BaseController open(Data2DDefinition def) { if (def == null) { return Data2DManageController.open(def); } else { return open(def, def.getType()); } } public static BaseController openType(DataType type) { return open(null, type); } public static BaseController open(Data2DDefinition def, DataType type) { if (type == null) { return Data2DManageController.open(def); } switch (type) { case CSV: case Excel: case Texts: case DatabaseTable: return Data2DManufactureController.openDef(def); case MyBoxClipboard: return DataInMyBoxClipboardController.open(def); case Matrix: return MatricesManageController.open(def); case InternalTable: return MyBoxTablesController.open(def); default: return Data2DManageController.open(def); } } /* get/set */ public long getDataID() { return dataID; } public void setDataID(long dataID) { this.dataID = dataID; } public DataType getType() { return dataType; } public Data2DDefinition setType(DataType type) { this.dataType = type; return this; } public String getDataName() { return dataName; } public Data2DDefinition setDataName(String dataName) { this.dataName = dataName; return this; } public Charset getCharset() { return charset; } public Data2DDefinition setCharset(Charset charset) { this.charset = charset; return this; } public String getDelimiter() { return delimiter; } public Data2DDefinition setDelimiter(String delimiter) { this.delimiter = delimiter; return this; } public boolean isHasHeader() { return hasHeader; } public Data2DDefinition setHasHeader(boolean hasHeader) { this.hasHeader = hasHeader; return this; } public String getComments() { return comments; } public Data2DDefinition setComments(String comments) { this.comments = comments; return this; } public Pagination getPagination() { return pagination; } public Data2DDefinition setPagination(Pagination pagination) { this.pagination = pagination; return this; } public long getColsNumber() { return colsNumber; } public Data2DDefinition setColsNumber(long colsNumber) { this.colsNumber = colsNumber; return this; } public long getRowsNumber() { return pagination.rowsNumber; } public Data2DDefinition setRowsNumber(long rowsNumber) { pagination.setRowsNumber(rowsNumber); return this; } public short getScale() { return scale; } public Data2DDefinition setScale(short scale) { this.scale = scale; return this; } public int getMaxRandom() { return maxRandom; } public Data2DDefinition setMaxRandom(int maxRandom) { this.maxRandom = maxRandom; return this; } public Date getModifyTime() { return modifyTime; } public Data2DDefinition setModifyTime(Date modifyTime) { this.modifyTime = modifyTime; return this; } public File getFile() { return file; } public Data2DDefinition setFile(File file) { this.file = file; return this; } public String getSheet() { return sheet; } public Data2DDefinition setSheet(String sheet) { this.sheet = sheet; return this; } public long getPagesNumber() { return pagination.getPagesNumber(); } public void setPagesNumber(long pagesNumber) { pagination.setPagesNumber(pagesNumber); } public int getPageSize() { return pagination.getPageSize(); } public void setPageSize(int pageSize) { pagination.setPageSize(pageSize); } public long getStartRowOfCurrentPage() { return pagination.getStartRowOfCurrentPage(); } public void setStartRowOfCurrentPage(long startRowOfCurrentPage) { pagination.setStartRowOfCurrentPage(startRowOfCurrentPage); } public long getEndRowOfCurrentPage() { return pagination.getEndRowOfCurrentPage(); } public void setEndRowOfCurrentPage(long endRowOfCurrentPage) { pagination.setEndRowOfCurrentPage(endRowOfCurrentPage); } public long getCurrentPage() { return pagination.getCurrentPage(); } public void setCurrentPage(long currentPage) { pagination.setCurrentPage(currentPage); } }
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/data/ImageClipboard.java
alpha/MyBox/src/main/java/mara/mybox/db/data/ImageClipboard.java
/* * Apache License Version 2.0 */ package mara.mybox.db.data; import java.awt.image.BufferedImage; import java.io.File; import java.util.Date; import java.util.Random; import javafx.embed.swing.SwingFXUtils; import javafx.scene.image.Image; import mara.mybox.image.tools.ScaleTools; import mara.mybox.controller.ImageInMyBoxClipboardController; import mara.mybox.db.table.TableImageClipboard; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.image.file.ImageFileReaders; import mara.mybox.image.file.ImageFileWriters; import mara.mybox.value.AppPaths; import mara.mybox.value.AppVariables; /** * @Author Mara * @CreateDate 2019-9-3 * @License Apache License Version 2.0 */ public class ImageClipboard extends BaseData { protected long icid; protected File imageFile, thumbnailFile; protected Image image, thumbnail; protected int width, height; protected ImageSource source; protected String sourceName; protected Date createTime; protected ImageClipboard self; public static enum ImageSource { SystemClipBoard, Copy, Crop, File, Example, Link, Unknown } private void init() { icid = -1; source = ImageSource.Unknown; createTime = new Date(); self = this; } public ImageClipboard() { 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); } public Image loadImage(FxTask task) { image = loadImage(task, this); return image; } public Image loadThumb(FxTask task) { thumbnail = loadThumb(task, this); return thumbnail; } /* Static methods */ public static ImageClipboard create() { return new ImageClipboard(); } public static boolean setValue(ImageClipboard data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "icid": data.setIcid(value == null ? -1 : (long) value); return true; case "image_file": data.setImageFile(null); if (value != null) { File f = new File((String) value); if (f.exists()) { data.setImageFile(f); } } return true; case "thumbnail_file": data.setThumbnailFile(null); if (value != null) { File f = new File((String) value); if (f.exists()) { data.setThumbnailFile(f); } } return true; case "width": data.setWidth(value == null ? 100 : (int) value); return true; case "height": data.setHeight(value == null ? 100 : (int) value); return true; case "source": short s = value == null ? -1 : (short) value; data.setSource(source(s)); return true; case "create_time": data.setCreateTime(value == null ? null : (Date) value); return true; } } catch (Exception e) { MyBoxLog.debug(e); } return false; } public static Object getValue(ImageClipboard data, String column) { if (data == null || column == null) { return null; } switch (column) { case "icid": return data.getIcid(); case "image_file": return data.getImageFile() != null ? data.getImageFile().getAbsolutePath() : null; case "thumbnail_file": return data.getThumbnailFile() != null ? data.getThumbnailFile().getAbsolutePath() : null; case "width": return data.getWidth(); case "height": return data.getHeight(); case "source": return source(data.getSource()); case "create_time": return data.getCreateTime(); } return null; } public static boolean valid(ImageClipboard data) { return data != null && data.getImageFile() != null; } public static ImageSource source(short value) { for (ImageSource source : ImageSource.values()) { if (source.ordinal() == value) { return source; } } return ImageSource.Unknown; } public static String sourceName(short value) { for (ImageSource source : ImageSource.values()) { if (source.ordinal() == value) { return source.name(); } } return ImageSource.Unknown.name(); } public static ImageSource source(String name) { for (ImageSource source : ImageSource.values()) { if (source.name().equals(name)) { return source; } } return ImageSource.Unknown; } public static short source(ImageSource value) { if (value == null || value == ImageSource.Unknown) { return -1; } return (short) value.ordinal(); } public static ImageClipboard create(FxTask task, BufferedImage image, ImageSource source) { try { if (image == null) { return null; } String prefix = AppPaths.getImageClipboardPath() + File.separator + (new Date().getTime()) + "_" + new Random().nextInt(1000); String imageFile = prefix + ".png"; while (new File(imageFile).exists()) { prefix = AppPaths.getImageClipboardPath() + File.separator + (new Date().getTime()) + "_" + new Random().nextInt(1000); imageFile = prefix + ".png"; } if (!ImageFileWriters.writeImageFile(task, image, "png", imageFile)) { return null; } if (task != null && !task.isWorking()) { return null; } String thumbFile = prefix + "_thumbnail.png"; BufferedImage thumbnail = ScaleTools.scaleImageWidthKeep(image, AppVariables.thumbnailWidth); if (thumbnail == null || (task != null && !task.isWorking())) { return null; } if (!ImageFileWriters.writeImageFile(task, thumbnail, "png", thumbFile)) { return null; } if (task != null && !task.isWorking()) { return null; } ImageClipboard clip = ImageClipboard.create() .setSource(source) .setImageFile(new File(imageFile)) .setThumbnailFile(new File(thumbFile)) .setWidth(image.getWidth()).setHeight(image.getHeight()) .setThumbnail(SwingFXUtils.toFXImage(thumbnail, null)) .setCreateTime(new Date()); return clip; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static ImageClipboard create(FxTask task, Image image, ImageSource source) { try { if (image == null) { return null; } return create(task, SwingFXUtils.fromFXImage(image, null), source); } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static ImageClipboard add(FxTask task, Image image, ImageSource source) { try { return add(task, SwingFXUtils.fromFXImage(image, null), source); } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static ImageClipboard add(FxTask task, File file) { try { BufferedImage bufferImage = ImageFileReaders.readImage(task, file); if (bufferImage == null || (task != null && !task.isWorking())) { return null; } return add(task, bufferImage, ImageSource.File); } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static ImageClipboard add(FxTask task, BufferedImage image, ImageSource source) { try { ImageClipboard clip = ImageClipboard.create(task, image, source); if (clip == null || (task != null && !task.isWorking())) { return null; } new TableImageClipboard().insertData(clip); ImageInMyBoxClipboardController.updateClipboards(); return clip; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static Image loadImage(FxTask task, ImageClipboard clip) { try { if (clip == null) { return null; } if (clip.getImage() != null) { return clip.getImage(); } File imageFile = clip.getImageFile(); if (imageFile == null || !imageFile.exists()) { return clip.getThumbnail(); } BufferedImage bfImage = ImageFileReaders.readImage(task, imageFile); if (bfImage == null || (task != null && !task.isWorking())) { return null; } Image image = SwingFXUtils.toFXImage(bfImage, null); return image; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static Image loadThumb(FxTask task, ImageClipboard clip) { try { if (clip == null) { return null; } if (clip.getThumbnail() != null) { return clip.getThumbnail(); } File thumbFile = clip.getThumbnailFile(); if (thumbFile == null || !thumbFile.exists()) { return clip.getImage(); } BufferedImage bfImage = ImageFileReaders.readImage(task, thumbFile); if (bfImage == null || (task != null && !task.isWorking())) { return null; } Image thumb = SwingFXUtils.toFXImage(bfImage, null); return thumb; } catch (Exception e) { MyBoxLog.debug(e); return null; } } /* get/set */ public File getImageFile() { return imageFile; } public ImageClipboard setImageFile(File imageFile) { this.imageFile = imageFile; return this; } public File getThumbnailFile() { return thumbnailFile; } public ImageClipboard setThumbnailFile(File thumbnailFile) { this.thumbnailFile = thumbnailFile; return this; } public Image getImage() { return image; } public ImageClipboard setImage(Image image) { this.image = image; return this; } public Image getThumbnail() { return thumbnail; } public ImageClipboard setThumbnail(Image thumbnail) { this.thumbnail = thumbnail; return this; } public int getWidth() { return width; } public ImageClipboard setWidth(int width) { this.width = width; return this; } public int getHeight() { return height; } public ImageClipboard setHeight(int height) { this.height = height; return this; } public ImageSource getSource() { return source; } public ImageClipboard setSource(ImageSource source) { this.source = source; if (source != null) { sourceName = source.name(); } else { sourceName = null; } return this; } public String getSourceName() { if (source != null) { sourceName = source.name(); } return sourceName; } public ImageClipboard setSourceName(String sourceName) { this.sourceName = sourceName; return this; } public Date getCreateTime() { return createTime; } public ImageClipboard setCreateTime(Date createTime) { this.createTime = createTime; return this; } public long getIcid() { return icid; } public ImageClipboard setIcid(long icid) { this.icid = icid; return this; } public ImageClipboard getSelf() { return self; } public void setSelf(ImageClipboard self) { this.self = self; } }
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/data/DataTag.java
alpha/MyBox/src/main/java/mara/mybox/db/data/DataTag.java
package mara.mybox.db.data; import javafx.scene.paint.Color; import mara.mybox.db.table.BaseTable; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.image.FxColorTools; /** * @Author Mara * @CreateDate 2021-3-20 * @License Apache License Version 2.0 */ public class DataTag extends BaseData { protected BaseTable dataTable; protected long tagid; protected String tag; protected Color color; private void init() { tagid = -1; tag = null; color = FxColorTools.randomColor(); } public DataTag() { init(); } @Override public boolean setValue(String column, Object value) { return setValue(this, column, value); } @Override public Object getValue(String column) { return getValue(this, column); } @Override public boolean valid() { return valid(this); } public DataTag setColorString(String v) { this.color = v == null ? FxColorTools.randomColor() : Color.web((String) v); return this; } /* Static methods */ public static DataTag create() { return new DataTag(); } public static boolean setValue(DataTag data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "tagid": data.setTagid(value == null ? -1 : (long) value); return true; case "tag": data.setTag(value == null ? null : (String) value); return true; case "color": data.setColor(value == null ? FxColorTools.randomColor() : Color.web((String) value)); return true; } } catch (Exception e) { MyBoxLog.debug(e); } return false; } public static Object getValue(DataTag data, String column) { if (data == null || column == null) { return null; } switch (column) { case "tagid": return data.getTagid(); case "tag": return data.getTag(); case "color": return data.getColor() == null ? FxColorTools.randomColor().toString() : data.getColor().toString(); } return null; } public static boolean valid(DataTag data) { return data != null && data.getTag() != null && !data.getTag().isBlank(); } /* get/set */ public long getTagid() { return tagid; } public DataTag setTagid(long tagid) { this.tagid = tagid; return this; } public String getTag() { return tag; } public DataTag setTag(String tag) { this.tag = tag; return this; } public Color getColor() { return color; } public DataTag setColor(Color color) { this.color = color; 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/data/TextClipboard.java
alpha/MyBox/src/main/java/mara/mybox/db/data/TextClipboard.java
/* * Apache License Version 2.0 */ package mara.mybox.db.data; import java.util.Date; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2021-7-3 * @License Apache License Version 2.0 */ public class TextClipboard extends BaseData { protected long tcid, length; protected String text; protected Date createTime; private void init() { tcid = -1; length = 0; createTime = new Date(); } public TextClipboard() { init(); } public TextClipboard(String text) { init(); this.text = text; } @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 TextClipboard create() { return new TextClipboard(); } public static boolean setValue(TextClipboard data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "tcid": data.setTcid(value == null ? -1 : (long) value); return true; case "text": data.setText(value == null ? null : (String) value); return true; case "create_time": data.setCreateTime(value == null ? null : (Date) value); return true; } } catch (Exception e) { MyBoxLog.debug(e); } return false; } public static Object getValue(TextClipboard data, String column) { if (data == null || column == null) { return null; } switch (column) { case "tcid": return data.getTcid(); case "text": return data.getText(); case "create_time": return data.getCreateTime(); } return null; } public static boolean valid(TextClipboard data) { return data != null && data.getText() != null; } /* get/set */ public long getTcid() { return tcid; } public void setTcid(long tcid) { this.tcid = tcid; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public long getLength() { if (text == null) { length = 0; } else { length = text.length(); } return length; } public void setLength(long length) { this.length = length; } }
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/data/NamedValues.java
alpha/MyBox/src/main/java/mara/mybox/db/data/NamedValues.java
package mara.mybox.db.data; import java.util.Date; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2022-3-8 * @License Apache License Version 2.0 */ public class NamedValues extends BaseData { protected String key, name, value; protected Date time; public NamedValues() { init(); } private void init() { key = null; name = null; value = null; time = new Date(); } public NamedValues(String key, String name, String value, Date time) { this.key = key; this.name = name; this.value = value; this.time = time; } @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 NamedValues create() { return new NamedValues(); } public static boolean setValue(NamedValues data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "key_name": data.setKey(value == null ? null : (String) value); return true; case "value": data.setValue(value == null ? null : (String) value); return true; case "value_name": data.setName(value == null ? null : (String) value); return true; case "update_time": data.setTime(value == null ? null : (Date) value); return true; } } catch (Exception e) { MyBoxLog.debug(e); } return false; } public static Object getValue(NamedValues data, String column) { if (data == null || column == null) { return null; } switch (column) { case "key_name": return data.getKey(); case "value": return data.getValue(); case "value_name": return data.getName(); case "update_time": return data.getTime(); } return null; } public static boolean valid(NamedValues data) { return data != null && data.getKey() != null && data.getValue() != null; } /* get/set */ public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } }
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/data/FileBackup.java
alpha/MyBox/src/main/java/mara/mybox/db/data/FileBackup.java
package mara.mybox.db.data; import java.io.File; import java.util.Date; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2020-9-7 * @License Apache License Version 2.0 */ public class FileBackup extends BaseData { public static final int Default_Max_Backups = 20; protected long fbid; protected File file, backup; protected Date recordTime; private void init() { fbid = -1; file = null; backup = null; recordTime = null; } public FileBackup() { init(); } public FileBackup(File file, File backup) { fbid = -1; this.file = file; this.backup = backup; recordTime = new Date(); } @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 String getName() { return backup != null ? backup.getAbsolutePath() : null; } public long getSize() { return backup != null ? backup.length() : 0; } /* Static methods */ public static FileBackup create() { return new FileBackup(); } public static boolean setValue(FileBackup data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "fbid": data.setFbid(value == null ? -1 : (long) value); return true; case "file": data.setFile(null); if (value != null) { File f = new File((String) value); if (f.exists()) { data.setFile(f); } } return true; case "backup": data.setBackup(null); if (value != null) { File f = new File((String) value); if (f.exists()) { data.setBackup(f); } } return true; case "record_time": data.setRecordTime(value == null ? null : (Date) value); return true; } } catch (Exception e) { MyBoxLog.debug(e); } return false; } public static Object getValue(FileBackup data, String column) { if (data == null || column == null) { return null; } switch (column) { case "fbid": return data.getFbid(); case "file": return data.getFile() != null ? data.getFile().getAbsolutePath() : null; case "backup": return data.getBackup() != null ? data.getBackup().getAbsolutePath() : null; case "record_time": return data.getRecordTime(); } return null; } public static boolean valid(FileBackup data) { return data != null && data.getFile() != null && data.getFile().exists() && data.getBackup() != null && data.getBackup().exists() && data.getRecordTime() != null; } /* customized get/set */ public void setFilename(String string) { if (string != null) { File f = new File((String) string); if (f.exists()) { file = f; } } } /* get/set */ public long getFbid() { return fbid; } public void setFbid(long fbid) { this.fbid = fbid; } public File getFile() { return file; } public void setFile(File file) { this.file = file; } public File getBackup() { return backup; } public void setBackup(File backup) { this.backup = backup; } public Date getRecordTime() { return recordTime; } public void setRecordTime(Date recordTime) { this.recordTime = recordTime; } }
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/data/ColumnDefinition.java
alpha/MyBox/src/main/java/mara/mybox/db/data/ColumnDefinition.java
package mara.mybox.db.data; import java.sql.Blob; import java.sql.Clob; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.util.Date; import java.util.List; import java.util.Random; import javafx.scene.paint.Color; import mara.mybox.calculation.DoubleStatistic; import mara.mybox.db.DerbyBase; import static mara.mybox.db.table.BaseTable.StringMaxLength; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.image.FxColorTools; import mara.mybox.tools.DateTools; import mara.mybox.tools.DoubleTools; import mara.mybox.tools.FloatTools; import mara.mybox.tools.IntTools; import mara.mybox.tools.LongTools; import mara.mybox.tools.NumberTools; import mara.mybox.tools.ShortTools; import mara.mybox.tools.StringTools; import mara.mybox.value.AppValues; import static mara.mybox.value.Languages.matchIgnoreCase; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2020-7-12 * @License Apache License Version 2.0 */ public class ColumnDefinition extends BaseData { protected String tableName, columnName, referName, referTable, referColumn, defaultValue, description, format, label; protected ColumnType type; protected int index, length, width, scale, century; protected Color color; protected boolean isPrimaryKey, notNull, editable, auto, fixTwoDigitYear; protected OnDelete onDelete; protected OnUpdate onUpdate; protected Object value; protected Number maxValue, minValue; protected DoubleStatistic statistic; final public static InvalidAs DefaultInvalidAs = InvalidAs.Skip; public static enum ColumnType { String, Boolean, Enumeration, EnumerationEditable, Color, // rgba File, Image, // string of the path Double, Float, Long, Integer, Short, Datetime, Date, Era, // Looks Derby does not support date of BC(before Christ) Clob, // CLOB is handled as string internally, and maxmium length is Integer.MAX(2G) Blob, // BLOB is handled as InputStream internally Longitude, Latitude, EnumeratedShort, NumberBoolean } public static enum OnDelete { NoAction, Restrict, Cascade, SetNull } public static enum OnUpdate { NoAction, Restrict } public enum InvalidAs { Zero, Empty, Null, Skip, Use, Fail } public final void initColumnDefinition() { tableName = null; columnName = null; type = ColumnType.String; index = -1; isPrimaryKey = notNull = auto = fixTwoDigitYear = false; editable = true; length = StringMaxLength; width = 100; // px scale = 8; onDelete = OnDelete.Restrict; onUpdate = OnUpdate.Restrict; format = null; maxValue = null; minValue = null; color = FxColorTools.randomColor(); defaultValue = null; referName = null; referTable = null; referColumn = null; statistic = null; description = null; century = 2000; label = null; } public ColumnDefinition() { initColumnDefinition(); } public ColumnDefinition(String name, ColumnType type) { initColumnDefinition(); this.columnName = name; this.type = type; } public ColumnDefinition(String name, ColumnType type, boolean notNull) { initColumnDefinition(); this.columnName = name; this.type = type; this.notNull = notNull; } public ColumnDefinition(String name, ColumnType type, boolean notNull, boolean isPrimaryKey) { initColumnDefinition(); this.columnName = name; this.type = type; this.notNull = notNull; this.isPrimaryKey = isPrimaryKey; } public ColumnDefinition cloneAll() { try { ColumnDefinition newData = (ColumnDefinition) super.clone(); return newData.cloneFrom(this); } catch (Exception e) { MyBoxLog.debug(e); return null; } } public ColumnDefinition cloneFrom(ColumnDefinition c) { try { if (c == null) { return this; } tableName = c.tableName; columnName = c.columnName; referName = c.referName; referTable = c.referTable; referColumn = c.referColumn; type = c.type; index = c.index; length = c.length; width = c.width; scale = c.scale; format = c.format; color = c.color; isPrimaryKey = c.isPrimaryKey; notNull = c.notNull; auto = c.auto; editable = c.editable; onDelete = c.onDelete; onUpdate = c.onUpdate; defaultValue = c.defaultValue; value = c.value; maxValue = c.maxValue; minValue = c.minValue; statistic = c.statistic; description = c.description; fixTwoDigitYear = c.fixTwoDigitYear; century = c.century; label = c.label; } catch (Exception e) { MyBoxLog.debug(e); } return this; } public boolean isForeignKey() { return referTable != null && referColumn != null; // return referTable != null && !referTable.isBlank() // && referColumn != null && !referColumn.isBlank() // && referName != null && !referName.isBlank(); } public String foreignText() { if (!isForeignKey()) { return null; } String sql = (referName != null && !referName.isBlank() ? "CONSTRAINT " + referName + " " : "") + "FOREIGN KEY (" + columnName + ") REFERENCES " + referTable + " (" + referColumn + ") ON DELETE "; switch (onDelete) { case NoAction: sql += "NO ACTION"; break; case Restrict: sql += "RESTRICT"; break; case SetNull: sql += "SET NULL"; break; default: sql += "CASCADE"; break; } sql += " ON UPDATE "; switch (onUpdate) { case NoAction: sql += "NO ACTION"; break; default: sql += "RESTRICT"; break; } return sql; } @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 boolean isId() { return isPrimaryKey && auto; } public boolean validValue(String value) { if (value == null || value.isBlank()) { return !notNull; } return fromString(value, InvalidAs.Fail) != null; } public boolean validNotNull(String value) { return !notNull || (value != null && !value.isEmpty()); } public int compare(Object value1, Object value2) { if (value1 == null) { if (value2 == null) { return 0; } else { return -1; } } else if (value2 == null) { return 1; } return compare(toString(value1), toString(value2)); } // invalid values are counted as smaller public int compare(String value1, String value2) { try { if (value1 == null) { if (value2 == null) { return 0; } else { return -1; } } else if (value2 == null) { return 1; } switch (type) { case Double: return DoubleTools.compare(value1, value2, false); case Float: return FloatTools.compare(value1, value2, false); case Long: return LongTools.compare(value1, value2, false); case Integer: return IntTools.compare(value1, value2, false); case Short: return ShortTools.compare(value1, value2, false); case Datetime: case Date: case Era: return compareDate(value1, value2, false); default: return StringTools.compare(value1, value2); } } catch (Exception e) { } return 1; } // invalid values are always in the end public int compareDate(String s1, String s2, boolean desc) { double d1, d2; try { d1 = toDate(s1).getTime(); } catch (Exception e) { d1 = Double.NaN; } try { d2 = toDate(s2).getTime(); } catch (Exception e) { d2 = Double.NaN; } return DoubleTools.compare(d1, d2, desc); } public boolean isBooleanType() { return type == ColumnType.Boolean; } public boolean isNumberType() { return isNumberType(type); } public boolean isDBNumberType() { return isDBNumberType(type); } public boolean isDBStringType() { return isDBStringType(type); } public boolean isDoubleType() { return type == ColumnType.Double; } public boolean isDBDoubleType() { return type == ColumnType.Double || type == ColumnType.Longitude || type == ColumnType.Latitude; } public boolean isTimeType() { return isTimeType(type); } public boolean isEnumType() { return type == ColumnType.Enumeration || type == ColumnType.EnumerationEditable || type == ColumnType.EnumeratedShort; } public List<String> enumNames() { if (!isEnumType()) { return null; } return StringTools.toList(format, "\n"); } public String enumName(Short v) { try { return enumNames().get((int) v); } catch (Exception e) { return v != null ? v + "" : null; } } public Short enumValue(String v) { List<String> names = enumNames(); try { Short s = Short.valueOf(v.replaceAll(",", "")); if (!ShortTools.invalidShort(s) && s >= 0 && s < names.size()) { return s; } } catch (Exception e) { } try { for (int i = 0; i < names.size(); i++) { if (matchIgnoreCase(v, names.get(i))) { return (short) i; } } } catch (Exception e) { } return null; } public boolean needScale() { return type == ColumnType.Double || type == ColumnType.Float; } public boolean supportMultipleLine() { return type == ColumnType.String || type == ColumnType.Clob; } public String random(Random random, int maxRandom, short scale, boolean nonNegative) { if (random == null) { random = new Random(); } switch (type) { case Double: return NumberTools.format(DoubleTools.random(random, maxRandom, nonNegative), scale); case Float: return NumberTools.format(FloatTools.random(random, maxRandom, nonNegative), scale); case Integer: return StringTools.format(IntTools.random(random, maxRandom, nonNegative)); case Long: return StringTools.format(LongTools.random(random, maxRandom, nonNegative)); case Short: return StringTools.format((short) IntTools.random(random, maxRandom, nonNegative)); case Boolean: return random.nextInt(2) > 0 ? "true" : "false"; case NumberBoolean: return random.nextInt(2) + ""; case Datetime: case Date: case Era: return DateTools.randomDateString(random, format); default: return NumberTools.format(DoubleTools.random(random, maxRandom, nonNegative), scale); // return (char) ('a' + random.nextInt(25)) + ""; } } public ColumnDefinition cloneBase() { try { return (ColumnDefinition) clone(); } catch (Exception e) { return null; } } // results.getDouble/getFloat/getInt/getShort returned is 0 if the value is SQL NULL. // But we need distinct zero and null. // https://docs.oracle.com/en/java/javase/18/docs/api/java.sql/java/sql/ResultSet.html#getDouble(java.lang.String) public Object value(ResultSet results) { Object o; String savedName; try { if (results == null || type == null || columnName == null) { return null; } savedName = DerbyBase.savedName(columnName); o = results.getObject(savedName); if (o == null) { return null; } } catch (Exception e) { return null; } try { // MyBoxLog.console(columnName + " " + type + " " + savedName + " " + o + " " + o.getClass()); switch (type) { case String: case Enumeration: case EnumerationEditable: case Color: case File: case Image: try { return (String) o; } catch (Exception e) { return null; } case Era: try { long e = Long.parseLong(o + ""); if (e >= 10000 || e <= -10000) { return e; } else { return e; } } catch (Exception e) { return null; } case Double: try { double d = Double.parseDouble(o + ""); if (DoubleTools.invalidDouble(d)) { return null; } else { return d; } } catch (Exception e) { return null; } case Longitude: try { double d = Double.parseDouble(o + ""); if (d >= -180 && d <= 180) { return d; } else { return null; } } catch (Exception e) { return null; } case Latitude: try { double d = Double.parseDouble(o + ""); if (d >= -90 && d <= 90) { return d; } else { return null; } } catch (Exception e) { return null; } case Float: try { float f = Float.parseFloat(o + ""); if (FloatTools.invalidFloat(f)) { return null; } else { return f; } } catch (Exception e) { return null; } case Long: try { long l = Long.parseLong(o + ""); if (LongTools.invalidLong(l)) { return null; } else { return l; } } catch (Exception e) { return null; } case Integer: try { int i = Integer.parseInt(o + ""); if (IntTools.invalidInt(i)) { return null; } else { return i; } } catch (Exception e) { return null; } case Short: try { short s = Short.parseShort(o + ""); if (ShortTools.invalidShort(s)) { return null; } else { return s; } } catch (Exception e) { return null; } case EnumeratedShort: try { short s = Short.parseShort(o + ""); if (ShortTools.invalidShort(s)) { return null; } else { return s; } } catch (Exception e) { return null; } case Boolean: return StringTools.isTrue(o + ""); case NumberBoolean: String s = o + ""; if (StringTools.isTrue(s)) { return 1; } if (StringTools.isFalse(s)) { return 0; } try { double d = Double.parseDouble(s); if (d > 0) { return 1; } else { return 0; } } catch (Exception e) { return 0; } case Datetime: return toDate(o + ""); case Date: return toDate(o + ""); case Clob: // MyBoxLog.console(columnName + " " + type + " " + savedName + " " + o + " " + o.getClass()); Clob clob = (Clob) o; return clob.getSubString(1, (int) clob.length()); case Blob: // MyBoxLog.console(tableName + " " + columnName + " " + type); Blob blob = (Blob) o; return blob.getBinaryStream(); default: MyBoxLog.debug(savedName + " " + type); } } catch (Exception e) { MyBoxLog.error(e.toString(), tableName + " " + columnName + " " + type); } return null; } // remove format and convert to real value type public Object fromString(String string, InvalidAs invalidAs) { try { switch (type) { case Double: Double d = Double.valueOf(string.replaceAll(",", "")); if (!DoubleTools.invalidDouble(d)) { return d; } break; case Longitude: Double lo = Double.valueOf(string.replaceAll(",", "")); if (lo >= -180 && lo <= 180) { return lo; } break; case Latitude: Double la = Double.valueOf(string.replaceAll(",", "")); if (la >= -90 && la <= 90) { return la; } break; case Float: Double df = Double.valueOf(string.replaceAll(",", "")); // MyBoxLog.console(string + " --- " + df); if (!DoubleTools.invalidDouble(df)) { return df; } // Float.valueOf may lose precision // Float f = Float.valueOf(string.replaceAll(",", "")); // MyBoxLog.console(string + " --- " + f); // if (!FloatTools.invalidFloat(f)) { // return f; // } // break; case Long: Long l = Long.valueOf(string.replaceAll(",", "")); if (!LongTools.invalidLong(l)) { return l; } break; case Integer: Integer i = Integer.valueOf(string.replaceAll(",", "")); if (!IntTools.invalidInt(i)) { return i; } break; case Short: Short s = Short.valueOf(string.replaceAll(",", "")); if (!ShortTools.invalidShort(s)) { return s; } break; case EnumeratedShort: Short es = enumValue(string); if (es != null) { return es; } break; case Boolean: return StringTools.isTrue(string); case NumberBoolean: if (StringTools.isTrue(string)) { return 1; } if (StringTools.isFalse(string)) { return 0; } double n = Double.parseDouble(string.replaceAll(",", "")); if (!DoubleTools.invalidDouble(n)) { if (n > 0) { return 1; } else { return 0; } } case Datetime: case Date: Date t = stringToDate(string, fixTwoDigitYear, century); if (t != null) { return t; } break; case Era: Date e = stringToDate(string, fixTwoDigitYear, century); if (e != null) { return e.getTime(); } break; case Color: try { Color.web(string); return string; } catch (Exception exx) { } default: return string; } } catch (Exception e) { } if (invalidAs == null) { return string; } switch (invalidAs) { case Fail: return null; case Zero: if (isDBNumberType()) { switch (type) { case Double: return 0d; case Float: return 0f; case Long: return 0l; case Short: case EnumeratedShort: return (short) 0; default: return 0; } } else { return "0"; } case Null: if (isDBStringType()) { return ""; } else { return null; } case Empty: return ""; case Skip: return string; case Use: return string; default: return string; } } public String toString(Object value) { if (value == null) { return null; } String s = value + ""; try { switch (type) { case Double: case Longitude: case Latitude: Double d = (Double) value; if (DoubleTools.invalidDouble(d)) { return null; } else { return s; } case Float: Float f = (Float) value; if (FloatTools.invalidFloat(f)) { return null; } else { return s; } case Long: Long l = (Long) value; if (LongTools.invalidLong(l)) { return null; } else { return s; } case Integer: Integer i = (Integer) value; if (IntTools.invalidInt(i)) { return null; } else { return s; } case Short: Short st = (Short) value; if (ShortTools.invalidShort(st)) { return null; } else { return s; } case EnumeratedShort: Short es = (Short) value; if (ShortTools.invalidShort(es) || enumName(es) == null) { return null; } else { return s; } case Datetime: case Date: return DateTools.datetimeToString((Date) value); case Era: { try { long lv = Long.parseLong(value.toString()); if (lv >= 10000 || lv <= -10000) { return DateTools.datetimeToString(new Date(lv)); } } catch (Exception exx) { return s; } } default: return s; } } catch (Exception e) { return s; } } public String formatValue(Object v) { return formatString(toString(v), InvalidAs.Use); } public String formatString(String v) { return formatString(v, InvalidAs.Use); } public String formatString(String string, InvalidAs inAs) { Object o = null; try { o = fromString(string, inAs); } catch (Exception e) { } if (o == null) { return null; } try { switch (type) { case Double: return DoubleTools.format((Double) o, format, scale); case Float: return FloatTools.format((Float) o, format, scale); case Long: return LongTools.format((Long) o, format, scale); case Integer: return IntTools.format((Integer) o, format, scale); case Short: return ShortTools.format((Short) o, format, scale); case EnumeratedShort: return enumName((Short) o); case Datetime: return DateTools.datetimeToString((Date) o, format); case Date: return DateTools.datetimeToString((Date) o, format); case Era: { String s = toString(o); try { long lv = Long.parseLong(s); if (lv >= 10000 || lv <= -10000) { return DateTools.datetimeToString(new Date(lv), format); } } catch (Exception ex) { return DateTools.datetimeToString(toDate(s), format); } } } } catch (Exception e) { } return toString(o); } public String exportValue(Object v, boolean format) { return format ? formatValue(v) : toString(v); } public String removeFormat(String string) { return removeFormat(string, InvalidAs.Use); } public String removeFormat(String string, InvalidAs invalidAs) { if (invalidAs == null) { return string; } switch (type) { case Datetime: case Date: case Era: case Enumeration: case EnumerationEditable: return string; default: Object o = null; try { o = fromString(string, invalidAs); } catch (Exception e) { } return toString(o); } } public boolean valueQuoted() { return !isDBNumberType() && type != ColumnType.Boolean; } public String dbDefaultValue() { Object v = fromString(defaultValue, InvalidAs.Null); switch (type) { case String: case Enumeration: case EnumerationEditable: case File: case Image: case Color: case Clob: if (v != null) { return "'" + defaultValue + "'"; } else { return "''"; } case Double: case Float: case Long: case Integer: case Short: case EnumeratedShort: case Longitude: case Latitude: case Era: if (v != null) { return v + ""; } else { return "0"; } case Boolean: return StringTools.isTrue(v + "") + ""; case NumberBoolean: return StringTools.isTrue(v + "") ? "1" : "0"; case Datetime: if (v != null) { return "'" + defaultValue + "'"; } else { return " CURRENT TIMESTAMP "; } case Date: if (v != null) { return "'" + defaultValue + "'"; } else { return " CURRENT DATE "; } default: return "''"; } } public Object defaultValue() { return fromString(defaultValue, InvalidAs.Null); } public String getFormatDisplay() { return format == null ? null : format.replaceAll(AppValues.MyBoxSeparator, "\n"); } public Date toDate(String string) { return stringToDate(string, fixTwoDigitYear, century); } public double toDouble(String string) { try { if (null == type || string == null) { return Double.NaN; } switch (type) { case Datetime: case Date: case Era: return toDate(string).getTime() + 0d; case Boolean: return StringTools.isTrue(string) ? 1 : 0; case NumberBoolean: if (StringTools.isTrue(string)) { return 1; } if (StringTools.isFalse(string)) { return 0; } double n = Double.parseDouble(string.replaceAll(",", "")); if (n > 0) { return 1; } else { return 0; } default: return Double.parseDouble(string.replaceAll(",", "")); } } catch (Exception e) { return Double.NaN; } } public String dummyValue() { switch (type) { case String: case Enumeration: case EnumerationEditable: case File: case Image: case Color: case Clob:
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/data/ConvolutionKernel.java
alpha/MyBox/src/main/java/mara/mybox/db/data/ConvolutionKernel.java
package mara.mybox.db.data; import java.util.ArrayList; import java.util.Date; import java.util.List; import mara.mybox.image.tools.BufferedImageTools; import mara.mybox.image.tools.BufferedImageTools.Direction; import mara.mybox.tools.DateTools; import mara.mybox.tools.FloatMatrixTools; import mara.mybox.tools.FloatTools; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2018-11-6 20:28:03 * @Version 1.0 * @Description * @License Apache License Version 2.0 */ public class ConvolutionKernel extends BaseData { private String name, description, modifyTime, createTime; private int width, height, type, edge, color; private float[][] matrix; private boolean invert; public static class Convolution_Type { public static int NONE = 0; public static int BLUR = 1; public static int SHARPNEN = 2; public static int EMBOSS = 3; public static int EDGE_DETECTION = 4; } public static class Edge_Op { public static int COPY = 0; public static int FILL_ZERO = 1; } public static class Color { public static int Keep = 0; public static int Grey = 1; public static int BlackWhite = 2; } public ConvolutionKernel() { name = ""; description = ""; modifyTime = DateTools.datetimeToString(new Date()); createTime = DateTools.datetimeToString(new Date()); width = 0; height = 0; type = 0; edge = 0; invert = false; } @Override public boolean valid() { return true; } @Override public boolean setValue(String column, Object value) { return true; } @Override public Object getValue(String column) { return null; } public ConvolutionKernel setGrey() { color = Color.Grey; return this; } public boolean isGrey() { return color == Color.Grey; } public ConvolutionKernel setBW() { color = Color.BlackWhite; return this; } public boolean isBW() { return color == Color.BlackWhite; } /* Static methods */ public static List<ConvolutionKernel> makeExample() { List<ConvolutionKernel> ExampleKernels = new ArrayList<>(); ExampleKernels.add(makeAverageBlur(3)); ExampleKernels.add(makeGaussBlur(3)); ExampleKernels.add(makeGaussBlur(5)); ExampleKernels.add(makeMotionBlur(1)); ExampleKernels.add(makeMotionBlur(2)); ExampleKernels.add(makeMotionBlur(3)); ExampleKernels.add(MakeSharpenFourNeighborLaplace()); ExampleKernels.add(MakeSharpenEightNeighborLaplace()); ExampleKernels.add(makeEdgeDetectionFourNeighborLaplace()); ExampleKernels.add(makeEdgeDetectionEightNeighborLaplace()); ExampleKernels.add(makeEdgeDetectionFourNeighborLaplaceInvert()); ExampleKernels.add(makeEdgeDetectionEightNeighborLaplaceInvert()); ExampleKernels.add(makeUnsharpMasking5()); ExampleKernels.add(makeEmbossTop3()); ExampleKernels.add(makeEmbossBottom3()); ExampleKernels.add(makeEmbossLeft3()); ExampleKernels.add(makeEmbossRight3()); ExampleKernels.add(makeEmbossLeftTop3()); ExampleKernels.add(makeEmbossRightBottom3()); ExampleKernels.add(makeEmbossLeftBottom3()); ExampleKernels.add(makeEmbossRightTop3()); return ExampleKernels; } public static ConvolutionKernel makeAverageBlur(int radius) { int size = 2 * radius + 1; ConvolutionKernel kernel = new ConvolutionKernel(); kernel.setName(message("AverageBlur") + " " + size + "*" + size); kernel.setCreateTime(DateTools.datetimeToString(new Date())); kernel.setModifyTime(DateTools.datetimeToString(new Date())); kernel.setWidth(size); kernel.setHeight(size); kernel.setType(Convolution_Type.BLUR); kernel.setDescription(""); float v = 1.0f / (size * size * 1.0f); float[][] k = new float[size][size]; for (int i = 0; i < size; ++i) { for (int j = 0; j < size; ++j) { k[i][j] = v; } } kernel.setMatrix(k); return kernel; } public static ConvolutionKernel makeGaussBlur(int radius) { ConvolutionKernel kernel = new ConvolutionKernel(); int length = radius * 2 + 1; kernel.setName(message("GaussianBlur") + " " + length + "*" + length); kernel.setCreateTime(DateTools.datetimeToString(new Date())); kernel.setModifyTime(DateTools.datetimeToString(new Date())); kernel.setWidth(length); kernel.setHeight(length); kernel.setType(Convolution_Type.BLUR); kernel.setDescription(""); float[][] k = makeGaussMatrix(radius); kernel.setMatrix(k); return kernel; } // https://en.wikipedia.org/wiki/Kernel_(image_processing) // https://lodev.org/cgtutor/filtering.html public static float[] makeGaussArray(int radius) { if (radius < 1) { return null; } float sum = 0.0f; int width = radius * 2 + 1; int size = width * width; float sigma = radius / 3.0f; float twoSigmaSquare = 2.0f * sigma * sigma; float sigmaRoot = (float) Math.PI * twoSigmaSquare; float[] data = new float[size]; int index = 0; float x, y; for (int i = -radius; i <= radius; ++i) { for (int j = -radius; j <= radius; ++j) { x = i * i; y = j * j; data[index] = (float) Math.exp(-(x + y) / twoSigmaSquare) / sigmaRoot; sum += data[index]; index++; } } for (int k = 0; k < size; k++) { data[k] = FloatTools.roundFloat5(data[k] / sum); } return data; } public static float[][] makeGaussMatrix(int radius) { return FloatMatrixTools.array2Matrix(makeGaussArray(radius), radius * 2 + 1); } public static ConvolutionKernel makeMotionBlur(int radius) { int size = 2 * radius + 1; ConvolutionKernel kernel = new ConvolutionKernel(); kernel.setName(message("MotionBlur") + " " + size + "*" + size); kernel.setCreateTime(DateTools.datetimeToString(new Date())); kernel.setModifyTime(DateTools.datetimeToString(new Date())); kernel.setWidth(size); kernel.setHeight(size); kernel.setType(Convolution_Type.BLUR); kernel.setDescription(""); float v = 1.0f / size; float[][] k = new float[size][size]; for (int i = 0; i < size; ++i) { for (int j = 0; j < size; ++j) { if (i == j) { k[i][j] = v; } else { k[i][j] = 0; } } } kernel.setMatrix(k); return kernel; } public static ConvolutionKernel makeMotionAngleBlur(int radius, int angle) { ConvolutionKernel kernel = new ConvolutionKernel(); int length = radius * 2 + 1; kernel.setName(message("MotionBlur") + " " + length + "*" + length); kernel.setCreateTime(DateTools.datetimeToString(new Date())); kernel.setModifyTime(DateTools.datetimeToString(new Date())); kernel.setWidth(length); kernel.setHeight(length); kernel.setType(Convolution_Type.BLUR); kernel.setDescription(""); float[][] k = new float[length][length]; for (int i = 0; i < length; ++i) { for (int j = 0; j < length; ++j) { k[i][j] = (float) Math.sin(angle); } } k[radius][radius] = 2 + k[radius][radius]; // MyBoxLog.debug(MatrixTools.print(FloatTools.toDouble(k), 0, 8)); kernel.setMatrix(k); return kernel; } public static ConvolutionKernel MakeSharpenFourNeighborLaplace() { ConvolutionKernel kernel = new ConvolutionKernel(); kernel.setName(message("Sharpen") + " " + message("FourNeighborLaplace")); kernel.setCreateTime(DateTools.datetimeToString(new Date())); kernel.setModifyTime(DateTools.datetimeToString(new Date())); kernel.setWidth(3); kernel.setHeight(3); kernel.setType(Convolution_Type.SHARPNEN); kernel.setDescription(""); float[][] k = { {0.0f, -1.0f, 0.0f}, {-1.0f, 5.0f, -1.0f}, {0.0f, -1.0f, 0.0f} }; kernel.setMatrix(k); return kernel; } // https://www.javaworld.com/article/2076764/java-se/image-processing-with-java-2d.html // https://en.wikipedia.org/wiki/Kernel_(image_processing) public static ConvolutionKernel MakeSharpenEightNeighborLaplace() { ConvolutionKernel kernel = new ConvolutionKernel(); kernel.setName(message("Sharpen") + " " + message("EightNeighborLaplace")); kernel.setCreateTime(DateTools.datetimeToString(new Date())); kernel.setModifyTime(DateTools.datetimeToString(new Date())); kernel.setWidth(3); kernel.setHeight(3); kernel.setType(Convolution_Type.SHARPNEN); kernel.setDescription(""); float[][] k = { {-1.0f, -1.0f, -1.0f}, {-1.0f, 9.0f, -1.0f}, {-1.0f, -1.0f, -1.0f} }; kernel.setMatrix(k); return kernel; } public static ConvolutionKernel makeEdgeDetectionFourNeighborLaplace() { ConvolutionKernel kernel = new ConvolutionKernel(); kernel.setName(message("EdgeDetection") + " " + message("FourNeighborLaplace")); kernel.setCreateTime(DateTools.datetimeToString(new Date())); kernel.setModifyTime(DateTools.datetimeToString(new Date())); kernel.setWidth(3); kernel.setHeight(3); kernel.setType(Convolution_Type.EDGE_DETECTION); kernel.setDescription(""); float[][] k = { {0.0f, -1.0f, 0.0f}, {-1.0f, 4.0f, -1.0f}, {0.0f, -1.0f, 0.0f} }; kernel.setMatrix(k); kernel.setInvert(false); return kernel; } public static ConvolutionKernel makeEdgeDetectionFourNeighborLaplaceInvert() { ConvolutionKernel kernel = new ConvolutionKernel(); kernel.setName(message("EdgeDetection") + " " + message("FourNeighborLaplaceInvert")); kernel.setCreateTime(DateTools.datetimeToString(new Date())); kernel.setModifyTime(DateTools.datetimeToString(new Date())); kernel.setWidth(3); kernel.setHeight(3); kernel.setType(Convolution_Type.EDGE_DETECTION); kernel.setDescription(""); float[][] k = { {0.0f, -1.0f, 0.0f}, {-1.0f, 4.0f, -1.0f}, {0.0f, -1.0f, 0.0f} }; kernel.setMatrix(k); kernel.setInvert(true); return kernel; } // https://www.javaworld.com/article/2076764/java-se/image-processing-with-java-2d.html public static ConvolutionKernel makeEdgeDetectionEightNeighborLaplace() { ConvolutionKernel kernel = new ConvolutionKernel(); kernel.setName(message("EdgeDetection") + " " + message("EightNeighborLaplace")); kernel.setCreateTime(DateTools.datetimeToString(new Date())); kernel.setModifyTime(DateTools.datetimeToString(new Date())); kernel.setWidth(3); kernel.setHeight(3); kernel.setType(Convolution_Type.EDGE_DETECTION); kernel.setDescription(""); float[][] k = { {-1.0f, -1.0f, -1.0f}, {-1.0f, 8.0f, -1.0f}, {-1.0f, -1.0f, -1.0f} }; kernel.setMatrix(k); return kernel; } public static ConvolutionKernel makeEdgeDetectionEightNeighborLaplaceInvert() { ConvolutionKernel kernel = new ConvolutionKernel(); kernel.setName(message("EdgeDetection") + " " + message("EightNeighborLaplaceInvert")); kernel.setCreateTime(DateTools.datetimeToString(new Date())); kernel.setModifyTime(DateTools.datetimeToString(new Date())); kernel.setWidth(3); kernel.setHeight(3); kernel.setType(Convolution_Type.EDGE_DETECTION); kernel.setDescription(""); float[][] k = { {-1.0f, -1.0f, -1.0f}, {-1.0f, 8.0f, -1.0f}, {-1.0f, -1.0f, -1.0f} }; kernel.setMatrix(k); kernel.setInvert(true); return kernel; } public static ConvolutionKernel makeUnsharpMasking(int radius) { ConvolutionKernel kernel = new ConvolutionKernel(); int length = radius * 2 + 1; kernel.setName(message("UnsharpMasking") + " " + length + "*" + length); kernel.setCreateTime(DateTools.datetimeToString(new Date())); kernel.setModifyTime(DateTools.datetimeToString(new Date())); kernel.setWidth(length); kernel.setHeight(length); kernel.setType(Convolution_Type.SHARPNEN); kernel.setDescription(""); float[][] k = makeGaussMatrix(radius); // MyBoxLog.debug(DoubleMatrixTools.print(FloatTools.toDouble(k), 0, 8)); for (int i = 0; i < k.length; ++i) { for (int j = 0; j < k[i].length; ++j) { k[i][j] = 0 - k[i][j]; } } k[radius][radius] = 2 + k[radius][radius]; // MyBoxLog.debug(DoubleMatrixTools.print(FloatTools.toDouble(k), 0, 8)); kernel.setMatrix(k); return kernel; } public static ConvolutionKernel makeUnsharpMasking5() { ConvolutionKernel kernel = new ConvolutionKernel(); kernel.setName(message("UnsharpMasking") + " 5*5"); kernel.setCreateTime(DateTools.datetimeToString(new Date())); kernel.setModifyTime(DateTools.datetimeToString(new Date())); kernel.setWidth(5); kernel.setHeight(5); kernel.setType(Convolution_Type.SHARPNEN); kernel.setDescription(""); float[][] k = { {-1 / 256.0f, -4 / 256.0f, -6 / 256.0f, -4 / 256.0f, -1 / 256.0f}, {-4 / 256.0f, -16 / 256.0f, -24 / 256.0f, -16 / 256.0f, -4 / 256.0f}, {-6 / 256.0f, -24 / 256.0f, 476 / 256.0f, -24 / 256.0f, -6 / 256.0f}, {-4 / 256.0f, -16 / 256.0f, -24 / 256.0f, -16 / 256.0f, -4 / 256.0f}, {-1 / 256.0f, -4 / 256.0f, -6 / 256.0f, -4 / 256.0f, -1 / 256.0f} }; kernel.setMatrix(k); // MyBoxLog.debug(DoubleMatrixTools.print(FloatTools.toDouble(k), 0, 8)); return kernel; } // https://en.wikipedia.org/wiki/Image_embossing public static ConvolutionKernel makeEmbossTop3() { ConvolutionKernel kernel = new ConvolutionKernel(); kernel.setName(message("Emboss") + " " + message("Top") + " 3*3"); kernel.setCreateTime(DateTools.datetimeToString(new Date())); kernel.setModifyTime(DateTools.datetimeToString(new Date())); kernel.setWidth(3); kernel.setHeight(3); kernel.setType(Convolution_Type.EMBOSS); kernel.setGrey(); kernel.setDescription(""); float[][] k = { {0, 1, 0}, {0, 0, 0}, {0, -1, 0} }; kernel.setMatrix(k); return kernel; } public static ConvolutionKernel makeEmbossBottom3() { ConvolutionKernel kernel = new ConvolutionKernel(); kernel.setName(message("Emboss") + " " + message("Bottom") + " 3*3"); kernel.setCreateTime(DateTools.datetimeToString(new Date())); kernel.setModifyTime(DateTools.datetimeToString(new Date())); kernel.setWidth(3); kernel.setHeight(3); kernel.setType(Convolution_Type.EMBOSS); kernel.setGrey(); kernel.setDescription(""); float[][] k = { {0, -1, 0}, {0, 0, 0}, {0, 1, 0} }; kernel.setMatrix(k); return kernel; } public static ConvolutionKernel makeEmbossLeft3() { ConvolutionKernel kernel = new ConvolutionKernel(); kernel.setName(message("Emboss") + " " + message("Left") + " 3*3"); kernel.setCreateTime(DateTools.datetimeToString(new Date())); kernel.setModifyTime(DateTools.datetimeToString(new Date())); kernel.setWidth(3); kernel.setHeight(3); kernel.setType(Convolution_Type.EMBOSS); kernel.setGrey(); kernel.setDescription(""); float[][] k = { {0, 0, 0}, {1, 0, -1}, {0, 0, 0} }; kernel.setMatrix(k); return kernel; } public static ConvolutionKernel makeEmbossRight3() { ConvolutionKernel kernel = new ConvolutionKernel(); kernel.setName(message("Emboss") + " " + message("Right") + " 3*3"); kernel.setCreateTime(DateTools.datetimeToString(new Date())); kernel.setModifyTime(DateTools.datetimeToString(new Date())); kernel.setWidth(3); kernel.setHeight(3); kernel.setType(Convolution_Type.EMBOSS); kernel.setGrey(); kernel.setDescription(""); float[][] k = { {0, 0, 0}, {-1, 0, 1}, {0, 0, 0} }; kernel.setMatrix(k); return kernel; } public static ConvolutionKernel makeEmbossLeftTop3() { ConvolutionKernel kernel = new ConvolutionKernel(); kernel.setName(message("Emboss") + " " + message("LeftTop") + " 3*3"); kernel.setCreateTime(DateTools.datetimeToString(new Date())); kernel.setModifyTime(DateTools.datetimeToString(new Date())); kernel.setWidth(3); kernel.setHeight(3); kernel.setType(Convolution_Type.EMBOSS); kernel.setGrey(); kernel.setDescription(""); float[][] k = { {1, 0, 0}, {0, 0, 0}, {0, 0, -1} }; kernel.setMatrix(k); return kernel; } public static ConvolutionKernel makeEmbossRightBottom3() { ConvolutionKernel kernel = new ConvolutionKernel(); kernel.setName(message("Emboss") + " " + message("RightBottom") + " 3*3"); kernel.setCreateTime(DateTools.datetimeToString(new Date())); kernel.setModifyTime(DateTools.datetimeToString(new Date())); kernel.setWidth(3); kernel.setHeight(3); kernel.setType(Convolution_Type.EMBOSS); kernel.setGrey(); kernel.setDescription(""); float[][] k = { {-1, 0, 0}, {0, 0, 0}, {0, 0, 1} }; kernel.setMatrix(k); return kernel; } public static ConvolutionKernel makeEmbossLeftBottom3() { ConvolutionKernel kernel = new ConvolutionKernel(); kernel.setName(message("Emboss") + " " + message("LeftBottom") + " 3*3"); kernel.setCreateTime(DateTools.datetimeToString(new Date())); kernel.setModifyTime(DateTools.datetimeToString(new Date())); kernel.setWidth(3); kernel.setHeight(3); kernel.setType(Convolution_Type.EMBOSS); kernel.setGrey(); kernel.setDescription(""); float[][] k = { {0, 0, -1}, {0, 0, 0}, {1, 0, 0} }; kernel.setMatrix(k); return kernel; } public static ConvolutionKernel makeEmbossRightTop3() { ConvolutionKernel kernel = new ConvolutionKernel(); kernel.setName(message("Emboss") + " " + message("RightTop") + " 3*3"); kernel.setCreateTime(DateTools.datetimeToString(new Date())); kernel.setModifyTime(DateTools.datetimeToString(new Date())); kernel.setWidth(3); kernel.setHeight(3); kernel.setType(Convolution_Type.EMBOSS); kernel.setGrey(); kernel.setDescription(""); float[][] k = { {0, 0, 1}, {0, 0, 0}, {-1, 0, 0} }; kernel.setMatrix(k); return kernel; } public static float[] embossTopKernel = { 0, 1, 0, 0, 0, 0, 0, -1, 0 }; public static float[] embossBottomKernel = { 0, -1, 0, 0, 0, 0, 0, 1, 0 }; public static float[] embossLeftKernel = { 0, 0, 0, 1, 0, -1, 0, 0, 0 }; public static float[] embossRightKernel = { 0, 0, 0, -1, 0, 1, 0, 0, 0 }; public static float[] embossLeftTopKernel = { 1, 0, 0, 0, 0, 0, 0, 0, -1 }; public static float[] embossRightBottomKernel = { -1, 0, 0, 0, 0, 0, 0, 0, 1 }; public static float[] embossLeftBottomKernel = { 0, 0, -1, 0, 0, 0, 1, 0, 0 }; public static float[] embossRightTopKernel = { 0, 0, 1, 0, 0, 0, -1, 0, 0 }; public static float[] embossTopKernel5 = { 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0 }; public static float[] embossBottomKernel5 = { 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0 }; public static float[] embossLeftKernel5 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public static float[] embossRightKernel5 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public static float[] embossLeftTopKernel5 = { 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, -1 }; public static float[] embossRightBottomKernel5 = { -1, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1 }; public static float[] embossLeftBottomKernel5 = { 0, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0 }; public static float[] embossRightTopKernel5 = { 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, 0 }; public static float[][] makeEmbossMatrix(Direction direction, int size) { float[][] m = null; if (direction == BufferedImageTools.Direction.Top) { if (size == 3) { m = FloatMatrixTools.array2Matrix(embossTopKernel, size); } else if (size == 5) { m = FloatMatrixTools.array2Matrix(embossTopKernel5, size); } } else if (direction == BufferedImageTools.Direction.Bottom) { if (size == 3) { m = FloatMatrixTools.array2Matrix(embossBottomKernel, size); } else if (size == 5) { m = FloatMatrixTools.array2Matrix(embossBottomKernel5, size); } } else if (direction == BufferedImageTools.Direction.Left) { if (size == 3) { m = FloatMatrixTools.array2Matrix(embossLeftKernel, size); } else if (size == 5) { m = FloatMatrixTools.array2Matrix(embossLeftKernel5, size); } } else if (direction == BufferedImageTools.Direction.Right) { if (size == 3) { m = FloatMatrixTools.array2Matrix(embossRightKernel, size); } else if (size == 5) { m = FloatMatrixTools.array2Matrix(embossRightKernel5, size); } } else if (direction == BufferedImageTools.Direction.LeftTop) { if (size == 3) { m = FloatMatrixTools.array2Matrix(embossLeftTopKernel, size); } else if (size == 5) { m = FloatMatrixTools.array2Matrix(embossLeftTopKernel5, size); } } else if (direction == BufferedImageTools.Direction.RightBottom) { if (size == 3) { m = FloatMatrixTools.array2Matrix(embossRightBottomKernel, size); } else if (size == 5) { m = FloatMatrixTools.array2Matrix(embossRightBottomKernel5, size); } } else if (direction == BufferedImageTools.Direction.LeftBottom) { if (size == 3) { m = FloatMatrixTools.array2Matrix(embossLeftBottomKernel, size); } else if (size == 5) { m = FloatMatrixTools.array2Matrix(embossLeftBottomKernel5, size); } } else if (direction == BufferedImageTools.Direction.RightTop) { if (size == 3) { m = FloatMatrixTools.array2Matrix(embossRightTopKernel, size); } else if (size == 5) { m = FloatMatrixTools.array2Matrix(embossRightTopKernel5, size); } } return m; } public static ConvolutionKernel makeEmbossKernel(Direction direction, int size, int color) { ConvolutionKernel kernel = new ConvolutionKernel(); kernel.setName(message("Emboss") + " " + message("Direction") + ": " + message("direction") + " " + message("Size") + ":" + size); kernel.setCreateTime(DateTools.datetimeToString(new Date())); kernel.setModifyTime(DateTools.datetimeToString(new Date())); kernel.setWidth(size); kernel.setHeight(size); kernel.setType(Convolution_Type.EMBOSS); kernel.setColor(color); kernel.setDescription(""); float[][] k = makeEmbossMatrix(direction, size); kernel.setMatrix(k); return kernel; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getModifyTime() { return modifyTime; } public void setModifyTime(String modifyTime) { this.modifyTime = modifyTime; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getEdge() { return edge; } public void setEdge(int edge) { this.edge = edge; } public int getColor() { return color; } public ConvolutionKernel setColor(int color) { this.color = color; return this; } public float[][] getMatrix() { return matrix; } public void setMatrix(float[][] matrix) { this.matrix = matrix; } public boolean isInvert() { return invert; } public void setInvert(boolean invert) { this.invert = invert; } }
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/data/WebHistory.java
alpha/MyBox/src/main/java/mara/mybox/db/data/WebHistory.java
/* * Apache License Version 2.0 */ package mara.mybox.db.data; import java.util.Date; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2021-5-4 * @License Apache License Version 2.0 */ public class WebHistory extends BaseData { private long whid; private String address, title, icon; private Date visitTime; private void init() { whid = -1; } public WebHistory() { 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 WebHistory create() { return new WebHistory(); } public static boolean setValue(WebHistory data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "whid": data.setWhid(value == null ? -1 : (long) value); return true; case "title": data.setTitle(value == null ? null : (String) value); return true; case "address": data.setAddress(value == null ? null : (String) value); return true; case "icon": data.setIcon(value == null ? null : (String) value); return true; case "visit_time": data.setVisitTime(value == null ? null : (Date) value); return true; } } catch (Exception e) { MyBoxLog.debug(e); } return false; } public static Object getValue(WebHistory data, String column) { if (data == null || column == null) { return null; } switch (column) { case "whid": return data.getWhid(); case "title": return data.getTitle(); case "address": return data.getAddress(); case "icon": return data.getIcon(); case "visit_time": return data.getVisitTime(); } return null; } public static boolean valid(WebHistory data) { return data != null && data.getVisitTime() != null && data.getAddress() != null && !data.getAddress().isBlank(); } /* get/set */ public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public long getWhid() { return whid; } public void setWhid(long whid) { this.whid = whid; } public Date getVisitTime() { return visitTime; } public void setVisitTime(Date visitTime) { this.visitTime = visitTime; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } }
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/data/ImageEditHistory.java
alpha/MyBox/src/main/java/mara/mybox/db/data/ImageEditHistory.java
package mara.mybox.db.data; import java.awt.image.BufferedImage; import java.io.File; import java.util.Date; import javafx.embed.swing.SwingFXUtils; import javafx.scene.image.Image; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.image.file.ImageFileReaders; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2018-10-20 11:31:20 * @Version 1.0 * @Description * @License Apache License Version 2.0 */ public class ImageEditHistory extends BaseData { public static final int Default_Max_Histories = 20; protected long iehid; protected File imageFile, historyFile, thumbnailFile; protected String updateType, objectType, opType, scopeType, scopeName; protected Date operationTime; protected Image thumbnail; private void init() { iehid = -1; operationTime = new Date(); } public ImageEditHistory() { 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); } @Override public Object clone() throws CloneNotSupportedException { try { ImageEditHistory his = (ImageEditHistory) super.clone(); his.setThumbnail(thumbnail); his.setOperationTime(new Date()); his.setIehid(-1); return his; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public String getType() { if (opType != null && !opType.isEmpty()) { return message(opType); } else if (objectType != null && !objectType.isEmpty()) { return message(objectType); } else if (updateType != null && !updateType.isEmpty()) { return message(updateType); } else if (scopeType != null && !scopeType.isEmpty()) { return message(scopeType); } else if (scopeName != null && !scopeName.isEmpty()) { return message(scopeName); } return null; } public String getDesc() { String s; if (objectType != null && !objectType.isEmpty()) { s = objectType + " "; } else if (opType != null && !opType.isEmpty()) { s = opType + " "; } else if (updateType != null && !updateType.isEmpty()) { s = updateType + " "; } else { s = " "; } if (scopeType != null && !scopeType.isEmpty()) { s += message(scopeType); } if (scopeName != null && !scopeName.isEmpty()) { s += " " + message(scopeName); } return s; } public long getSize() { return historyFile != null && historyFile.exists() ? historyFile.length() : 0; } public String getFileName() { return historyFile != null && historyFile.exists() ? historyFile.getName() : null; } public Image historyImage(FxTask task) { try { if (!historyFile.exists()) { return null; } BufferedImage bufferedImage = ImageFileReaders.readImage(task, historyFile); if (bufferedImage != null) { return SwingFXUtils.toFXImage(bufferedImage, null); } return null; } catch (Exception e) { return null; } } /* static methods */ public static ImageEditHistory create() { return new ImageEditHistory(); } public static boolean valid(ImageEditHistory data) { return data != null && data.getImageFile() != null && data.getHistoryFile() != null && data.getImageFile().exists() && data.getHistoryFile().exists() && data.getOperationTime() != null; } public static Object getValue(ImageEditHistory data, String column) { if (data == null || column == null) { return null; } switch (column) { case "iehid": return data.getIehid(); case "image_location": File imageFile = data.getImageFile(); return imageFile == null ? null : imageFile.getAbsolutePath(); case "history_location": File hisFile = data.getHistoryFile(); return hisFile == null ? null : hisFile.getAbsolutePath(); case "thumbnail_file": File thumbFile = data.getThumbnailFile(); return thumbFile == null ? null : thumbFile.getAbsolutePath(); case "operation_time": return data.getOperationTime(); case "update_type": return data.getUpdateType(); case "object_type": return data.getObjectType(); case "op_type": return data.getOpType(); case "scope_type": return data.getScopeType(); case "scope_name": return data.getScopeName(); } return null; } public static boolean setValue(ImageEditHistory data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "iehid": data.setIehid(value == null ? -1 : (long) value); return true; case "image_location": data.setImageFile(null); if (value != null) { File f = new File((String) value); if (f.exists()) { data.setImageFile(f); } } return true; case "history_location": data.setHistoryFile(null); if (value != null) { File f = new File((String) value); if (f.exists()) { data.setHistoryFile(f); } } return true; case "thumbnail_file": data.setThumbnailFile(null); if (value != null) { File f = new File((String) value); if (f.exists()) { data.setThumbnailFile(f); } } return true; case "operation_time": data.setOperationTime(value == null ? null : (Date) value); return true; case "update_type": data.setUpdateType(value == null ? null : (String) value); return true; case "object_type": data.setObjectType(value == null ? null : (String) value); return true; case "op_type": data.setOpType(value == null ? null : (String) value); return true; case "scope_type": data.setScopeType(value == null ? null : (String) value); return true; case "scope_name": data.setScopeName(value == null ? null : (String) value); return true; } } catch (Exception e) { MyBoxLog.debug(e); } return false; } /* get/set */ public long getIehid() { return iehid; } public ImageEditHistory setIehid(long iehid) { this.iehid = iehid; return this; } public File getImageFile() { return imageFile; } public ImageEditHistory setImageFile(File imageFile) { this.imageFile = imageFile; return this; } public File getHistoryFile() { return historyFile; } public ImageEditHistory setHistoryFile(File historyFile) { this.historyFile = historyFile; return this; } public File getThumbnailFile() { return thumbnailFile; } public ImageEditHistory setThumbnailFile(File thumbnailFile) { this.thumbnailFile = thumbnailFile; return this; } public Image getThumbnail() { return thumbnail; } public ImageEditHistory setThumbnail(Image thumbnail) { this.thumbnail = thumbnail; return this; } public String getUpdateType() { return updateType; } public ImageEditHistory setUpdateType(String updateType) { this.updateType = updateType; return this; } public Date getOperationTime() { return operationTime; } public ImageEditHistory setOperationTime(Date operationTime) { this.operationTime = operationTime; return this; } public String getObjectType() { return objectType; } public ImageEditHistory setObjectType(String objectType) { this.objectType = objectType; return this; } public String getOpType() { return opType; } public ImageEditHistory setOpType(String opType) { this.opType = opType; return this; } public String getScopeType() { return scopeType; } public ImageEditHistory setScopeType(String scopeType) { this.scopeType = scopeType; return this; } public String getScopeName() { return scopeName; } public ImageEditHistory setScopeName(String scopeName) { this.scopeName = scopeName; 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/data/DataNodeTag.java
alpha/MyBox/src/main/java/mara/mybox/db/data/DataNodeTag.java
package mara.mybox.db.data; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2022-3-11 * @License Apache License Version 2.0 */ public class DataNodeTag extends BaseData { protected long tnodeid, ttagid; protected DataNode node; protected DataTag tag; private void init() { tnodeid = ttagid = -1; node = null; tag = null; } public DataNodeTag() { init(); } public DataNodeTag(long tnodeid, long tagid) { init(); this.tnodeid = tnodeid; this.ttagid = tagid; } public DataNodeTag(DataNode node, DataTag tag) { init(); this.node = node; this.tag = tag; this.tnodeid = node == null ? -1 : node.getNodeid(); this.ttagid = tag == null ? -1 : tag.getTagid(); } @Override public boolean setValue(String column, Object value) { return setValue(this, column, value); } @Override public Object getValue(String column) { return getValue(this, column); } @Override public boolean valid() { return valid(this); } /* Static methods */ public static DataNodeTag create() { return new DataNodeTag(); } public static boolean setValue(DataNodeTag data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "tnodeid": data.setTnodeid(value == null ? -1 : (long) value); return true; case "ttagid": data.setTtagid(value == null ? -1 : (long) value); return true; } } catch (Exception e) { MyBoxLog.debug(e); } return false; } public static Object getValue(DataNodeTag data, String column) { if (data == null || column == null) { return null; } switch (column) { case "tnodeid": return data.getTnodeid(); case "ttagid": return data.getTtagid(); } return null; } public static boolean valid(DataNodeTag data) { return data != null && data.getTnodeid() > 0 && data.getTtagid() > 0; } /* get/set */ public long getTnodeid() { return tnodeid; } public DataNodeTag setTnodeid(long tnodeid) { this.tnodeid = tnodeid; return this; } public long getTtagid() { return ttagid; } public DataNodeTag setTtagid(long ttagid) { this.ttagid = ttagid; return this; } public DataNode getNode() { return node; } public DataNodeTag setNode(DataNode node) { this.node = node; return this; } public DataTag getTag() { return tag; } public DataNodeTag setTag(DataTag tag) { this.tag = tag; 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/data/StringValues.java
alpha/MyBox/src/main/java/mara/mybox/db/data/StringValues.java
package mara.mybox.db.data; import java.util.Date; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2020-10-4 * @License Apache License Version 2.0 */ public class StringValues extends BaseData { protected String key, value; protected Date time; public StringValues() { init(); } private void init() { key = null; value = null; time = new Date(); } public StringValues(String key, String value, Date time) { this.key = key; this.value = value; this.time = time; } @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 StringValues create() { return new StringValues(); } public static boolean setValue(StringValues data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "key_name": data.setKey(value == null ? null : (String) value); return true; case "string_value": data.setValue(value == null ? null : (String) value); return true; case "create_time": data.setTime(value == null ? null : (Date) value); return true; } } catch (Exception e) { MyBoxLog.debug(e); } return false; } public static Object getValue(StringValues data, String column) { if (data == null || column == null) { return null; } switch (column) { case "key_name": return data.getKey(); case "string_value": return data.getValue(); case "create_time": return data.getTime(); } return null; } public static boolean valid(StringValues data) { return data != null && data.getKey() != null && data.getValue() != null; } /* get/set */ public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } }
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/data/BaseData.java
alpha/MyBox/src/main/java/mara/mybox/db/data/BaseData.java
package mara.mybox.db.data; /** * @Author Mara * @CreateDate 2020-7-19 * @License Apache License Version 2.0 */ public abstract class BaseData implements Cloneable { protected long baseID = -1; protected int rowIndex = -1; /* abstract */ public abstract boolean valid(); public abstract boolean setValue(String column, Object value); public abstract Object getValue(String column); /* others */ @Override public Object clone() throws CloneNotSupportedException { try { BaseData newData = (BaseData) super.clone(); return newData; } catch (Exception e) { return null; } } /* get/set */ public long getBaseID() { return baseID; } public void setBaseID(long baseID) { this.baseID = baseID; } public int getRowIndex() { return rowIndex; } public void setRowIndex(int rowIndex) { this.rowIndex = rowIndex; } }
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/data/ColorDataTools.java
alpha/MyBox/src/main/java/mara/mybox/db/data/ColorDataTools.java
package mara.mybox.db.data; import java.io.File; import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import mara.mybox.db.DerbyBase; import mara.mybox.db.table.TableColor; import mara.mybox.db.table.TableColorPalette; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.tools.CsvTools; import mara.mybox.tools.FileTools; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVPrinter; import org.apache.commons.csv.CSVRecord; /** * @Author Mara * @CreateDate 2020-12-13 * @License Apache License Version 2.0 */ public class ColorDataTools { public static void printHeader(CSVPrinter printer, boolean orderNumber) { try { if (printer == null) { return; } List<String> names = new ArrayList<>(); names.addAll(Arrays.asList("name", "rgba", "rgb", "SRGB", "HSB", "rybAngle", "AdobeRGB", "AppleRGB", "EciRGB", "SRGBLinear", "AdobeRGBLinear", "AppleRGBLinear", "CalculatedCMYK", "EciCMYK", "AdobeCMYK", "XYZ", "CieLab", "Lchab", "CieLuv", "Lchuv", "invert", "complementray", "value")); if (orderNumber) { names.add("PaletteIndex"); } printer.printRecord(names); } catch (Exception e) { MyBoxLog.debug(e); } } public static void exportCSV(TableColor tableColor, File file) { try (Connection conn = DerbyBase.getConnection(); CSVPrinter printer = CsvTools.csvPrinter(file)) { conn.setReadOnly(true); printHeader(printer, false); String sql = " SELECT * FROM Color ORDER BY color_value"; try (PreparedStatement statement = conn.prepareStatement(sql); ResultSet results = statement.executeQuery()) { List<String> row = new ArrayList<>(); while (results.next()) { ColorData data = tableColor.readData(results); printRow(printer, row, data, false); } } } catch (Exception e) { MyBoxLog.debug(e); } } public static void exportCSV(TableColorPalette tableColorPalette, File file, ColorPaletteName palette) { try (Connection conn = DerbyBase.getConnection(); CSVPrinter printer = CsvTools.csvPrinter(file)) { conn.setReadOnly(true); printHeader(printer, true); String sql = "SELECT * FROM Color_Palette_View WHERE paletteid=" + palette.getCpnid() + " ORDER BY order_number"; try (PreparedStatement statement = conn.prepareStatement(sql); ResultSet results = statement.executeQuery()) { List<String> row = new ArrayList<>(); while (results.next()) { ColorPalette data = tableColorPalette.readData(results); ColorData color = data.getData(); color.setColorName(data.getName()); color.setOrderNumner(data.getOrderNumber()); color.setPaletteid(data.getPaletteid()); color.setCpid(data.getCpid()); printRow(printer, row, color, true); } } catch (Exception e) { MyBoxLog.error(e, sql); } } catch (Exception e) { MyBoxLog.debug(e); } } public static void exportCSV(List<ColorData> dataList, File file, boolean orderNumber) { try (final CSVPrinter printer = CsvTools.csvPrinter(file)) { printHeader(printer, orderNumber); List<String> row = new ArrayList<>(); for (ColorData data : dataList) { printRow(printer, row, data, orderNumber); } } catch (Exception e) { MyBoxLog.debug(e); } } public static void printRow(CSVPrinter printer, List<String> row, ColorData data, boolean orderNumber) { try { if (printer == null || row == null || data == null) { return; } if (data.needConvert()) { data.convert(); } row.clear(); row.add(data.getColorName()); row.add(data.getRgba()); row.add(data.getRgb()); row.add(data.getSrgb()); row.add(data.getHsb()); row.add(data.getRybAngle()); row.add(data.getAdobeRGB()); row.add(data.getAppleRGB()); row.add(data.getEciRGB()); row.add(data.getSRGBLinear()); row.add(data.getAdobeRGBLinear()); row.add(data.getAppleRGBLinear()); row.add(data.getCalculatedCMYK()); row.add(data.getEciCMYK()); row.add(data.getAdobeCMYK()); row.add(data.getXyz()); row.add(data.getCieLab()); row.add(data.getLchab()); row.add(data.getCieLuv()); row.add(data.getLchuv()); row.add(data.getInvertRGB()); row.add(data.getComplementaryRGB()); row.add(data.getColorValue() + ""); if (orderNumber) { row.add(data.getOrderNumner() + ""); } printer.printRecord(row); } catch (Exception e) { MyBoxLog.debug(e); } } public static List<ColorData> readCSV(FxTask task, File file, boolean reOrder) { List<ColorData> data = new ArrayList(); File validFile = FileTools.removeBOM(task, file); if (validFile == null || (task != null && !task.isWorking())) { return null; } try (CSVParser parser = CSVParser.parse(validFile, StandardCharsets.UTF_8, CsvTools.csvFormat())) { List<String> names = parser.getHeaderNames(); if (names == null || (!names.contains("rgba") && !names.contains("rgb"))) { return null; } int index = 0; for (CSVRecord record : parser) { if (task != null && !task.isWorking()) { parser.close(); return null; } try { ColorData item = new ColorData(); if (names.contains("rgba")) { item.setWeb(record.get("rgba")); } if (names.contains("rgb")) { item.setRgb(record.get("rgb")); } if (names.contains("name")) { item.setColorName(record.get("name")); } try { item.setColorValue(Integer.parseInt(record.get("value"))); item.setSrgb(record.get("SRGB")); item.setHsb(record.get("HSB")); item.setAdobeRGB(record.get("AdobeRGB")); item.setAppleRGB(record.get("AppleRGB")); item.setEciRGB(record.get("EciRGB")); item.setSRGBLinear(record.get("SRGBLinear")); item.setAdobeRGBLinear(record.get("AdobeRGBLinear")); item.setAppleRGBLinear(record.get("AppleRGBLinear")); item.setCalculatedCMYK(record.get("CalculatedCMYK")); item.setEciCMYK(record.get("EciCMYK")); item.setAdobeCMYK(record.get("AdobeCMYK")); item.setXyz(record.get("XYZ")); item.setCieLab(record.get("CieLab")); item.setLchab(record.get("Lchab")); item.setCieLuv(record.get("CieLuv")); item.setLchuv(record.get("Lchuv")); } catch (Exception e) { item.calculate(); } index++; if (!reOrder && names.contains("PaletteIndex")) { item.setOrderNumner(Float.parseFloat(record.get("PaletteIndex"))); } else { item.setOrderNumner(index); } data.add(item); } catch (Exception e) { MyBoxLog.debug(e); } } } catch (Exception e) { MyBoxLog.debug(e); } return data; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/db/data/StringValue.java
alpha/MyBox/src/main/java/mara/mybox/db/data/StringValue.java
package mara.mybox.db.data; import java.util.Date; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2020-10-4 * @License Apache License Version 2.0 */ public class StringValue extends BaseData { protected String key, value; protected Date time; public StringValue() { init(); } private void init() { key = null; value = null; time = new Date(); } public StringValue(String key, String value, Date time) { this.key = key; this.value = value; this.time = time; } @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 StringValue create() { return new StringValue(); } public static boolean setValue(StringValue data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "key_name": data.setKey(value == null ? null : (String) value); return true; case "string_value": data.setValue(value == null ? null : (String) value); return true; case "create_time": data.setTime(value == null ? null : (Date) value); return true; } } catch (Exception e) { MyBoxLog.debug(e); } return false; } public static Object getValue(StringValue data, String column) { if (data == null || column == null) { return null; } switch (column) { case "key_name": return data.getKey(); case "string_value": return data.getValue(); case "create_time": return data.getTime(); } return null; } public static boolean valid(StringValue data) { return data != null && data.getKey() != null && data.getValue() != null; } /* get/set */ public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } }
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/data/Data2DRow.java
alpha/MyBox/src/main/java/mara/mybox/db/data/Data2DRow.java
package mara.mybox.db.data; import java.util.HashMap; import java.util.Map; /** * @Author Mara * @CreateDate 2021-10-17 * @License Apache License Version 2.0 */ public class Data2DRow extends BaseData { protected Map<String, Object> values; @Override public boolean valid() { return true; } @Override public boolean setValue(String column, Object value) { try { if (values == null) { values = new HashMap<>(); } else { if (value == null) { values.remove(column); return true; } } values.put(column, value); return true; } catch (Exception e) { // MyBoxLog.debug(e); return false; } } @Override public Object getValue(String column) { try { if (values == null) { return null; } return values.get(column); } catch (Exception e) { // MyBoxLog.debug(e); return null; } } public boolean isEmpty() { try { return values == null || values.keySet().isEmpty(); } catch (Exception e) { // MyBoxLog.debug(e); return true; } } /* get/set */ public Map<String, Object> getValues() { return values; } public void setValues(Map<String, Object> values) { this.values = values; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/db/data/ColorData.java
alpha/MyBox/src/main/java/mara/mybox/db/data/ColorData.java
package mara.mybox.db.data; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javafx.scene.paint.Color; import mara.mybox.color.AdobeRGB; import mara.mybox.color.AppleRGB; import mara.mybox.color.CIEColorSpace; import mara.mybox.color.RGBColorSpace; import mara.mybox.color.SRGB; import mara.mybox.data.StringTable; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.image.FxColorTools; import mara.mybox.fxml.style.HtmlStyles; import mara.mybox.image.data.ImageColorSpace; import mara.mybox.image.tools.ColorConvertTools; import mara.mybox.tools.DoubleTools; import mara.mybox.tools.FloatTools; import mara.mybox.tools.HtmlWriteTools; import mara.mybox.tools.StringTools; import mara.mybox.value.AppValues; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2020-1-7 * @License Apache License Version 2.0 */ public class ColorData extends BaseData { protected int colorValue; protected javafx.scene.paint.Color color, invertColor, complementaryColor; protected String rgba, rgb, colorName, colorDisplay, colorSimpleDisplay, vSeparator; protected String srgb, hsb, hue, rybAngle, saturation, brightness, opacity, invertRGB, complementaryRGB, adobeRGB, appleRGB, eciRGB, SRGBLinear, adobeRGBLinear, appleRGBLinear, calculatedCMYK, eciCMYK, adobeCMYK, xyz, cieLab, lchab, cieLuv, lchuv; protected float[] adobeRGBValues, appleRGBValues, eciRGBValues, eciCmykValues, adobeCmykValues; protected double[] cmyk, xyzD50, cieLabValues, lchabValues, cieLuvValues, lchuvValues; protected boolean isSettingValues; protected long paletteid, cpid; protected float orderNumner, ryb; // rgba is saved as upper-case in db private void init() { colorValue = AppValues.InvalidInteger; orderNumner = Float.MAX_VALUE; ryb = -1; paletteid = -1; cpid = -1; vSeparator = " "; } @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 ColorData() { init(); } public ColorData(Color color) { init(); try { this.color = color; rgba = FxColorTools.color2rgba(color); rgb = FxColorTools.color2rgb(color); colorValue = FxColorTools.color2Value(color); } catch (Exception e) { } } public ColorData(int value) { init(); setValue(value); } public ColorData(int value, String name) { init(); colorName = name; setValue(value); } final public void setValue(int value) { colorValue = value; try { color = FxColorTools.value2color(value); rgba = FxColorTools.color2rgba(color); // rgba is saved as upper-case in db rgb = FxColorTools.color2rgb(color); } catch (Exception e) { MyBoxLog.debug(e); } } public ColorData(String web) { init(); setWeb(web); } public ColorData(String web, String name) { init(); colorName = name; setWeb(web); } // https://openjfx.io/javadoc/14/javafx.graphics/javafx/scene/paint/Color.html#web(java.lang.String) final public void setWeb(String web) { try { String value = web.trim(); color = Color.web(value); rgba = FxColorTools.color2rgba(color); rgb = FxColorTools.color2rgb(color); colorValue = FxColorTools.color2Value(color); if (colorName == null && !value.startsWith("#") && !value.startsWith("0x") && !value.startsWith("0X") && !value.startsWith("rgb") && !value.startsWith("hsl")) { colorName = value; } } catch (Exception e) { // MyBoxLog.debug(e); } } public boolean isValid() { return srgb != null; } public boolean needCalculate() { return color == null || srgb == null; } public boolean needConvert() { return ryb < 0 || hsb == null || invertRGB == null; } public boolean calculateBase() { if (colorValue != AppValues.InvalidInteger) { color = FxColorTools.value2color(colorValue); rgba = FxColorTools.color2rgba(color); rgb = FxColorTools.color2rgb(color); } else if (color != null) { colorValue = FxColorTools.color2Value(color); rgba = FxColorTools.color2rgba(color); rgb = FxColorTools.color2rgb(color); } else if (rgba != null) { color = Color.web(rgba); rgb = FxColorTools.color2rgb(color); colorValue = FxColorTools.color2Value(color); } else if (rgb != null) { color = Color.web(rgb); rgba = FxColorTools.color2rgba(color); colorValue = FxColorTools.color2Value(color); } else { return false; } return true; } public ColorData calculate() { if (!needCalculate()) { return this; } if (colorName == null) { colorName = ""; } if (!calculateBase()) { return this; } srgb = Math.round(color.getRed() * 255) + vSeparator + Math.round(color.getGreen() * 255) + vSeparator + Math.round(color.getBlue() * 255) + vSeparator + Math.round(color.getOpacity() * 100) + "%"; adobeRGBValues = SRGB.srgb2profile(ImageColorSpace.adobeRGBProfile(), color); adobeRGB = Math.round(adobeRGBValues[0] * 255) + vSeparator + Math.round(adobeRGBValues[1] * 255) + vSeparator + Math.round(adobeRGBValues[2] * 255); appleRGBValues = SRGB.srgb2profile(ImageColorSpace.appleRGBProfile(), color); appleRGB = Math.round(appleRGBValues[0] * 255) + vSeparator + Math.round(appleRGBValues[1] * 255) + vSeparator + Math.round(appleRGBValues[2] * 255); eciRGBValues = SRGB.srgb2profile(ImageColorSpace.eciRGBProfile(), color); eciRGB = Math.round(eciRGBValues[0] * 255) + vSeparator + Math.round(eciRGBValues[1] * 255) + vSeparator + Math.round(eciRGBValues[2] * 255); SRGBLinear = Math.round(RGBColorSpace.linearSRGB(color.getRed()) * 255) + vSeparator + Math.round(RGBColorSpace.linearSRGB(color.getGreen()) * 255) + vSeparator + Math.round(RGBColorSpace.linearSRGB(color.getBlue()) * 255); adobeRGBLinear = Math.round(AdobeRGB.linearAdobeRGB(adobeRGBValues[0]) * 255) + vSeparator + Math.round(AdobeRGB.linearAdobeRGB(adobeRGBValues[1]) * 255) + vSeparator + Math.round(AdobeRGB.linearAdobeRGB(adobeRGBValues[2]) * 255); appleRGBLinear = Math.round(AppleRGB.linearAppleRGB(appleRGBValues[0]) * 255) + vSeparator + Math.round(AppleRGB.linearAppleRGB(appleRGBValues[1]) * 255) + vSeparator + Math.round(AppleRGB.linearAppleRGB(appleRGBValues[2]) * 255); cmyk = SRGB.rgb2cmyk(color); calculatedCMYK = Math.round(cmyk[0] * 100) + vSeparator + Math.round(cmyk[1] * 100) + vSeparator + Math.round(cmyk[2] * 100) + vSeparator + Math.round(cmyk[3] * 100); eciCmykValues = SRGB.srgb2profile(ImageColorSpace.eciCmykProfile(), color); eciCMYK = Math.round(eciCmykValues[0] * 100) + vSeparator + Math.round(eciCmykValues[1] * 100) + vSeparator + Math.round(eciCmykValues[2] * 100) + vSeparator + Math.round(eciCmykValues[3] * 100); adobeCmykValues = SRGB.srgb2profile(ImageColorSpace.adobeCmykProfile(), color); adobeCMYK = Math.round(adobeCmykValues[0] * 100) + vSeparator + Math.round(adobeCmykValues[1] * 100) + vSeparator + Math.round(adobeCmykValues[2] * 100) + vSeparator + Math.round(adobeCmykValues[3] * 100); xyzD50 = SRGB.SRGBtoXYZd50(ColorConvertTools.converColor(color)); xyz = DoubleTools.scale(xyzD50[0], 6) + vSeparator + DoubleTools.scale(xyzD50[1], 6) + vSeparator + DoubleTools.scale(xyzD50[2], 6); cieLabValues = CIEColorSpace.XYZd50toCIELab(xyzD50[0], xyzD50[1], xyzD50[2]); cieLab = DoubleTools.scale(cieLabValues[0], 2) + vSeparator + DoubleTools.scale(cieLabValues[1], 2) + vSeparator + DoubleTools.scale(cieLabValues[2], 2); lchabValues = CIEColorSpace.LabtoLCHab(cieLabValues); lchab = DoubleTools.scale(lchabValues[0], 2) + vSeparator + DoubleTools.scale(lchabValues[1], 2) + vSeparator + DoubleTools.scale(lchabValues[2], 2); cieLuvValues = CIEColorSpace.XYZd50toCIELuv(xyzD50[0], xyzD50[1], xyzD50[2]); cieLuv = DoubleTools.scale(cieLuvValues[0], 2) + vSeparator + DoubleTools.scale(cieLuvValues[1], 2) + vSeparator + DoubleTools.scale(cieLuvValues[2], 2); lchuvValues = CIEColorSpace.LuvtoLCHuv(cieLuvValues); lchuv = DoubleTools.scale(lchuvValues[0], 2) + vSeparator + DoubleTools.scale(lchuvValues[1], 2) + vSeparator + DoubleTools.scale(lchuvValues[2], 2); return this; } public ColorData convert() { if (!needConvert()) { return this; } if (needCalculate()) { calculate(); } if (color == null) { return this; } long h = Math.round(color.getHue()); long s = Math.round(color.getSaturation() * 100); long b = Math.round(color.getBrightness() * 100); long a = Math.round(color.getOpacity() * 100); hsb = h + vSeparator + s + "%" + vSeparator + b + "%" + vSeparator + a + "%"; hue = StringTools.fillLeftZero(h, 3); saturation = StringTools.fillLeftZero(s, 3); brightness = StringTools.fillLeftZero(b, 3); opacity = StringTools.fillLeftZero(a, 3); ryb = ColorConvertTools.hue2ryb(h); rybAngle = StringTools.fillLeftZero(FloatTools.toInt(ryb), 3); invertColor = color.invert(); invertRGB = hsba(invertColor); complementaryColor = ColorConvertTools.converColor(ColorConvertTools.rybComplementary(this)); complementaryRGB = hsba(complementaryColor); return this; } public ColorData cloneValues() { try { ColorData newData = (ColorData) super.clone(); newData.setCpid(-1); newData.setPaletteid(-1); return newData; } catch (Exception e) { return null; } } public String hsba(Color c) { long h = Math.round(c.getHue()); long s = Math.round(c.getSaturation() * 100); long b = Math.round(c.getBrightness() * 100); long a = Math.round(c.getOpacity() * 100); return h + vSeparator + s + "%" + vSeparator + b + "%" + vSeparator + a + "%"; } public String display() { if (colorDisplay == null) { if (colorName != null) { colorDisplay = colorName + "\n"; } else { colorDisplay = ""; } if (needConvert()) { convert(); } colorDisplay += rgba + "\n" + rgb + "\n" + colorValue + "\n" + "sRGB: " + srgb + "\n" + "HSBA: " + hsb + "\n" + message("RYBAngle") + ": " + rybAngle + "°\n" + message("Opacity") + ": " + opacity + "\n" + message("CalculatedCMYK") + ": " + calculatedCMYK + "\n" + "Adobe RGB: " + adobeRGB + "\n" + "Apple RGB: " + appleRGB + "\n" + "ECI RGB: " + eciRGB + "\n" + "sRGB Linear: " + SRGBLinear + "\n" + "Adobe RGB Linear: " + adobeRGBLinear + "\n" + "Apple RGB Linear: " + appleRGBLinear + "\n" + "ECI CMYK: " + eciCMYK + "\n" + "Adobe CMYK Uncoated FOGRA29: " + adobeCMYK + "\n" + "XYZ: " + xyz + "\n" + "CIE-L*ab: " + cieLab + "\n" + "LCH(ab): " + lchab + "\n" + "CIE-L*uv: " + cieLuv + "\n" + "LCH(uv): " + lchuv + (orderNumner == Float.MAX_VALUE ? "" : ("\n" + message("OrderNumber") + ": " + orderNumner)); } return colorDisplay; } public String simpleDisplay() { if (colorSimpleDisplay == null) { if (colorName != null) { colorSimpleDisplay = colorName + "\n"; } else { colorSimpleDisplay = ""; } if (needConvert()) { convert(); } colorSimpleDisplay += colorValue + "\n" + rgba + "\n" + rgb + "\n" + "sRGB: " + srgb + "\n" + "HSBA: " + hsb + "\n" + message("RYBAngle") + ": " + rybAngle + "°\n" + message("CalculatedCMYK") + ": " + calculatedCMYK + "\n"; } return colorSimpleDisplay; } public String html() { if (needConvert()) { convert(); } ColorData invertData = new ColorData(invertColor).setvSeparator(vSeparator).convert(); ColorData complementaryData = new ColorData(complementaryColor).setvSeparator(vSeparator).convert(); List<String> names = new ArrayList<>(); names.addAll(Arrays.asList(message("Data"), message("Color"), message("RGBInvertColor"), message("RYBComplementaryColor"))); StringTable table = new StringTable(names, message("Color")); table = FxColorTools.colorsTable(table, this, invertData, complementaryData); return HtmlWriteTools.html(message("Color"), HtmlStyles.styleValue("Table"), table.body()); } public String title() { if (colorName != null && !colorName.isBlank()) { return colorName + " " + rgba; } else { return rgba; } } public String css() { return color != null ? FxColorTools.color2css(color) : null; } /* customzied get/set */ public Color getColor() { if (color == null) { if (rgba != null) { setWeb(rgba); } else if (rgb != null) { setWeb(rgb); } } return color; } public ColorData setRgba(String rgba) { this.rgba = rgba; if (color == null) { setWeb(rgba); } return this; } public String getRgba() { if (rgba == null && rgb != null) { setWeb(rgb); } if (rgba != null) { return rgba.toUpperCase(); } else { return null; } } public ColorData setRgb(String rgb) { if (rgb == null) { return this; } this.rgb = rgb; if (color == null) { setWeb(rgb); } return this; } public String getRgb() { if (rgb == null && rgba != null) { setWeb(rgba); } return rgb; } public String getRybAngle() { if (needConvert()) { convert(); } return rybAngle; } /* Static methods */ public static ColorData create() { return new ColorData(); } public static boolean setValue(ColorData data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "color_value": data.setColorValue(value == null ? AppValues.InvalidInteger : (int) value); return true; case "rgba": data.setRgba(value == null ? null : (String) value); return true; case "color_name": data.setColorName(value == null ? null : (String) value); return true; case "rgb": data.setRgb(value == null ? null : (String) value); return true; case "srgb": data.setSrgb(value == null ? null : (String) value); return true; case "hsb": data.setHsb(value == null ? null : (String) value); return true; case "ryb": data.setRyb(value == null ? -1 : (float) value); return true; case "lchuv": data.setLchuv(value == null ? null : (String) value); return true; case "cieLuv": data.setCieLuv(value == null ? null : (String) value); return true; case "lchab": data.setLchab(value == null ? null : (String) value); return true; case "cieLab": data.setCieLab(value == null ? null : (String) value); return true; case "xyz": data.setXyz(value == null ? null : (String) value); return true; case "adobeCMYK": data.setAdobeCMYK(value == null ? null : (String) value); return true; case "adobeRGB": data.setAdobeRGB(value == null ? null : (String) value); return true; case "appleRGB": data.setAppleRGB(value == null ? null : (String) value); return true; case "eciRGB": data.setEciRGB(value == null ? null : (String) value); return true; case "sRGBLinear": data.setSRGBLinear(value == null ? null : (String) value); return true; case "adobeRGBLinear": data.setAdobeRGBLinear(value == null ? null : (String) value); return true; case "appleRGBLinear": data.setAppleRGBLinear(value == null ? null : (String) value); return true; case "calculatedCMYK": data.setCalculatedCMYK(value == null ? null : (String) value); return true; case "eciCMYK": data.setEciCMYK(value == null ? null : (String) value); return true; } } catch (Exception e) { MyBoxLog.debug(e); } return false; } public static Object getValue(ColorData data, String column) { if (data == null || column == null) { return null; } switch (column) { case "color_value": return data.getColorValue(); case "rgba": return data.getRgba(); case "color_name": return data.getColorName(); case "rgb": return data.getRgb(); case "srgb": return data.getSrgb(); case "hsb": return data.getHsb(); case "ryb": return data.getRyb(); case "adobeRGB": return data.getAdobeRGB(); case "appleRGB": return data.getAppleRGB(); case "eciRGB": return data.getEciRGB(); case "sRGBLinear": return data.getSRGBLinear(); case "adobeRGBLinear": return data.getAdobeRGBLinear(); case "appleRGBLinear": return data.getAppleRGBLinear(); case "calculatedCMYK": return data.getCalculatedCMYK(); case "eciCMYK": return data.getEciCMYK(); case "adobeCMYK": return data.getAdobeCMYK(); case "xyz": return data.getXyz(); case "cieLab": return data.getCieLab(); case "lchab": return data.getLchab(); case "cieLuv": return data.getCieLuv(); case "lchuv": return data.getLchuv(); } return null; } public static boolean valid(ColorData data) { return data != null && data.getRgba() != null; } public static String htmlValue(ColorData data) { return StringTools.replaceHtmlLineBreak(data.display()); } public static String htmlSimpleValue(ColorData data) { return StringTools.replaceHtmlLineBreak(data.simpleDisplay()); } /* get/set */ public void setColor(Color color) { this.color = color; } public int getColorValue() { return colorValue; } public void setColorValue(int colorValue) { this.colorValue = colorValue; } public String getColorName() { return colorName; } public ColorData setColorName(String colorName) { this.colorName = colorName; return this; } public String getColorDisplay() { return display(); } public ColorData setColorDisplay(String colorDisplay) { this.colorDisplay = colorDisplay; return this; } public String getColorSimpleDisplay() { return simpleDisplay(); } public ColorData setColorSimpleDisplay(String colorSimpleDisplay) { this.colorSimpleDisplay = colorSimpleDisplay; return this; } public String getSrgb() { return srgb; } public void setSrgb(String srgb) { this.srgb = srgb; } public String getHsb() { return hsb; } public void setHsb(String hsb) { this.hsb = hsb; } public float[] getAdobeRGBValues() { return adobeRGBValues; } public void setAdobeRGBValues(float[] adobeRGBValues) { this.adobeRGBValues = adobeRGBValues; } public float[] getAppleRGBValues() { return appleRGBValues; } public void setAppleRGBValues(float[] appleRGBValues) { this.appleRGBValues = appleRGBValues; } public float[] getEciRGBValues() { return eciRGBValues; } public void setEciRGBValues(float[] eciRGBValues) { this.eciRGBValues = eciRGBValues; } public float[] getEciCmykValues() { return eciCmykValues; } public void setEciCmykValues(float[] eciCmykValues) { this.eciCmykValues = eciCmykValues; } public float[] getAdobeCmykValues() { return adobeCmykValues; } public void setAdobeCmykValues(float[] adobeCmykValues) { this.adobeCmykValues = adobeCmykValues; } public double[] getCmyk() { return cmyk; } public void setCmyk(double[] cmyk) { this.cmyk = cmyk; } public double[] getXyzD50() { return xyzD50; } public void setXyzD50(double[] xyzD50) { this.xyzD50 = xyzD50; } public double[] getCieLabValues() { return cieLabValues; } public void setCieLabValues(double[] cieLabValues) { this.cieLabValues = cieLabValues; } public double[] getLchabValues() { return lchabValues; } public void setLchabValues(double[] lchabValues) { this.lchabValues = lchabValues; } public double[] getCieLuvValues() { return cieLuvValues; } public void setCieLuvValues(double[] cieLuvValues) { this.cieLuvValues = cieLuvValues; } public double[] getLchuvValues() { return lchuvValues; } public void setLchuvValues(double[] lchuvValues) { this.lchuvValues = lchuvValues; } public String getAdobeRGB() { return adobeRGB; } public void setAdobeRGB(String adobeRGB) { this.adobeRGB = adobeRGB; } public String getAppleRGB() { return appleRGB; } public void setAppleRGB(String appleRGB) { this.appleRGB = appleRGB; } public String getEciRGB() { return eciRGB; } public void setEciRGB(String eciRGB) { this.eciRGB = eciRGB; } public String getSRGBLinear() { return SRGBLinear; } public void setSRGBLinear(String SRGBLinear) { this.SRGBLinear = SRGBLinear; } public String getAdobeRGBLinear() { return adobeRGBLinear; } public void setAdobeRGBLinear(String adobeRGBLinear) { this.adobeRGBLinear = adobeRGBLinear; } public String getAppleRGBLinear() { return appleRGBLinear; } public void setAppleRGBLinear(String appleRGBLinear) { this.appleRGBLinear = appleRGBLinear; } public String getCalculatedCMYK() { return calculatedCMYK; } public void setCalculatedCMYK(String calculatedCMYK) { this.calculatedCMYK = calculatedCMYK; } public String getEciCMYK() { return eciCMYK; } public void setEciCMYK(String eciCMYK) { this.eciCMYK = eciCMYK; } public String getAdobeCMYK() { return adobeCMYK; } public void setAdobeCMYK(String adobeCMYK) { this.adobeCMYK = adobeCMYK; } public String getXyz() { return xyz; } public void setXyz(String xyz) { this.xyz = xyz; } public String getCieLab() { return cieLab; } public void setCieLab(String cieLab) { this.cieLab = cieLab; } public String getLchab() { return lchab; } public void setLchab(String lchab) { this.lchab = lchab; } public String getCieLuv() { return cieLuv; } public void setCieLuv(String cieLuv) { this.cieLuv = cieLuv; } public String getLchuv() { return lchuv; } public void setLchuv(String lchuv) { this.lchuv = lchuv; } public float getOrderNumner() { return orderNumner; } public ColorData setOrderNumner(float orderNumner) { this.orderNumner = orderNumner; return this; } public long getPaletteid() { return paletteid; } public ColorData setPaletteid(long paletteid) { this.paletteid = paletteid; return this; } public ColorData setRyb(float ryb) { this.ryb = ryb; return this; } public long getCpid() { return cpid; } public ColorData setCpid(long cpid) { this.cpid = cpid; return this; } public Color getInvertColor() { return invertColor; } public Color getComplementaryColor() { return complementaryColor; } public String getHue() { return hue; } public String getSaturation() { return saturation; } public String getBrightness() { return brightness; } public String getInvertRGB() { return invertRGB; } public String getComplementaryRGB() { return complementaryRGB; } public boolean isIsSettingValues() { return isSettingValues; } public float getRyb() { return ryb; } public String getOpacity() { return opacity; } public void setOpacity(String opacity) { this.opacity = opacity; } public String getvSeparator() { return vSeparator; } public ColorData setvSeparator(String vSeparator) { this.vSeparator = vSeparator; 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/data/ColorPalette.java
alpha/MyBox/src/main/java/mara/mybox/db/data/ColorPalette.java
package mara.mybox.db.data; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.AppValues; /** * @Author Mara * @CreateDate 2021-3-31 * @License Apache License Version 2.0 */ public class ColorPalette extends BaseData { protected long cpid, paletteid; protected int colorValue; protected String name, description; protected ColorData data; protected float orderNumber; private void init() { cpid = -1; paletteid = 1; name = null; colorValue = -1; data = null; } public ColorPalette() { init(); } public ColorPalette(long paletteid, String name) { init(); this.paletteid = paletteid; this.name = name; } @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 ColorPalette create() { return new ColorPalette(); } public static boolean setValue(ColorPalette data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "cpid": data.setCpid(value == null ? -1 : (long) value); return true; case "paletteid": data.setPaletteid(value == null ? -1 : (long) value); return true; case "name_in_palette": data.setName(value == null ? null : (String) value); return true; case "cvalue": data.setColorValue(value == null ? AppValues.InvalidInteger : (int) value); return true; case "order_number": data.setOrderNumber(value == null ? -1 : (float) value); return true; case "description": data.setDescription(value == null ? null : (String) value); return true; } } catch (Exception e) { MyBoxLog.debug(e); } return false; } public static Object getValue(ColorPalette data, String column) { if (data == null || column == null) { return null; } switch (column) { case "cpid": return data.getCpid(); case "paletteid": return data.getPaletteid(); case "name_in_palette": return data.getName(); case "cvalue": return data.getColorValue(); case "order_number": return data.getOrderNumber(); case "description": return data.getDescription(); } return null; } public static boolean valid(ColorPalette data) { return data != null && data.getPaletteid() >= 0 && data.getColorValue() != AppValues.InvalidInteger; } /* get/set */ public long getCpid() { return cpid; } public ColorPalette setCpid(long cpid) { this.cpid = cpid; return this; } public long getPaletteid() { return paletteid; } public ColorPalette setPaletteid(long paletteid) { this.paletteid = paletteid; return this; } public String getName() { return name; } public ColorPalette setName(String name) { this.name = name; return this; } public int getColorValue() { return colorValue; } public ColorPalette setColorValue(int colorValue) { this.colorValue = colorValue; return this; } public ColorData getData() { return data; } public ColorPalette setData(ColorData data) { this.data = data; return this; } public float getOrderNumber() { return orderNumber; } public ColorPalette setOrderNumber(float orderNumber) { this.orderNumber = orderNumber; return this; } public String getDescription() { return description; } public ColorPalette setDescription(String description) { this.description = description; 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/data/VisitHistory.java
alpha/MyBox/src/main/java/mara/mybox/db/data/VisitHistory.java
package mara.mybox.db.data; import java.util.Date; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2019-4-5 * @License Apache License Version 2.0 */ public class VisitHistory extends BaseData { public static final int Default_Max_Histories = 12; private short resourceType, fileType, operationType; private String resourceValue, dataMore; private Date lastVisitTime; private int visitCount; public static class ResourceType { public static int Path = 1; public static int File = 2; public static int URI = 3; public static int Menu = 4; public static int None = 100; } public static class FileType { public static int All = 0; public static int General = 1; public static int Image = 2; public static int PDF = 3; public static int Text = 4; public static int Bytes = 5; public static int Gif = 6; public static int Tif = 7; public static int MultipleFrames = 8; public static int Audio = 9; public static int Video = 10; public static int Html = 11; public static int Icc = 12; public static int XML = 13; public static int Markdown = 14; public static int Media = 15; public static int Certificate = 16; public static int StreamMedia = 17; public static int TTC = 18; public static int TTF = 19; public static int Excel = 20; public static int CSV = 21; public static int Sheet = 22; public static int Cert = 23; public static int Word = 24; public static int PPT = 25; public static int PPTX = 26; public static int PPTS = 27; public static int WordX = 28; public static int WordS = 29; public static int ImagesList = 30; public static int Jar = 31; public static int DataFile = 32; public static int JSON = 33; public static int SVG = 34; public static int Javascript = 35; public static int None = 100; } public static class OperationType { public static int Access = 1; public static int Read = 2; public static int Write = 3; public static int Alpha = 4; public static int Download = 5; public static int None = 100; } public static int[] typeGroup(int fileType) { if (fileType == FileType.MultipleFrames) { int[] types = {FileType.Gif, FileType.Tif, FileType.MultipleFrames}; return types; } else if (fileType == FileType.Image) { int[] types = {FileType.Image, FileType.Gif, FileType.Tif, FileType.MultipleFrames}; return types; } else if (fileType == FileType.Media) { int[] types = {FileType.Media, FileType.Video, FileType.Audio}; return types; } else if (fileType == FileType.Sheet) { int[] types = {FileType.Sheet, FileType.Excel, FileType.CSV}; return types; } else if (fileType == FileType.ImagesList) { int[] types = {FileType.Image, FileType.Gif, FileType.Tif, FileType.MultipleFrames, FileType.PDF, FileType.PPT}; return types; } else if (fileType == FileType.DataFile) { int[] types = {FileType.DataFile, FileType.CSV, FileType.Excel, FileType.Text}; return types; } else if (fileType == FileType.Text) { int[] types = {FileType.Text, FileType.CSV, FileType.JSON, FileType.XML, FileType.Markdown, FileType.Html, FileType.SVG, FileType.Javascript}; return types; } else { return null; } } public VisitHistory() { } public VisitHistory(String value) { resourceValue = value; } @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 VisitHistory create() { return new VisitHistory(); } public static boolean setValue(VisitHistory data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "resource_type": data.setResourceType(value == null ? null : (short) value); return true; case "file_type": data.setFileType(value == null ? null : (short) value); return true; case "operation_type": data.setOperationType(value == null ? null : (short) value); return true; case "resource_value": data.setResourceValue(value == null ? null : (String) value); return true; case "last_visit_time": data.setLastVisitTime(value == null ? null : (Date) value); return true; case "data_more": data.setDataMore(value == null ? null : (String) value); return true; case "visit_count": data.setVisitCount(value == null ? null : (int) value); return true; } } catch (Exception e) { MyBoxLog.debug(e); } return false; } public static Object getValue(VisitHistory data, String column) { if (data == null || column == null) { return null; } switch (column) { case "resource_type": return data.getResourceType(); case "file_type": return data.getFileType(); case "operation_type": return data.getOperationType(); case "resource_value": return data.getResourceValue(); case "last_visit_time": return data.getLastVisitTime(); case "data_more": return data.getDataMore(); case "visit_count": return data.getVisitCount(); } return null; } public static boolean valid(VisitHistory data) { return data != null; } public static boolean isImageType(int fileType) { return fileType == FileType.Image || fileType == FileType.Gif || fileType == FileType.Tif || fileType == FileType.MultipleFrames; } /* get/set */ public short getResourceType() { return resourceType; } public VisitHistory setResourceType(short resourceType) { this.resourceType = resourceType; return this; } public short getFileType() { return fileType; } public VisitHistory setFileType(short fileType) { this.fileType = fileType; return this; } public short getOperationType() { return operationType; } public VisitHistory setOperationType(short operationType) { this.operationType = operationType; return this; } public String getResourceValue() { return resourceValue; } public VisitHistory setResourceValue(String resourceValue) { this.resourceValue = resourceValue; return this; } public String getDataMore() { return dataMore; } public VisitHistory setDataMore(String dataMore) { this.dataMore = dataMore; return this; } public Date getLastVisitTime() { return lastVisitTime; } public VisitHistory setLastVisitTime(Date lastVisitTime) { this.lastVisitTime = lastVisitTime; return this; } public int getVisitCount() { return visitCount; } public VisitHistory setVisitCount(int visitCount) { this.visitCount = visitCount; 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/data/Data2DStyle.java
alpha/MyBox/src/main/java/mara/mybox/db/data/Data2DStyle.java
package mara.mybox.db.data; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.StringTools; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-4-7 * @License Apache License Version 2.0 */ public class Data2DStyle extends BaseData { public static final String ColumnSeparator = "::"; protected Data2DDefinition data2DDefinition; protected long styleID, dataID; protected long rowStart, rowEnd; // 0-based, exlcuded protected String title, columns, filter, fontColor, bgColor, fontSize, moreStyle; protected boolean matchFalse, abnoramlValues, bold; protected float sequence; private void init() { styleID = -1; dataID = -1; title = null; rowStart = -1; rowEnd = -1; columns = null; filter = null; fontColor = null; bgColor = null; fontSize = null; moreStyle = null; matchFalse = false; abnoramlValues = false; bold = false; sequence = 0; } public Data2DStyle() { 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); } public Data2DStyle cloneAll() { try { Data2DStyle newData = (Data2DStyle) super.clone(); newData.cloneFrom(this); return newData; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public void cloneFrom(Data2DStyle style) { try { if (style == null) { return; } data2DDefinition = style.data2DDefinition; styleID = style.styleID; dataID = style.dataID; title = style.title; rowStart = style.rowStart; rowEnd = style.rowEnd; columns = style.columns; filter = style.filter; fontColor = style.fontColor; bgColor = style.bgColor; fontSize = style.fontSize; moreStyle = style.moreStyle; bold = style.bold; sequence = style.sequence; abnoramlValues = style.abnoramlValues; } catch (Exception e) { MyBoxLog.debug(e); } } public String finalStyle() { String styleValue = ""; if (fontSize != null && !message("Default").equals(fontSize)) { styleValue = "-fx-font-size: " + fontSize + "; "; } if (fontColor != null && !message("Default").equals(fontColor)) { styleValue += "-fx-text-fill: " + fontColor + "; "; } if (bgColor != null && !message("Default").equals(bgColor)) { styleValue += "-fx-background-color: " + bgColor + "; "; } if (bold) { styleValue += "-fx-font-weight: bolder; "; } if (moreStyle != null && !moreStyle.isBlank()) { styleValue += StringTools.replaceLineBreak(moreStyle); } return styleValue.isBlank() ? null : styleValue.trim(); } /* static methods */ public static Data2DStyle create() { return new Data2DStyle(); } public static boolean valid(Data2DStyle data) { return data != null && data.getDataID() >= 0; } public static boolean setValue(Data2DStyle data, String column, Object value) { if (data == null || column == null) { return false; } try { switch (column) { case "d2sid": data.setStyleID(value == null ? -1 : (long) value); return true; case "d2id": data.setDataID(value == null ? -1 : (long) value); return true; case "title": data.setTitle(value == null ? null : (String) value); return true; case "rowStart": data.setRowStart(value == null ? -1 : (long) value); return true; case "rowEnd": data.setRowEnd(value == null ? -1 : (long) value); return true; case "columns": data.setColumns(value == null ? null : (String) value); return true; case "filter": data.setFilter(value == null ? null : (String) value); return true; case "filterReversed": data.setMatchFalse(value == null ? false : (boolean) value); return true; case "fontColor": data.setFontColor(value == null ? null : (String) value); return true; case "bgColor": data.setBgColor(value == null ? null : (String) value); return true; case "fontSize": data.setFontSize(value == null ? null : (String) value); return true; case "moreStyle": data.setMoreStyle(value == null ? null : (String) value); return true; case "bold": data.setBold(value == null ? false : (boolean) value); return true; case "sequence": data.setSequence(value == null ? 0 : (float) value); return true; case "abnoramlValues": data.setAbnoramlValues(value == null ? false : (boolean) value); return true; } } catch (Exception e) { MyBoxLog.debug(e); } return false; } public static Object getValue(Data2DStyle data, String column) { if (data == null || column == null) { return null; } try { switch (column) { case "d2sid": return data.getStyleID(); case "d2id": return data.getDataID(); case "title": return data.getTitle(); case "rowStart": return data.getRowStart(); case "rowEnd": return data.getRowEnd(); case "columns": return data.getColumns(); case "filter": return data.getFilter(); case "filterReversed": return data.isMatchFalse(); case "fontColor": return data.getFontColor(); case "bgColor": return data.getBgColor(); case "fontSize": return data.getFontSize(); case "moreStyle": return data.getMoreStyle(); case "bold": return data.isBold(); case "sequence": return data.getSequence(); case "abnoramlValues": return data.isAbnoramlValues(); } } catch (Exception e) { MyBoxLog.debug(e); } return null; } /* interface get 1-based, inlcuded */ public long getFrom() { return rowStart < 0 ? -1 : rowStart + 1; } public long getTo() { return rowEnd; } /* get/set */ public long getStyleID() { return styleID; } public Data2DStyle setStyleID(long d2sid) { this.styleID = d2sid; return this; } public long getDataID() { return dataID; } public Data2DStyle setDataID(long d2id) { this.dataID = d2id; return this; } public String getTitle() { return title; } public Data2DStyle setTitle(String title) { this.title = title; return this; } public long getRowStart() { return rowStart; } public Data2DStyle setRowStart(long rowStart) { this.rowStart = rowStart; return this; } public long getRowEnd() { return rowEnd; } public Data2DStyle setRowEnd(long rowEnd) { this.rowEnd = rowEnd; return this; } public String getColumns() { return columns; } public Data2DStyle setColumns(String columns) { this.columns = columns; return this; } public String getFontColor() { return fontColor; } public Data2DStyle setFontColor(String fontColor) { this.fontColor = fontColor; return this; } public String getBgColor() { return bgColor; } public Data2DStyle setBgColor(String bgColor) { this.bgColor = bgColor; return this; } public String getFontSize() { return fontSize; } public Data2DStyle setFontSize(String fontSize) { this.fontSize = fontSize; return this; } public String getMoreStyle() { return moreStyle; } public Data2DStyle setMoreStyle(String moreStyle) { this.moreStyle = moreStyle; return this; } public boolean isBold() { return bold; } public Data2DStyle setBold(boolean bold) { this.bold = bold; return this; } public float getSequence() { return sequence; } public Data2DStyle setSequence(float sequence) { this.sequence = sequence; return this; } public boolean isAbnoramlValues() { return abnoramlValues; } public Data2DStyle setAbnoramlValues(boolean abnoramlValues) { this.abnoramlValues = abnoramlValues; return this; } public Data2DDefinition getData2DDefinition() { return data2DDefinition; } public Data2DStyle setData2DDefinition(Data2DDefinition data2DDefinition) { this.data2DDefinition = data2DDefinition; return this; } public String getFilter() { return filter; } public Data2DStyle setFilter(String filter) { this.filter = filter; return this; } public boolean isMatchFalse() { return matchFalse; } public Data2DStyle setMatchFalse(boolean matchFalse) { this.matchFalse = matchFalse; 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/data/QueryCondition.java
alpha/MyBox/src/main/java/mara/mybox/db/data/QueryCondition.java
package mara.mybox.db.data; /** * @Author Mara * @CreateDate 2020-5-14 * @License Apache License Version 2.0 */ public class QueryCondition { private long qcid, time; private int operation, top; private String dataName, title, prefix, where, order, fetch; private DataOperation dataOperation; public enum DataOperation { QueryData, UpdateData, ClearData, ExportData, Unknown } public QueryCondition() { qcid = -1; operation = top = -1; dataName = null; title = null; prefix = null; where = null; order = null; fetch = null; time = -1; } public boolean isValid() { return operation > 0 && operation < 5 && prefix != null && title != null; } public String statement() { if (prefix == null) { return null; } String s = prefix; s += where == null || where.trim().isBlank() ? "" : " WHERE " + where; s += order == null || order.trim().isBlank() ? "" : " ORDER BY " + order; s += fetch == null || fetch.trim().isBlank() ? "" : " " + fetch; return s; } /* static methods */ public static QueryCondition create() { return new QueryCondition(); } public static DataOperation dataOperation(int operation) { switch (operation) { case 1: return DataOperation.QueryData; case 2: return DataOperation.UpdateData; case 3: return DataOperation.ClearData; case 4: return DataOperation.ExportData; default: return DataOperation.Unknown; } } public static int operation(DataOperation dataOperation) { if (dataOperation == null) { return -1; } switch (dataOperation) { case QueryData: return 1; case UpdateData: return 2; case ClearData: return 3; case ExportData: return 4; default: return -1; } } /* get/set */ public long getQcid() { return qcid; } public QueryCondition setQcid(long qcid) { this.qcid = qcid; return this; } public String getDataName() { return dataName; } public QueryCondition setDataName(String dataName) { this.dataName = dataName; return this; } public int getOperation() { return operation; } public QueryCondition setOperation(int operation) { this.operation = operation; this.dataOperation = dataOperation(operation); return this; } public int getTop() { return top; } public QueryCondition setTop(int top) { this.top = top; return this; } public String getTitle() { return title; } public QueryCondition setTitle(String title) { this.title = title; return this; } public String getWhere() { return where; } public QueryCondition setWhere(String where) { this.where = where; return this; } public String getOrder() { return order; } public QueryCondition setOrder(String order) { this.order = order; return this; } public String getFetch() { return fetch; } public QueryCondition setFetch(String fetch) { this.fetch = fetch; return this; } public DataOperation getDataOperation() { return dataOperation; } public QueryCondition setDataOperation(DataOperation dataOperation) { this.dataOperation = dataOperation; this.operation = operation(dataOperation); return this; } public String getPrefix() { return prefix; } public QueryCondition setPrefix(String prefix) { this.prefix = prefix; return this; } public long getTime() { return time; } public QueryCondition setTime(long time) { this.time = time; 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/table/TableStringValue.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableStringValue.java
package mara.mybox.db.table; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.Date; import java.util.HashMap; import java.util.Map; import mara.mybox.db.DerbyBase; import static mara.mybox.db.DerbyBase.stringValue; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.StringValue; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.DateTools; /** * @Author Mara * @CreateDate 2019-8-21 * @License Apache License Version 2.0 */ public class TableStringValue extends BaseTable<StringValue> { public TableStringValue() { tableName = "String_Value"; defineColumns(); } public TableStringValue(boolean defineColumns) { tableName = "String_Value"; if (defineColumns) { defineColumns(); } } public final TableStringValue defineColumns() { addColumn(new ColumnDefinition("key_name", ColumnDefinition.ColumnType.String, true, true).setLength(StringMaxLength)); addColumn(new ColumnDefinition("string_value", ColumnDefinition.ColumnType.String, true).setLength(StringMaxLength)); addColumn(new ColumnDefinition("create_time", ColumnDefinition.ColumnType.Datetime, true)); orderColumns = "create_time DESC"; return this; } public static final String Query = "SELECT * FROM String_Value WHERE key_name=?"; public static final String Update = "UPDATE String_Value SET create_time=?, string_value=? WHERE key_name=?"; public static final String Insert = "INSERT INTO String_Value (key_name, string_value , create_time) VALUES (?,?,?)"; public static final String Delete = "DELETE FROM String_Value WHERE key_name=?"; @Override public boolean setValue(StringValue data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(StringValue data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(StringValue data) { if (data == null) { return false; } return data.valid(); } public static String read(String name) { if (name == null || name.trim().isEmpty()) { return null; } try (Connection conn = DerbyBase.getConnection()) { conn.setReadOnly(true); return read(conn, name); } catch (Exception e) { MyBoxLog.error(e); } return null; } public static String read(Connection conn, String name) { if (conn == null || name == null || name.trim().isEmpty()) { return null; } try (PreparedStatement statement = conn.prepareStatement(Query)) { statement.setMaxRows(1); statement.setString(1, name); conn.setAutoCommit(true); try (ResultSet results = statement.executeQuery()) { if (results.next()) { return results.getString("string_value"); } } } catch (Exception e) { MyBoxLog.error(e); } return null; } public static boolean write(String name, String value) { if (name == null || name.trim().isEmpty() || value == null || value.trim().isEmpty()) { return false; } try (Connection conn = DerbyBase.getConnection()) { return write(conn, name, value); } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean write(Connection conn, String name, String value) { try { boolean existed = false; try (PreparedStatement statement = conn.prepareStatement(Query)) { statement.setMaxRows(1); statement.setString(1, name); conn.setAutoCommit(true); try (ResultSet results = statement.executeQuery()) { if (results.next()) { existed = true; } } } if (existed) { try (PreparedStatement statement = conn.prepareStatement(Update)) { statement.setString(1, DateTools.datetimeToString(new Date())); statement.setString(2, value); statement.setString(3, name); return statement.executeUpdate() > 0; } } else { try (PreparedStatement statement = conn.prepareStatement(Insert)) { statement.setString(1, name); statement.setString(2, value); statement.setString(3, DateTools.datetimeToString(new Date())); return statement.executeUpdate() > 0; } } } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean write(Map<String, String> nameValues) { return writeWithPrefix(null, nameValues); } public static boolean writeWithPrefix(String prefix, Map<String, String> nameValues) { if (nameValues == null || nameValues.isEmpty()) { return false; } try (Connection conn = DerbyBase.getConnection()) { conn.setAutoCommit(false); for (String name : nameValues.keySet()) { String value = nameValues.get(name); if (prefix != null) { write(conn, prefix + name, value); } else { write(conn, name, value); } } conn.commit(); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean delete(String name) { if (name == null || name.trim().isEmpty()) { return false; } try (Connection conn = DerbyBase.getConnection(); PreparedStatement statement = conn.prepareStatement(Delete)) { statement.setString(1, name); return statement.executeUpdate() > 0; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static Map<String, String> readWithPrefix(String prefix) { try (Connection conn = DerbyBase.getConnection()) { conn.setReadOnly(true); return readWithPrefix(conn, prefix); } catch (Exception e) { MyBoxLog.error(e); // MyBoxLog.debug(e); return null; } } public static Map<String, String> readWithPrefix(Connection conn, String prefix) { Map<String, String> keyValues = new HashMap<>(); if (conn == null || prefix == null || prefix.trim().isEmpty()) { return keyValues; } String sql = " SELECT key_name, string_value FROM String_Value WHERE key_name like '" + stringValue(prefix) + "%' "; try (Statement statement = conn.createStatement(); ResultSet results = statement.executeQuery(sql)) { while (results.next()) { keyValues.put(results.getString("key_name"), results.getString("string_value")); } } catch (Exception e) { MyBoxLog.error(e); // MyBoxLog.debug(e); } return keyValues; } public static boolean clearPrefix(String prefix) { if (prefix == null || prefix.trim().isEmpty()) { return false; } try (Connection conn = DerbyBase.getConnection(); Statement statement = conn.createStatement()) { String sql = "DELETE FROM String_Value WHERE key_name like '" + stringValue(prefix) + "%' "; statement.executeUpdate(sql); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/db/table/TableData2DStyle.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableData2DStyle.java
package mara.mybox.db.table; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import mara.mybox.db.Database; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.Data2DDefinition; import mara.mybox.db.data.Data2DStyle; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2022-4-7 * @License Apache License Version 2.0 */ public class TableData2DStyle extends BaseTable<Data2DStyle> { protected TableData2DDefinition tableData2DDefinition; public TableData2DStyle() { tableName = "Data2D_Style"; defineColumns(); } public TableData2DStyle(boolean defineColumns) { tableName = "Data2D_Style"; if (defineColumns) { defineColumns(); } } public final TableData2DStyle defineColumns() { addColumn(new ColumnDefinition("d2sid", ColumnType.Long, true, true).setAuto(true)); addColumn(new ColumnDefinition("d2id", ColumnType.Long, true) .setReferName("Data2D_Style_d2id_fk").setReferTable("Data2D_Definition").setReferColumn("d2did") .setOnDelete(ColumnDefinition.OnDelete.Cascade)); addColumn(new ColumnDefinition("title", ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("rowStart", ColumnType.Long)); // 0-based addColumn(new ColumnDefinition("rowEnd", ColumnType.Long)); // Exclude addColumn(new ColumnDefinition("columns", ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("filter", ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("filterReversed", ColumnType.Boolean)); addColumn(new ColumnDefinition("fontColor", ColumnType.String).setLength(64)); addColumn(new ColumnDefinition("fontSize", ColumnType.String).setLength(64)); addColumn(new ColumnDefinition("bgColor", ColumnType.String).setLength(64)); addColumn(new ColumnDefinition("bold", ColumnType.Boolean)); addColumn(new ColumnDefinition("moreStyle", ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("sequence", ColumnType.Float)); addColumn(new ColumnDefinition("abnoramlValues", ColumnType.Boolean)); orderColumns = "d2id, sequence, d2sid"; return this; } public static final String QueryStyles = "SELECT * FROM Data2D_Style WHERE d2id=? ORDER BY sequence,d2sid"; public static final String ClearStyles = "DELETE FROM Data2D_Style WHERE d2id=?"; @Override public Object readForeignValue(ResultSet results, String column) { if (results == null || column == null) { return null; } try { if ("d2id".equals(column) && results.findColumn("d2did") > 0) { return getTableData2DDefinition().readData(results); } } catch (Exception e) { } return null; } @Override public boolean setForeignValue(Data2DStyle data, String column, Object value) { if (data == null || column == null || value == null) { return true; } if ("d2id".equals(column) && value instanceof Data2DDefinition) { data.setData2DDefinition((Data2DDefinition) value); } return true; } @Override public boolean setValue(Data2DStyle data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(Data2DStyle data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(Data2DStyle data) { if (data == null) { return false; } return data.valid(); } public boolean clear(Connection conn, long d2id) { if (conn == null || d2id < 0) { return false; } try (PreparedStatement statement = conn.prepareStatement(ClearStyles)) { statement.setLong(1, d2id); statement.executeUpdate(); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public int copyStyles(Connection conn, long sourceid, long targetid) { if (conn == null || sourceid < 0 || targetid < 0 || sourceid == targetid) { return -1; } clear(conn, targetid); int count = 0; try (PreparedStatement statement = conn.prepareStatement(QueryStyles)) { statement.setLong(1, sourceid); conn.setAutoCommit(true); ResultSet results = statement.executeQuery(); conn.setAutoCommit(false); while (results.next()) { Data2DStyle s = readData(results); s.setStyleID(-1); s.setDataID(targetid); if (insertData(conn, s) != null) { count++; if (count % Database.BatchSize == 0) { conn.commit(); } } } conn.commit(); } catch (Exception e) { MyBoxLog.error(e); return -1; } return count; } /* get/set */ public TableData2DDefinition getTableData2DDefinition() { if (tableData2DDefinition == null) { tableData2DDefinition = new TableData2DDefinition(); } return tableData2DDefinition; } public void setTableData2DDefinition(TableData2DDefinition tableData2DDefinition) { this.tableData2DDefinition = tableData2DDefinition; } }
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/table/TableTextClipboard.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableTextClipboard.java
package mara.mybox.db.table; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Date; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.TextClipboard; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2021-7-3 * @License Apache License Version 2.0 */ public class TableTextClipboard extends BaseTable<TextClipboard> { public TableTextClipboard() { tableName = "Text_Clipboard"; defineColumns(); } public TableTextClipboard(boolean defineColumns) { tableName = "Text_Clipboard"; if (defineColumns) { defineColumns(); } } public final TableTextClipboard defineColumns() { addColumn(new ColumnDefinition("tcid", ColumnType.Long, true, true).setAuto(true)); addColumn(new ColumnDefinition("text", ColumnType.String, true).setLength(StringMaxLength)); addColumn(new ColumnDefinition("create_time", ColumnType.Datetime)); orderColumns = "create_time DESC"; return this; } public static final String QueryText = "SELECT * FROM Text_Clipboard WHERE text=?"; @Override public boolean setValue(TextClipboard data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(TextClipboard data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(TextClipboard data) { if (data == null) { return false; } return data.valid(); } public TextClipboard save(Connection conn, String text) { if (text == null || text.isEmpty()) { return null; } try { Connection conn1 = conn; if (conn1 == null || conn1.isClosed()) { conn1 = DerbyBase.getConnection(); } if (UserConfig.getBoolean("TextClipboardNoDuplication", true)) { TextClipboard exist = null; try (PreparedStatement statement = conn1.prepareStatement(QueryText)) { statement.setString(1, text); statement.setMaxRows(1); conn1.setAutoCommit(true); try (ResultSet results = statement.executeQuery()) { if (results.next()) { exist = readData(results); exist.setCreateTime(new Date()); } } } catch (Exception e) { MyBoxLog.error(e); } if (exist != null) { return updateData(conn1, exist); } } return insertData(conn1, new TextClipboard(text)); } 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/table/TableData2DDefinition.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableData2DDefinition.java
package mara.mybox.db.table; import java.io.File; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import mara.mybox.controller.BaseTaskController; import mara.mybox.data2d.Data2D; import mara.mybox.data2d.DataTable; import mara.mybox.data2d.TmpTable; import mara.mybox.db.Database; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.Data2DDefinition; import mara.mybox.db.data.Data2DDefinition.DataType; import mara.mybox.dev.MyBoxLog; import static mara.mybox.fxml.WindowTools.recordError; import static mara.mybox.fxml.WindowTools.recordInfo; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2021-11-2 * @License Apache License Version 2.0 */ public class TableData2DDefinition extends BaseTable<Data2DDefinition> { public TableData2DDefinition() { tableName = "Data2D_Definition"; defineColumns(); } public TableData2DDefinition(boolean defineColumns) { tableName = "Data2D_Definition"; if (defineColumns) { defineColumns(); } } public final TableData2DDefinition defineColumns() { addColumn(new ColumnDefinition("d2did", ColumnType.Long, true, true).setAuto(true)); addColumn(new ColumnDefinition("data_type", ColumnType.Short, true)); addColumn(new ColumnDefinition("data_name", ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("file", ColumnType.File).setLength(StringMaxLength)); addColumn(new ColumnDefinition("sheet", ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("charset", ColumnType.String).setLength(32)); addColumn(new ColumnDefinition("delimiter", ColumnType.String).setLength(1024)); addColumn(new ColumnDefinition("has_header", ColumnType.Boolean)); addColumn(new ColumnDefinition("columns_number", ColumnType.Long)); addColumn(new ColumnDefinition("rows_number", ColumnType.Long)); addColumn(new ColumnDefinition("scale", ColumnType.Short)); addColumn(new ColumnDefinition("max_random", ColumnType.Integer)); addColumn(new ColumnDefinition("modify_time", ColumnType.Datetime)); addColumn(new ColumnDefinition("comments", ColumnType.String).setLength(StringMaxLength)); orderColumns = "modify_time DESC"; return this; } public static final String QueryID = "SELECT * FROM Data2D_Definition WHERE d2did=?"; public static final String Query_File = "SELECT * FROM Data2D_Definition WHERE file=? ORDER BY modify_time DESC"; public static final String Query_TypeFile = "SELECT * FROM Data2D_Definition WHERE data_type=? AND file=? ORDER BY modify_time DESC"; public static final String Query_TypeFileSheet = "SELECT * FROM Data2D_Definition WHERE data_type=? AND file=? AND sheet=? ORDER BY modify_time DESC"; public static final String Query_Files = "SELECT * FROM Data2D_Definition WHERE data_type < 5"; public static final String Query_Table = "SELECT * FROM Data2D_Definition WHERE data_type=? AND sheet=? ORDER BY modify_time DESC"; public static final String Query_UserTable = "SELECT * FROM Data2D_Definition WHERE data_type=5 AND sheet=? ORDER BY modify_time DESC"; public static final String Query_Type = "SELECT * FROM Data2D_Definition WHERE data_type=? ORDER BY modify_time DESC"; public static final String DeleteID = "DELETE FROM Data2D_Definition WHERE d2did=?"; public static final String Delete_TypeFile = "DELETE FROM Data2D_Definition WHERE data_type=? AND file=?"; public static final String Delete_TypeName = "DELETE FROM Data2D_Definition WHERE data_type=? AND data_name=?"; public static final String Delete_UserTable = "DELETE FROM Data2D_Definition WHERE data_type=5 AND sheet=?"; @Override public boolean setValue(Data2DDefinition data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(Data2DDefinition data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(Data2DDefinition data) { if (data == null) { return false; } return data.valid(); } /* local methods */ public Data2DDefinition queryID(Connection conn, long d2did) { if (conn == null || d2did < 0) { return null; } try (PreparedStatement statement = conn.prepareStatement(QueryID)) { statement.setLong(1, d2did); return query(conn, statement); } catch (Exception e) { MyBoxLog.error(e); return null; } } public Data2DDefinition queryFile(File file) { if (file == null) { return null; } try (Connection conn = DerbyBase.getConnection();) { return queryFile(conn, file); } catch (Exception e) { MyBoxLog.error(e); return null; } } public Data2DDefinition queryFile(Connection conn, File file) { if (conn == null || file == null) { return null; } try (PreparedStatement statement = conn.prepareStatement(Query_File)) { statement.setString(1, file.getAbsolutePath()); return query(conn, statement); } catch (Exception e) { MyBoxLog.error(e); return null; } } public Data2DDefinition queryFile(DataType type, File file) { if (file == null) { return null; } try (Connection conn = DerbyBase.getConnection();) { return queryFile(conn, type, file); } catch (Exception e) { MyBoxLog.error(e); return null; } } public Data2DDefinition queryFile(Connection conn, DataType type, File file) { if (conn == null || file == null) { return null; } try (PreparedStatement statement = conn.prepareStatement(Query_TypeFile)) { statement.setShort(1, Data2DDefinition.type(type)); statement.setString(2, file.getAbsolutePath()); return query(conn, statement); } catch (Exception e) { MyBoxLog.error(e); return null; } } public Data2DDefinition queryClipboard(Connection conn, File file) { return queryFile(conn, DataType.MyBoxClipboard, file); } public Data2DDefinition queryMatrix(Connection conn, File file) { return queryFile(conn, DataType.Matrix, file); } public Data2DDefinition queryFileSheet(Connection conn, DataType type, File file, String sheet) { if (conn == null || file == null) { return null; } if (sheet == null || sheet.isBlank()) { return queryFile(conn, type, file); } try (PreparedStatement statement = conn.prepareStatement(Query_TypeFileSheet)) { statement.setShort(1, Data2DDefinition.type(type)); statement.setString(2, file.getAbsolutePath()); statement.setString(3, sheet); return query(conn, statement); } catch (Exception e) { MyBoxLog.error(e); return null; } } public Data2DDefinition queryTable(Connection conn, String tname, DataType type) { if (conn == null || tname == null) { return null; } try (PreparedStatement statement = conn.prepareStatement(Query_Table)) { statement.setShort(1, Data2DDefinition.type(type)); statement.setString(2, tname); return query(conn, statement); } catch (Exception e) { MyBoxLog.error(e); return null; } } public Data2DDefinition queryUserTable(Connection conn, String tname) { if (conn == null || tname == null) { return null; } try (PreparedStatement statement = conn.prepareStatement(Query_UserTable)) { statement.setString(1, tname); return query(conn, statement); } catch (Exception e) { MyBoxLog.error(e); return null; } } public DataTable writeTable(Connection conn, DataTable table) { if (conn == null || table == null) { return null; } try { Data2DDefinition def = table.queryDefinition(conn); if (def != null) { table.setDataID(def.getDataID()); def = updateData(conn, table); } else { def = insertData(conn, table); } return def != null ? (DataTable) def : null; } catch (Exception e) { MyBoxLog.error(e); return null; } } public int deleteDefinition(Connection conn, long id) { if (conn == null || id < 0) { return -1; } try (PreparedStatement statement = conn.prepareStatement(DeleteID)) { statement.setLong(1, id); return statement.executeUpdate(); } catch (Exception e) { MyBoxLog.error(e); return -2; } } public int deleteFileDefinition(Connection conn, DataType type, File file) { if (conn == null || file == null) { return -1; } try (PreparedStatement statement = conn.prepareStatement(Delete_TypeFile)) { statement.setShort(1, Data2DDefinition.type(type)); statement.setString(2, file.getAbsolutePath()); return statement.executeUpdate(); } catch (Exception e) { MyBoxLog.error(e); return -1; } } public int deleteNameDefinition(Connection conn, DataType type, String name) { if (conn == null || name == null || name.isBlank()) { return -1; } try (PreparedStatement statement = conn.prepareStatement(Delete_TypeName)) { statement.setShort(1, Data2DDefinition.type(type)); statement.setString(2, name); return statement.executeUpdate(); } catch (Exception e) { MyBoxLog.error(e); return -1; } } public int deleteUserTable(Connection conn, String tname) { if (conn == null || tname == null) { return -1; } String fixedName = DerbyBase.fixedIdentifier(tname); try (PreparedStatement statement = conn.prepareStatement("DROP TABLE " + fixedName)) { if (statement.executeUpdate() < 0) { return -2; } } catch (Exception e) { // MyBoxLog.error(e); return -3; } try (PreparedStatement statement = conn.prepareStatement(Delete_UserTable)) { statement.setString(1, DerbyBase.savedName(fixedName)); return statement.executeUpdate(); } catch (Exception e) { // MyBoxLog.error(e); return -1; } } public int deleteClipboard(Connection conn, File file) { return deleteFileDefinition(conn, DataType.MyBoxClipboard, file); } public int clearInvalid(BaseTaskController taskController, Connection conn, boolean clearTmpTables) { int invalidCount = 0; try { recordInfo(taskController, message("Check") + ": " + tableName); invalidCount = clearInvalidFiles(taskController, conn); if (taskController != null && taskController.getTask() != null && taskController.getTask().isCancelled()) { return invalidCount; } invalidCount += clearInvalidTable(taskController, conn); if (taskController != null && taskController.getTask() != null && taskController.getTask().isCancelled()) { return invalidCount; } if (clearTmpTables) { invalidCount += clearTmpTables(taskController, conn); } } catch (Exception e) { recordError(taskController, e.toString() + "\n" + tableName); } return invalidCount; } public int clearInvalidFiles(BaseTaskController taskController, Connection conn) { int rowCount = 0, invalidCount = 0; try { String sql = Query_Files; recordInfo(taskController, sql); try (PreparedStatement query = conn.prepareStatement(sql); PreparedStatement delete = conn.prepareStatement(deleteStatement())) { conn.setAutoCommit(true); try (ResultSet results = query.executeQuery()) { conn.setAutoCommit(false); while (results.next()) { rowCount++; if (taskController != null && taskController.getTask() != null && taskController.getTask().isCancelled()) { return invalidCount; } Data2DDefinition data = readData(results); File file = data.getFile(); if (file == null || !file.exists() || !file.isFile()) { if (setDeleteStatement(conn, delete, data)) { delete.addBatch(); if (invalidCount > 0 && (invalidCount % Database.BatchSize == 0)) { int[] res = delete.executeBatch(); for (int r : res) { if (r > 0) { invalidCount += r; } } conn.commit(); delete.clearBatch(); } } if (file != null) { recordInfo(taskController, message("NotFound") + ": " + file.getAbsolutePath()); } } } } catch (Exception e) { recordError(taskController, e.toString() + "\n" + tableName); } int[] res = delete.executeBatch(); for (int r : res) { if (r > 0) { invalidCount += r; } } conn.commit(); } catch (Exception e) { recordError(taskController, e.toString() + "\n" + tableName); } recordInfo(taskController, message("Checked") + ": " + rowCount + " " + message("Invalid") + ": " + invalidCount); } catch (Exception e) { recordError(taskController, e.toString() + "\n" + tableName); } return invalidCount; } public int clearInvalidTable(BaseTaskController taskController, Connection conn) { int rowCount = 0, invalidCount = 0; try { String sql = "SELECT * FROM Data2D_Definition WHERE data_type =" + Data2D.type(Data2DDefinition.DataType.DatabaseTable); recordInfo(taskController, sql); conn.setAutoCommit(true); try (ResultSet results = conn.prepareStatement(sql).executeQuery(); PreparedStatement delete = conn.prepareStatement(deleteStatement())) { while (results.next()) { rowCount++; if (taskController != null && taskController.getTask() != null && taskController.getTask().isCancelled()) { return invalidCount; } Data2DDefinition data = readData(results); String tname = data.getSheet(); if (DerbyBase.exist(conn, tname) == 0) { if (setDeleteStatement(conn, delete, data)) { delete.addBatch(); if (invalidCount > 0 && (invalidCount % Database.BatchSize == 0)) { int[] res = delete.executeBatch(); for (int r : res) { if (r > 0) { invalidCount += r; } } conn.commit(); delete.clearBatch(); } } recordInfo(taskController, message("NotFound") + ": " + tname); } } int[] res = delete.executeBatch(); for (int r : res) { if (r > 0) { invalidCount += r; } } } catch (Exception e) { recordError(taskController, e.toString() + "\n" + tableName); } recordInfo(taskController, message("Checked") + ": " + rowCount + " " + message("Expired") + ": " + invalidCount); } catch (Exception e) { recordError(taskController, e.toString() + "\n" + tableName); } return invalidCount; } public int clearTmpTables(BaseTaskController taskController, Connection conn) { int rowCount = 0, invalidCount = 0; try { conn.setAutoCommit(true); String sql = "SELECT * FROM Data2D_Definition WHERE data_type=" + Data2D.type(Data2DDefinition.DataType.DatabaseTable) + " AND ( sheet like '" + TmpTable.TmpTablePrefix + "%'" + " OR sheet like '" + TmpTable.TmpTablePrefix.toLowerCase() + "%' )"; recordInfo(taskController, sql); try (ResultSet results = conn.prepareStatement(sql).executeQuery()) { while (results.next()) { rowCount++; if (taskController != null && taskController.getTask() != null && taskController.getTask().isCancelled()) { return invalidCount; } Data2DDefinition data = readData(results); String tname = data.getSheet(); deleteUserTable(conn, tname); recordInfo(taskController, message("Delete") + ": " + tname); } } catch (Exception e) { recordError(taskController, e.toString() + "\n" + tableName); } conn.commit(); recordInfo(taskController, message("Checked") + ": " + rowCount + " " + message("Expired") + ": " + invalidCount); } catch (Exception e) { recordError(taskController, e.toString() + "\n" + tableName); } return invalidCount; } }
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/table/TableNamedValues.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableNamedValues.java
package mara.mybox.db.table; import java.sql.Connection; import java.sql.PreparedStatement; import java.util.ArrayList; import java.util.List; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.NamedValues; import static mara.mybox.db.table.BaseTable.StringMaxLength; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2022-3-8 * @License Apache License Version 2.0 */ public class TableNamedValues extends BaseTable<NamedValues> { public TableNamedValues() { tableName = "Named_Values"; defineColumns(); } public TableNamedValues(boolean defineColumns) { tableName = "Named_Values"; if (defineColumns) { defineColumns(); } } public final TableNamedValues defineColumns() { addColumn(new ColumnDefinition("key_name", ColumnDefinition.ColumnType.String, true, true).setLength(StringMaxLength)); addColumn(new ColumnDefinition("value", ColumnDefinition.ColumnType.String, true, true).setLength(StringMaxLength)); addColumn(new ColumnDefinition("value_name", ColumnDefinition.ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("update_time", ColumnDefinition.ColumnType.Datetime, true)); orderColumns = "update_time DESC"; return this; } public static final String QueryKey = "SELECT * FROM Named_Values WHERE key_name=?"; @Override public boolean setValue(NamedValues data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(NamedValues data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(NamedValues data) { if (data == null) { return false; } return data.valid(); } public List<NamedValues> read(String key) { if (key == null || key.trim().isEmpty()) { return new ArrayList<>(); } try (Connection conn = DerbyBase.getConnection()) { conn.setReadOnly(true); return read(conn, key); } catch (Exception e) { MyBoxLog.error(e); return new ArrayList<>(); } } public List<NamedValues> read(Connection conn, String key) { if (conn == null || key == null || key.trim().isEmpty()) { return new ArrayList<>(); } try (PreparedStatement statement = conn.prepareStatement(QueryKey)) { statement.setString(1, key); return query(statement); } catch (Exception e) { MyBoxLog.error(e); return new ArrayList<>(); } } }
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/table/TableMediaList.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableMediaList.java
package mara.mybox.db.table; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.Date; import java.util.List; import static mara.mybox.controller.MediaPlayerController.MiaoGuaiGuaiBenBen; import mara.mybox.data.MediaInformation; import mara.mybox.data.MediaList; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColumnDefinition; import static mara.mybox.db.table.BaseTable.StringMaxLength; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.DateTools; /** * @Author Mara * @CreateDate 2019-8-21 * @License Apache License Version 2.0 */ public class TableMediaList extends BaseTable<MediaList> { public TableMediaList() { tableName = "media_list"; defineColumns(); } public TableMediaList(boolean defineColumns) { tableName = "media_list"; if (defineColumns) { defineColumns(); } } public final TableMediaList defineColumns() { addColumn(new ColumnDefinition("list_name", ColumnDefinition.ColumnType.String, true, true).setLength(StringMaxLength)); addColumn(new ColumnDefinition("address_index", ColumnDefinition.ColumnType.Integer, true, true)); addColumn(new ColumnDefinition("address", ColumnDefinition.ColumnType.String, true, true).setLength(StringMaxLength)); addColumn(new ColumnDefinition("modify_time", ColumnDefinition.ColumnType.Datetime, true)); return this; } @Override public boolean setValue(MediaList data, String column, Object value) { return false; } @Override public Object getValue(MediaList data, String column) { return null; } @Override public boolean valid(MediaList data) { return false; } public static List<MediaList> read() { try (Connection conn = DerbyBase.getConnection(); Statement statement = conn.createStatement()) { conn.setReadOnly(true); List<String> names = new ArrayList(); String sql = " SELECT DISTINCT list_name FROM media_list"; try (ResultSet results = statement.executeQuery(sql)) { while (results.next()) { names.add(results.getString("list_name")); } } names.remove(MiaoGuaiGuaiBenBen); List<MediaList> mediaLists = new ArrayList(); for (String name : names) { sql = " SELECT * FROM media_list WHERE list_name='" + DerbyBase.stringValue(name) + "' ORDER BY address_index"; List<String> addresses; try (ResultSet results = statement.executeQuery(sql)) { addresses = new ArrayList(); while (results.next()) { addresses.add(results.getString("address")); } } List<MediaInformation> medias = TableMedia.read(conn, addresses); MediaList mediaList = MediaList.create().setName(name).setMedias(medias); mediaLists.add(mediaList); } return mediaLists; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static List<String> names() { try (Connection conn = DerbyBase.getConnection(); Statement statement = conn.createStatement()) { conn.setReadOnly(true); List<String> names = new ArrayList(); String sql = " SELECT DISTINCT list_name FROM media_list"; try (ResultSet results = statement.executeQuery(sql)) { while (results.next()) { names.add(results.getString("list_name")); } } names.remove(MiaoGuaiGuaiBenBen); return names; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static MediaList read(String name) { if (name == null || name.trim().isEmpty()) { return null; } try (Connection conn = DerbyBase.getConnection(); Statement statement = conn.createStatement()) { conn.setReadOnly(true); String sql = " SELECT * FROM media_list WHERE list_name='" + DerbyBase.stringValue(name) + "' ORDER BY address_index"; List<String> addresses = new ArrayList(); try (ResultSet results = statement.executeQuery(sql)) { while (results.next()) { addresses.add(results.getString("address")); } } if (addresses.isEmpty()) { return null; } MediaList list = new MediaList(name); list.setMedias(TableMedia.read(conn, addresses)); return list; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static boolean set(String name, List<MediaInformation> medias) { if (medias == null || medias.isEmpty()) { return false; } try (Connection conn = DerbyBase.getConnection(); Statement statement = conn.createStatement()) { // TableMedia.write(statement, medias); String sql = "DELETE FROM media_list WHERE list_name='" + DerbyBase.stringValue(name) + "'"; statement.executeUpdate(sql); int index = 0; for (MediaInformation media : medias) { try { sql = "INSERT INTO media_list(list_name, address_index , address, modify_time) VALUES('" + DerbyBase.stringValue(name) + "', " + index + ", '" + DerbyBase.stringValue(media.getAddress()) + "', '" + DateTools.datetimeToString(new Date()) + "')"; statement.executeUpdate(sql); index++; } catch (Exception e) { MyBoxLog.error(e); // MyBoxLog.debug(e); } } return true; } catch (Exception e) { MyBoxLog.error(e); // MyBoxLog.debug(e); return false; } } public static boolean delete(String name) { try (Connection conn = DerbyBase.getConnection(); Statement statement = conn.createStatement()) { List<String> addresses = new ArrayList(); String sql = " SELECT * FROM media_list WHERE list_name='" + DerbyBase.stringValue(name) + "'"; try (ResultSet results = statement.executeQuery(sql)) { while (results.next()) { addresses.add(results.getString("address")); } } TableMedia.delete(conn, addresses); sql = "DELETE FROM media_list WHERE list_name='" + DerbyBase.stringValue(name) + "'"; statement.executeUpdate(sql); return true; } catch (Exception e) { MyBoxLog.error(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/table/TableQueryCondition.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableQueryCondition.java
package mara.mybox.db.table; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.Date; import java.util.List; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.QueryCondition; import mara.mybox.db.data.QueryCondition.DataOperation; import mara.mybox.db.data.StringValue; import static mara.mybox.db.table.BaseTable.StringMaxLength; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.DateTools; /** * @Author Mara * @CreateDate 2020-5-14 * @License Apache License Version 2.0 */ public class TableQueryCondition extends BaseTable<StringValue> { public TableQueryCondition() { tableName = "Query_Condition"; defineColumns(); } public TableQueryCondition(boolean defineColumns) { tableName = "Query_Condition"; if (defineColumns) { defineColumns(); } } public final TableQueryCondition defineColumns() { addColumn(new ColumnDefinition("qcid", ColumnDefinition.ColumnType.Long, true, true).setAuto(true)); addColumn(new ColumnDefinition("data_name", ColumnDefinition.ColumnType.String, true).setLength(StringMaxLength)); addColumn(new ColumnDefinition("operation", ColumnDefinition.ColumnType.Short, true)); // 1: query 2:chart 3:export 4:clear addColumn(new ColumnDefinition("title", ColumnDefinition.ColumnType.String, true).setLength(StringMaxLength)); addColumn(new ColumnDefinition("prefix", ColumnDefinition.ColumnType.String, true).setLength(StringMaxLength)); addColumn(new ColumnDefinition("qwhere", ColumnDefinition.ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("qorder", ColumnDefinition.ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("qfetch", ColumnDefinition.ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("top", ColumnDefinition.ColumnType.Integer, true)); addColumn(new ColumnDefinition("time", ColumnDefinition.ColumnType.Datetime, true)); return this; } public static final String QCidQeury = "SELECT * FROM Query_Condition WHERE qcid=?"; public static final String OperationQeury = " SELECT * FROM Query_Condition WHERE data_name=? AND operation=? ORDER BY time DESC"; public static final String Insert = "INSERT INTO Query_Condition " + " ( data_name, operation, title, prefix, qwhere, qorder, qfetch, top, time )" + "VALUES(?,?,?,?,?,?,?,?,?)"; public static final String Update = "UPDATE Query_Condition SET " + " data_name=?, operation=?, title=?, prefix=?, qwhere=?, qorder=?, qfetch=?, top=?, time=?" + " WHERE qcid=?"; public static final String Delete = "DELETE FROM Query_Condition WHERE qcid=?"; @Override public boolean setValue(StringValue data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(StringValue data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(StringValue data) { if (data == null) { return false; } return data.valid(); } public static List<QueryCondition> readList(String dataName, DataOperation dataOperation) { return readList(dataName, dataOperation, 0); } public static List<QueryCondition> readList(String dataName, DataOperation dataOperation, int max) { try (Connection conn = DerbyBase.getConnection()) { conn.setReadOnly(true); return read(conn, dataName, dataOperation, max); } catch (Exception e) { MyBoxLog.error(e); return new ArrayList(); } } public static List<QueryCondition> read(Connection conn, String dataName, DataOperation dataOperation, int max) { List<QueryCondition> conditions = new ArrayList(); int operation = QueryCondition.operation(dataOperation); if (dataName == null || conn == null || operation <= 0) { return conditions; } try (PreparedStatement statement = conn.prepareStatement(OperationQeury)) { statement.setMaxRows(max); statement.setString(1, dataName); statement.setShort(2, (short) operation); conn.setAutoCommit(true); try (ResultSet results = statement.executeQuery()) { while (results.next()) { QueryCondition condition = read(results); if (condition != null) { conditions.add(condition); } } } } catch (Exception e) { MyBoxLog.error(e); } return conditions; } public static QueryCondition read(ResultSet results) { if (results == null) { return null; } try { QueryCondition condition = new QueryCondition(); condition.setQcid(results.getLong("qcid")); condition.setDataName(results.getString("data_name")); condition.setOperation(results.getShort("operation")); condition.setTitle(results.getString("title")); condition.setPrefix(results.getString("prefix")); condition.setWhere(results.getString("qwhere")); condition.setOrder(results.getString("qorder")); condition.setFetch(results.getString("qfetch")); condition.setTop(results.getShort("top")); condition.setTime(results.getTimestamp("time").getTime()); return condition; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static QueryCondition read(long qcid) { if (qcid <= 0) { return null; } try (Connection conn = DerbyBase.getConnection()) { conn.setReadOnly(true); return read(conn, qcid); } catch (Exception e) { MyBoxLog.error(e); } return null; } public static QueryCondition read(Connection conn, long qcid) { if (conn == null || qcid < 0) { return null; } try (PreparedStatement statement = conn.prepareStatement(QCidQeury)) { return read(statement, qcid); } catch (Exception e) { MyBoxLog.error(e); } return null; } public static QueryCondition read(PreparedStatement statement, long qcid) { if (statement == null || qcid < 0) { return null; } try { statement.setMaxRows(1); statement.setLong(1, qcid); statement.getConnection().setAutoCommit(true); try (ResultSet results = statement.executeQuery()) { if (results.next()) { return read(results); } } } catch (Exception e) { MyBoxLog.error(e); } return null; } public static QueryCondition read(QueryCondition queryCondition) { if (queryCondition == null) { return null; } try (Connection conn = DerbyBase.getConnection()) { conn.setReadOnly(true); return read(conn, queryCondition); } catch (Exception e) { MyBoxLog.error(e); } return null; } public static QueryCondition read(Connection conn, QueryCondition queryCondition) { if (queryCondition == null) { return null; } try (Statement statement = conn.createStatement()) { statement.setMaxRows(1); String sql = "SELECT * FROM Query_Condition WHERE " + "data_name='" + DerbyBase.stringValue(queryCondition.getDataName()) + "' AND " + "operation=" + queryCondition.getOperation() + " AND " + "prefix='" + DerbyBase.stringValue(queryCondition.getPrefix()) + "' AND " + "top=" + queryCondition.getTop() + " AND " + (queryCondition.getWhere() == null ? " qwhere IS NULL " : " qwhere='" + DerbyBase.stringValue(queryCondition.getWhere()) + "'") + " AND " + (queryCondition.getOrder() == null ? " qorder IS NULL " : " qorder='" + DerbyBase.stringValue(queryCondition.getOrder()) + "'") + " AND " + (queryCondition.getFetch() == null ? " qfetch IS NULL " : " qfetch='" + DerbyBase.stringValue(queryCondition.getFetch()) + "'"); try (ResultSet results = statement.executeQuery(sql)) { if (results.next()) { return read(results); } } } catch (Exception e) { MyBoxLog.error(e); } return null; } public static boolean write(QueryCondition condition, boolean checkEqual) { if (condition == null) { return false; } try (Connection conn = DerbyBase.getConnection()) { return write(conn, condition, checkEqual); } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean write(Connection conn, QueryCondition condition, boolean checkEqual) { if (conn == null || condition == null || !condition.isValid()) { return false; } try { QueryCondition exist = null; if (condition.getQcid() > 0) { exist = read(conn, condition.getQcid()); } else if (checkEqual) { exist = read(conn, condition); if (exist != null) { condition.setQcid(exist.getQcid()); } } if (exist != null) { update(conn, condition); } else { insert(conn, condition); } return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean write(List<QueryCondition> conditions, boolean checkEqual) { if (conditions == null || conditions.isEmpty()) { return false; } try (Connection conn = DerbyBase.getConnection(); PreparedStatement idQuery = conn.prepareStatement(QCidQeury); PreparedStatement insert = conn.prepareStatement(Insert); PreparedStatement update = conn.prepareStatement(Update)) { conn.setAutoCommit(false); for (QueryCondition condition : conditions) { QueryCondition exist = null; if (condition.getQcid() > 0) { exist = read(idQuery, condition.getQcid()); } else if (checkEqual) { exist = read(conn, condition); if (exist != null) { condition.setQcid(exist.getQcid()); } } if (exist != null) { update(update, condition); } else { insert(insert, condition); } } conn.commit(); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean insert(QueryCondition condition) { if (condition == null) { return false; } try (Connection conn = DerbyBase.getConnection()) { return insert(conn, condition); } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean insert(Connection conn, QueryCondition condition) { if (conn == null || condition == null || !condition.isValid()) { return false; } try (PreparedStatement statement = conn.prepareStatement(Insert)) { return insert(statement, condition); } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean insert(PreparedStatement statement, QueryCondition condition) { if (statement == null || condition == null || !condition.isValid()) { return false; } try { statement.setString(1, condition.getDataName()); statement.setShort(2, (short) condition.getOperation()); statement.setString(3, condition.getTitle()); statement.setString(4, condition.getPrefix()); statement.setString(5, condition.getWhere()); statement.setString(6, condition.getOrder()); statement.setString(7, condition.getFetch()); statement.setInt(8, condition.getTop()); statement.setString(9, DateTools.datetimeToString(new Date())); return statement.executeUpdate() > 0; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean update(QueryCondition condition) { if (condition == null) { return false; } try (Connection conn = DerbyBase.getConnection()) { return update(conn, condition); } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean update(Connection conn, QueryCondition condition) { if (conn == null || condition == null || condition.getQcid() <= 0 || !condition.isValid()) { return false; } try (PreparedStatement statement = conn.prepareStatement(Update)) { return update(statement, condition); } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean update(PreparedStatement statement, QueryCondition condition) { if (statement == null || condition == null || condition.getQcid() <= 0 || !condition.isValid()) { return false; } try { statement.setString(1, condition.getDataName()); statement.setShort(2, (short) condition.getOperation()); statement.setString(3, condition.getTitle()); statement.setString(4, condition.getPrefix()); statement.setString(5, condition.getWhere()); statement.setString(6, condition.getOrder()); statement.setString(7, condition.getFetch()); statement.setInt(8, condition.getTop()); statement.setString(9, DateTools.datetimeToString(new Date())); statement.setLong(10, condition.getQcid()); return statement.executeUpdate() > 0; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean delete(QueryCondition condition) { if (condition == null || condition.getQcid() <= 0) { return false; } return delete(condition.getQcid()); } public static boolean delete(long qcid) { if (qcid <= 0) { return false; } try (Connection conn = DerbyBase.getConnection()) { return delete(conn, qcid); } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean delete(Connection conn, long qcid) { if (conn == null || qcid <= 0) { return false; } try (PreparedStatement statement = conn.prepareStatement(Delete)) { statement.setLong(1, qcid); return statement.executeUpdate() > 0; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean delete(List<QueryCondition> conditions) { if (conditions == null || conditions.isEmpty()) { return false; } try (Connection conn = DerbyBase.getConnection()) { conn.setAutoCommit(false); try (PreparedStatement statement = conn.prepareStatement(Delete)) { for (QueryCondition condition : conditions) { statement.setLong(1, condition.getQcid()); statement.executeUpdate(); } } conn.commit(); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/db/table/TableStringValues.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableStringValues.java
package mara.mybox.db.table; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import mara.mybox.db.DerbyBase; import static mara.mybox.db.DerbyBase.stringValue; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.StringValues; import static mara.mybox.db.table.BaseTable.StringMaxLength; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.DateTools; /** * @Author Mara * @CreateDate 2019-8-21 * @License Apache License Version 2.0 */ public class TableStringValues extends BaseTable<StringValues> { public TableStringValues() { tableName = "String_Values"; defineColumns(); } public TableStringValues(boolean defineColumns) { tableName = "String_Values"; if (defineColumns) { defineColumns(); } } public final TableStringValues defineColumns() { addColumn(new ColumnDefinition("key_name", ColumnDefinition.ColumnType.String, true, true).setLength(StringMaxLength)); addColumn(new ColumnDefinition("string_value", ColumnDefinition.ColumnType.String, true, true).setLength(StringMaxLength)); addColumn(new ColumnDefinition("create_time", ColumnDefinition.ColumnType.Datetime, true)); orderColumns = "create_time DESC"; return this; } @Override public boolean setValue(StringValues data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(StringValues data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(StringValues data) { if (data == null) { return false; } return data.valid(); } public static List<String> read(String name) { List<String> records = new ArrayList<>(); if (name == null || name.trim().isEmpty()) { return records; } try (Connection conn = DerbyBase.getConnection()) { conn.setReadOnly(true); return read(conn, name); } catch (Exception e) { MyBoxLog.error(e); } return records; } public static List<String> read(Connection conn, String name) { List<String> records = new ArrayList<>(); if (conn == null || name == null || name.trim().isEmpty()) { return records; } String sql = " SELECT * FROM String_Values WHERE key_name='" + stringValue(name) + "' ORDER BY create_time DESC"; try (Statement statement = conn.createStatement(); ResultSet results = statement.executeQuery(sql)) { while (results.next()) { records.add(results.getString("string_value")); } } catch (Exception e) { MyBoxLog.error(e); } return records; } public static List<StringValues> values(String name) { List<StringValues> records = new ArrayList<>(); if (name == null || name.trim().isEmpty()) { return records; } try (Connection conn = DerbyBase.getConnection()) { conn.setReadOnly(true); return values(conn, name); } catch (Exception e) { MyBoxLog.error(e); } return records; } public static List<StringValues> values(Connection conn, String name) { List<StringValues> records = new ArrayList<>(); if (conn == null || name == null || name.trim().isEmpty()) { return records; } String sql = " SELECT * FROM String_Values WHERE key_name='" + stringValue(name) + "' ORDER BY create_time DESC"; try (Statement statement = conn.createStatement(); ResultSet results = statement.executeQuery(sql)) { while (results.next()) { StringValues record = new StringValues(name, results.getString("string_value"), results.getTimestamp("create_time")); records.add(record); } } catch (Exception e) { MyBoxLog.error(e); } return records; } public static String last(String name) { if (name == null || name.trim().isEmpty()) { return null; } String value = null; try (Connection conn = DerbyBase.getConnection(); Statement statement = conn.createStatement()) { conn.setReadOnly(true); statement.setMaxRows(1); String sql = " SELECT * FROM String_Values WHERE key_name='" + stringValue(name) + "' ORDER BY create_time DESC"; try (ResultSet results = statement.executeQuery(sql)) { if (results.next()) { value = results.getString("string_value"); } } } catch (Exception e) { MyBoxLog.error(e); } return value; } public static List<String> max(String name, int max) { List<String> records = new ArrayList<>(); if (name == null || name.trim().isEmpty() || max < 0) { return records; } try (Connection conn = DerbyBase.getConnection()) { return max(conn, name, max); } catch (Exception e) { MyBoxLog.error(e); } return records; } public static List<String> max(Connection conn, String name, int max) { List<String> records = new ArrayList<>(); if (conn == null || name == null || name.trim().isEmpty() || max < 0) { return records; } try (Statement statement = conn.createStatement()) { String sql = " SELECT * FROM String_Values WHERE key_name='" + stringValue(name) + "' ORDER BY create_time DESC"; List<String> invalid = new ArrayList<>(); try (ResultSet results = statement.executeQuery(sql)) { while (results.next()) { String value = results.getString("string_value"); if (records.size() >= max) { invalid.add(value); } else { records.add(value); } } } for (String v : invalid) { sql = "DELETE FROM String_Values WHERE key_name='" + stringValue(name) + "' AND string_value='" + stringValue(v) + "'"; statement.executeUpdate(sql); } conn.commit(); } catch (Exception e) { MyBoxLog.error(e); } return records; } public static boolean add(String name, String value) { if (name == null || name.isBlank() || value == null || value.isBlank()) { return false; } try (Connection conn = DerbyBase.getConnection()) { conn.setAutoCommit(false); if (!add(conn, name, value)) { return false; } conn.commit(); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean add(Connection conn, String name, String value) { if (name == null || name.isBlank() || value == null || value.isBlank()) { return false; } try { String sql = "INSERT INTO String_Values (key_name, string_value , create_time) VALUES('" + stringValue(name) + "', '" + stringValue(value) + "', '" + DateTools.datetimeToString(new Date()) + "')"; conn.createStatement().executeUpdate(sql); return true; } catch (Exception e) { try { String sql = "UPDATE String_Values SET create_time='" + DateTools.datetimeToString(new Date()) + "' WHERE " + "key_name='" + stringValue(name) + "' AND string_value='" + stringValue(value) + "'"; conn.createStatement().executeUpdate(sql); return true; } catch (Exception ex) { MyBoxLog.error(ex); return false; } } } public static boolean add(String name, List<String> values) { if (values == null || values.isEmpty()) { return false; } try (Connection conn = DerbyBase.getConnection()) { return add(conn, name, values); } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean add(Connection conn, String name, List<String> values) { if (conn == null || values == null || values.isEmpty()) { return false; } try { conn.setAutoCommit(false); for (int i = 0; i < values.size(); i++) { add(conn, name, values.get(i)); } conn.commit(); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean add(Map<String, String> nameValues) { if (nameValues == null || nameValues.isEmpty()) { return false; } try (Connection conn = DerbyBase.getConnection()) { conn.setAutoCommit(false); for (String name : nameValues.keySet()) { String value = nameValues.get(name); add(conn, name, value); } conn.commit(); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean delete(String name, String value) { if (name == null || name.trim().isEmpty() || value == null || value.trim().isEmpty()) { return false; } try (Connection conn = DerbyBase.getConnection(); Statement statement = conn.createStatement()) { String sql = "DELETE FROM String_Values WHERE key_name='" + stringValue(name) + "' AND string_value='" + stringValue(value) + "'"; statement.executeUpdate(sql); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean clear(String name) { try (Connection conn = DerbyBase.getConnection(); Statement statement = conn.createStatement()) { String sql = "DELETE FROM String_Values WHERE key_name='" + stringValue(name) + "'"; statement.executeUpdate(sql); return true; } catch (Exception e) { MyBoxLog.error(e); // MyBoxLog.debug(e); return false; } } public static int size(String name) { if (name == null || name.trim().isEmpty()) { return -1; } try (Connection conn = DerbyBase.getConnection()) { conn.setReadOnly(true); return size(conn, name); } catch (Exception e) { MyBoxLog.error(e); } return -1; } public static int size(Connection conn, String name) { if (conn == null || name == null || name.trim().isEmpty()) { return -1; } String sql = " SELECT count(*) FROM String_Values WHERE key_name='" + stringValue(name) + "'"; return DerbyBase.size(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/table/TableData2DColumn.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableData2DColumn.java
package mara.mybox.db.table; import java.io.File; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.List; import mara.mybox.data2d.Data2D; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.Data2DColumn; import mara.mybox.db.data.Data2DDefinition; import static mara.mybox.db.table.BaseTable.StringMaxLength; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2021-1-23 * @License Apache License Version 2.0 */ public class TableData2DColumn extends BaseTable<Data2DColumn> { protected TableData2DDefinition tableData2DDefinition; public TableData2DColumn() { tableName = "Data2D_Column"; defineColumns(); } public TableData2DColumn(boolean defineColumns) { tableName = "Data2D_Column"; if (defineColumns) { defineColumns(); } } public final TableData2DColumn defineColumns() { addColumn(new Data2DColumn("d2cid", ColumnType.Long, true, true).setAuto(true)); addColumn(new Data2DColumn("d2id", ColumnType.Long, true) .setReferName("Data2D_Column_d2id_fk").setReferTable("Data2D_Definition").setReferColumn("d2did") .setOnDelete(Data2DColumn.OnDelete.Cascade)); addColumn(new Data2DColumn("column_type", ColumnType.Short, true)); addColumn(new Data2DColumn("column_name", ColumnType.String, true).setLength(StringMaxLength)); addColumn(new Data2DColumn("label", ColumnType.String).setLength(StringMaxLength)); addColumn(new Data2DColumn("index", ColumnType.Integer)); addColumn(new Data2DColumn("length", ColumnType.Integer)); addColumn(new Data2DColumn("width", ColumnType.Integer)); addColumn(new Data2DColumn("scale", ColumnType.Integer)); addColumn(new Data2DColumn("color", ColumnType.Color).setLength(16)); addColumn(new Data2DColumn("is_primary", ColumnType.Boolean)); addColumn(new Data2DColumn("is_auto", ColumnType.Boolean)); addColumn(new Data2DColumn("not_null", ColumnType.Boolean)); addColumn(new Data2DColumn("editable", ColumnType.Boolean)); addColumn(new Data2DColumn("on_delete", ColumnType.Short)); addColumn(new Data2DColumn("on_update", ColumnType.Short)); addColumn(new Data2DColumn("fix_year", ColumnType.Boolean)); addColumn(new Data2DColumn("century", ColumnType.Integer)); addColumn(new Data2DColumn("format", ColumnType.String).setLength(StringMaxLength)); addColumn(new Data2DColumn("default_value", ColumnType.String).setLength(StringMaxLength)); addColumn(new Data2DColumn("max_value", ColumnType.String).setLength(StringMaxLength)); addColumn(new Data2DColumn("min_value", ColumnType.String).setLength(StringMaxLength)); addColumn(new Data2DColumn("foreign_name", ColumnType.String).setLength(StringMaxLength)); addColumn(new Data2DColumn("foreign_table", ColumnType.String).setLength(StringMaxLength)); addColumn(new Data2DColumn("foreign_column", ColumnType.String).setLength(StringMaxLength)); addColumn(new Data2DColumn("description", ColumnType.String).setLength(StringMaxLength)); return this; } /* View */ public static final String CreateView = " CREATE VIEW Data2D_Column_View AS " + " SELECT Data2D_Column.*, Data2D_Definition.* " + " FROM Data2D_Column JOIN Data2D_Definition ON Data2D_Column.d2id=Data2D_Definition.d2did"; public static final String ClearData = "DELETE FROM Data2D_Column WHERE d2id=?"; public static final String QueryData = "SELECT * FROM Data2D_Column WHERE d2id=? ORDER BY index"; /* local methods */ @Override public Object readForeignValue(ResultSet results, String column) { if (results == null || column == null) { return null; } try { if ("d2id".equals(column) && results.findColumn("d2did") > 0) { return getTableData2DDefinition().readData(results); } } catch (Exception e) { } return null; } @Override public boolean setForeignValue(Data2DColumn data, String column, Object value) { if (data == null || column == null || value == null) { return true; } if ("d2id".equals(column) && value instanceof Data2DDefinition) { data.setData2DDefinition((Data2DDefinition) value); } return true; } @Override public boolean setValue(Data2DColumn data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(Data2DColumn data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(Data2DColumn data) { if (data == null) { return false; } return data.valid(); } public List<Data2DColumn> read(long d2id) { if (d2id < 0) { return null; } try (Connection conn = DerbyBase.getConnection();) { return read(conn, d2id); } catch (Exception e) { MyBoxLog.error(e); return null; } } public List<Data2DColumn> read(Connection conn, long d2id) { if (conn == null || d2id < 0) { return null; } try { String sql = "SELECT * FROM Data2D_Column WHERE d2id=" + d2id + " ORDER BY index"; return query(conn, sql); } catch (Exception e) { MyBoxLog.error(e); return null; } } public List<Data2DColumn> queryFile(Connection conn, Data2DDefinition.DataType type, File file) { if (file == null) { return null; } try { Data2DDefinition dataDefinition = getTableData2DDefinition().queryFile(conn, type, file); if (dataDefinition == null) { return null; } return read(conn, dataDefinition.getDataID()); } catch (Exception e) { MyBoxLog.error(e); return null; } } public boolean clear(Data2D data) { if (data == null) { return false; } try (Connection conn = DerbyBase.getConnection()) { if (data.getDataID() >= 0) { return clearColumns(conn, data.getDataID()); } else { return clearFileColumns(conn, data.getType(), data.getFile()); } } catch (Exception e) { MyBoxLog.error(e); return false; } } public boolean clearFileColumns(Data2DDefinition.DataType type, File file) { if (file == null) { return false; } try (Connection conn = DerbyBase.getConnection();) { return TableData2DColumn.this.clearFileColumns(conn, type, file); } catch (Exception e) { MyBoxLog.error(e); return false; } } public boolean clearFileColumns(Connection conn, Data2DDefinition.DataType type, File file) { if (conn == null || file == null) { return false; } Data2DDefinition dataDefinition = getTableData2DDefinition().queryFile(conn, type, file); if (dataDefinition == null) { return false; } return clearColumns(conn, dataDefinition.getDataID()); } public boolean clearColumns(Connection conn, long d2id) { if (conn == null || d2id < 0) { return false; } try (PreparedStatement statement = conn.prepareStatement(ClearData)) { statement.setLong(1, d2id); statement.executeUpdate(); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public boolean save(Connection conn, long dataid, List<Data2DColumn> columns) { if (dataid < 0 || columns == null) { return false; } try { boolean ac = conn.getAutoCommit(); conn.setAutoCommit(false); List<Data2DColumn> existed = read(conn, dataid); conn.setAutoCommit(true); if (existed != null && !existed.isEmpty()) { for (Data2DColumn ecolumn : existed) { boolean keep = false; for (Data2DColumn icolumn : columns) { if (ecolumn.getColumnID() == icolumn.getColumnID()) { keep = true; break; } } if (!keep) { deleteData(conn, ecolumn); // MyBoxLog.console("delete:" + ecolumn.getColumnName() + " " + ecolumn.getType()); } } conn.commit(); } for (int i = 0; i < columns.size(); i++) { Data2DColumn column = columns.get(i); column.setDataID(dataid); column.setIndex(i); if (column.getColumnID() >= 0) { column = updateData(conn, column); } else { column = insertData(conn, column); } if (column == null) { MyBoxLog.error("Failed"); return false; } columns.set(i, column); // MyBoxLog.console(i + " " + column.getColumnName() + " " + column.getType()); } conn.commit(); conn.setAutoCommit(ac); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } /* get/set */ public TableData2DDefinition getTableData2DDefinition() { if (tableData2DDefinition == null) { tableData2DDefinition = new TableData2DDefinition(); } return tableData2DDefinition; } public void setTableData2DDefinition(TableData2DDefinition tableData2DDefinition) { this.tableData2DDefinition = tableData2DDefinition; } }
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/table/TableImageEditHistory.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableImageEditHistory.java
package mara.mybox.db.table; 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 mara.mybox.controller.BaseTaskController; import mara.mybox.db.Database; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.ImageEditHistory; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import static mara.mybox.fxml.WindowTools.recordError; import static mara.mybox.fxml.WindowTools.recordInfo; import static mara.mybox.fxml.WindowTools.taskError; import static mara.mybox.fxml.WindowTools.taskInfo; import mara.mybox.tools.FileDeleteTools; import mara.mybox.value.AppPaths; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2018-10-15 9:31:28 * @Version 1.0 * @Description * @License Apache License Version 2.0 */ public class TableImageEditHistory extends BaseTable<ImageEditHistory> { public TableImageEditHistory() { tableName = "Image_Edit_History"; defineColumns(); } public TableImageEditHistory(boolean defineColumns) { tableName = "Image_Edit_History"; if (defineColumns) { defineColumns(); } } public final TableImageEditHistory defineColumns() { addColumn(new ColumnDefinition("iehid", ColumnType.Long, true, true).setAuto(true)); addColumn(new ColumnDefinition("image_location", ColumnType.File, true).setLength(FilenameMaxLength)); addColumn(new ColumnDefinition("history_location", ColumnType.File, true).setLength(FilenameMaxLength)); addColumn(new ColumnDefinition("thumbnail_file", ColumnType.File).setLength(FilenameMaxLength)); addColumn(new ColumnDefinition("operation_time", ColumnType.Datetime, true)); addColumn(new ColumnDefinition("update_type", ColumnType.String).setLength(128)); addColumn(new ColumnDefinition("object_type", ColumnType.String).setLength(128)); addColumn(new ColumnDefinition("op_type", ColumnType.String).setLength(128)); addColumn(new ColumnDefinition("scope_type", ColumnType.String).setLength(128)); addColumn(new ColumnDefinition("scope_name", ColumnType.String).setLength(StringMaxLength)); orderColumns = "operation_time DESC"; return this; } public static final String QueryPath = "SELECT * FROM Image_Edit_History WHERE image_location=? "; public static final String QueryHistories = "SELECT * FROM Image_Edit_History WHERE image_location=? ORDER BY operation_time DESC"; public static final String DeleteHistories = "DELETE FROM Image_Edit_History WHERE image_location=?"; public static final String QueryFile = "SELECT * FROM Image_Edit_History WHERE history_location=? OR thumbnail_file=?"; @Override public boolean setValue(ImageEditHistory data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(ImageEditHistory data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(ImageEditHistory data) { if (data == null) { return false; } return data.valid(); } public File path(File file) { if (file == null || !file.exists()) { return null; } try (Connection conn = DerbyBase.getConnection()) { return path(conn, file); } catch (Exception e) { return null; } } public File path(Connection conn, File file) { if (conn == null || file == null || !file.exists()) { return null; } try (PreparedStatement query = conn.prepareStatement(QueryPath)) { query.setString(1, file.getAbsolutePath()); ImageEditHistory his = query(conn, query); if (his != null) { File hisFile = his.getHistoryFile(); if (hisFile != null && hisFile.exists()) { return hisFile.getParentFile(); } } } catch (Exception e) { MyBoxLog.error(e); } return null; } public List<ImageEditHistory> read(File srcFile) { if (srcFile == null || !srcFile.exists()) { return null; } try (Connection conn = DerbyBase.getConnection()) { return read(conn, srcFile); } catch (Exception e) { MyBoxLog.error(e); } return null; } public List<ImageEditHistory> read(Connection conn, File srcFile) { List<ImageEditHistory> records = new ArrayList<>(); if (conn == null || srcFile == null || !srcFile.exists()) { return records; } try (PreparedStatement statement = conn.prepareStatement(QueryHistories)) { int max = UserConfig.getInt(conn, "MaxImageHistories", ImageEditHistory.Default_Max_Histories); if (max <= 0) { max = ImageEditHistory.Default_Max_Histories; UserConfig.setInt(conn, "MaxImageHistories", ImageEditHistory.Default_Max_Histories); } conn.setAutoCommit(true); statement.setMaxRows(max); statement.setString(1, srcFile.getAbsolutePath()); try (ResultSet results = statement.executeQuery()) { while (results.next()) { ImageEditHistory his = readData(results); if (his == null) { continue; } if (!his.valid() || records.size() >= max) { deleteData(conn, his); } else { records.add(his); } } } } catch (Exception e) { MyBoxLog.error(e); } return records; } public ImageEditHistory index(Connection conn, File srcFile, int index) { List<ImageEditHistory> records = read(conn, srcFile); if (records == null || srcFile == null || !srcFile.exists()) { return null; } int size = records.size(); if (index >= 0 && index < size) { return records.get(index); } else { return null; } } public int count(Connection conn, File file) { List<ImageEditHistory> records = read(conn, file); if (records == null) { return -1; } else { return records.size(); } } @Override public int deleteData(ImageEditHistory data) { if (data == null) { return 0; } try (Connection conn = DerbyBase.getConnection()) { return deleteData(conn, data); } catch (Exception e) { MyBoxLog.error(e); return 0; } } @Override public int deleteData(Connection conn, ImageEditHistory data) { if (data == null) { return 0; } int count = super.deleteData(conn, data); if (count > 0) { FileDeleteTools.delete(data.getHistoryFile()); FileDeleteTools.delete(data.getThumbnailFile()); } return count; } public long clearHistories(FxTask task, File srcFile) { long count = 0; if (srcFile == null) { return count; } try (Connection conn = DerbyBase.getConnection()) { List<String> files = new ArrayList<>(); files.add(srcFile.getAbsolutePath()); return clearHistories(task, conn, files); } catch (Exception e) { MyBoxLog.error(e); return count; } } public long clearHistories(FxTask task, Connection conn, List<String> files) { long count = 0; if (conn == null || files == null || files.isEmpty()) { return count; } taskInfo(task, QueryHistories); try (PreparedStatement statement = conn.prepareStatement(QueryHistories)) { conn.setAutoCommit(true); for (String file : files) { if (task != null && task.isCancelled()) { return count; } taskInfo(task, message("Check") + ": " + file); statement.setString(1, file); try (ResultSet results = statement.executeQuery()) { while (results.next()) { if (task != null && task.isCancelled()) { return count; } ImageEditHistory data = readData(results); File hisFile = data.getHistoryFile(); if (hisFile != null) { taskInfo(task, message("Delete") + ": " + hisFile); FileDeleteTools.delete(hisFile); } File thumbFile = data.getThumbnailFile(); if (thumbFile != null) { taskInfo(task, message("Delete") + ": " + thumbFile); FileDeleteTools.delete(thumbFile); } } } catch (Exception e) { taskError(task, e.toString() + "\n" + tableName); } } } catch (Exception e) { taskError(task, e.toString() + "\n" + tableName); } taskInfo(task, DeleteHistories); if (task != null && task.isCancelled()) { return count; } try (PreparedStatement statement = conn.prepareStatement(DeleteHistories)) { conn.setAutoCommit(true); for (String file : files) { if (task != null && task.isCancelled()) { return count; } taskInfo(task, message("Clear") + ": " + file); statement.setString(1, file); statement.executeUpdate(); } } catch (Exception e) { taskError(task, e.toString() + "\n" + tableName); } return count; } public int clearAll() { try (Connection conn = DerbyBase.getConnection(); Statement statement = conn.createStatement()) { String sql = " SELECT history_location FROM Image_Edit_History"; try (ResultSet results = statement.executeQuery(sql)) { while (results.next()) { FileDeleteTools.delete(results.getString("history_location")); } } String imageHistoriesPath = AppPaths.getImageHisPath(); File path = new File(imageHistoriesPath); if (path.exists()) { File[] files = path.listFiles(); if (files != null) { for (File f : files) { FileDeleteTools.delete(f); } } } sql = "DELETE FROM Image_Edit_History"; return statement.executeUpdate(sql); } catch (Exception e) { MyBoxLog.error(e); return -1; } } public int clearInvalid(BaseTaskController taskController, Connection conn) { int count = clearInvalidRows(taskController, conn); return count + clearInvalidFiles(taskController, conn); } public int clearInvalidRows(BaseTaskController taskController, Connection conn) { int rowCount = 0, invalidCount = 0; try { recordInfo(taskController, message("Check") + ": " + tableName); try (PreparedStatement query = conn.prepareStatement(queryAllStatement()); PreparedStatement delete = conn.prepareStatement(deleteStatement())) { conn.setAutoCommit(true); try (ResultSet results = query.executeQuery()) { conn.setAutoCommit(false); while (results.next()) { rowCount++; if (taskController != null && taskController.getTask() != null && taskController.getTask().isCancelled()) { return invalidCount; } ImageEditHistory data = readData(results); if (!ImageEditHistory.valid(data)) { File hisFile = data.getHistoryFile(); if (hisFile != null) { recordInfo(taskController, message("Delete") + ": " + hisFile); FileDeleteTools.delete(hisFile); } File thumbFile = data.getThumbnailFile(); if (thumbFile != null) { recordInfo(taskController, message("Delete") + ": " + thumbFile); FileDeleteTools.delete(thumbFile); } if (setDeleteStatement(conn, delete, data)) { delete.addBatch(); if (invalidCount > 0 && (invalidCount % Database.BatchSize == 0)) { int[] res = delete.executeBatch(); for (int r : res) { if (r > 0) { invalidCount += r; } } conn.commit(); delete.clearBatch(); } } } } } catch (Exception e) { recordError(taskController, e.toString() + "\n" + tableName); } int[] res = delete.executeBatch(); for (int r : res) { if (r > 0) { invalidCount += r; } } conn.commit(); } catch (Exception e) { recordError(taskController, e.toString() + "\n" + tableName); } conn.setAutoCommit(true); } catch (Exception e) { recordError(taskController, e.toString() + "\n" + tableName); } recordInfo(taskController, message("Checked") + ": " + rowCount + " " + message("Expired") + ": " + invalidCount); return invalidCount; } public int clearInvalidFiles(BaseTaskController taskController, Connection conn) { int rowCount = 0, invalidCount = 0; try { String ihRootpath = AppPaths.getImageHisPath(); recordInfo(taskController, message("Check") + ": " + ihRootpath); String[] ihPaths = new File(ihRootpath).list(); if (ihPaths == null || ihPaths.length == 0) { return invalidCount; } try (PreparedStatement query = conn.prepareStatement(QueryFile)) { conn.setAutoCommit(true); for (String pathname : ihPaths) { if (taskController != null && taskController.getTask() != null && taskController.getTask().isCancelled()) { return invalidCount; } String path = ihRootpath + File.separator + pathname; String[] names = new File(path).list(); if (names == null || names.length == 0) { try { new File(path).delete(); recordInfo(taskController, message("Delete") + ": " + path); } catch (Exception ex) { } continue; } for (String name : names) { rowCount++; if (taskController != null && taskController.getTask() != null && taskController.getTask().isCancelled()) { return invalidCount; } String file = path + File.separator + name; query.setString(1, file); query.setString(2, file); try (ResultSet results = query.executeQuery()) { if (!results.next()) { invalidCount++; if (FileDeleteTools.delete(file)) { recordInfo(taskController, message("Delete") + ": " + file); } } } catch (Exception e) { recordError(taskController, e.toString() + "\n" + file); } } names = new File(path).list(); if (names == null || names.length == 0) { try { new File(path).delete(); recordInfo(taskController, message("Delete") + ": " + path); } catch (Exception ex) { } } } } catch (Exception ex) { recordError(taskController, ex.toString() + "\n" + tableName); } } catch (Exception exx) { recordError(taskController, exx.toString() + "\n" + tableName); } recordInfo(taskController, message("Checked") + ": " + rowCount + " " + message("Expired") + ": " + invalidCount); return invalidCount; } }
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/table/BaseTableTools.java
alpha/MyBox/src/main/java/mara/mybox/db/table/BaseTableTools.java
package mara.mybox.db.table; import java.sql.Connection; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import mara.mybox.db.DerbyBase; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2018-10-15 9:31:28 * @License Apache License Version 2.0 */ public class BaseTableTools { public static Map<String, BaseTable> internalTables() { Map<String, BaseTable> tables = new LinkedHashMap<>() { { put("ALARM_CLOCK", new TableAlarmClock()); put("COLOR", new TableColor()); put("COLOR_PALETTE_NAME", new TableColorPaletteName()); put("COLOR_PALETTE", new TableColorPalette()); put("CONVOLUTION_KERNEL", new TableConvolutionKernel()); put("DATA2D_DEFINITION", new TableData2DDefinition()); put("DATA2D_COLUMN", new TableData2DColumn()); put("DATA2D_STYLE", new TableData2DStyle()); put("FILE_BACKUP", new TableFileBackup()); put("FLOAT_MATRIX", new TableFloatMatrix()); put("IMAGE_CLIPBOARD", new TableImageClipboard()); put("IMAGE_EDIT_HISTORY", new TableImageEditHistory()); put("MEDIA", new TableMedia()); put("MEDIA_LIST", new TableMediaList()); put("MYBOX_LOG", new TableMyBoxLog()); put("NAMED_VALUES", new TableNamedValues()); put("NODE_DATA_COLUMN", new TableNodeDataColumn()); put("NODE_DATA_COLUMN_NODE_TAG", new TableDataNodeTag(new TableNodeDataColumn())); put("NODE_DATA_COLUMN_TAG", new TableDataTag(new TableNodeDataColumn())); put("NODE_GEOGRAPHY_CODE", new TableNodeGeographyCode()); put("NODE_GEOGRAPHY_CODE_NODE_TAG", new TableDataNodeTag(new TableNodeGeographyCode())); put("NODE_GEOGRAPHY_CODE_TAG", new TableDataTag(new TableNodeGeographyCode())); put("NODE_HTML", new TableNodeHtml()); put("NODE_HTML_NODE_TAG", new TableDataNodeTag(new TableNodeHtml())); put("NODE_HTML_TAG", new TableDataTag(new TableNodeHtml())); put("NODE_IMAGE_SCOPE", new TableNodeImageScope()); put("NODE_IMAGE_SCOPE_NODE_TAG", new TableDataNodeTag(new TableNodeImageScope())); put("NODE_IMAGE_SCOPE_TAG", new TableDataTag(new TableNodeImageScope())); put("NODE_JEXL", new TableNodeJEXL()); put("NODE_JEXL_NODE_TAG", new TableDataNodeTag(new TableNodeJEXL())); put("NODE_JEXL_TAG", new TableDataTag(new TableNodeJEXL())); put("NODE_JSHELL", new TableNodeJShell()); put("NODE_JSHELL_NODE_TAG", new TableDataNodeTag(new TableNodeJShell())); put("NODE_JSHELL_TAG", new TableDataTag(new TableNodeJShell())); put("NODE_JAVASCRIPT", new TableNodeJavaScript()); put("NODE_JAVASCRIPT_NODE_TAG", new TableDataNodeTag(new TableNodeJavaScript())); put("NODE_JAVASCRIPT_TAG", new TableDataTag(new TableNodeJavaScript())); put("NODE_MACRO", new TableNodeMacro()); put("NODE_MACRO_NODE_TAG", new TableDataNodeTag(new TableNodeMacro())); put("NODE_MACRO_TAG", new TableDataTag(new TableNodeMacro())); put("NODE_MATH_FUNCTION", new TableNodeMathFunction()); put("NODE_MATH_FUNCTION_NODE_TAG", new TableDataNodeTag(new TableNodeMathFunction())); put("NODE_MATH_FUNCTION_TAG", new TableDataTag(new TableNodeMathFunction())); put("NODE_ROW_EXPRESSION", new TableNodeRowExpression()); put("NODE_ROW_EXPRESSION_NODE_TAG", new TableDataNodeTag(new TableNodeRowExpression())); put("NODE_ROW_EXPRESSION_TAG", new TableDataTag(new TableNodeRowExpression())); put("NODE_SQL", new TableNodeSQL()); put("NODE_SQL_NODE_TAG", new TableDataNodeTag(new TableNodeSQL())); put("NODE_SQL_TAG", new TableDataTag(new TableNodeSQL())); put("NODE_TEXT", new TableNodeText()); put("NODE_TEXT_NODE_TAG", new TableDataNodeTag(new TableNodeText())); put("NODE_TEXT_TAG", new TableDataTag(new TableNodeText())); put("NODE_WEB_FAVORITE", new TableNodeWebFavorite()); put("NODE_WEB_FAVORITE_NODE_TAG", new TableDataNodeTag(new TableNodeWebFavorite())); put("NODE_WEB_FAVORITE_TAG", new TableDataTag(new TableNodeWebFavorite())); put("PATH_CONNECTION", new TablePathConnection()); put("QUERY_CONDITION", new TableQueryCondition()); put("STRING_VALUE", new TableStringValue()); put("STRING_VALUES", new TableStringValues()); put("SYSTEM_CONF", new TableSystemConf()); put("TEXT_CLIPBOARD", new TableTextClipboard()); put("USER_CONF", new TableUserConf()); put("VISIT_HISTORY", new TableVisitHistory()); put("WEB_HISTORY", new TableWebHistory()); } }; return tables; } public static List<String> internalTableNames() { List<String> names = new ArrayList<>(); for (String name : internalTables().keySet()) { names.add(name); } return names; } public static boolean isInternalTable(String name) { if (name == null) { return false; } return internalTables().containsKey(name.toUpperCase()); } public static String allTableNames() { try (Connection conn = DerbyBase.getConnection()) { List<String> tables = DerbyBase.allTables(conn); StringBuilder s = new StringBuilder(); for (String referredName : tables) { if (!s.isEmpty()) { s.append(", "); } s.append("\"").append(referredName.toUpperCase()).append("\""); } return s.toString(); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static List<String> userTables() { List<String> userTables = new ArrayList<>(); try (Connection conn = DerbyBase.getConnection()) { List<String> allTables = DerbyBase.allTables(conn); for (String name : allTables) { if (!isInternalTable(name)) { userTables.add(name); } } } catch (Exception e) { MyBoxLog.console(e); } return userTables; } }
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/table/TableSystemConf.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableSystemConf.java
package mara.mybox.db.table; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Map; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.StringValue; import static mara.mybox.db.table.BaseTable.StringMaxLength; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.ConfigTools; import mara.mybox.value.AppValues; /** * @Author Mara * @CreateDate 2018-10-15 9:31:28 * @License Apache License Version 2.0 */ public class TableSystemConf extends BaseTable<StringValue> { public TableSystemConf() { tableName = "System_Conf"; defineColumns(); } public TableSystemConf(boolean defineColumns) { tableName = "System_Conf"; if (defineColumns) { defineColumns(); } } public final TableSystemConf defineColumns() { addColumn(new ColumnDefinition("key_name", ColumnDefinition.ColumnType.String, true, true).setLength(StringMaxLength)); addColumn(new ColumnDefinition("string_value", ColumnDefinition.ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("int_Value", ColumnDefinition.ColumnType.Integer)); return this; } final static String QueryString = "SELECT string_Value FROM System_Conf WHERE key_Name=?"; final static String QueryInt = " SELECT int_Value FROM System_Conf WHERE key_Name=?"; final static String InsertInt = "INSERT INTO System_Conf (key_Name, int_Value) VALUES(?, ? )"; final static String InsertString = "INSERT INTO System_Conf(key_Name, string_Value) VALUES(?, ? )"; final static String UpdateString = "UPDATE System_Conf SET string_Value=? WHERE key_Name=?"; final static String UpdateInt = "UPDATE System_Conf SET int_Value=? WHERE key_Name=?"; final static String Delete = "DELETE FROM System_Conf WHERE key_Name=?"; final static String DeleteLike = "DELETE FROM System_Conf WHERE key_Name like ?"; @Override public boolean setValue(StringValue data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(StringValue data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(StringValue data) { if (data == null) { return false; } return data.valid(); } @Override public boolean createTable(Connection conn) { try { if (!super.createTable(conn)) { return false; } Map<String, String> values = ConfigTools.readValues(); if (values == null || values.isEmpty()) { return false; } try (PreparedStatement intStatement = conn.prepareStatement(InsertInt); PreparedStatement stringStatement = conn.prepareStatement(InsertString)) { for (String key : values.keySet()) { String value = values.get(key); switch (value.toLowerCase()) { case "true": intStatement.setString(1, key); intStatement.setInt(2, 1); intStatement.executeUpdate(); break; case "false": intStatement.setString(1, key); intStatement.setInt(2, 0); intStatement.executeUpdate(); break; default: { try { int v = Integer.parseInt(value); intStatement.setString(1, key); intStatement.setInt(2, v); intStatement.executeUpdate(); } catch (Exception e) { stringStatement.setString(1, key); stringStatement.setString(2, value); stringStatement.executeUpdate(); } } } } } return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static String readString(String keyName, String defaultValue) { try (Connection conn = DerbyBase.getConnection()) { return readString(conn, keyName, defaultValue); } catch (Exception e) { MyBoxLog.error(e); return defaultValue; } } public static String readString(Connection conn, String keyName, String defaultValue) { if (conn == null || keyName == null) { return null; } try (PreparedStatement queryStatement = conn.prepareStatement(QueryString)) { queryStatement.setMaxRows(1); queryStatement.setString(1, keyName); conn.setAutoCommit(true); try (ResultSet resultSet = queryStatement.executeQuery()) { if (resultSet.next()) { String value = resultSet.getString(1); if (value == null) { delete(conn, keyName); } else { return value; } } } if (defaultValue != null) { try (PreparedStatement insert = conn.prepareStatement(InsertString)) { insert.setString(1, keyName); insert.setString(2, defaultValue); insert.executeUpdate(); } } } catch (Exception e) { MyBoxLog.error(e); } return defaultValue; } public static String readString(Connection conn, String keyName) { return readString(conn, keyName, null); } public static int readInt(String keyName, int defaultValue) { try (Connection conn = DerbyBase.getConnection()) { int exist = readInt(conn, keyName); if (exist != AppValues.InvalidInteger) { return exist; } else { try (PreparedStatement insert = conn.prepareStatement(UpdateInt)) { insert.setInt(1, defaultValue); insert.setString(2, keyName); insert.executeUpdate(); } } } catch (Exception e) { // MyBoxLog.error(e); } return defaultValue; } public static int readInt(Connection conn, String keyName) { int value = AppValues.InvalidInteger; try (PreparedStatement queryStatement = conn.prepareStatement(QueryInt)) { queryStatement.setMaxRows(1); queryStatement.setString(1, keyName); conn.setAutoCommit(true); try (ResultSet resultSet = queryStatement.executeQuery()) { if (resultSet.next()) { value = resultSet.getInt(1); } } } catch (Exception e) { // MyBoxLog.error(e); } return value; } public static boolean readBoolean(String keyName, boolean defaultValue) { int v = readInt(keyName, defaultValue ? 1 : 0); return v > 0; } public static int writeString(String keyName, String stringValue) { try (Connection conn = DerbyBase.getConnection()) { return writeString(conn, keyName, stringValue); } catch (Exception e) { // MyBoxLog.error(e); return -1; } } public static int writeString(Connection conn, String keyName, String stringValue) { if (conn == null || keyName == null) { return 0; } try { if (stringValue == null) { return delete(conn, keyName) ? 1 : 0; } String exist = readString(conn, keyName); if (exist != null) { if (!stringValue.equals(exist)) { try (PreparedStatement statement = conn.prepareStatement(UpdateString)) { statement.setString(1, stringValue); statement.setString(2, keyName); return statement.executeUpdate(); } } else { return 0; } } else { try (PreparedStatement statement = conn.prepareStatement(InsertString)) { statement.setString(1, keyName); statement.setString(2, stringValue); return statement.executeUpdate(); } } } catch (Exception e) { // MyBoxLog.error(e); return -1; } } public static int writeInt(String keyName, int intValue) { try (Connection conn = DerbyBase.getConnection()) { return writeInt(conn, keyName, intValue); } catch (Exception e) { // MyBoxLog.error(e); return -1; } } public static int writeInt(Connection conn, String keyName, int intValue) { try { int exist = readInt(conn, keyName); if (exist != AppValues.InvalidInteger) { if (intValue != exist) { try (PreparedStatement statement = conn.prepareStatement(UpdateInt)) { statement.setInt(1, intValue); statement.setString(2, keyName); return statement.executeUpdate(); } } else { return 0; } } else { try (PreparedStatement statement = conn.prepareStatement(InsertInt)) { statement.setString(1, keyName); statement.setInt(2, intValue); return statement.executeUpdate(); } } } catch (Exception e) { // MyBoxLog.error(e); return -1; } } public static int writeBoolean(String keyName, boolean booleanValue) { return writeInt(keyName, booleanValue ? 1 : 0); } public static int writeBoolean(Connection conn, String keyName, boolean booleanValue) { return writeInt(conn, keyName, booleanValue ? 1 : 0); } public static boolean delete(String keyName) { if (keyName == null || keyName.isEmpty()) { return false; } try (Connection conn = DerbyBase.getConnection()) { return delete(conn, keyName); } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean delete(Connection conn, String keyName) { if (keyName == null || keyName.isEmpty()) { return false; } try (PreparedStatement statement = conn.prepareStatement(Delete)) { statement.setString(1, keyName); return statement.executeUpdate() >= 0; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean deletePrefix(String keyName) { if (keyName == null || keyName.isEmpty()) { return false; } try (Connection conn = DerbyBase.getConnection()) { return deletePrefix(conn, keyName); } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean deletePrefix(Connection conn, String keyName) { if (keyName == null || keyName.isEmpty()) { return false; } try (PreparedStatement statement = conn.prepareStatement(DeleteLike)) { statement.setString(1, keyName + "%"); return statement.executeUpdate() >= 0; } catch (Exception e) { MyBoxLog.error(e); return false; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/db/table/TableFloatMatrix.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableFloatMatrix.java
package mara.mybox.db.table; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.List; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.BaseData; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ConvolutionKernel; import static mara.mybox.db.table.BaseTable.StringMaxLength; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2018-11-7 * @License Apache License Version 2.0 */ public class TableFloatMatrix extends BaseTable<BaseData> { public TableFloatMatrix() { tableName = "Float_Matrix"; defineColumns(); } public TableFloatMatrix(boolean defineColumns) { tableName = "Float_Matrix"; if (defineColumns) { defineColumns(); } } public final TableFloatMatrix defineColumns() { addColumn(new ColumnDefinition("name", ColumnDefinition.ColumnType.String, true, true).setLength(StringMaxLength)); addColumn(new ColumnDefinition("row", ColumnDefinition.ColumnType.Integer, true, true)); addColumn(new ColumnDefinition("col", ColumnDefinition.ColumnType.Integer, true, true)); addColumn(new ColumnDefinition("value", ColumnDefinition.ColumnType.Float, true)); return this; } @Override public boolean setValue(BaseData data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(BaseData data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(BaseData data) { if (data == null) { return false; } return data.valid(); } public static float[][] read(String name, int width, int height) { float[][] matrix = new float[height][width]; try (Connection conn = DerbyBase.getConnection()) { conn.setReadOnly(true); try (PreparedStatement statement = conn.prepareStatement(" SELECT * FROM Float_Matrix WHERE name=? AND row=? AND col=?")) { for (int j = 0; j < height; ++j) { for (int i = 0; i < width; ++i) { statement.setString(1, name); statement.setInt(2, j); statement.setInt(3, i); try (ResultSet result = statement.executeQuery()) { if (result.next()) { matrix[j][i] = result.getFloat("value"); } } } } } } catch (Exception e) { MyBoxLog.error(e); } return matrix; } public static boolean write(String name, float[][] values) { if (name == null || values == null) { return false; } try (Connection conn = DerbyBase.getConnection()) { try (PreparedStatement statement = conn.prepareStatement( "DELETE FROM Float_Matrix WHERE name=?")) { statement.setString(1, name); statement.executeUpdate(); } conn.setAutoCommit(false); try (PreparedStatement insert = conn.prepareStatement( "INSERT INTO Float_Matrix(name, row , col, value) VALUES(?,?,?,?)")) { for (int j = 0; j < values.length; ++j) { for (int i = 0; i < values[j].length; ++i) { float v = values[j][i]; insert.setString(1, name); insert.setInt(2, j); insert.setInt(3, i); insert.setFloat(4, v); insert.executeUpdate(); } } } conn.commit(); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean write(String name, int row, int col, float value) { if (name == null || row < 0 || col < 0) { return false; } try (Connection conn = DerbyBase.getConnection(); PreparedStatement statement = conn.prepareStatement(" SELECT * FROM Float_Matrix WHERE name=? AND row=? AND col=?")) { statement.setString(1, name); statement.setInt(2, row); statement.setInt(3, col); try (ResultSet result = statement.executeQuery()) { if (result.next()) { try (PreparedStatement update = conn.prepareStatement("UPDATE Float_Matrix SET value=? WHERE name=? AND row=? AND col=?")) { update.setFloat(1, value); update.setString(2, name); update.setInt(3, row); update.setInt(4, col); update.executeUpdate(); } } else { try (PreparedStatement insert = conn.prepareStatement("INSERT INTO Float_Matrix(name, row , col, value) VALUES(?,?,?,?)")) { insert.setString(1, name); insert.setInt(2, row); insert.setInt(3, col); insert.setFloat(4, value); insert.executeUpdate(); } } } return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean delete(String name, int row, int col) { if (name == null || row < 0 || col < 0) { return false; } try (Connection conn = DerbyBase.getConnection()) { try (PreparedStatement statement = conn.prepareStatement( "DELETE FROM Float_Matrix WHERE name=? AND row=? AND col=?")) { statement.setString(1, name); statement.setInt(2, row); statement.setInt(3, col); statement.executeUpdate(); } return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean delete(String name) { if (name == null) { return false; } try (Connection conn = DerbyBase.getConnection()) { try (PreparedStatement statement = conn.prepareStatement( "DELETE FROM Float_Matrix WHERE name=?")) { statement.setString(1, name); statement.executeUpdate(); } return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean delete(List<String> names) { if (names == null || names.isEmpty()) { return false; } try (Connection conn = DerbyBase.getConnection()) { conn.setAutoCommit(false); try (PreparedStatement statement = conn.prepareStatement( "DELETE FROM Float_Matrix WHERE name=?")) { for (int i = 0; i < names.size(); ++i) { statement.setString(1, names.get(i)); statement.executeUpdate(); } } conn.commit(); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean writeExamples() { try (Connection conn = DerbyBase.getConnection(); PreparedStatement query = conn.prepareStatement(" SELECT row FROM Float_Matrix WHERE name=?"); PreparedStatement insert = conn.prepareStatement("INSERT INTO Float_Matrix(name, row , col, value) VALUES(?,?,?,?)")) { for (ConvolutionKernel k : ConvolutionKernel.makeExample()) { String name = k.getName(); query.setString(1, name); try (ResultSet result = query.executeQuery()) { if (!result.next()) { float[][] m = k.getMatrix(); for (int j = 0; j < m.length; ++j) { for (int i = 0; i < m[j].length; ++i) { float v = m[j][i]; insert.setString(1, name); insert.setInt(2, j); insert.setInt(3, i); insert.setFloat(4, v); insert.executeUpdate(); } } } } } return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/db/table/TableNodeJEXL.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableNodeJEXL.java
package mara.mybox.db.table; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.DataNode; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2021-4-23 * @License Apache License Version 2.0 */ public class TableNodeJEXL extends BaseNodeTable { public TableNodeJEXL() { tableName = "Node_JEXL"; treeName = message("JEXL"); dataName = message("JexlScript"); dataFxml = Fxmls.ControlDataJEXLFxml; examplesFileName = "JEXL"; majorColumnName = "script"; nodeExecutable = true; defineColumns(); } public final TableNodeJEXL defineColumns() { defineNodeColumns(); addColumn(new ColumnDefinition("script", ColumnType.Clob) .setLabel(message("JexlScript"))); addColumn(new ColumnDefinition("context", ColumnType.Clob) .setLabel(message("JexlContext"))); addColumn(new ColumnDefinition("parameters", ColumnType.String) .setLength(FilenameMaxLength) .setLabel(message("JexlParamters"))); return this; } @Override public boolean isNodeExecutable(DataNode node) { if (node == null) { return false; } String script = node.getStringValue("script"); return script != null && !script.isBlank(); } }
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/table/TableUserConf.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableUserConf.java
package mara.mybox.db.table; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.StringValue; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.AppValues; /** * @Author Mara * @CreateDate 2018-10-15 9:31:28 * @License Apache License Version 2.0 */ public class TableUserConf extends BaseTable<StringValue> { public TableUserConf() { tableName = "User_Conf"; defineColumns(); } public TableUserConf(boolean defineColumns) { tableName = "User_Conf"; if (defineColumns) { defineColumns(); } } public final TableUserConf defineColumns() { addColumn(new ColumnDefinition("key_name", ColumnDefinition.ColumnType.String, true, true).setLength(StringMaxLength)); addColumn(new ColumnDefinition("string_value", ColumnDefinition.ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("int_Value", ColumnDefinition.ColumnType.Integer)); return this; } final static String QueryString = "SELECT string_Value FROM User_Conf WHERE key_Name=? FETCH FIRST ROW ONLY"; final static String QueryInt = " SELECT int_Value FROM User_Conf WHERE key_Name=? FETCH FIRST ROW ONLY"; final static String InsertInt = "INSERT INTO User_Conf (key_Name, int_Value) VALUES(?, ? )"; final static String InsertString = "INSERT INTO User_Conf(key_Name, string_Value) VALUES(?, ? )"; final static String UpdateString = "UPDATE User_Conf SET string_Value=? WHERE key_Name=?"; final static String UpdateInt = "UPDATE User_Conf SET int_Value=? WHERE key_Name=?"; final static String Delete = "DELETE FROM User_Conf WHERE key_Name=?"; final static String DeleteLike = "DELETE FROM User_Conf WHERE key_Name like ?"; @Override public boolean setValue(StringValue data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(StringValue data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(StringValue data) { if (data == null) { return false; } return data.valid(); } public static String readString(String keyName, String defaultValue) { try (Connection conn = DerbyBase.getConnection()) { return readString(conn, keyName, defaultValue); } catch (Exception e) { // MyBoxLog.debug(e); return defaultValue; } } public static String readString(Connection conn, String keyName, String defaultValue) { if (conn == null || keyName == null) { return defaultValue; } String value = defaultValue; try (PreparedStatement queryStatement = conn.prepareStatement(QueryString)) { queryStatement.setString(1, keyName); conn.setAutoCommit(true); try (ResultSet resultSet = queryStatement.executeQuery()) { if (resultSet.next()) { value = resultSet.getString(1); } } catch (Exception e) { MyBoxLog.debug(e); } if (value == null) { delete(conn, keyName); if (defaultValue != null) { try (PreparedStatement insert = conn.prepareStatement(InsertString)) { insert.setString(1, keyName); insert.setString(2, defaultValue); insert.executeUpdate(); } catch (Exception e) { MyBoxLog.debug(e); } value = defaultValue; } } } catch (Exception e) { MyBoxLog.debug(e); } return value; } public static String readString(Connection conn, String keyName) { return readString(conn, keyName, null); } public static int readInt(String keyName, int defaultValue) { try (Connection conn = DerbyBase.getConnection()) { return readInt(conn, keyName, defaultValue); } catch (Exception e) { // MyBoxLog.debug(e); return defaultValue; } } public static int readInt(Connection conn, String keyName) { return readInt(conn, keyName, AppValues.InvalidInteger); } public static int readInt(Connection conn, String keyName, int defaultValue) { if (conn == null || keyName == null) { return defaultValue; } int value = defaultValue; try (PreparedStatement queryStatement = conn.prepareStatement(QueryInt)) { queryStatement.setString(1, keyName); conn.setAutoCommit(true); try (ResultSet resultSet = queryStatement.executeQuery()) { if (resultSet != null && resultSet.next()) { value = resultSet.getInt(1); } } catch (Exception e) { MyBoxLog.debug(e); } } catch (Exception e) { MyBoxLog.debug(e); } if (value == AppValues.InvalidInteger) { delete(conn, keyName); if (defaultValue != AppValues.InvalidInteger) { try (PreparedStatement insert = conn.prepareStatement(InsertString)) { insert.setString(1, keyName); insert.setInt(2, defaultValue); insert.executeUpdate(); } catch (Exception e) { MyBoxLog.debug(e); } value = defaultValue; } } return value; } public static boolean readBoolean(Connection conn, String keyName, boolean defaultValue) { int v = readInt(conn, keyName, defaultValue ? 1 : 0); return v > 0; } public static boolean readBoolean(String keyName, boolean defaultValue) { int v = readInt(keyName, defaultValue ? 1 : 0); return v > 0; } public static int writeString(String keyName, String stringValue) { try (Connection conn = DerbyBase.getConnection()) { return writeString(conn, keyName, stringValue); } catch (Exception e) { // MyBoxLog.error(e); return 0; } } public static int writeString(Connection conn, String keyName, String stringValue) { if (keyName == null) { return 0; } try { if (stringValue == null) { return delete(conn, keyName) ? 1 : 0; } String exist = readString(conn, keyName); if (exist != null) { if (!stringValue.equals(exist)) { try (PreparedStatement statement = conn.prepareStatement(UpdateString)) { statement.setString(1, stringValue); statement.setString(2, keyName); return statement.executeUpdate(); } } else { return 1; } } else { try (PreparedStatement statement = conn.prepareStatement(InsertString)) { statement.setString(1, keyName); statement.setString(2, stringValue); return statement.executeUpdate(); } } } catch (Exception e) { MyBoxLog.debug(e); return -1; } } public static int writeInt(String keyName, int intValue) { try (Connection conn = DerbyBase.getConnection()) { return writeInt(conn, keyName, intValue); } catch (Exception e) { MyBoxLog.error(e); return -1; } } public static int writeInt(Connection conn, String keyName, int intValue) { try { int exist = readInt(conn, keyName); if (exist != AppValues.InvalidInteger) { if (intValue != exist) { try (PreparedStatement statement = conn.prepareStatement(UpdateInt)) { statement.setInt(1, intValue); statement.setString(2, keyName); return statement.executeUpdate(); } } else { return 1; } } else { try (PreparedStatement statement = conn.prepareStatement(InsertInt)) { statement.setString(1, keyName); statement.setInt(2, intValue); return statement.executeUpdate(); } } } catch (Exception e) { MyBoxLog.debug(e); return -1; } } public static int writeBoolean(String keyName, boolean booleanValue) { return writeInt(keyName, booleanValue ? 1 : 0); } public static int writeBoolean(Connection conn, String keyName, boolean booleanValue) { return writeInt(conn, keyName, booleanValue ? 1 : 0); } public static boolean delete(String keyName) { if (keyName == null || keyName.isEmpty()) { return false; } try (Connection conn = DerbyBase.getConnection()) { return delete(conn, keyName); } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static boolean delete(Connection conn, String keyName) { if (keyName == null || keyName.isEmpty()) { return false; } try (PreparedStatement statement = conn.prepareStatement(Delete)) { statement.setString(1, keyName); return statement.executeUpdate() >= 0; } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static boolean deletePrefix(String keyName) { if (keyName == null || keyName.isEmpty()) { return false; } try (Connection conn = DerbyBase.getConnection()) { return deletePrefix(conn, keyName); } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static boolean deletePrefix(Connection conn, String keyName) { if (keyName == null || keyName.isEmpty()) { return false; } try (PreparedStatement statement = conn.prepareStatement(DeleteLike)) { statement.setString(1, keyName + "%"); return statement.executeUpdate() >= 0; } 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/table/TableMedia.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableMedia.java
package mara.mybox.db.table; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.Date; import java.util.List; import mara.mybox.data.MediaInformation; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColumnDefinition; import static mara.mybox.db.table.BaseTable.StringMaxLength; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.DateTools; /** * @Author Mara * @CreateDate 2019-12-8 * @License Apache License Version 2.0 */ public class TableMedia extends BaseTable<MediaInformation> { public TableMedia() { tableName = "media"; defineColumns(); } public TableMedia(boolean defineColumns) { tableName = "media"; if (defineColumns) { defineColumns(); } } public final TableMedia defineColumns() { addColumn(new ColumnDefinition("address", ColumnDefinition.ColumnType.String, true, true).setLength(StringMaxLength)); addColumn(new ColumnDefinition("video_encoding", ColumnDefinition.ColumnType.String).setLength(1024)); addColumn(new ColumnDefinition("audio_encoding", ColumnDefinition.ColumnType.String).setLength(1024)); addColumn(new ColumnDefinition("duration", ColumnDefinition.ColumnType.Long)); addColumn(new ColumnDefinition("size", ColumnDefinition.ColumnType.Long)); addColumn(new ColumnDefinition("width", ColumnDefinition.ColumnType.Integer)); addColumn(new ColumnDefinition("height", ColumnDefinition.ColumnType.Integer)); addColumn(new ColumnDefinition("info", ColumnDefinition.ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("html", ColumnDefinition.ColumnType.Clob)); addColumn(new ColumnDefinition("modify_time", ColumnDefinition.ColumnType.Datetime, true)); return this; } @Override public boolean setValue(MediaInformation data, String column, Object value) { return false; } @Override public Object getValue(MediaInformation data, String column) { return null; } @Override public boolean valid(MediaInformation data) { return false; } public static MediaInformation read(String address) { if (address == null || address.trim().isEmpty()) { return null; } try (Connection conn = DerbyBase.getConnection(); Statement statement = conn.createStatement()) { conn.setReadOnly(true); statement.setMaxRows(1); String sql = " SELECT * FROM media WHERE address='" + DerbyBase.stringValue(address) + "'"; try (ResultSet results = statement.executeQuery(sql)) { if (results.next()) { MediaInformation media = new MediaInformation(address); media.setVideoEncoding(results.getString("video_encoding")); media.setAudioEncoding(results.getString("audio_encoding")); media.setFileSize(results.getLong("size")); media.setDuration(results.getLong("duration")); media.setWidth(results.getInt("width")); media.setHeight(results.getInt("height")); media.setInfo(results.getString("info")); media.setHtml(results.getString("html")); return media; } } } catch (Exception e) { MyBoxLog.error(e); } return null; } public static List<MediaInformation> read(List<String> addresses) { List<MediaInformation> medias = new ArrayList(); if (addresses == null || addresses.isEmpty()) { return medias; } try (Connection conn = DerbyBase.getConnection()) { conn.setReadOnly(true); medias = read(conn, addresses); } catch (Exception e) { MyBoxLog.error(e); } return medias; } public static List<MediaInformation> read(Connection conn, List<String> addresses) { List<MediaInformation> medias = new ArrayList(); if (conn == null || addresses == null || addresses.isEmpty()) { return medias; } try (Statement statement = conn.createStatement()) { String inStr = "( '" + addresses.get(0) + "'"; for (int i = 1; i < addresses.size(); ++i) { inStr += ", '" + addresses.get(i) + "'"; } inStr += " )"; String sql = " SELECT * FROM media WHERE address IN " + inStr; try (ResultSet results = statement.executeQuery(sql)) { while (results.next()) { MediaInformation media = new MediaInformation(results.getString("address")); media.setVideoEncoding(results.getString("video_encoding")); media.setAudioEncoding(results.getString("audio_encoding")); media.setFileSize(results.getLong("size")); media.setDuration(results.getLong("duration")); media.setWidth(results.getInt("width")); media.setHeight(results.getInt("height")); media.setInfo(results.getString("info")); media.setHtml(results.getString("html")); medias.add(media); } } } catch (Exception e) { MyBoxLog.error(e); } return medias; } public static boolean write(MediaInformation media) { if (media == null || media.getAddress() == null) { return false; } try (Connection conn = DerbyBase.getConnection(); Statement statement = conn.createStatement()) { String sql = "DELETE FROM media WHERE address='" + DerbyBase.stringValue(media.getAddress()) + "'"; statement.executeUpdate(sql); sql = "INSERT INTO media(address,video_encoding,audio_encoding,duration,size,width,height,info,html,modify_time) VALUES('" + DerbyBase.stringValue(media.getAddress()) + "', '" + media.getVideoEncoding() + "', '" + media.getAudioEncoding() + "', " + media.getDuration() + ", " + media.getFileSize() + ", " + media.getWidth() + ", " + media.getHeight() + ", '" + DerbyBase.stringValue(media.getInfo()) + "', '" + DerbyBase.stringValue(media.getHtml()) + "', '" + DateTools.datetimeToString(new Date()) + "')"; statement.executeUpdate(sql); return true; } catch (Exception e) { MyBoxLog.error(e); // MyBoxLog.debug(e); return false; } } public static boolean write(List<MediaInformation> medias) { if (medias == null || medias.isEmpty()) { return false; } try (Connection conn = DerbyBase.getConnection()) { return write(conn, medias); } catch (Exception e) { MyBoxLog.error(e); // MyBoxLog.debug(e); return false; } } public static boolean write(Connection conn, List<MediaInformation> medias) { if (conn == null || medias == null || medias.isEmpty()) { return false; } try (Statement statement = conn.createStatement()) { String sql; conn.setAutoCommit(false); for (MediaInformation media : medias) { sql = "DELETE FROM media WHERE address='" + media.getAddress() + "'"; statement.executeUpdate(sql); sql = "INSERT INTO media(address,video_encoding,audio_encoding,duration,size,width,height,info,html,modify_time) VALUES('" + DerbyBase.stringValue(media.getAddress()) + "', '" + media.getVideoEncoding() + "', '" + media.getAudioEncoding() + "', " + media.getDuration() + ", " + media.getFileSize() + ", " + media.getWidth() + ", " + media.getHeight() + ", '" + DerbyBase.stringValue(media.getInfo()) + "', '" + DerbyBase.stringValue(media.getHtml()) + "', '" + DateTools.datetimeToString(new Date()) + "')"; statement.executeUpdate(sql); } conn.commit(); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean delete(List<String> addresses) { if (addresses == null || addresses.isEmpty()) { return true; } try (Connection conn = DerbyBase.getConnection()) { return delete(conn, addresses); } catch (Exception e) { MyBoxLog.error(e); // MyBoxLog.debug(e); return false; } } public static boolean delete(Connection conn, List<String> addresses) { if (conn == null || addresses == null || addresses.isEmpty()) { return true; } try (Statement statement = conn.createStatement()) { String inStr = "( '" + DerbyBase.stringValue(addresses.get(0)) + "'"; for (int i = 1; i < addresses.size(); ++i) { inStr += ", '" + DerbyBase.stringValue(addresses.get(i)) + "'"; } inStr += " )"; String sql = "DELETE FROM media WHERE address IN " + inStr; statement.executeUpdate(sql); return true; } catch (Exception e) { MyBoxLog.error(e); // MyBoxLog.debug(e); return false; } } public static boolean delete(String address) { try (Connection conn = DerbyBase.getConnection(); Statement statement = conn.createStatement()) { String sql = "DELETE FROM media WHERE address='" + DerbyBase.stringValue(address) + "'"; statement.executeUpdate(sql); return true; } catch (Exception e) { MyBoxLog.error(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/table/TableNodeJavaScript.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableNodeJavaScript.java
package mara.mybox.db.table; import java.sql.Connection; import mara.mybox.controller.BaseController; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.DataNode; import mara.mybox.fxml.FxTask; import mara.mybox.tools.HtmlWriteTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2021-4-23 * @License Apache License Version 2.0 */ public class TableNodeJavaScript extends BaseNodeTable { public TableNodeJavaScript() { tableName = "Node_JavaScript"; treeName = message("JavaScript"); dataName = message("JavaScript"); dataFxml = Fxmls.ControlDataJavaScriptFxml; examplesFileName = "JavaScript"; majorColumnName = "script"; nodeExecutable = true; defineColumns(); } public final TableNodeJavaScript defineColumns() { defineNodeColumns(); addColumn(new ColumnDefinition("script", ColumnType.Clob) .setLabel(message("JavaScript"))); return this; } @Override public boolean isNodeExecutable(DataNode node) { if (node == null) { return false; } String script = node.getStringValue("script"); return script != null && !script.isBlank(); } @Override public String valuesHtml(FxTask task, Connection conn, BaseController controller, DataNode node) { try { String text = node.getStringValue("script"); return text == null || text.isBlank() ? null : HtmlWriteTools.codeToHtml(text); } catch (Exception e) { return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/db/table/TableNodeJShell.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableNodeJShell.java
package mara.mybox.db.table; import java.sql.Connection; import mara.mybox.controller.BaseController; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.DataNode; import mara.mybox.fxml.FxTask; import mara.mybox.tools.HtmlWriteTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2021-4-23 * @License Apache License Version 2.0 */ public class TableNodeJShell extends BaseNodeTable { public TableNodeJShell() { tableName = "Node_JShell"; treeName = message("JShell"); dataName = message("Codes"); dataFxml = Fxmls.ControlDataJShellFxml; examplesFileName = "JShell"; majorColumnName = "codes"; nodeExecutable = true; defineColumns(); } public final TableNodeJShell defineColumns() { defineNodeColumns(); addColumn(new ColumnDefinition("codes", ColumnType.Clob) .setLabel(message("Codes"))); return this; } @Override public boolean isNodeExecutable(DataNode node) { if (node == null) { return false; } String codes = node.getStringValue("codes"); return codes != null && !codes.isBlank(); } @Override public String valuesHtml(FxTask task, Connection conn, BaseController controller, DataNode node) { try { String text = node.getStringValue("codes"); return text == null || text.isBlank() ? null : HtmlWriteTools.codeToHtml(text); } catch (Exception e) { return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/db/table/TableNodeGeographyCode.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableNodeGeographyCode.java
package mara.mybox.db.table; import java.sql.Connection; import mara.mybox.data.GeographyCode; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.DataNode; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.DoubleTools; import mara.mybox.tools.GeographyCodeTools; import mara.mybox.tools.LongTools; import mara.mybox.value.Fxmls; 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 TableNodeGeographyCode extends BaseNodeTable { public TableNodeGeographyCode() { tableName = "Node_Geography_Code"; treeName = message("GeographyCode"); dataName = message("GeographyCode"); dataFxml = Fxmls.ControlDataGeographyCodeFxml; examplesFileName = "GeographyCode"; majorColumnName = Languages.isChinese() ? "chinese_name" : "english_name"; nodeExecutable = true; defineColumns(); } public final TableNodeGeographyCode defineColumns() { defineNodeColumns(); addColumn(new ColumnDefinition("chinese_name", ColumnType.String) .setLabel(message("ChineseName"))); addColumn(new ColumnDefinition("english_name", ColumnType.String) .setLabel(message("EnglishName"))); addColumn(new ColumnDefinition("level", ColumnType.EnumeratedShort) .setFormat(GeographyCodeTools.addressLevelMessageNames()) .setLabel(message("Level"))); addColumn(new ColumnDefinition("coordinate_system", ColumnType.EnumeratedShort) .setFormat(GeographyCodeTools.coordinateSystemMessageNames()) .setLabel(message("CoordinateSystem"))); addColumn(new ColumnDefinition("longitude", ColumnType.Longitude) .setLabel(message("Longitude"))); addColumn(new ColumnDefinition("latitude", ColumnType.Latitude) .setLabel(message("Latitude"))); addColumn(new ColumnDefinition("altitude", ColumnType.Double) .setLabel(message("Altitude"))); addColumn(new ColumnDefinition("precision", ColumnType.Double) .setLabel(message("Precision"))); addColumn(new ColumnDefinition("continent", ColumnType.String) .setLabel(message("Continent"))); addColumn(new ColumnDefinition("country", ColumnType.String) .setLabel(message("Country"))); addColumn(new ColumnDefinition("province", ColumnType.String) .setLabel(message("Province"))); addColumn(new ColumnDefinition("city", ColumnType.String) .setLabel(message("City"))); addColumn(new ColumnDefinition("county", ColumnType.String) .setLabel(message("County"))); addColumn(new ColumnDefinition("town", ColumnType.String) .setLabel(message("Town"))); addColumn(new ColumnDefinition("village", ColumnType.String) .setLabel(message("Village"))); addColumn(new ColumnDefinition("building", ColumnType.String) .setLabel(message("Building"))); addColumn(new ColumnDefinition("poi", ColumnType.String) .setLabel(message("PointOfInterest"))); addColumn(new ColumnDefinition("code1", ColumnType.String) .setLabel(message("Code1"))); addColumn(new ColumnDefinition("code2", ColumnType.String) .setLabel(message("Code2"))); addColumn(new ColumnDefinition("code3", ColumnType.String) .setLabel(message("Code3"))); addColumn(new ColumnDefinition("code4", ColumnType.String) .setLabel(message("Code4"))); addColumn(new ColumnDefinition("code5", ColumnType.String) .setLabel(message("Code5"))); addColumn(new ColumnDefinition("alias1", ColumnType.String) .setLabel(message("Alias1"))); addColumn(new ColumnDefinition("alias2", ColumnType.String) .setLabel(message("Alias2"))); addColumn(new ColumnDefinition("alias3", ColumnType.String) .setLabel(message("Alias3"))); addColumn(new ColumnDefinition("alias4", ColumnType.String) .setLabel(message("Alias4"))); addColumn(new ColumnDefinition("alias5", ColumnType.String) .setLabel(message("Alias5"))); addColumn(new ColumnDefinition("area", ColumnType.Double).setFormat("GroupInThousands") .setLabel(message("SquareMeters"))); addColumn(new ColumnDefinition("population", ColumnType.Long).setFormat("GroupInThousands") .setLabel(message("Population"))); addColumn(new ColumnDefinition("description", ColumnType.String) .setLabel(message("Description"))); addColumn(new ColumnDefinition("image", ColumnType.Image) .setLabel(message("Image"))); return this; } @Override public DataNode getRoot(Connection conn) { try { if (conn == null || tableName == null) { return null; } DataNode root = super.getRoot(conn); if (root.getStringValue("chinese_name") == null || root.getStringValue("english_name") == null) { root.setValue("chinese_name", message("zh", "GeographyCode")); root.setValue("english_name", message("en", "GeographyCode")); root = updateData(conn, root); } return root; } catch (Exception e) { MyBoxLog.debug(e); return null; } } @Override public String displayValue(ColumnDefinition column, Object v) { if (column == null || v == null) { return null; } switch (column.getColumnName().toLowerCase()) { case "area": double area = (double) v; if (area <= 0 || DoubleTools.invalidDouble(area)) { return null; } break; case "population": long population = (long) v; if (population <= 0 || LongTools.invalidLong(population)) { return null; } break; case "precision": case "altitude": case "image": return null; } return column.formatValue(v); } @Override public String exportValue(ColumnDefinition column, Object v, boolean format) { return displayValue(column, v); } @Override public Object importValue(ColumnDefinition column, String v) { if (column == null || v == null) { return null; } switch (column.getColumnName().toLowerCase()) { case "area": return area(v); case "population": return population(v); case "precision": case "altitude": case "image": return null; } return column.fromString(v, ColumnDefinition.InvalidAs.Use); } public Object area(String v) { try { double area = Double.parseDouble(v.replaceAll(",", "")); if (area <= 0 || DoubleTools.invalidDouble(area)) { return null; } else { return area; } } catch (Exception e) { return null; } } public Object population(String v) { try { long population = Math.round(Double.parseDouble(v.replaceAll(",", ""))); if (population <= 0 || LongTools.invalidLong(population)) { return null; } else { return population; } } catch (Exception e) { return null; } } public DataNode toNode(GeographyCode code) { return GeographyCodeTools.toNode(code); } public GeographyCode fromNode(DataNode node) { return GeographyCodeTools.fromNode(node); } public String text(GeographyCode code) { return valuesText(GeographyCodeTools.toNode(code)); } }
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/table/TableNodeImageScope.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableNodeImageScope.java
package mara.mybox.db.table; import java.sql.Connection; import mara.mybox.controller.BaseController; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.DataNode; import mara.mybox.fxml.FxTask; import mara.mybox.image.data.ImageScope; import mara.mybox.image.tools.ImageScopeTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2021-4-23 * @License Apache License Version 2.0 */ public class TableNodeImageScope extends BaseNodeTable { public TableNodeImageScope() { tableName = "Node_Image_Scope"; treeName = message("ImageScope"); dataName = message("ImageScope"); dataFxml = Fxmls.ControlDataImageScopeFxml; examplesFileName = "ImageScope"; majorColumnName = "area_data"; defineColumns(); } public final TableNodeImageScope defineColumns() { defineNodeColumns(); addColumn(new ColumnDefinition("shape_type", ColumnType.String) .setLength(128) .setLabel(message("ShapeType"))); addColumn(new ColumnDefinition("color_algorithm", ColumnType.String) .setLength(128) .setLabel(message("ColorMatchAlgorithm"))); addColumn(new ColumnDefinition("shape_excluded", ColumnType.Boolean) .setLabel(message("ShapeExcluded"))); addColumn(new ColumnDefinition("color_excluded", ColumnType.Boolean) .setLabel(message("ColorExcluded"))); addColumn(new ColumnDefinition("color_threshold", ColumnType.Double) .setLabel(message("ColorMatchThreshold"))); addColumn(new ColumnDefinition("color_weights", ColumnType.String) .setLabel(message("ColorWeights"))); addColumn(new ColumnDefinition("background_file", ColumnType.File) .setLabel(message("Background"))); addColumn(new ColumnDefinition("outline_file", ColumnType.File) .setLabel(message("Outline"))); addColumn(new ColumnDefinition("shape_data", ColumnType.Clob) .setLabel(message("Shape"))); addColumn(new ColumnDefinition("color_data", ColumnType.Clob) .setLabel(message("Colors"))); return this; } @Override public String valuesHtml(FxTask task, Connection conn, BaseController controller, DataNode node) { try { ImageScope scope = ImageScopeTools.fromDataNode(task, controller, node); if (scope == null) { return null; } return ImageScopeTools.toHtml(task, scope); } catch (Exception e) { return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/db/table/BaseNodeTable.java
alpha/MyBox/src/main/java/mara/mybox/db/table/BaseNodeTable.java
package mara.mybox.db.table; import java.io.File; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import java.util.Map; import mara.mybox.controller.BaseController; import mara.mybox.controller.DataTreeNodeEditorController; import mara.mybox.controller.HtmlTableController; import mara.mybox.controller.WebBrowserController; import mara.mybox.data.StringTable; import mara.mybox.data2d.DataInternalTable; import mara.mybox.db.Database; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.DataNode; import static mara.mybox.db.data.DataNode.TitleSeparater; import mara.mybox.db.data.DataNodeTools; import mara.mybox.dev.MyBoxLog; import static mara.mybox.fxml.FxFileTools.getInternalFile; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.FxTask; import mara.mybox.tools.HtmlWriteTools; import mara.mybox.tools.JsonTools; import static mara.mybox.value.AppValues.Indent; 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 BaseNodeTable extends BaseTable<DataNode> { public static final long RootID = 1l; public static final String NodeFields = "nodeid,title,order_number,update_time,parentid"; public String treeName, dataName, dataFxml, examplesFileName, majorColumnName; public boolean nodeExecutable; public BaseNodeTable() { idColumnName = "nodeid"; orderColumns = "order_number ASC,nodeid ASC"; nodeExecutable = false; } public final BaseNodeTable defineNodeColumns() { addColumn(new ColumnDefinition("nodeid", ColumnType.Long, true, true) .setAuto(true) .setLabel(message("NodeID"))); addColumn(new ColumnDefinition("title", ColumnType.String, true) .setLength(StringMaxLength) .setLabel(message("Title"))); addColumn(new ColumnDefinition("order_number", ColumnType.Float) .setLabel(message("OrderNumber"))); addColumn(new ColumnDefinition("update_time", ColumnType.Datetime) .setLabel(message("UpdateTime"))); addColumn(new ColumnDefinition("parentid", ColumnType.Long, true) .setLabel(message("ParentID")) .setReferName(tableName + "_parentid_fk") .setReferTable(tableName).setReferColumn(idColumnName) .setOnDelete(ColumnDefinition.OnDelete.Cascade) ); return this; } @Override public boolean setValue(DataNode node, String column, Object value) { if (node == null || column == null) { return false; } return node.setValue(column, value); } @Override public Object getValue(DataNode node, String column) { if (node == null || column == null) { return null; } return node.getValue(column); } @Override public boolean valid(DataNode node) { if (node == null) { return false; } return node.valid(); } @Override public boolean createTable(Connection conn) { try { if (!super.createTable(conn)) { return false; } conn.setAutoCommit(true); createIndices(conn); new TableDataTag(this).createTable(conn); new TableDataNodeTag(this).createTable(conn); return createRoot(conn) != null; } catch (Exception e) { MyBoxLog.debug(e); return false; } } private boolean createIndices(Connection conn) { if (conn == null || tableName == null) { return false; } String sql = "CREATE INDEX " + tableName + "_parent_index on " + tableName + " ( parentid )"; try (PreparedStatement statement = conn.prepareStatement(sql)) { statement.executeUpdate(); } catch (Exception e) { // MyBoxLog.debug(e); // return false; } sql = "CREATE INDEX " + tableName + "_title_index on " + tableName + " ( parentid, title )"; try (PreparedStatement statement = conn.prepareStatement(sql)) { statement.executeUpdate(); } catch (Exception e) { // MyBoxLog.debug(e); // return false; } sql = "CREATE INDEX " + tableName + "_order_index on " + tableName + " ( parentid, order_number )"; try (PreparedStatement statement = conn.prepareStatement(sql)) { statement.executeUpdate(); } catch (Exception e) { // MyBoxLog.debug(e); // return false; } return true; } public boolean isNodeExecutable(DataNode node) { if (node == null) { return false; } return nodeExecutable; } public DataInternalTable dataTable() { DataInternalTable dataTable = new DataInternalTable(); dataTable.setDataName(treeName).setSheet(tableName); return dataTable; } /* static */ public static BaseNodeTable create(String name) { if (name == null) { return null; } if (Languages.match("TextTree", name)) { return new TableNodeText(); } else if (Languages.match("HtmlTree", name)) { return new TableNodeHtml(); } else if (Languages.match("MathFunction", name)) { return new TableNodeMathFunction(); } else if (Languages.match("WebFavorite", name)) { return new TableNodeWebFavorite(); } else if (Languages.match("DatabaseSQL", name)) { return new TableNodeSQL(); } else if (Languages.match("ImageScope", name)) { return new TableNodeImageScope(); } else if (Languages.match("JShell", name)) { return new TableNodeJShell(); } else if (Languages.match("JEXL", name)) { return new TableNodeJEXL(); } else if (Languages.match("JavaScript", name)) { return new TableNodeJavaScript(); } else if (Languages.match("RowExpression", name)) { return new TableNodeRowExpression(); } else if (Languages.match("DataColumn", name)) { return new TableNodeDataColumn(); } else if (Languages.match("GeographyCode", name)) { return new TableNodeGeographyCode(); } else if (Languages.match("MacroCommands", name)) { return new TableNodeMacro(); } return null; } /* rows */ @Override public DataNode newData() { return DataNode.create(); } public DataNode createRoot() { try (Connection conn = DerbyBase.getConnection()) { return createRoot(conn); } catch (Exception e) { MyBoxLog.debug(e); return null; } } private DataNode createRoot(Connection conn) { try { if (clearData(conn) < 0) { return null; } String sql = "INSERT INTO " + tableName + " ( nodeid, title, parentid ) " + " VALUES ( " + RootID + ", '" + treeName + "', " + RootID + " )"; if (update(conn, sql) < 0) { return null; } sql = "ALTER TABLE " + tableName + " ALTER COLUMN nodeid RESTART WITH 2"; if (update(conn, sql) < 0) { return null; } return query(conn, RootID); } catch (Exception e) { MyBoxLog.debug(e); return null; } } public DataNode getRoot() { try (Connection conn = DerbyBase.getConnection()) { return getRoot(conn); } catch (Exception e) { MyBoxLog.debug(e); return null; } } public DataNode getRoot(Connection conn) { try { if (conn == null || tableName == null) { return null; } DataNode root = query(conn, RootID); if (root == null) { root = createRoot(conn); } if (treeName != null && !treeName.equals(root.getTitle())) { root.setTitle(treeName); } root.setHierarchyNumber("").setChainName(root.getTitle()); root = updateData(conn, root); return root; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public DataNode 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 DataNode find(Connection conn, long id) { if (conn == null || id < 0) { return null; } String sql = "SELECT * FROM " + tableName + " WHERE nodeid=?"; try (PreparedStatement statement = conn.prepareStatement(sql)) { statement.setLong(1, id); return query(conn, statement); } catch (Exception e) { MyBoxLog.debug(e); return null; } } public List<DataNode> 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<DataNode> children(Connection conn, long parent) { if (conn == null || parent < 0) { return null; } String sql = "SELECT " + NodeFields + " FROM " + tableName + " WHERE parentid=? AND parentid<>nodeid ORDER BY " + orderColumns; try (PreparedStatement statement = conn.prepareStatement(sql)) { statement.setLong(1, parent); return query(statement); } catch (Exception e) { MyBoxLog.debug(e); return null; } } // its decentants will be deleted automatically public long deleteNode(long nodeid) { if (nodeid < 0) { return -1; } if (nodeid == RootID) { return createRoot() != null ? 1 : -3; } String sql = "DELETE FROM " + tableName + " WHERE nodeid=?"; try (Connection conn = DerbyBase.getConnection(); PreparedStatement statement = conn.prepareStatement(sql)) { statement.setLong(1, nodeid); return statement.executeUpdate(); } catch (Exception e) { MyBoxLog.debug(e); return -2; } } public long deleteDecentants(long nodeid) { if (nodeid < 0) { return -1; } String sql = "DELETE FROM " + tableName + " WHERE parentid=? AND parentid<>nodeid"; try (Connection conn = DerbyBase.getConnection(); PreparedStatement statement = conn.prepareStatement(sql)) { statement.setLong(1, nodeid); return statement.executeUpdate(); } catch (Exception e) { MyBoxLog.debug(e); return -2; } } // this will clear all data and start from 1 public long truncate() { try (Connection conn = DerbyBase.getConnection()) { return truncate(conn); } catch (Exception e) { MyBoxLog.error(e); return -3; } } public long truncate(Connection conn) { if (conn == null) { return -1; } String sql = "DELETE FROM " + tableName + " WHERE nodeid=" + RootID; try (PreparedStatement statement = conn.prepareStatement(sql)) { return statement.executeUpdate(); } catch (Exception e) { MyBoxLog.error(e); return -2; } } public boolean hasChildren(Connection conn, DataNode node) { if (node == null || node.getChildrenSize() == 0) { return false; } if (node.getChildrenSize() > 0) { return true; } return hasChildren(conn, node.getNodeid()); } public boolean hasChildren(Connection conn, long nodeid) { if (conn == null || nodeid < 0) { return false; } boolean hasChildren = false; String sql = "SELECT nodeid FROM " + tableName + " WHERE parentid=? AND parentid<>nodeid FETCH FIRST ROW ONLY"; try (PreparedStatement statement = conn.prepareStatement(sql)) { statement.setLong(1, nodeid); try (ResultSet results = statement.executeQuery()) { hasChildren = results != null && results.next(); } } catch (Exception e) { MyBoxLog.debug(e); } return hasChildren; } public long childrenSize(Connection conn, long nodeid) { String sql = "SELECT count(nodeid) FROM " + tableName + " WHERE parentid=? AND parentid<>nodeid"; long size = -1; try (PreparedStatement statement = conn.prepareStatement(sql)) { statement.setLong(1, nodeid); conn.setAutoCommit(true); ResultSet results = statement.executeQuery(); if (results != null && results.next()) { size = results.getInt(1); } } catch (Exception e) { MyBoxLog.debug(e); } return size; } public DataNode copyNode(Connection conn, DataNode sourceNode, DataNode targetNode) { if (conn == null || sourceNode == null || targetNode == null) { return null; } try { DataNode newNode = sourceNode.cloneAll() .setNodeid(-1).setParentid(targetNode.getNodeid()); newNode = insertData(conn, newNode); if (newNode == null) { return null; } conn.commit(); return newNode; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public int copyDescendants(FxTask task, Connection conn, DataNode sourceNode, DataNode targetNode, boolean allDescendants, int inCount) { int count = inCount; try { if (conn == null || sourceNode == null || targetNode == null) { return -count; } long sourceid = sourceNode.getNodeid(); long targetid = targetNode.getNodeid(); if (sourceid < 0 || targetid < 0 || (task != null && !task.isWorking())) { return -count; } conn.setAutoCommit(false); String sql = "SELECT * FROM " + tableName + " WHERE parentid=? AND parentid<>nodeid ORDER BY " + orderColumns; try (PreparedStatement statement = conn.prepareStatement(sql)) { statement.setLong(1, sourceid); try (ResultSet results = statement.executeQuery()) { while (results != null && results.next()) { if (task != null && !task.isWorking()) { return -count; } DataNode childNode = readData(results); DataNode newNode = childNode.cloneAll() .setNodeid(-1).setParentid(targetid); newNode = insertData(conn, newNode); if (newNode == null) { return -count; } if (++count % Database.BatchSize == 0) { conn.commit(); } if (allDescendants) { copyDescendants(task, conn, childNode, newNode, allDescendants, count); } } } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } return -count; } } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } return -count; } conn.commit(); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } return -count; } return count; } public int copyNodeAndDescendants(FxTask task, Connection conn, DataNode sourceNode, DataNode targetNode, boolean allDescendants) { DataNode copiedNode = copyNode(conn, sourceNode, targetNode); if (copiedNode == null) { return 0; } return copyDescendants(task, conn, sourceNode, copiedNode, allDescendants, 1); } public boolean equalOrDescendant(FxTask<Void> task, Connection conn, DataNode targetNode, DataNode sourceNode) { if (sourceNode == null) { return false; } return equalOrDescendant(task, conn, targetNode, sourceNode.getNodeid()); } public boolean equalOrDescendant(FxTask<Void> task, Connection conn, DataNode targetNode, Long sourceID) { if (conn == null || targetNode == null || (task != null && !task.isWorking())) { return false; } long targetID = targetNode.getNodeid(); if (targetID == sourceID) { return true; } DataNode parent = query(conn, targetNode.getParentid()); if (parent == null || targetID == parent.getNodeid()) { return false; } return equalOrDescendant(task, conn, parent, sourceID); } public String chainName(FxTask<Void> task, Connection conn, DataNode node) { if (conn == null || node == null) { return null; } String chainName = ""; DataNode cnode = node; while (cnode.getNodeid() != cnode.getParentid()) { if (conn == null || (task != null && !task.isWorking())) { return null; } cnode = query(conn, cnode.getParentid()); if (cnode == null) { return null; } chainName = cnode.getTitle() + TitleSeparater + chainName; } chainName += node.getTitle(); return chainName; } public DataNode find(Connection conn, long parent, String title) { if (conn == null || title == null || title.isBlank()) { return null; } String sql = "SELECT * FROM " + tableName + " WHERE parentid=? AND parentid<> nodeid AND title=? " + "ORDER BY nodeid DESC FETCH FIRST ROW ONLY"; try (PreparedStatement statement = conn.prepareStatement(sql)) { statement.setLong(1, parent); statement.setString(2, title); return query(conn, statement); } catch (Exception e) { MyBoxLog.debug(e); return null; } } public int trimDescedentsOrders(FxTask task, Connection conn, DataNode node, boolean allDescendants, int inCount) { if (node == null) { return -inCount; } long nodeid = node.getNodeid(); if (nodeid < 0 || (task != null && !task.isWorking())) { return -inCount; } int count = inCount; String sql = "SELECT * FROM " + tableName + " WHERE parentid=? AND parentid<>nodeid ORDER BY " + orderColumns; try (PreparedStatement statement = conn.prepareStatement(sql)) { conn.setAutoCommit(false); int num = 0; statement.setLong(1, nodeid); try (ResultSet results = statement.executeQuery()) { while (results != null && results.next()) { if (task != null && !task.isWorking()) { return -count; } DataNode childNode = readData(results); if (childNode == null) { continue; } childNode.setOrderNumber(++num); childNode = updateData(conn, childNode); if (childNode == null) { return -count; } if (++count % Database.BatchSize == 0) { conn.commit(); } if (allDescendants) { count = trimDescedentsOrders(task, conn, childNode, allDescendants, count); } } } catch (Exception e) { MyBoxLog.console(e.toString()); return -count; } conn.commit(); } catch (Exception e) { MyBoxLog.console(e.toString()); return -count; } return count; } public DataNode readChain(FxTask<Void> task, Connection conn, DataNode node) { return readChain(task, conn, node == null ? RootID : node.getNodeid()); } public DataNode readChain(FxTask<Void> task, Connection conn, long id) { if (conn == null || id < 0) { return null; } String chainName = ""; List<DataNode> chainNodes = new ArrayList<>(); DataNode node = query(conn, id); if (node == null) { return node; } chainNodes.add(node); DataNode child = node, parent; long parentid, childid; String h = ""; while (true) { if (conn == null || (task != null && !task.isWorking())) { return null; } childid = child.getNodeid(); parentid = child.getParentid(); if (parentid == childid || childid == RootID) { break; } parent = query(conn, parentid); if (parent == null) { break; } chainName = parent.getTitle() + TitleSeparater + chainName; chainNodes.add(0, parent); child.setParentNode(parent); String sql = "SELECT nodeid FROM " + tableName + " WHERE parentid=? AND parentid<>nodeid ORDER BY " + orderColumns; int index = -1; try (PreparedStatement statement = conn.prepareStatement(sql)) { statement.setLong(1, parentid); try (ResultSet results = statement.executeQuery()) { while (results != null && results.next()) { index++; long itemid = results.getLong("nodeid"); if (itemid == childid) { break; } } } catch (Exception e) { MyBoxLog.console(e); return null; } } catch (Exception e) { MyBoxLog.console(e); return null; } if (index < 0) { return null; } child.setIndex(index); h = "." + (index + 1) + h; child = parent; } node.setChainNodes(chainNodes); node.setChainName(chainName + node.getTitle()); if (h.startsWith(".")) { h = h.substring(1, h.length()); } node.setHierarchyNumber(h); return node; } public String title(Connection conn, long id) { if (conn == null || id < 0) { return null; } String sql = "SELECT title FROM " + tableName + " WHERE nodeid=?"; try (PreparedStatement statement = conn.prepareStatement(sql)) { statement.setLong(1, id); try (ResultSet results = statement.executeQuery()) { if (results.next()) { return results.getString("title"); } } } catch (Exception e) { } return null; } /* values */ public File exampleFile() { return exampleFile(null); } public File exampleFile(String name) { return exampleFile(name, null); } public File exampleFileLang(String lang) { return exampleFile(null, lang); } public File exampleFile(String name, String lang) { if (name == null) { name = examplesFileName; } if (lang == null) { lang = Languages.embedFileLang(); } return getInternalFile("/data/examples/" + name + "_Examples_" + lang + ".xml", "data", name + "_Examples_" + lang + ".xml", true); } public List<String> dataColumnNames() { List<String> names = new ArrayList<>(); for (int i = 5; i < columns.size(); ++i) { ColumnDefinition column = columns.get(i); names.add(column.getColumnName()); } return names; } // Node should be queried with all fields public String nodeHtml(FxTask task, Connection conn, BaseController controller, DataNode node) { return DataNodeTools.nodeHtml(task, conn, controller, this, node); } public String valuesHtml(FxTask task, Connection conn, BaseController controller, DataNode node) { if (node == null) { return null; } Map<String, Object> values = node.getValues(); if (values == null || values.isEmpty()) { return null; } StringTable table = new StringTable(); for (String name : dataColumnNames()) { ColumnDefinition column = column(name); String value = displayValue(column, values.get(name)); if (value == null || value.isBlank()) { continue; } List<String> row = new ArrayList<>(); row.add(column.getLabel()); row.add(HtmlWriteTools.codeToHtml(value)); table.add(row); } if (table.isEmpty()) { return null; } else { return table.div(); } } public String valuesXml(String prefix, DataNode node, boolean format) { if (node == null) { return null; } Map<String, Object> values = node.getValues(); if (values == null || values.isEmpty()) { return null; } String prefix2 = prefix + Indent; String xml = ""; for (String name : dataColumnNames()) { ColumnDefinition column = column(name); Object value = values.get(name); if (value == null) { continue; } String sValue = exportValue(column, value, format); if (sValue == null || sValue.isBlank()) { continue; } if (column.isDBStringType()) { xml += prefix + "<" + name + ">\n"; xml += prefix2 + "<![CDATA[" + sValue + "]]>\n"; xml += prefix + "</" + name + ">\n"; } else { xml += prefix + "<" + name + ">" + sValue + "</" + name + ">\n"; } } return xml; } public String valuesJson(String prefix, DataNode node, boolean format) { if (node == null) { return null; } Map<String, Object> values = node.getValues(); if (values == null || values.isEmpty()) { return null; } String json = ""; for (String name : dataColumnNames()) { ColumnDefinition column = column(name); Object value = values.get(name); if (value == null) { continue; } String sValue = exportValue(column, value, format); if (sValue == null || sValue.isBlank()) { continue; } if (!json.isBlank()) { json += ",\n"; } json += prefix + "\"" + column.getLabel() + "\": " + JsonTools.encode(sValue); } return json; } public String valuesString(DataNode node) { return valuesJson("", node, true); } // Node should be queried with all fields public String valuesText(DataNode node) { if (node == null) { return null; } String s = message("Title") + ": " + node.getTitle(); Map<String, Object> values = node.getValues(); if (values == null || values.isEmpty()) { return s; } for (String name : dataColumnNames()) { ColumnDefinition column = column(name); String value = displayValue(column, values.get(name)); if (value == null || value.isBlank()) { continue; } s += "\n" + column.getLabel() + ": " + value; } return s; } public Object majorValue(DataNode node) { return getValue(node, majorColumnName); } /* tools */ public void popNode(BaseController controller, DataNode node) { if (node == null) { return; } FxTask popTask = new FxSingletonTask<Void>(controller) { private String html; private DataNode savedNode; @Override protected boolean handle() { try (Connection conn = DerbyBase.getConnection()) { savedNode = readChain(this, conn, node.getNodeid()); if (savedNode == null) { return false; } html = nodeHtml(this, conn, controller, savedNode); return html != null && !html.isBlank(); } catch (Exception e) { error = e.toString(); return false; } } @Override protected void whenSucceeded() { HtmlTableController.open(null, html); } }; controller.start(popTask, false); } public void executeNode(BaseController controller, DataNode node) { if (node == null) { controller.popError(message("SelectToHandle")); return; } if (this instanceof TableNodeWebFavorite) { FxTask exTask = new FxTask<Void>(controller) { private String address; @Override protected boolean handle() { try (Connection conn = DerbyBase.getConnection()) { DataNode savedNode = query(conn, node.getNodeid()); if (savedNode == null) { return false; } address = savedNode.getStringValue("address"); return address != null; } catch (Exception e) { error = e.toString(); return false; } } @Override protected void whenSucceeded() { WebBrowserController.openAddress(address, true); } }; controller.start(exTask, false, message("Handling...")); } else { DataTreeNodeEditorController.loadNode(controller, this, node, true); } } /* get/set */ public String getDataName() { return dataName; } public void setDataName(String dataName) { this.dataName = dataName; } public String getDataFxml() { return dataFxml; } public BaseNodeTable setDataFxml(String dataFxml) { this.dataFxml = dataFxml; return this; } public String getTreeName() { return treeName; }
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/table/TableVisitHistory.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableVisitHistory.java
package mara.mybox.db.table; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Date; import java.util.List; import mara.mybox.db.Database; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.VisitHistory; import mara.mybox.db.data.VisitHistory.FileType; import mara.mybox.db.data.VisitHistory.OperationType; import mara.mybox.db.data.VisitHistory.ResourceType; import mara.mybox.db.data.VisitHistoryTools; import static mara.mybox.db.table.BaseTable.StringMaxLength; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.DateTools; import mara.mybox.value.AppVariables; /** * @Author Mara * @CreateDate 2019-4-5 * @License Apache License Version 2.0 */ public class TableVisitHistory extends BaseTable<VisitHistory> { public TableVisitHistory() { tableName = "visit_history"; defineColumns(); } public TableVisitHistory(boolean defineColumns) { tableName = "visit_history"; if (defineColumns) { defineColumns(); } } public final TableVisitHistory defineColumns() { addColumn(new ColumnDefinition("resource_type", ColumnDefinition.ColumnType.Short, true, true)); addColumn(new ColumnDefinition("file_type", ColumnDefinition.ColumnType.Short, true, true)); addColumn(new ColumnDefinition("operation_type", ColumnDefinition.ColumnType.Short, true, true)); addColumn(new ColumnDefinition("resource_value", ColumnDefinition.ColumnType.String, true, true).setLength(StringMaxLength)); addColumn(new ColumnDefinition("data_more", ColumnDefinition.ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("last_visit_time", ColumnDefinition.ColumnType.Datetime, true)); addColumn(new ColumnDefinition("visit_count", ColumnDefinition.ColumnType.Integer)); orderColumns = "last_visit_time DESC"; return this; } private static final String Query_Resource_Type = "SELECT * FROM visit_history WHERE resource_type=? " + "ORDER BY last_visit_time DESC"; private static final String Query_File_Type = "SELECT * FROM visit_history WHERE file_type=? " + "ORDER BY last_visit_time DESC"; private static final String Query_Resource_File_Type = "SELECT * FROM visit_history WHERE resource_type=? AND file_type=?" + " ORDER BY last_visit_time DESC"; private static final String Query_Operation_Type = "SELECT * FROM visit_history WHERE operation_type=? " + "ORDER BY last_visit_time DESC"; private static final String Query_Operation_File_Type = "SELECT * FROM visit_history WHERE file_type=? AND operation_type=?" + " ORDER BY last_visit_time DESC"; private static final String Query_Resource_Operation_Type = "SELECT * FROM visit_history WHERE resource_type=? AND operation_type=? " + "ORDER BY last_visit_time DESC"; private static final String Query_Types = "SELECT * FROM visit_history WHERE resource_type=? AND file_type=? AND operation_type=? " + "ORDER BY last_visit_time DESC"; private static final String Query_More = " SELECT * FROM visit_history WHERE resource_type=? AND file_type=? AND operation_type=?" + " AND resource_value=? AND data_more=?"; private static final String Update_Visit = "UPDATE visit_history SET visit_count=?, last_visit_time=?" + " WHERE resource_type=? AND file_type=? AND operation_type=? AND resource_value=?"; private static final String Update_More = "UPDATE visit_history SET visit_count=?, data_more=?, last_visit_time=?" + " WHERE resource_type=? AND file_type=? AND operation_type=? AND resource_value=?"; private static final String Update_Visit_More = "UPDATE visit_history SET visit_count=?, last_visit_time=?" + " WHERE resource_type=? AND file_type=? AND operation_type=?" + " AND resource_value=? AND data_more=?"; private static final String Insert_Visit = "INSERT INTO visit_history " + "(resource_type, file_type, operation_type, resource_value, last_visit_time, visit_count) " + "VALUES(?,?,?,?,?,?)"; private static final String Insert_More = "INSERT INTO visit_history " + "(resource_type, file_type, operation_type, resource_value, data_more, last_visit_time, visit_count) " + "VALUES(?,?,?,?,?,?,?)"; private static final String Delete_Visit = "DELETE FROM visit_history " + " WHERE resource_type=? AND file_type=? AND operation_type=? AND resource_value=?"; private static final String Clear_Visit = "DELETE FROM visit_history " + " WHERE resource_type=? AND file_type=? AND operation_type=?"; @Override public boolean setValue(VisitHistory data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(VisitHistory data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(VisitHistory record) { if (record == null) { return false; } int resourceType = record.getResourceType(); if (resourceType == ResourceType.File || resourceType == ResourceType.Path) { String fname = record.getResourceValue(); return VisitHistoryTools.validFile(fname, resourceType, record.getFileType()); } else { return true; } } public List<VisitHistory> read(Connection conn, PreparedStatement statement, int count) { List<VisitHistory> records = new ArrayList<>(); try { conn.setAutoCommit(true); List<String> names = new ArrayList<>(); try (ResultSet results = statement.executeQuery(); PreparedStatement delete = conn.prepareStatement(Delete_Visit)) { while (results.next()) { VisitHistory data = readData(results); if (valid(data)) { String name = data.getResourceValue(); if (!names.contains(name)) { names.add(name); records.add(data); if (count > 0 && records.size() >= count) { break; } } } else { try { delete.setInt(1, data.getResourceType()); delete.setInt(2, data.getFileType()); delete.setInt(3, data.getOperationType()); delete.setString(4, data.getResourceValue()); delete.executeUpdate(); } catch (Exception e) { } } } } } catch (Exception e) { MyBoxLog.debug(e); } return records; } public List<VisitHistory> read(int resourceType, int count) { List<VisitHistory> records = new ArrayList<>(); if (resourceType < 0) { return records; } try (Connection conn = DerbyBase.getConnection(); PreparedStatement statement = conn.prepareStatement(Query_Resource_Type)) { conn.setAutoCommit(true); statement.setInt(1, resourceType); records = read(conn, statement, count); } catch (Exception e) { MyBoxLog.error(e); } return records; } public List<VisitHistory> read(int resourceType, int fileType, int count) { if (fileType == 0) { return read(resourceType, count); } List<VisitHistory> records = new ArrayList<>(); if (fileType < 0) { return records; } int[] types = VisitHistory.typeGroup(fileType); if (types != null) { return read(resourceType, types, count); } try (Connection conn = DerbyBase.getConnection()) { if (resourceType <= 0) { try (PreparedStatement statement = conn.prepareStatement(Query_File_Type)) { statement.setInt(1, fileType); records = read(conn, statement, count); } } else { try (PreparedStatement statement = conn.prepareStatement(Query_Resource_File_Type)) { statement.setInt(1, resourceType); statement.setInt(2, fileType); records = read(conn, statement, count); } } } catch (Exception e) { // MyBoxLog.debug(e); } return records; } public List<VisitHistory> read(int resourceType, int[] fileTypes, int count) { List<VisitHistory> records = new ArrayList<>(); if (fileTypes == null || fileTypes.length == 0) { return records; } String sql = "SELECT * FROM visit_history WHERE ( file_type=" + fileTypes[0]; for (int i = 1; i < fileTypes.length; ++i) { sql += " OR file_type=" + fileTypes[i]; } sql += " )"; if (resourceType > 0) { sql += " AND resource_type=" + resourceType; } sql += " ORDER BY last_visit_time DESC"; try (Connection conn = DerbyBase.getConnection(); PreparedStatement statement = conn.prepareStatement(sql)) { records = read(conn, statement, count); } catch (Exception e) { // MyBoxLog.debug(e); } return records; } public List<VisitHistory> read(int resourceType, int fileType, int operationType, int count) { int[] types = VisitHistory.typeGroup(fileType); if (types != null) { return read(resourceType, types, operationType, count); } if (operationType < 0) { return read(resourceType, fileType, count); } List<VisitHistory> records = new ArrayList<>(); try (Connection conn = DerbyBase.getConnection()) { if (resourceType <= 0) { if (fileType <= 0) { try (PreparedStatement statement = conn.prepareStatement(Query_Operation_Type)) { statement.setInt(1, operationType); records = read(conn, statement, count); } } else { try (PreparedStatement statement = conn.prepareStatement(Query_Operation_File_Type)) { statement.setInt(1, fileType); statement.setInt(2, operationType); records = read(conn, statement, count); } } } else { if (fileType <= 0) { try (PreparedStatement statement = conn.prepareStatement(Query_Resource_Operation_Type)) { statement.setInt(1, resourceType); statement.setInt(2, operationType); records = read(conn, statement, count); } } else { try (PreparedStatement statement = conn.prepareStatement(Query_Types)) { statement.setInt(1, resourceType); statement.setInt(2, fileType); statement.setInt(3, operationType); records = read(conn, statement, count); } } } } catch (Exception e) { MyBoxLog.debug(e); } return records; } public List<VisitHistory> read(int resourceType, int[] fileTypes, int operationType, int count) { if (operationType < 0) { return read(resourceType, fileTypes, count); } List<VisitHistory> records = new ArrayList<>(); if (fileTypes == null || fileTypes.length == 0) { return records; } String sql = " SELECT * FROM visit_history WHERE" + " operation_type=" + operationType + " AND ( file_type=" + fileTypes[0]; for (int i = 1; i < fileTypes.length; ++i) { sql += " OR file_type=" + fileTypes[i]; } sql += " )"; if (resourceType > 0) { sql += " AND resource_type=" + resourceType; } sql += " ORDER BY last_visit_time DESC "; try (Connection conn = DerbyBase.getConnection(); PreparedStatement statement = conn.prepareStatement(sql)) { records = read(conn, statement, count); } catch (Exception e) { // MyBoxLog.debug(e); } return records; } public VisitHistory read(int resourceType, int fileType, int operationType, String value) { if (resourceType < 0 || fileType < 0 || operationType < 0 || value == null) { return null; } try (Connection conn = DerbyBase.getConnection()) { return read(conn, resourceType, fileType, operationType, value); } catch (Exception e) { // MyBoxLog.debug(e); } return null; } public VisitHistory read(Connection conn, int resourceType, int fileType, int operationType, String value) { if (conn == null || resourceType < 0 || operationType < 0 || value == null) { return null; } try { if (fileType <= 0) { final String sql = "SELECT * FROM visit_history WHERE resource_type=?" + " AND operation_type=? AND resource_value=?"; try (PreparedStatement statement = conn.prepareStatement(sql)) { statement.setMaxRows(1); statement.setInt(1, resourceType); statement.setInt(2, operationType); statement.setString(3, value); VisitHistory his = null; conn.setAutoCommit(true); statement.setMaxRows(1); try (ResultSet results = statement.executeQuery()) { if (results.next()) { his = readData(results); } } return his; } } else { final String sql = "SELECT * FROM visit_history WHERE resource_type=?" + " AND file_type=? AND operation_type=? AND resource_value=?"; try (PreparedStatement statement = conn.prepareStatement(sql)) { statement.setMaxRows(1); statement.setInt(1, resourceType); statement.setInt(2, fileType); statement.setInt(3, operationType); statement.setString(4, value); VisitHistory his = null; conn.setAutoCommit(true); statement.setMaxRows(1); try (ResultSet results = statement.executeQuery()) { if (results.next()) { his = readData(results); } } return his; } } } catch (Exception e) { MyBoxLog.debug(e); } return null; } public List<VisitHistory> readAlphaImages(int count) { List<VisitHistory> records = new ArrayList<>(); try (Connection conn = DerbyBase.getConnection()) { final String sql = " SELECT * FROM visit_history " + " WHERE resource_type=? AND file_type=? " + " AND SUBSTR(LOWER(resource_value), LENGTH(resource_value) - 3 ) IN ('.png', '.tif', 'tiff') " + " ORDER BY last_visit_time DESC "; try (PreparedStatement statement = conn.prepareStatement(sql)) { statement.setInt(1, ResourceType.File); statement.setInt(2, FileType.Image); records = read(conn, statement, count); } } catch (Exception e) { // MyBoxLog.debug(e); } return records; } public List<VisitHistory> readNoAlphaImages(int count) { List<VisitHistory> records = new ArrayList<>(); try (Connection conn = DerbyBase.getConnection()) { final String sql = " SELECT * FROM visit_history " + " WHERE resource_type=? AND file_type=? " + " AND SUBSTR(LOWER(resource_value), LENGTH(resource_value) - 3 ) IN ('.jpg', '.bmp', '.gif', '.pnm', 'wbmp') " + " ORDER BY last_visit_time DESC "; try (PreparedStatement statement = conn.prepareStatement(sql)) { statement.setInt(1, ResourceType.File); statement.setInt(2, FileType.Image); records = read(conn, statement, count); } } catch (Exception e) { // MyBoxLog.debug(e); } return records; } public boolean update(int resourceType, int fileType, int operationType, String value) { return update(resourceType, fileType, operationType, value, null); } public boolean update(int resourceType, int fileType, int operationType, String value, String more) { if (resourceType < 0 || fileType < 0 || operationType < 0 || value == null) { return false; } try (Connection conn = DerbyBase.getConnection()) { return update(conn, resourceType, fileType, operationType, value, more); } catch (Exception e) { // MyBoxLog.debug(e); return false; } } public boolean update(Connection conn, int resourceType, int fileType, int operationType, String value) { return update(conn, resourceType, fileType, operationType, value, null); } public boolean update(Connection conn, int resourceType, int fileType, int operationType, String value, String more) { if (resourceType < 0 || fileType < 0 || operationType < 0 || value == null) { return false; } if (!VisitHistoryTools.validFile(value, resourceType, fileType)) { return false; } int finalType = fileType; if (fileType == FileType.MultipleFrames || fileType == FileType.Image) { String v = value.toLowerCase(); if (v.endsWith(".gif")) { finalType = FileType.Gif; } else if (v.endsWith(".tif") || v.endsWith(".tiff")) { finalType = FileType.Tif; } else { finalType = FileType.Image; } } if (fileType == FileType.DataFile) { String v = value.toLowerCase(); if (v.endsWith(".csv")) { finalType = FileType.CSV; } else if (v.endsWith(".xlsx") || v.endsWith(".xls")) { finalType = FileType.Excel; } else { finalType = FileType.Text; } } try { VisitHistory exist = read(conn, resourceType, finalType, operationType, value); String d = DateTools.datetimeToString(new Date()); if (exist != null) { if (more == null) { try (PreparedStatement statement = conn.prepareStatement(Update_Visit)) { statement.setInt(1, exist.getVisitCount() + 1); statement.setString(2, d); statement.setInt(3, resourceType); statement.setInt(4, finalType); statement.setInt(5, operationType); statement.setString(6, value); return statement.executeUpdate() >= 0; } } else { try (PreparedStatement statement = conn.prepareStatement(Update_More)) { statement.setInt(1, exist.getVisitCount() + 1); statement.setString(2, more); statement.setString(3, d); statement.setInt(4, resourceType); statement.setInt(5, finalType); statement.setInt(6, operationType); statement.setString(7, value); return statement.executeUpdate() >= 0; } } } else { int ret; if (more == null) { try (PreparedStatement statement = conn.prepareStatement(Insert_Visit)) { statement.setInt(1, resourceType); statement.setInt(2, finalType); statement.setInt(3, operationType); statement.setString(4, value); statement.setString(5, d); statement.setInt(6, 1); ret = statement.executeUpdate(); } } else { try (PreparedStatement statement = conn.prepareStatement(Insert_More)) { statement.setInt(1, resourceType); statement.setInt(2, finalType); statement.setInt(3, operationType); statement.setString(4, value); statement.setString(5, more); statement.setString(6, d); statement.setInt(7, 1); ret = statement.executeUpdate(); } } trim(conn, resourceType, fileType, operationType); return ret >= 0; } } catch (Exception e) { MyBoxLog.debug(e); return false; } } public boolean updateMenu(int fileType, String name, String fxml) { return updateMenu(fileType, OperationType.Access, name, fxml); } public boolean updateMenu(int fileType, int operationType, String name, String fxml) { if (fileType < 0 || operationType < 0 || name == null || fxml == null) { return false; } try (Connection conn = DerbyBase.getConnection()) { VisitHistory exist = null; try (PreparedStatement statement = conn.prepareStatement(Query_More)) { statement.setInt(1, ResourceType.Menu); statement.setInt(2, fileType); statement.setInt(3, operationType); statement.setString(4, name); statement.setString(5, fxml); conn.setAutoCommit(true); ResultSet results = statement.executeQuery(); if (results.next()) { exist = readData(results); } } Date d = new Date(); if (exist != null) { try (PreparedStatement statement = conn.prepareStatement(Update_Visit_More)) { statement.setInt(1, exist.getVisitCount() + 1); statement.setString(2, DateTools.datetimeToString(d)); statement.setInt(3, ResourceType.Menu); statement.setInt(4, fileType); statement.setInt(5, operationType); statement.setString(6, name); statement.setString(7, fxml); return statement.executeUpdate() >= 0; } } else { try (PreparedStatement statement = conn.prepareStatement(Insert_More)) { statement.setInt(1, ResourceType.Menu); statement.setInt(2, fileType); statement.setInt(3, operationType); statement.setString(4, name); statement.setString(5, fxml); statement.setString(6, DateTools.datetimeToString(d)); statement.setInt(7, 1); return statement.executeUpdate() >= 0; } } } catch (Exception e) { MyBoxLog.debug(e); return false; } } public boolean delete(Connection conn, int resourceType, int fileType, int operationType, String value) { if (conn == null || resourceType < 0 || fileType < 0 || operationType < 0 || value == null) { return false; } try (PreparedStatement statement = conn.prepareStatement(Delete_Visit)) { statement.setInt(1, resourceType); statement.setInt(2, fileType); statement.setInt(3, operationType); statement.setString(4, value); return statement.executeUpdate() >= 0; } catch (Exception e) { // MyBoxLog.debug(e); return false; } } public boolean delete(Connection conn, VisitHistory v) { return delete(conn, v.getResourceType(), v.getFileType(), v.getOperationType(), v.getResourceValue()); } public boolean clear(int resourceType, int fileType, int operationType) { try (Connection conn = DerbyBase.getConnection(); PreparedStatement statement = conn.prepareStatement(Clear_Visit)) { statement.setInt(1, resourceType); statement.setInt(2, fileType); statement.setInt(3, operationType); return statement.executeUpdate() >= 0; } catch (Exception e) { // MyBoxLog.debug(e); return false; } } public int clear() { final String sql = "DELETE FROM visit_history"; try (Connection conn = DerbyBase.getConnection(); PreparedStatement statement = conn.prepareStatement(sql)) { return statement.executeUpdate(); } catch (Exception e) { // MyBoxLog.debug(e); return -1; } } public void trim(Connection conn, int resourceType, int fileType, int operationType) { try (PreparedStatement query = conn.prepareStatement(Query_Types); PreparedStatement delete = conn.prepareStatement(deleteStatement())) { conn.setAutoCommit(true); query.setInt(1, resourceType); query.setInt(2, fileType); query.setInt(3, operationType); int qcount = 0, dcount = 0; try (ResultSet results = query.executeQuery()) { conn.setAutoCommit(false); while (results.next()) { VisitHistory data = readData(results); if (++qcount > AppVariables.fileRecentNumber || !valid(data)) { if (setDeleteStatement(conn, delete, data)) { delete.addBatch(); if (dcount > 0 && (dcount % Database.BatchSize == 0)) { int[] res = delete.executeBatch(); for (int r : res) { if (r > 0) { dcount += r; } } conn.commit(); delete.clearBatch(); } } } } delete.executeBatch(); conn.commit(); conn.setAutoCommit(true); } } catch (Exception e) { // MyBoxLog.error(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/db/table/TableFileBackup.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableFileBackup.java
package mara.mybox.db.table; import java.io.File; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Date; import java.util.List; import mara.mybox.controller.BaseTaskController; import mara.mybox.db.Database; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.FileBackup; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import static mara.mybox.fxml.WindowTools.recordError; import static mara.mybox.fxml.WindowTools.recordInfo; import static mara.mybox.fxml.WindowTools.taskError; import mara.mybox.tools.DateTools; import mara.mybox.tools.FileCopyTools; import mara.mybox.tools.FileDeleteTools; import mara.mybox.tools.FileNameTools; import mara.mybox.value.AppPaths; import static mara.mybox.value.AppPaths.getBackupsPath; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2021-2-26 * @License Apache License Version 2.0 */ public class TableFileBackup extends BaseTable<FileBackup> { public static final String BackupQuery = "SELECT * FROM File_Backup WHERE backup=?"; public TableFileBackup() { tableName = "File_Backup"; defineColumns(); } public TableFileBackup(boolean defineColumns) { tableName = "File_Backup"; if (defineColumns) { defineColumns(); } } public final TableFileBackup defineColumns() { addColumn(new ColumnDefinition("fbid", ColumnType.Long, true, true).setAuto(true)); addColumn(new ColumnDefinition("file", ColumnType.String, true).setLength(FilenameMaxLength)); addColumn(new ColumnDefinition("backup", ColumnType.String, true).setLength(FilenameMaxLength)); addColumn(new ColumnDefinition("record_time", ColumnType.Datetime, true)); return this; } public static final String Create_Index = "CREATE INDEX File_Backup_index on File_Backup ( file, backup, record_time )"; public static final String QueryPath = "SELECT * FROM File_Backup WHERE file=? "; public static final String FileQuery = "SELECT * FROM File_Backup WHERE file=? ORDER BY record_time DESC"; public static final String DeleteFile = "DELETE FROM File_Backup WHERE file=?"; public static final String DeleteBackup = "DELETE FROM File_Backup WHERE file=? AND backup=?"; @Override public boolean setValue(FileBackup data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(FileBackup data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(FileBackup data) { if (data == null) { return false; } return data.valid(); } public File path(File file) { if (file == null || !file.exists()) { return null; } try (Connection conn = DerbyBase.getConnection()) { return path(conn, file); } catch (Exception e) { return null; } } public File path(Connection conn, File file) { if (conn == null || file == null || !file.exists()) { return null; } try (PreparedStatement s = conn.prepareStatement(QueryPath)) { s.setString(1, file.getAbsolutePath()); FileBackup backup = query(conn, s); if (backup != null) { File backFile = backup.getBackup(); if (backFile != null && backFile.exists()) { return backFile.getParentFile(); } } } catch (Exception e) { MyBoxLog.error(e); } return null; } public List<FileBackup> read(File file) { List<FileBackup> records = new ArrayList<>(); if (file == null || !file.exists()) { return records; } try (Connection conn = DerbyBase.getConnection()) { return read(conn, file); } catch (Exception e) { MyBoxLog.debug(e, file.getAbsolutePath()); return records; } } public List<FileBackup> read(Connection conn, File file) { List<FileBackup> records = new ArrayList<>(); if (conn == null || file == null || !file.exists()) { return records; } try (PreparedStatement statement = conn.prepareStatement(FileQuery)) { int max = UserConfig.getInt(conn, "MaxFileBackups", FileBackup.Default_Max_Backups); if (max <= 0) { max = FileBackup.Default_Max_Backups; UserConfig.setInt(conn, "MaxFileBackups", FileBackup.Default_Max_Backups); } conn.setAutoCommit(true); statement.setString(1, file.getAbsolutePath()); try (ResultSet results = statement.executeQuery()) { while (results.next()) { FileBackup data = readData(results); if (data == null) { continue; } if (!data.valid() || records.size() >= max) { deleteData(conn, data); } else { records.add(data); } } } } catch (Exception e) { MyBoxLog.debug(e, file.getAbsolutePath()); } return records; } public FileBackup addBackup(File file) { if (file == null) { return null; } try (Connection conn = DerbyBase.getConnection()) { return addBackup(conn, file); } catch (Exception e) { MyBoxLog.debug(e, file.getAbsolutePath()); return null; } } public FileBackup addBackup(Connection conn, File file) { if (conn == null || file == null) { return null; } try { File backupPath = path(conn, file); if (backupPath == null) { String fname = file.getName(); String ext = FileNameTools.ext(fname); backupPath = new File(getBackupsPath() + File.separator + (ext == null || ext.isBlank() ? "x" : ext) + File.separator + FileNameTools.prefix(fname) + new Date().getTime() + File.separator); } backupPath.mkdirs(); File backupFile = new File(backupPath, FileNameTools.append(file.getName(), "-" + DateTools.nowFileString())); while (backupFile.exists()) { backupFile = new File(backupPath, FileNameTools.append(file.getName(), "-" + DateTools.nowFileString())); Thread.sleep(100); } if (!FileCopyTools.copyFile(file, backupFile, false, false)) { return null; } FileBackup data = new FileBackup(file, backupFile); data = insertData(conn, data); return data; } catch (Exception e) { MyBoxLog.debug(e, file.getAbsolutePath()); return null; } } public int count(Connection conn, File file) { List<FileBackup> records = read(conn, file); if (records == null) { return -1; } else { return records.size(); } } @Override public int deleteData(Connection conn, FileBackup data) { if (data == null) { return 0; } int count = super.deleteData(conn, data); if (count > 0) { FileDeleteTools.delete(data.getBackup()); } return count; } public long clearBackups(FxTask task, String filename) { long count = 0; if (filename == null) { return count; } try (Connection conn = DerbyBase.getConnection()) { List<String> files = new ArrayList<>(); files.add(filename); return clearBackups(task, conn, files); } catch (Exception e) { MyBoxLog.error(e); return count; } } public long clearBackups(FxTask task, Connection conn, List<String> files) { long count = 0; if (conn == null || files == null || files.isEmpty()) { return count; } // taskInfo(task, FileQuery); try (PreparedStatement query = conn.prepareStatement(FileQuery)) { conn.setAutoCommit(true); for (String file : files) { if (task != null && task.isCancelled()) { return count; } // taskInfo(task, message("Check") + ": " + file); query.setString(1, file); try (ResultSet results = query.executeQuery()) { while (results.next()) { if (task != null && task.isCancelled()) { return -3; } FileBackup data = readData(results); // taskInfo(task, message("Delete") + ": " + data.getBackup()); FileDeleteTools.delete(data.getBackup()); } } catch (Exception e) { taskError(task, e.toString() + "\n" + tableName); } } } catch (Exception e) { taskError(task, e.toString() + "\n" + tableName); } // taskInfo(task, DeleteFile); if (task != null && task.isCancelled()) { return count; } try (PreparedStatement statement = conn.prepareStatement(DeleteFile)) { conn.setAutoCommit(true); for (String file : files) { if (task != null && task.isCancelled()) { return count; } // taskInfo(task, message("Clear") + ": " + file); statement.setString(1, file); statement.executeUpdate(); count++; } } catch (Exception e) { taskError(task, e.toString() + "\n" + tableName); } return count; } public int clearInvalid(BaseTaskController taskController, Connection conn) { int count = clearInvalidRows(taskController, conn); return count + clearInvalidFiles(taskController, conn); } public int clearInvalidRows(BaseTaskController taskController, Connection conn) { int rowCount = 0, invalidCount = 0; try { recordInfo(taskController, message("Check") + ": " + tableName); try (PreparedStatement query = conn.prepareStatement(queryAllStatement()); PreparedStatement delete = conn.prepareStatement(deleteStatement())) { conn.setAutoCommit(true); try (ResultSet results = query.executeQuery()) { conn.setAutoCommit(false); while (results.next()) { rowCount++; if (taskController != null && taskController.getTask() != null && taskController.getTask().isCancelled()) { return invalidCount; } FileBackup data = readData(results); File file = data.getFile(); File backup = data.getBackup(); if (file == null || !file.exists() || backup == null || !backup.exists()) { if (backup != null && FileDeleteTools.delete(backup)) { recordInfo(taskController, message("Delete") + ": " + backup); } if (setDeleteStatement(conn, delete, data)) { delete.addBatch(); if (invalidCount > 0 && (invalidCount % Database.BatchSize == 0)) { int[] res = delete.executeBatch(); for (int r : res) { if (r > 0) { invalidCount += r; } } conn.commit(); delete.clearBatch(); } } } } } catch (Exception e) { recordError(taskController, e.toString() + "\n" + tableName); } int[] res = delete.executeBatch(); for (int r : res) { if (r > 0) { invalidCount += r; } } conn.commit(); } catch (Exception e) { recordError(taskController, e.toString() + "\n" + tableName); } conn.setAutoCommit(true); } catch (Exception e) { recordError(taskController, e.toString() + "\n" + tableName); } recordInfo(taskController, message("Checked") + ": " + rowCount + " " + message("Expired") + ": " + invalidCount); return invalidCount; } public int clearInvalidFiles(BaseTaskController taskController, Connection conn) { int rowCount = 0, invalidCount = 0; try { String fbRootpath = AppPaths.getBackupsPath(); recordInfo(taskController, message("Check") + ": " + fbRootpath); String[] fbPaths = new File(fbRootpath).list(); if (fbPaths == null || fbPaths.length == 0) { return invalidCount; } try (PreparedStatement query = conn.prepareStatement(BackupQuery)) { conn.setAutoCommit(true); for (String fbpath : fbPaths) { if (taskController != null && taskController.getTask() != null && taskController.getTask().isCancelled()) { return invalidCount; } File level1path = new File(fbRootpath + File.separator + fbpath); String[] level1names = level1path.list(); if (level1names == null || level1names.length == 0) { try { level1path.delete(); recordInfo(taskController, message("Delete") + ": " + level1path); } catch (Exception ex) { } continue; } for (String level1name : level1names) { rowCount++; if (taskController != null && taskController.getTask() != null && taskController.getTask().isCancelled()) { return invalidCount; } File level2file = new File(level1path, level1name); if (level2file.isDirectory()) { String[] level2names = level2file.list(); if (level2names == null || level2names.length == 0) { try { level2file.delete(); recordInfo(taskController, message("Delete") + ": " + level2file); } catch (Exception ex) { } } else { for (String level2name : level2names) { rowCount++; if (taskController != null && taskController.getTask() != null && taskController.getTask().isCancelled()) { return invalidCount; } File level3file = new File(level2file, level2name); query.setString(1, level3file.getAbsolutePath()); try (ResultSet results = query.executeQuery()) { if (!results.next()) { invalidCount++; if (FileDeleteTools.delete(level3file)) { recordInfo(taskController, message("Delete") + ": " + level3file); } } } catch (Exception e) { recordError(taskController, e.toString() + "\n" + level3file); } } level2names = level2file.list(); if (level2names == null || level2names.length == 0) { try { level2file.delete(); recordInfo(taskController, message("Delete") + ": " + level2file); } catch (Exception ex) { } } } } else { query.setString(1, level2file.getAbsolutePath()); try (ResultSet results = query.executeQuery()) { if (!results.next()) { invalidCount++; if (FileDeleteTools.delete(level2file)) { recordInfo(taskController, message("Delete") + ": " + level2file); } } } catch (Exception e) { recordError(taskController, e.toString() + "\n" + level2file); } } } level1names = level1path.list(); if (level1names == null || level1names.length == 0) { try { level1path.delete(); recordInfo(taskController, message("Delete") + ": " + level1path); } catch (Exception ex) { } } } } catch (Exception ex) { recordError(taskController, ex.toString() + "\n" + tableName); } } catch (Exception exx) { recordError(taskController, exx.toString() + "\n" + tableName); } recordInfo(taskController, message("Checked") + ": " + rowCount + " " + message("Expired") + ": " + invalidCount); return invalidCount; } }
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/table/TableAlarmClock.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableAlarmClock.java
package mara.mybox.db.table; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.List; import mara.mybox.db.data.AlarmClock; import mara.mybox.db.data.ColumnDefinition; import static mara.mybox.db.table.BaseTable.StringMaxLength; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2018-10-15 9:31:28 * @License Apache License Version 2.0 */ public class TableAlarmClock extends BaseTable<AlarmClock> { public TableAlarmClock() { tableName = "Alarm_Clock"; defineColumns(); } public TableAlarmClock(boolean defineColumns) { tableName = "Alarm_Clock"; if (defineColumns) { defineColumns(); } } @Override public boolean setValue(AlarmClock data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(AlarmClock data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(AlarmClock data) { if (data == null) { return false; } return data.valid(); } public final TableAlarmClock defineColumns() { addColumn(new ColumnDefinition("atid", ColumnDefinition.ColumnType.Long, true, true).setAuto(true)); addColumn(new ColumnDefinition("alarm_type", ColumnDefinition.ColumnType.Integer, true)); addColumn(new ColumnDefinition("every_value", ColumnDefinition.ColumnType.Integer)); addColumn(new ColumnDefinition("start_time", ColumnDefinition.ColumnType.Datetime)); addColumn(new ColumnDefinition("last_time", ColumnDefinition.ColumnType.Datetime)); addColumn(new ColumnDefinition("next_time", ColumnDefinition.ColumnType.Datetime)); addColumn(new ColumnDefinition("sound_loop_times", ColumnDefinition.ColumnType.Integer)); addColumn(new ColumnDefinition("is_sound_loop", ColumnDefinition.ColumnType.Boolean)); addColumn(new ColumnDefinition("is_sound_continully", ColumnDefinition.ColumnType.Boolean)); addColumn(new ColumnDefinition("is_active", ColumnDefinition.ColumnType.Boolean)); addColumn(new ColumnDefinition("volume", ColumnDefinition.ColumnType.Float)); addColumn(new ColumnDefinition("title", ColumnDefinition.ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("sound", ColumnDefinition.ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("description", ColumnDefinition.ColumnType.String).setLength(StringMaxLength)); return this; } @Override public int deleteData(Connection conn, AlarmClock alarmClock) { if (alarmClock == null) { return -1; } alarmClock.removeFromSchedule(); return super.deleteData(conn, alarmClock); } @Override public int deleteData(Connection conn, List<AlarmClock> dataList) { if (conn == null || dataList == null || dataList.isEmpty()) { return 0; } for (AlarmClock alarmClock : dataList) { alarmClock.removeFromSchedule(); } return super.deleteData(conn, dataList); } @Override public long clearData(Connection conn) { try (PreparedStatement statement = conn.prepareStatement("SELECT * FROM Alarm_Clock")) { conn.setAutoCommit(true); try (ResultSet results = statement.executeQuery()) { while (results.next()) { AlarmClock alarmClock = readData(results); if (alarmClock != null) { alarmClock.removeFromSchedule(); } } } } catch (Exception e) { MyBoxLog.error(e); return -1; } return super.clearData(conn); } }
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/table/TableColorPalette.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableColorPalette.java
package mara.mybox.db.table; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import javafx.scene.paint.Color; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColorData; import mara.mybox.db.data.ColorPalette; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2021-3-31 * @License Apache License Version 2.0 */ public class TableColorPalette extends BaseTable<ColorPalette> { protected TableColor tableColor; public TableColorPalette() { tableName = "Color_Palette"; defineColumns(); } public TableColorPalette(boolean defineColumns) { tableName = "Color_Palette"; if (defineColumns) { defineColumns(); } } public final TableColorPalette defineColumns() { addColumn(new ColumnDefinition("cpid", ColumnType.Long, true, true).setAuto(true)); addColumn(new ColumnDefinition("name_in_palette", ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("order_number", ColumnType.Float)); addColumn(new ColumnDefinition("paletteid", ColumnType.Long, true) .setReferName("Color_Palette_palette_fk").setReferTable("Color_Palette_Name").setReferColumn("cpnid") .setOnDelete(ColumnDefinition.OnDelete.Cascade) ); addColumn(new ColumnDefinition("cvalue", ColumnType.Integer, true) .setReferName("Color_Palette_color_fk").setReferTable("Color").setReferColumn("color_value") .setOnDelete(ColumnDefinition.OnDelete.Cascade) ); addColumn(new ColumnDefinition("description", ColumnType.String).setLength(StringMaxLength)); return this; } public static final String CreateView = " CREATE VIEW Color_Palette_View AS " + " SELECT Color_Palette.*, Color.* " + " FROM Color_Palette JOIN Color ON Color_Palette.cvalue=Color.color_value"; public static final String QueryValue = "SELECT * FROM Color_Palette WHERE paletteid=? AND cvalue=?"; public static final String QueryID = "SELECT * FROM Color_Palette WHERE cpid=?"; public static final String QueryPalette = "SELECT * FROM Color_Palette_View WHERE paletteid=? ORDER BY order_number"; public static final String MaxOrder = "SELECT max(order_number) FROM Color_Palette_View WHERE paletteid=?"; public static final String DeleteID = "DELETE FROM Color_Palette WHERE cpid=?"; public static final String ClearPalette = "DELETE FROM Color_Palette WHERE paletteid=?"; @Override public Object readForeignValue(ResultSet results, String column) { if (results == null || column == null) { return null; } try { if ("cvalue".equals(column) && results.findColumn("color_value") > 0) { return getTableColor().readData(results); } } catch (Exception e) { } return null; } @Override public boolean setForeignValue(ColorPalette data, String column, Object value) { if (data == null || column == null || value == null) { return true; } if ("cvalue".equals(column) && value instanceof ColorData) { data.setData((ColorData) value); } return true; } @Override public boolean setValue(ColorPalette data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(ColorPalette data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(ColorPalette data) { if (data == null) { return false; } return data.valid(); } public ColorPalette find(Connection conn, ColorData color, boolean asValue) { if (conn == null || color == null) { return null; } ColorPalette data = null; try (PreparedStatement qid = conn.prepareStatement(QueryID); PreparedStatement qvalue = conn.prepareStatement(QueryValue)) { data = find(qid, qvalue, color, asValue); } catch (Exception e) { MyBoxLog.error(e); } return data; } public ColorPalette find(PreparedStatement qid, PreparedStatement qvalue, ColorData color, boolean asValue) { if (color == null || qid == null || qvalue == null) { return null; } try { ColorPalette data = null; long cpid = color.getCpid(); if (cpid >= 0) { qid.setLong(1, cpid); qid.setMaxRows(1); try (ResultSet results = qid.executeQuery()) { if (results != null && results.next()) { data = readData(results); } } } if (data == null && asValue) { qvalue.setLong(1, color.getPaletteid()); qvalue.setInt(2, color.getColorValue()); qvalue.setMaxRows(1); try (ResultSet results = qvalue.executeQuery()) { if (results != null && results.next()) { data = readData(results); } } catch (Exception e) { MyBoxLog.error(e); } } return data; } catch (Exception e) { MyBoxLog.error(e); } return null; } public ColorPalette findAndCreate(long paletteid, ColorData color) { if (color == null || paletteid < 0) { return null; } try (Connection conn = DerbyBase.getConnection()) { color.setPaletteid(paletteid); return findAndCreate(conn, color, false, false); } catch (Exception e) { MyBoxLog.error(e); } return null; } public ColorPalette findAndCreate(ColorData color, boolean noDuplicate) { if (color == null) { return null; } try (Connection conn = DerbyBase.getConnection()) { return findAndCreate(conn, color, false, noDuplicate); } catch (Exception e) { MyBoxLog.error(e); } return null; } public ColorPalette findAndCreate(Connection conn, ColorData color, boolean keepOrder, boolean noDuplicate) { if (conn == null || color == null) { return null; } try { ColorData savedColor = getTableColor().write(conn, color, false); if (savedColor == null) { return null; } long paletteid = color.getPaletteid(); if (paletteid < 0) { return null; } boolean ac = conn.getAutoCommit(); conn.setAutoCommit(true); ColorPalette colorPalette = find(conn, color, noDuplicate); if (colorPalette == null) { float order = keepOrder ? color.getOrderNumner() : Float.MAX_VALUE; order = order == Float.MAX_VALUE ? max(conn, paletteid) + 1 : order; colorPalette = new ColorPalette() .setData(savedColor) .setName(color.getColorName()) .setColorValue(color.getColorValue()) .setPaletteid(paletteid) .setOrderNumber(order); colorPalette = insertData(conn, colorPalette); } conn.setAutoCommit(ac); return colorPalette; } catch (Exception e) { MyBoxLog.error(e); return null; } } public List<ColorData> colors(Connection conn, long paletteid, long start, long size) { if (start < 0 || size <= 0) { return new ArrayList<>(); } String condition = " WHERE paletteid=" + paletteid + " ORDER BY order_number " + " OFFSET " + start + " ROWS FETCH NEXT " + size + " ROWS ONLY"; return colors(conn, condition); } public List<ColorData> colors(long paletteid) { if (paletteid < 0) { return new ArrayList<>(); } String condition = " WHERE paletteid=" + paletteid + " ORDER BY order_number "; return colors(condition); } public List<ColorData> colors(String condition) { try (Connection conn = DerbyBase.getConnection()) { conn.setReadOnly(true); return colors(conn, condition); } catch (Exception e) { MyBoxLog.error(e); return null; } } public List<ColorData> colors(Connection conn, long paletteid) { if (paletteid < 0) { return new ArrayList<>(); } String condition = " WHERE paletteid=" + paletteid + " ORDER BY order_number "; return colors(conn, condition); } public List<ColorData> colors(Connection conn, String condition) { List<ColorData> colors = new ArrayList<>(); if (conn == null) { return colors; } String sql = "SELECT * FROM Color_Palette_View " + (condition == null || condition.isBlank() ? "" : condition); try (PreparedStatement statement = conn.prepareStatement(sql)) { conn.setAutoCommit(true); try (ResultSet results = statement.executeQuery()) { while (results.next()) { ColorPalette data = readData(results); ColorData color = data.getData(); color.setColorName(data.getName()); color.setOrderNumner(data.getOrderNumber()); color.setPaletteid(data.getPaletteid()); color.setCpid(data.getCpid()); colors.add(color); } } } catch (Exception e) { MyBoxLog.error(e, sql); } return colors; } public ColorPalette setOrder(long paletteid, ColorData color, float orderNumber) { if (paletteid < 0 || color == null) { return null; } try (Connection conn = DerbyBase.getConnection()) { color.setPaletteid(paletteid); ColorPalette data = find(conn, color, false); if (data != null) { data.setOrderNumber(orderNumber); data = updateData(conn, data); } else { ColorData savedColor = getTableColor().write(conn, color, false); if (savedColor == null) { return null; } data = new ColorPalette() .setData(savedColor) .setName(color.getColorName()) .setColorValue(color.getColorValue()) .setPaletteid(paletteid) .setOrderNumber(orderNumber); data = insertData(conn, data); } conn.commit(); return data; } catch (Exception e) { MyBoxLog.error(e); return null; } } public ColorPalette setName(long paletteid, ColorData color, String name) { if (paletteid < 0 || color == null) { return null; } try (Connection conn = DerbyBase.getConnection()) { color.setPaletteid(paletteid); ColorPalette data = find(conn, color, false); if (data != null) { data.setName(name); data = updateData(conn, data); } else { ColorData savedColor = getTableColor().write(conn, color, false); if (savedColor == null) { return null; } data = new ColorPalette() .setData(savedColor) .setName(name) .setColorValue(color.getColorValue()) .setPaletteid(paletteid) .setOrderNumber(max(conn, paletteid) + 1); data = insertData(conn, data); } conn.commit(); return data; } catch (Exception e) { MyBoxLog.error(e); return null; } } public List<ColorPalette> write(long paletteid, List<ColorData> colors, boolean keepOrder, boolean noDuplicate) { if (colors == null || colors.isEmpty()) { return null; } try (Connection conn = DerbyBase.getConnection()) { return write(conn, paletteid, colors, keepOrder, noDuplicate); } catch (Exception e) { MyBoxLog.error(e); return null; } } public List<ColorPalette> write(Connection conn, long paletteid, List<ColorData> colors, boolean keepOrder, boolean noDuplicate) { if (conn == null || colors == null || colors.isEmpty()) { return null; } List<ColorPalette> cpList = new ArrayList<>(); try (PreparedStatement qid = conn.prepareStatement(QueryID); PreparedStatement qvalue = conn.prepareStatement(QueryValue)) { conn.setAutoCommit(false); for (ColorData color : colors) { float order = keepOrder ? color.getOrderNumner() : Float.MAX_VALUE; order = order == Float.MAX_VALUE ? max(conn, paletteid) + 1 : order; color.setPaletteid(paletteid); ColorPalette colorPalette = find(qid, qvalue, color, noDuplicate); ColorPalette item; if (colorPalette == null) { ColorData savedColor = getTableColor().write(conn, color, false); if (savedColor == null) { return null; } colorPalette = new ColorPalette() .setData(savedColor) .setName(color.getColorName()) .setColorValue(color.getColorValue()) .setPaletteid(paletteid) .setOrderNumber(order); item = insertData(conn, colorPalette); } else { colorPalette.setData(color) .setName(color.getColorName()) .setOrderNumber(order); item = updateData(conn, colorPalette); } if (item != null) { cpList.add(item); } } conn.commit(); } catch (Exception e) { MyBoxLog.error(e); } return cpList; } public List<ColorPalette> writeColors(long paletteid, List<Color> colors, boolean noDuplicate) { if (colors == null || colors.isEmpty()) { return null; } List<ColorData> data = new ArrayList<>(); for (Color color : colors) { data.add(new ColorData(color)); } return write(paletteid, data, false, noDuplicate); } public int delete(ColorData color) { if (color == null) { return -1; } long cpid = color.getCpid(); if (cpid < 0) { return -2; } try (Connection conn = DerbyBase.getConnection()) { return delete(conn, cpid); } catch (Exception e) { MyBoxLog.error(e); return -3; } } public int delete(Connection conn, long cpid) { if (conn == null || cpid < 0) { return -1; } int count = 0; try (PreparedStatement statement = conn.prepareStatement(DeleteID)) { statement.setLong(1, cpid); count = statement.executeUpdate(); } catch (Exception e) { MyBoxLog.error(e); } return count; } public int delete(List<ColorData> colors) { if (colors == null || colors.isEmpty()) { return -1; } try (Connection conn = DerbyBase.getConnection()) { return delete(conn, colors); } catch (Exception e) { MyBoxLog.error(e); return -1; } } public int delete(Connection conn, List<ColorData> colors) { if (conn == null || colors == null || colors.isEmpty()) { return -1; } int count = 0; try (PreparedStatement statement = conn.prepareStatement(DeleteID)) { conn.setAutoCommit(false); for (ColorData color : colors) { long cpid = color.getCpid(); if (cpid < 0) { continue; } statement.setLong(1, cpid); count += statement.executeUpdate(); } conn.commit(); } catch (Exception e) { MyBoxLog.error(e); } return count; } public int clear(long paletteid) { try (Connection conn = DerbyBase.getConnection()) { return clear(conn, paletteid); } catch (Exception e) { MyBoxLog.error(e); return -1; } } public int clear(Connection conn, long paletteid) { if (conn == null) { return -1; } int count = 0; try (PreparedStatement statement = conn.prepareStatement(ClearPalette)) { statement.setLong(1, paletteid); count = statement.executeUpdate(); } catch (Exception e) { MyBoxLog.error(e); } return count; } public boolean trim(long paletteid) { try (Connection conn = DerbyBase.getConnection()) { return trim(conn, paletteid); } catch (Exception e) { MyBoxLog.error(e); return false; } } public boolean trim(Connection conn, long paletteid) { if (paletteid < 0) { return false; } try (PreparedStatement statement = conn.prepareStatement(QueryPalette)) { statement.setLong(1, paletteid); float order = 1f; conn.setAutoCommit(true); try (ResultSet results = statement.executeQuery()) { while (results.next()) { ColorPalette data = readData(results); data.setOrderNumber(order); updateData(conn, data); order += 1; } } } catch (Exception e) { MyBoxLog.error(e); return false; } return true; } public int size(Connection conn, long paletteid) { return conditionSize(conn, "paletteid=" + paletteid); } /* static methods */ public static float max(Connection conn, long paletteid) { try (PreparedStatement statement = conn.prepareStatement(MaxOrder)) { statement.setLong(1, paletteid); conn.setAutoCommit(true); try (ResultSet results = statement.executeQuery()) { if (results.next()) { return results.getFloat(1); } } } catch (Exception e) { } return 1f; } /* get/set */ public TableColor getTableColor() { if (tableColor == null) { tableColor = new TableColor(); } return tableColor; } public void setTableColor(TableColor tableColor) { this.tableColor = tableColor; } }
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/table/TableData2D.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableData2D.java
package mara.mybox.db.table; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.InvalidAs; import mara.mybox.db.data.Data2DRow; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2022-2-12 * @License Apache License Version 2.0 */ public class TableData2D extends BaseTable<Data2DRow> { @Override public boolean setValue(Data2DRow data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(Data2DRow data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(Data2DRow data) { if (data == null) { return false; } return data.valid(); } public Data2DRow newRow() { Data2DRow data2DRow = new Data2DRow(); for (ColumnDefinition column : columns) { data2DRow.setValue(column.getColumnName(), column.fromString(column.getDefaultValue(), InvalidAs.Empty)); } return data2DRow; } /* static */ public static String tableDefinition(String tableName) { try { TableData2D table = new TableData2D(); table.readDefinitionFromDB(tableName); return table.definitionHtml(); } catch (Exception e) { MyBoxLog.console(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/table/TableNodeWebFavorite.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableNodeWebFavorite.java
package mara.mybox.db.table; import java.io.File; import java.sql.Connection; import mara.mybox.controller.BaseController; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.DataNode; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.image.FxImageTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2021-4-23 * @License Apache License Version 2.0 */ public class TableNodeWebFavorite extends BaseNodeTable { public TableNodeWebFavorite() { tableName = "Node_Web_Favorite"; treeName = message("WebFavorite"); dataName = message("WebPageAddress"); dataFxml = Fxmls.ControlDataWebFavoriteFxml; examplesFileName = "WebFavorite"; majorColumnName = "address"; nodeExecutable = true; defineColumns(); } public final TableNodeWebFavorite defineColumns() { defineNodeColumns(); addColumn(new ColumnDefinition("address", ColumnType.File) .setLength(FilenameMaxLength) .setLabel(message("Address"))); addColumn(new ColumnDefinition("icon", ColumnType.Image) .setLength(FilenameMaxLength) .setLabel(message("Icon"))); return this; } @Override public boolean isNodeExecutable(DataNode node) { if (node == null) { return false; } String address = node.getStringValue("address"); return address != null && !address.isBlank(); } @Override public String valuesHtml(FxTask task, Connection conn, BaseController controller, DataNode node) { try { String address = node.getStringValue("address"); String icon = node.getStringValue("icon"); if (address == null || address.isBlank()) { return null; } String html = "<A href=\"" + address + "\">"; if (icon != null && !icon.isBlank()) { try { String base64 = FxImageTools.base64(null, new File(icon), "png"); if (base64 != null) { html += "<img src=\"data:image/png;base64," + base64 + "\" width=" + 40 + " >"; } } catch (Exception e) { } } html += address + "</A>\n"; return html; } catch (Exception e) { return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/db/table/TableNodeMacro.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableNodeMacro.java
package mara.mybox.db.table; import java.sql.Connection; import mara.mybox.controller.BaseController; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.DataNode; import mara.mybox.fxml.FxTask; import mara.mybox.tools.HtmlWriteTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2025-9-1 * @License Apache License Version 2.0 */ public class TableNodeMacro extends BaseNodeTable { public TableNodeMacro() { tableName = "Node_Macro"; treeName = message("MacroCommands"); dataName = message("MacroCommands"); dataFxml = Fxmls.ControlDataMacroFxml; examplesFileName = "Macro"; majorColumnName = "script"; nodeExecutable = true; defineColumns(); } public final TableNodeMacro defineColumns() { defineNodeColumns(); addColumn(new ColumnDefinition("script", ColumnType.Clob) .setLabel(message("MacroCommands"))); return this; } @Override public boolean isNodeExecutable(DataNode node) { if (node == null) { return false; } String script = node.getStringValue("script"); return script != null && !script.isBlank(); } @Override public String valuesHtml(FxTask task, Connection conn, BaseController controller, DataNode node) { try { String text = node.getStringValue("script"); return text == null || text.isBlank() ? null : HtmlWriteTools.codeToHtml(text); } catch (Exception e) { return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/db/table/BaseTable.java
alpha/MyBox/src/main/java/mara/mybox/db/table/BaseTable.java
package mara.mybox.db.table; import java.io.BufferedReader; import java.io.InputStream; import java.io.StringReader; import java.lang.reflect.ParameterizedType; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.sql.Timestamp; import java.sql.Types; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import mara.mybox.data.StringTable; import mara.mybox.data2d.DataInternalTable; import mara.mybox.data2d.DataTable; import mara.mybox.db.Database; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.BaseData; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import static mara.mybox.db.data.ColumnDefinition.ColumnType.Boolean; import static mara.mybox.db.data.ColumnDefinition.ColumnType.Clob; import static mara.mybox.db.data.ColumnDefinition.ColumnType.Enumeration; import static mara.mybox.db.data.ColumnDefinition.ColumnType.Era; import static mara.mybox.db.data.ColumnDefinition.ColumnType.Short; import mara.mybox.db.data.ColumnDefinition.InvalidAs; import mara.mybox.db.data.Data2DColumn; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.style.HtmlStyles; import mara.mybox.tools.DateTools; import mara.mybox.tools.DoubleTools; import mara.mybox.tools.FloatTools; import mara.mybox.tools.HtmlWriteTools; import mara.mybox.tools.IntTools; import mara.mybox.tools.LongTools; import mara.mybox.tools.ShortTools; import mara.mybox.tools.StringTools; import mara.mybox.value.AppValues; import static mara.mybox.value.Languages.message; /** * @param <D> Should be extened from "BaseData" * @Author Mara * @CreateDate 2020-7-12 * @License Apache License Version 2.0 */ public abstract class BaseTable<D> { public final static int FilenameMaxLength = 32672; public final static int StringMaxLength = 32672; public String tableName, idColumnName, orderColumns, tableTitle; public List<ColumnDefinition> columns, primaryColumns, foreignColumns, referredColumns; public boolean supportBatchUpdate; public long newID = -1; public abstract boolean valid(D data); public abstract boolean setValue(D data, String column, Object value); public abstract Object getValue(D data, String column); /* methods need implemented */ public Object readForeignValue(ResultSet results, String column) { return null; } public boolean setForeignValue(D data, String column, Object value) { return true; } public D readData(Connection conn, D data) { if (conn == null || data == null) { return null; } String sql = queryStatement(); if (sql == null || sql.isBlank()) { return null; } try (PreparedStatement statement = conn.prepareStatement(sql)) { if (setColumnsValues(statement, primaryColumns, data, 1) < 0) { return null; } return query(conn, statement); } catch (Exception e) { MyBoxLog.debug(e, sql); return null; } } public D readData(ResultSet results) { if (results == null) { return null; } try { D data = newData(); for (int i = 0; i < columns.size(); ++i) { ColumnDefinition column = columns.get(i); Object value = readColumnValue(results, column); setValue(data, column.getColumnName(), value); } for (int i = 0; i < foreignColumns.size(); ++i) { ColumnDefinition column = foreignColumns.get(i); String name = column.getColumnName(); Object value = readForeignValue(results, name); if (!setForeignValue(data, name, value)) { return null; } } return data; } catch (Exception e) { MyBoxLog.debug(e, tableName); } return null; } public Object readColumnValue(ResultSet results, ColumnDefinition column) { if (results == null || column == null) { return null; } return column.value(results); } public boolean setColumnValue(PreparedStatement statement, ColumnDefinition column, D data, int index) { if (statement == null || data == null || column == null || index < 0) { return false; } try { Object value = getValue(data, column.getColumnName()); // Not check maxValue/minValue. boolean notPermitNull = column.isNotNull(); switch (column.getType()) { case String: case Color: case File: case Image: case Enumeration: case EnumerationEditable: if (value == null && !notPermitNull) { statement.setNull(index, Types.VARCHAR); } else { String s; try { s = (String) value; } catch (Exception ex) { try { s = (String) column.defaultValue(); } catch (Exception exs) { s = ""; } } if (s == null && !notPermitNull) { s = ""; } if (s == null) { statement.setNull(index, Types.VARCHAR); } else { if (column.getLength() > 0 && s.length() > column.getLength()) { s = s.substring(0, column.getLength()); } statement.setString(index, s); } } break; case Double: if (value == null && !notPermitNull) { statement.setNull(index, Types.DOUBLE); } else { double d; try { d = (double) value; } catch (Exception ex) { try { d = (double) column.defaultValue(); } catch (Exception exs) { d = AppValues.InvalidDouble; } } if (DoubleTools.invalidDouble(d)) { d = AppValues.InvalidDouble; if (!notPermitNull) { statement.setNull(index, Types.DOUBLE); break; } } statement.setDouble(index, d); } break; case Longitude: if (value == null && !notPermitNull) { statement.setNull(index, Types.DOUBLE); } else { double d; try { d = (double) value; } catch (Exception ex) { d = -200; } if (DoubleTools.invalidDouble(d) || d > 180 || d < -180) { d = -200; if (!notPermitNull) { statement.setNull(index, Types.DOUBLE); break; } } statement.setDouble(index, d); } break; case Latitude: if (value == null && !notPermitNull) { statement.setNull(index, Types.DOUBLE); } else { double d; try { d = (double) value; } catch (Exception ex) { d = -200; } if (DoubleTools.invalidDouble(d) || d > 90 || d < -90) { d = -200; if (!notPermitNull) { statement.setNull(index, Types.DOUBLE); break; } } statement.setDouble(index, d); } break; case Float: if (value == null && !notPermitNull) { statement.setNull(index, Types.FLOAT); } else { float f; try { f = (float) value; } catch (Exception ex) { try { f = (float) column.defaultValue(); } catch (Exception exs) { f = AppValues.InvalidFloat; } } if (FloatTools.invalidFloat(f)) { f = AppValues.InvalidFloat; if (!notPermitNull) { statement.setNull(index, Types.FLOAT); break; } } statement.setFloat(index, f); } break; case Long: if (value == null && !notPermitNull) { statement.setNull(index, Types.BIGINT); } else { long l; try { l = (long) value; } catch (Exception ex) { try { l = (long) column.defaultValue(); } catch (Exception exx) { l = AppValues.InvalidLong; } } if (LongTools.invalidLong(l)) { l = AppValues.InvalidLong; if (!notPermitNull) { statement.setNull(index, Types.BIGINT); break; } } statement.setLong(index, l); } break; case Integer: if (value == null && !notPermitNull) { statement.setNull(index, Types.INTEGER); } else { int i; try { i = (int) value; } catch (Exception ex) { try { i = (int) column.defaultValue(); } catch (Exception exx) { i = AppValues.InvalidInteger; } } if (IntTools.invalidInt(i)) { i = AppValues.InvalidInteger; if (!notPermitNull) { statement.setNull(index, Types.INTEGER); break; } } statement.setInt(index, i); } break; case Short: if (value == null && !notPermitNull) { statement.setNull(index, Types.SMALLINT); } else { short r; try { if (value instanceof Integer) { // sometime value becomes Integer... r = (short) ((int) value); } else { r = (short) value; } } catch (Exception ex) { try { r = (short) column.defaultValue(); } catch (Exception exx) { r = AppValues.InvalidShort; } } if (ShortTools.invalidShort(r)) { r = AppValues.InvalidShort; if (!notPermitNull) { statement.setNull(index, Types.SMALLINT); break; } } statement.setShort(index, r); } break; case EnumeratedShort: if (value == null && !notPermitNull) { statement.setNull(index, Types.SMALLINT); } else { short r; try { if (value instanceof Integer) { // sometime value becomes Integer... r = (short) ((int) value); } else { r = (short) value; } } catch (Exception ex) { r = 0; } if (ShortTools.invalidShort(r)) { r = 0; if (!notPermitNull) { statement.setNull(index, Types.SMALLINT); break; } } statement.setShort(index, r); } break; case Boolean: if (value == null && !notPermitNull) { statement.setNull(index, Types.BOOLEAN); } else { boolean b; try { b = (boolean) value; } catch (Exception ex) { try { b = (boolean) column.defaultValue(); } catch (Exception exx) { b = false; } } statement.setBoolean(index, b); } break; case NumberBoolean: if (value == null && !notPermitNull) { statement.setNull(index, Types.SMALLINT); } else { short r; try { if (value instanceof Integer) { r = (short) ((int) value); } else { r = (short) value; } } catch (Exception ex) { r = 0; } if (ShortTools.invalidShort(r)) { r = 0; if (!notPermitNull) { statement.setNull(index, Types.SMALLINT); break; } } statement.setShort(index, r); } break; case Datetime: if (value == null && !notPermitNull) { statement.setNull(index, Types.TIMESTAMP); } else { Date dt; try { dt = (Date) value; } catch (Exception ex) { try { dt = (Timestamp) column.defaultValue(); } catch (Exception exx) { dt = null; } } if (dt == null) { if (!notPermitNull) { statement.setNull(index, Types.TIMESTAMP); break; } dt = new Date(); } statement.setTimestamp(index, new Timestamp(dt.getTime())); } break; case Date: if (value == null && !notPermitNull) { statement.setNull(index, Types.DATE); } else { Date dd; try { dd = (Date) value; } catch (Exception ex) { try { dd = (java.sql.Date) column.defaultValue(); } catch (Exception exx) { dd = null; } } if (dd == null) { if (!notPermitNull) { statement.setNull(index, Types.DATE); break; } dd = new Date(); } statement.setDate(index, new java.sql.Date(dd.getTime())); } break; case Era: if (value == null && !notPermitNull) { statement.setNull(index, Types.BIGINT); } else { long el; try { el = Long.parseLong(value + ""); if (el < 10000 && el > -10000) { Date ed = DateTools.encodeDate((String) value); el = ed.getTime(); } } catch (Exception ex) { try { Date ed = DateTools.encodeDate((String) value); el = ed.getTime(); } catch (Exception e) { el = AppValues.InvalidLong; } } if (LongTools.invalidLong(el)) { el = AppValues.InvalidLong; if (!notPermitNull) { statement.setNull(index, Types.BIGINT); break; } } statement.setLong(index, el); } break; case Clob: if (value == null && !notPermitNull) { statement.setNull(index, Types.CLOB); } else { String cb; try { cb = (String) value; } catch (Exception ex) { try { cb = (String) column.defaultValue(); } catch (Exception exs) { cb = null; } } if (cb == null) { if (!notPermitNull) { statement.setNull(index, Types.CLOB); break; } cb = ""; } // CLOB is handled as string internally, and maxmium length is Integer.MAX(2G) statement.setCharacterStream(index, new BufferedReader(new StringReader(cb)), cb.length()); } break; case Blob: if (value == null) { statement.setNull(index, Types.BLOB); } else { // BLOB is handled as InputStream internally try { statement.setBinaryStream(index, (InputStream) value); } catch (Exception ex) { statement.setNull(index, Types.BLOB); } } break; default: MyBoxLog.debug(column.getColumnName() + " " + column.getType() + " " + value); return false; } return true; } catch (Exception e) { MyBoxLog.debug(e.toString(), tableName + " " + column.getColumnName()); return false; } } public int setColumnsValues(PreparedStatement statement, List<ColumnDefinition> valueColumns, D data, int startIndex) { if (statement == null || data == null || startIndex < 0) { return -1; } try { int index = startIndex; for (int i = 0; i < valueColumns.size(); ++i) { ColumnDefinition column = valueColumns.get(i); if (!setColumnValue(statement, column, data, index++)) { return -1; } } return index; } catch (Exception e) { MyBoxLog.debug(e, tableName); return -1; } } public int setColumnNamesValues(PreparedStatement statement, List<String> valueColumns, D data, int startIndex) { if (statement == null || data == null || startIndex < 0) { return -1; } try { int index = startIndex; for (int i = 0; i < valueColumns.size(); ++i) { ColumnDefinition column = column(valueColumns.get(i)); if (!setColumnValue(statement, column, data, index++)) { return -1; } } return index; } catch (Exception e) { MyBoxLog.debug(e, tableName); return -1; } } public boolean setInsertStatement(Connection conn, PreparedStatement statement, D data) { if (conn == null || statement == null || data == null) { return false; } return setColumnsValues(statement, insertColumns(), data, 1) > 0; } public boolean setUpdateStatement(Connection conn, PreparedStatement statement, D data) { if (conn == null || statement == null || !valid(data)) { return false; } try { int index = setColumnsValues(statement, updateColumns(), data, 1); if (index < 0) { return false; } return setColumnsValues(statement, primaryColumns, data, index) > 0; } catch (Exception e) { MyBoxLog.debug(e, tableName); return false; } } public boolean setDeleteStatement(Connection conn, PreparedStatement statement, D data) { if (conn == null || statement == null || data == null) { return false; } return setColumnsValues(statement, primaryColumns, data, 1) > 0; } public List<String> allFields() { List<String> names = new ArrayList<>(); for (ColumnDefinition column : columns) { names.add(column.getColumnName()); } return names; } public List<String> importNecessaryFields() { List<String> names = new ArrayList<>(); for (ColumnDefinition column : columns) { if (column.isNotNull() && !column.isAuto()) { names.add(column.getColumnName()); } } return names; } public List<String> importAllFields() { return allFields(); } public List<String> exportAllFields() { return allFields(); } /* general methods which may need not change */ private void init() { tableName = null; idColumnName = null; orderColumns = null; columns = new ArrayList<>(); primaryColumns = new ArrayList<>(); foreignColumns = new ArrayList<>(); referredColumns = new ArrayList<>(); supportBatchUpdate = false; newID = -1; } public BaseTable() { init(); } public void reset() { init(); } public BaseTable addColumn(ColumnDefinition column) { if (column != null) { column.setTableName(tableName); column.setIndex(columns.size() + 1); if (column.isIsPrimaryKey()) { primaryColumns.add(column); if (column.isAuto()) { idColumnName = column.getColumnName(); } } if (column.getReferTable() != null && column.getReferColumn() != null) { foreignColumns.add(column); } columns.add(column); } return this; } public String createTableStatement() { if (tableName == null || columns.isEmpty()) { return null; } String sql = "CREATE TABLE " + DerbyBase.fixedIdentifier(tableName) + " ( \n"; for (int i = 0; i < columns.size(); ++i) { if (i > 0) { sql += ", \n"; } sql += createColumnDefiniton(columns.get(i)); } if (!primaryColumns.isEmpty()) { sql += ", \n"; sql += "PRIMARY KEY ( "; for (int i = 0; i < primaryColumns.size(); ++i) { if (i > 0) { sql += ", "; } sql += primaryColumns.get(i).getColumnName(); } sql += " ) "; } for (int i = 0; i < columns.size(); ++i) { ColumnDefinition column = columns.get(i); String f = column.foreignText(); if (f != null && !f.isBlank()) { sql += ", \n" + f; } } sql += "\n)"; return sql; } public String createColumnDefiniton(ColumnDefinition column) { if (tableName == null || columns.isEmpty()) { return null; } String colName = DerbyBase.fixedIdentifier(column.getColumnName()); String def = colName + " "; ColumnType type = column.getType(); switch (type) { case String: case File: case Image: case Enumeration: case EnumerationEditable: def += "VARCHAR(" + column.getLength() + ")"; break; case Color: def += "VARCHAR(16)"; break; case Double: case Longitude: case Latitude: def += "DOUBLE"; break; case Float: def += "FLOAT"; break; case Long: def += "BIGINT"; break; case Integer: def += "INT"; break; case Short: case EnumeratedShort: def += "SMALLINT"; break; case Boolean: def += "BOOLEAN"; break; case NumberBoolean: def += "SMALLINT"; break; case Datetime: def += "TIMESTAMP"; break; case Date: def += "DATE"; break; case Era: def += "BIGINT"; break; case Clob: def += "CLOB"; break; case Blob: def += "BLOB"; break; default: MyBoxLog.debug(colName + " " + type); return null; } if (column.isAuto()) { def += " NOT NULL GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1)"; } else if (column.isNotNull()) { def += " NOT NULL WITH DEFAULT " + column.dbDefaultValue(); } else if (column.getDefaultValue() != null) { def += " WITH DEFAULT " + column.dbDefaultValue(); } return def; } public boolean createTable(Connection conn) { if (conn == null) { return false; } String sql = null; try { sql = createTableStatement(); conn.createStatement().executeUpdate(sql); // MyBoxLog.console(sql); return true; } catch (Exception e) { MyBoxLog.debug(e, sql); return false; } } public final boolean createTable(Connection conn, boolean dropExisted) { if (conn == null || tableName == null) { return false; } try { if (DerbyBase.exist(conn, tableName) > 0) { if (!dropExisted) { return true; } dropTable(conn); conn.commit(); } createTable(conn); return true; } catch (Exception e) { MyBoxLog.debug(e); return false; } } public boolean dropTable(Connection conn) { if (conn == null) { return false; } String sql = null; try { sql = "DROP TABLE " + DerbyBase.fixedIdentifier(tableName); conn.createStatement().executeUpdate(sql); return true; } catch (Exception e) { MyBoxLog.debug(e, sql); return false; } } public boolean dropColumn(Connection conn, String colName) { if (conn == null || colName == null || colName.isBlank()) { return false; } String sql = null; try { sql = "ALTER TABLE " + DerbyBase.fixedIdentifier(tableName) + " DROP COLUMN " + DerbyBase.fixedIdentifier(colName); // MyBoxLog.console(sql); return conn.createStatement().executeUpdate(sql) >= 0; } catch (Exception e) { MyBoxLog.debug(e, sql); return false; } } public boolean addColumn(Connection conn, ColumnDefinition column) { if (conn == null || column == null) { return false; } String sql = null; try { sql = "ALTER TABLE " + DerbyBase.fixedIdentifier(tableName) + " ADD COLUMN " + createColumnDefiniton(column); return conn.createStatement().executeUpdate(sql) >= 0; } catch (Exception e) { MyBoxLog.debug(e, sql); return false; } } public void setId(D source, D target) { if (source == null || target == null || idColumnName == null) { return; } setValue(target, idColumnName, getValue(source, idColumnName)); } // https://stackoverflow.com/questions/18555122/create-instance-of-generic-type-in-java-when-parameterized-type-passes-through-h?r=SearchResults // https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Class.html#newInstance() public D newData() { try { Class<D> entityClass = (Class<D>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; D data = entityClass.getDeclaredConstructor().newInstance(); return data; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public String name() { return tableName; } public List<String> columnNames() { List<String> names = new ArrayList<>(); for (int i = 0; i < columns.size(); ++i) {
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/table/TableImageClipboard.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableImageClipboard.java
package mara.mybox.db.table; import java.io.File; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import mara.mybox.controller.BaseTaskController; import mara.mybox.db.Database; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.ImageClipboard; import static mara.mybox.fxml.WindowTools.recordError; import static mara.mybox.fxml.WindowTools.recordInfo; import mara.mybox.tools.FileDeleteTools; import mara.mybox.value.AppPaths; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2021-6-7 * @License Apache License Version 2.0 */ public class TableImageClipboard extends BaseTable<ImageClipboard> { public TableImageClipboard() { tableName = "Image_Clipboard"; defineColumns(); } public TableImageClipboard(boolean defineColumns) { tableName = "Image_Clipboard"; if (defineColumns) { defineColumns(); } } public final TableImageClipboard defineColumns() { addColumn(new ColumnDefinition("icid", ColumnType.Long, true, true).setAuto(true)); addColumn(new ColumnDefinition("image_file", ColumnType.File, true).setLength(FilenameMaxLength)); addColumn(new ColumnDefinition("thumbnail_file", ColumnType.File).setLength(FilenameMaxLength)); addColumn(new ColumnDefinition("width", ColumnType.Integer)); addColumn(new ColumnDefinition("height", ColumnType.Integer)); addColumn(new ColumnDefinition("source", ColumnType.Short)); addColumn(new ColumnDefinition("create_time", ColumnType.Datetime)); orderColumns = "create_time DESC"; return this; } public static final String FileQuery = "SELECT * FROM Image_Clipboard WHERE image_file=? OR thumbnail_file=?"; public static final String DeleteFile = "DELETE FROM Image_Clipboard WHERE image_file=?"; @Override public boolean setValue(ImageClipboard data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(ImageClipboard data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(ImageClipboard data) { if (data == null) { return false; } return data.valid(); } public int clearInvalid(BaseTaskController taskController, Connection conn) { int count = clearInvalidRows(taskController, conn); return count + clearInvalidFiles(taskController, conn); } public int clearInvalidRows(BaseTaskController taskController, Connection conn) { int rowCount = 0, invalidCount = 0; try { recordInfo(taskController, message("Check") + ": " + tableName); try (PreparedStatement query = conn.prepareStatement(queryAllStatement()); PreparedStatement delete = conn.prepareStatement(deleteStatement())) { conn.setAutoCommit(true); try (ResultSet results = query.executeQuery()) { conn.setAutoCommit(false); while (results.next()) { rowCount++; if (taskController != null && taskController.getTask() != null && taskController.getTask().isCancelled()) { return invalidCount; } ImageClipboard data = readData(results); File imageFile = data.getImageFile(); File thumbnailFile = data.getThumbnailFile(); if (imageFile == null || !imageFile.exists() || thumbnailFile == null || !thumbnailFile.exists()) { if (imageFile != null) { FileDeleteTools.delete(imageFile); recordInfo(taskController, message("Delete") + ": " + imageFile); } if (thumbnailFile != null) { FileDeleteTools.delete(thumbnailFile); recordInfo(taskController, message("Delete") + ": " + thumbnailFile); } if (setDeleteStatement(conn, delete, data)) { delete.addBatch(); if (invalidCount > 0 && (invalidCount % Database.BatchSize == 0)) { int[] res = delete.executeBatch(); for (int r : res) { if (r > 0) { invalidCount += r; } } conn.commit(); delete.clearBatch(); } } } } } catch (Exception e) { recordError(taskController, e.toString() + "\n" + tableName); } int[] res = delete.executeBatch(); for (int r : res) { if (r > 0) { invalidCount += r; } } conn.commit(); } catch (Exception e) { recordError(taskController, e.toString() + "\n" + tableName); } conn.setAutoCommit(true); } catch (Exception e) { recordError(taskController, e.toString() + "\n" + tableName); } recordInfo(taskController, message("Checked") + ": " + rowCount + " " + message("Expired") + ": " + invalidCount); return invalidCount; } public int clearInvalidFiles(BaseTaskController taskController, Connection conn) { int rowCount = 0, invalidCount = 0; try { String icpath = AppPaths.getImageClipboardPath(); recordInfo(taskController, message("Check") + ": " + icpath); String[] files = new File(icpath).list(); if (files == null || files.length == 0) { return invalidCount; } try (PreparedStatement query = conn.prepareStatement(FileQuery)) { conn.setAutoCommit(true); for (String name : files) { rowCount++; if (taskController != null && taskController.getTask() != null && taskController.getTask().isCancelled()) { return invalidCount; } String fname = icpath + File.separator + name; query.setString(1, fname); query.setString(2, fname); try (ResultSet results = query.executeQuery()) { if (!results.next()) { invalidCount++; FileDeleteTools.delete(fname); recordInfo(taskController, message("Delete") + ": " + fname); } } catch (Exception e) { recordError(taskController, e.toString() + "\n" + name); } } } catch (Exception ex) { recordError(taskController, ex.toString() + "\n" + tableName); } } catch (Exception exx) { recordError(taskController, exx.toString() + "\n" + tableName); } recordInfo(taskController, message("Checked") + ": " + rowCount + " " + message("Expired") + ": " + invalidCount); return invalidCount; } }
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/table/TableNodeDataColumn.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableNodeDataColumn.java
package mara.mybox.db.table; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.Data2DColumn; import mara.mybox.db.data.DataNode; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2024-12-19 * @License Apache License Version 2.0 */ public class TableNodeDataColumn extends BaseNodeTable { public TableNodeDataColumn() { tableName = "Node_Data_Column"; treeName = message("DataColumn"); dataName = message("DataColumn"); tableTitle = message("DataColumn"); dataFxml = Fxmls.ControlDataDataColumnFxml; examplesFileName = "DataColumn"; majorColumnName = "column_name"; defineColumns(); } public final TableNodeDataColumn defineColumns() { defineNodeColumns(); addColumn(new ColumnDefinition("column_name", ColumnType.String) .setLength(StringMaxLength) .setLabel(message("ColumnName"))); addColumn(new ColumnDefinition("column_type", ColumnType.String) .setLabel(message("Type"))); addColumn(new ColumnDefinition("length", ColumnType.Integer) .setLabel(message("Length"))); addColumn(new ColumnDefinition("width", ColumnType.Integer) .setLabel(message("Width"))); addColumn(new ColumnDefinition("scale", ColumnType.Integer) .setLabel(message("DecimalScale"))); addColumn(new ColumnDefinition("color", ColumnType.Color).setLength(16) .setLabel(message("Color"))); addColumn(new ColumnDefinition("is_auto", ColumnType.Boolean) .setLabel(message("AutoGenerated"))); addColumn(new ColumnDefinition("not_null", ColumnType.Boolean) .setLabel(message("NotNull"))); addColumn(new ColumnDefinition("editable", ColumnType.Boolean) .setLabel(message("Editable"))); addColumn(new ColumnDefinition("fix_year", ColumnType.Boolean) .setLabel(message("FixTwoDigitYears"))); addColumn(new ColumnDefinition("century", ColumnType.Integer) .setLabel(message("Century"))); addColumn(new ColumnDefinition("format", ColumnType.String) .setLength(StringMaxLength) .setLabel(message("DisplayFormat"))); addColumn(new ColumnDefinition("default_value", ColumnType.String) .setLength(StringMaxLength) .setLabel(message("DefaultValue"))); addColumn(new ColumnDefinition("description", ColumnType.String) .setLength(StringMaxLength) .setLabel(message("Description"))); return this; } public static DataNode fromColumn(DataNode node, Data2DColumn column) { if (column == null) { return null; } if (node == null) { node = DataNode.create().setTitle(column.getColumnName()); } node.setValue("column_name", column.getColumnName()); node.setValue("column_type", ColumnDefinition.columnTypeName(column.getType())); node.setValue("length", column.getLength()); node.setValue("width", column.getWidth()); node.setValue("scale", column.getScale()); node.setValue("color", ColumnDefinition.colorValue(column.getColor())); node.setValue("is_auto", column.isAuto()); node.setValue("not_null", column.isNotNull()); node.setValue("editable", column.isEditable()); node.setValue("fix_year", column.isFixTwoDigitYear()); node.setValue("century", column.getCentury()); node.setValue("format", column.getFormat()); node.setValue("default_value", column.getDefaultValue()); node.setValue("description", column.getDescription()); return node; } public static DataNode fromColumn(Data2DColumn column) { return fromColumn(null, column); } public static Data2DColumn toColumn(DataNode node) { if (node == null) { return null; } Data2DColumn column = new Data2DColumn(); column.setColumnName(node.getStringValue("column_name")); column.setType(ColumnDefinition.columnTypeFromName(node.getStringValue("column_type"))); column.setLength(node.getIntValue("length")); column.setWidth(node.getIntValue("width")); column.setScale(node.getIntValue("scale")); column.setColor(ColumnDefinition.color(node.getStringValue("color"))); column.setAuto(node.getBooleanValue("is_auto")); column.setNotNull(node.getBooleanValue("not_null")); column.setFixTwoDigitYear(node.getBooleanValue("fix_year")); column.setCentury(node.getIntValue("century")); column.setFormat(node.getStringValue("format")); column.setDefaultValue(node.getStringValue("default_value")); column.setDescription(node.getStringValue("description")); return column; } }
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/table/TableNodeSQL.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableNodeSQL.java
package mara.mybox.db.table; import java.sql.Connection; import mara.mybox.controller.BaseController; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.DataNode; import mara.mybox.fxml.FxTask; import mara.mybox.tools.HtmlWriteTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2021-4-23 * @License Apache License Version 2.0 */ public class TableNodeSQL extends BaseNodeTable { public TableNodeSQL() { tableName = "Node_SQL"; treeName = message("DatabaseSQL"); dataName = message("DatabaseSQL"); dataFxml = Fxmls.ControlDataSQLFxml; examplesFileName = "SQL"; majorColumnName = "statement"; nodeExecutable = true; defineColumns(); } public final TableNodeSQL defineColumns() { defineNodeColumns(); addColumn(new ColumnDefinition("statement", ColumnType.String) .setLength(FilenameMaxLength) .setLabel(message("SQL"))); return this; } @Override public boolean isNodeExecutable(DataNode node) { if (node == null) { return false; } String sql = node.getStringValue("statement"); return sql != null && !sql.isBlank(); } @Override public String valuesHtml(FxTask task, Connection conn, BaseController controller, DataNode node) { try { String sql = node.getStringValue("statement"); return sql == null || sql.isBlank() ? null : HtmlWriteTools.codeToHtml(sql); } catch (Exception e) { return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/db/table/TableConvolutionKernel.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableConvolutionKernel.java
package mara.mybox.db.table; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Date; import java.util.List; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ConvolutionKernel; import static mara.mybox.db.table.BaseTable.StringMaxLength; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.DateTools; /** * @Author Mara * @CreateDate 2018-11-6 20:54:43 * @License Apache License Version 2.0 */ public class TableConvolutionKernel extends BaseTable<ConvolutionKernel> { public TableConvolutionKernel() { tableName = "Convolution_Kernel"; defineColumns(); } public TableConvolutionKernel(boolean defineColumns) { tableName = "Convolution_Kernel"; if (defineColumns) { defineColumns(); } } public final TableConvolutionKernel defineColumns() { addColumn(new ColumnDefinition("name", ColumnDefinition.ColumnType.String, true, true).setLength(StringMaxLength)); addColumn(new ColumnDefinition("width", ColumnDefinition.ColumnType.Integer, true)); addColumn(new ColumnDefinition("height", ColumnDefinition.ColumnType.Integer, true)); addColumn(new ColumnDefinition("type", ColumnDefinition.ColumnType.Short)); addColumn(new ColumnDefinition("edge", ColumnDefinition.ColumnType.Short)); addColumn(new ColumnDefinition("color", ColumnDefinition.ColumnType.Short)); addColumn(new ColumnDefinition("is_invert", ColumnDefinition.ColumnType.Boolean)); addColumn(new ColumnDefinition("modify_time", ColumnDefinition.ColumnType.Datetime)); addColumn(new ColumnDefinition("create_time", ColumnDefinition.ColumnType.Datetime)); addColumn(new ColumnDefinition("description", ColumnDefinition.ColumnType.String).setLength(StringMaxLength)); return this; } @Override public boolean setValue(ConvolutionKernel data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(ConvolutionKernel data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(ConvolutionKernel data) { if (data == null) { return false; } return data.valid(); } public static List<ConvolutionKernel> read() { List<ConvolutionKernel> records = new ArrayList<>(); try (Connection conn = DerbyBase.getConnection(); PreparedStatement query = conn.prepareStatement("SELECT * FROM Convolution_Kernel ORDER BY name")) { conn.setReadOnly(true); try (ResultSet kResult = query.executeQuery()) { while (kResult.next()) { ConvolutionKernel record = read(conn, kResult); if (record != null) { records.add(record); } } } } catch (Exception e) { MyBoxLog.error(e); } return records; } public static ConvolutionKernel read(String name) { if (name == null) { return null; } try (Connection conn = DerbyBase.getConnection(); PreparedStatement kernelQuery = conn.prepareStatement(" SELECT * FROM Convolution_Kernel WHERE name=?");) { conn.setReadOnly(true); kernelQuery.setString(1, name); try (ResultSet kResult = kernelQuery.executeQuery()) { if (kResult.next()) { return read(conn, kResult); } } } catch (Exception e) { MyBoxLog.error(e); } return null; } public static ConvolutionKernel read(Connection conn, ResultSet kResult) { if (kResult == null) { return null; } try { ConvolutionKernel record = new ConvolutionKernel(); int w = kResult.getInt("width"); int h = kResult.getInt("height"); record.setName(kResult.getString("name")); record.setWidth(w); record.setHeight(h); record.setType(kResult.getInt("type")); record.setColor(kResult.getInt("color")); record.setInvert(kResult.getBoolean("is_invert")); record.setEdge(kResult.getInt("edge")); Date t = kResult.getTimestamp("create_time"); if (t != null) { record.setCreateTime(DateTools.datetimeToString(t)); } t = kResult.getTimestamp("modify_time"); if (t != null) { record.setModifyTime(DateTools.datetimeToString(t)); } record.setDescription(kResult.getString("description")); conn.setAutoCommit(true); try (PreparedStatement matrixQuery = conn.prepareStatement(" SELECT * FROM Float_Matrix WHERE name=? AND row=? AND col=?")) { float[][] matrix = new float[h][w]; for (int j = 0; j < h; ++j) { for (int i = 0; i < w; ++i) { matrixQuery.setString(1, record.getName()); matrixQuery.setInt(2, j); matrixQuery.setInt(3, i); try (ResultSet mResult = matrixQuery.executeQuery()) { if (mResult.next()) { matrix[j][i] = mResult.getFloat("value"); } } } } record.setMatrix(matrix); } return record; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static boolean existData(String name) { if (name == null) { return false; } try (Connection conn = DerbyBase.getConnection()) { conn.setReadOnly(true); return existData(conn, name); } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean existData(Connection conn, String name) { if (conn == null || name == null) { return false; } try (PreparedStatement kernelQuery = conn.prepareStatement(" SELECT width FROM Convolution_Kernel WHERE name=?")) { kernelQuery.setString(1, name); conn.setAutoCommit(true); try (ResultSet kResult = kernelQuery.executeQuery()) { return (kResult.next()); } } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean insert(Connection conn, ConvolutionKernel record) { String sql = "INSERT INTO Convolution_Kernel " + "(name, width , height, type, edge, color, is_invert, create_time, modify_time, description) " + " VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "; try (PreparedStatement update = conn.prepareStatement(sql)) { update.setString(1, record.getName()); update.setInt(2, record.getWidth()); update.setInt(3, record.getHeight()); update.setInt(4, record.getType()); update.setInt(5, record.getEdge()); update.setInt(6, record.getColor()); update.setBoolean(7, record.isInvert()); update.setString(8, record.getCreateTime()); update.setString(9, record.getModifyTime()); update.setString(10, record.getDescription()); update.executeUpdate(); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean update(Connection conn, ConvolutionKernel record) { String sql = "UPDATE Convolution_Kernel SET " + " width=?, height=?, type=?, edge=?, is_gray=?, is_invert=?, create_time=?, " + " modify_time=?, description=?" + " WHERE name=?"; try (PreparedStatement update = conn.prepareStatement(sql)) { update.setInt(1, record.getWidth()); update.setInt(2, record.getHeight()); update.setInt(3, record.getType()); update.setInt(4, record.getEdge()); update.setInt(5, record.getColor()); update.setBoolean(6, record.isInvert()); update.setString(7, record.getCreateTime()); update.setString(8, record.getModifyTime()); update.setString(9, record.getDescription()); update.setString(10, record.getName()); update.executeUpdate(); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean write(ConvolutionKernel record) { if (record == null || record.getName() == null || record.getWidth() < 3 || record.getWidth() % 2 == 0 || record.getHeight() < 3 || record.getHeight() % 2 == 0) { return false; } try (Connection conn = DerbyBase.getConnection()) { if (existData(conn, record.getName())) { return update(conn, record); } else { return insert(conn, record); } } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean writeExamples() { return write(ConvolutionKernel.makeExample()); } public static boolean write(List<ConvolutionKernel> records) { if (records == null || records.isEmpty()) { return false; } try (Connection conn = DerbyBase.getConnection()) { for (ConvolutionKernel k : records) { if (existData(conn, k.getName())) { update(conn, k); } else { insert(conn, k); } } return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean deleteRecords(List<ConvolutionKernel> records) { if (records == null || records.isEmpty()) { return false; } try (Connection conn = DerbyBase.getConnection()) { conn.setAutoCommit(false); try (PreparedStatement statement = conn.prepareStatement( "DELETE FROM Convolution_Kernel WHERE name=?")) { for (int i = 0; i < records.size(); ++i) { statement.setString(1, records.get(i).getName()); statement.executeUpdate(); } } conn.commit(); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean delete(List<String> names) { if (names == null || names.isEmpty()) { return false; } try (Connection conn = DerbyBase.getConnection()) { conn.setAutoCommit(false); try (PreparedStatement statement = conn.prepareStatement( "DELETE FROM Convolution_Kernel WHERE name=?")) { for (int i = 0; i < names.size(); ++i) { statement.setString(1, names.get(i)); statement.executeUpdate(); } } conn.commit(); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static float[][] readMatrix(String name) { float[][] matrix = null; if (name == null) { return matrix; } ConvolutionKernel k = read(name); if (k == null) { return matrix; } return TableFloatMatrix.read(name, k.getWidth(), k.getHeight()); } }
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/table/TableColorPaletteName.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableColorPaletteName.java
package mara.mybox.db.table; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Date; import java.util.List; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColorPaletteName; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2021-3-31 * @License Apache License Version 2.0 */ public class TableColorPaletteName extends BaseTable<ColorPaletteName> { protected TableColor tableColor; protected TableColorPalette tableColorPalette; public TableColorPaletteName() { tableName = "Color_Palette_Name"; defineColumns(); } public TableColorPaletteName(boolean defineColumns) { tableName = "Color_Palette_Name"; if (defineColumns) { defineColumns(); } } public final TableColorPaletteName defineColumns() { addColumn(new ColumnDefinition("cpnid", ColumnType.Long, true, true).setAuto(true)); addColumn(new ColumnDefinition("palette_name", ColumnType.String, true).setLength(StringMaxLength)); addColumn(new ColumnDefinition("visit_time", ColumnType.Datetime, true)); orderColumns = "visit_time DESC"; return this; } public static final String Create_Unique_Index = "CREATE UNIQUE INDEX Color_Palette_Name_unique_index on Color_Palette_Name ( palette_name )"; public static final String QueryName = "SELECT * FROM Color_Palette_Name WHERE palette_name=?"; @Override public boolean setValue(ColorPaletteName data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(ColorPaletteName data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(ColorPaletteName data) { if (data == null) { return false; } return data.valid(); } public ColorPaletteName find(String name) { if (name == null || name.isBlank()) { return null; } ColorPaletteName colorPaletteName = null; try (Connection conn = DerbyBase.getConnection()) { colorPaletteName = find(conn, name); } catch (Exception e) { MyBoxLog.error(e); } return colorPaletteName; } public ColorPaletteName find(Connection conn, String name) { if (conn == null || name == null || name.isBlank()) { return null; } ColorPaletteName palette = null; try (PreparedStatement statement = conn.prepareStatement(QueryName)) { statement.setString(1, name); statement.setMaxRows(1); conn.setAutoCommit(true); try (ResultSet results = statement.executeQuery()) { if (results.next()) { palette = readData(results); } } } catch (Exception e) { MyBoxLog.error(e); } if (palette != null) { try { palette.setVisitTime(new Date()); updateData(conn, palette); } catch (Exception e) { MyBoxLog.error(e); } } return palette; } public ColorPaletteName findAndCreate(String name) { if (name == null || name.isBlank()) { return null; } try (Connection conn = DerbyBase.getConnection()) { return findAndCreate(conn, name); } catch (Exception e) { MyBoxLog.error(e); return null; } } public ColorPaletteName findAndCreate(Connection conn, String name) { if (conn == null || name == null || name.isBlank()) { return null; } try { ColorPaletteName colorPaletteName = find(conn, name); if (colorPaletteName == null) { colorPaletteName = new ColorPaletteName(name); colorPaletteName = insertData(conn, colorPaletteName); conn.commit(); } return colorPaletteName; } catch (Exception e) { MyBoxLog.error(e); return null; } } public List<ColorPaletteName> recentVisited(Connection conn) { return query(conn, queryAllStatement(), 10); } /* get/set */ public TableColor getTableColor() { if (tableColor == null) { tableColor = new TableColor(); } return tableColor; } public void setTableDataset(TableColor tableColor) { this.tableColor = tableColor; } public TableColorPalette getTableColorPalette() { if (tableColorPalette == null) { tableColorPalette = new TableColorPalette(); } return tableColorPalette; } public void setTableColorPalette(TableColorPalette tableColorPalette) { this.tableColorPalette = tableColorPalette; } }
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/table/TableNodeMathFunction.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableNodeMathFunction.java
package mara.mybox.db.table; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2021-4-23 * @License Apache License Version 2.0 */ public class TableNodeMathFunction extends BaseNodeTable { public TableNodeMathFunction() { tableName = "Node_Math_Function"; treeName = message("MathFunction"); dataName = message("MathFunction"); tableTitle = message("MathFunction"); dataFxml = Fxmls.ControlDataMathFunctionFxml; examplesFileName = "MathFunction"; majorColumnName = "expression"; defineColumns(); } public final TableNodeMathFunction defineColumns() { defineNodeColumns(); addColumn(new ColumnDefinition("variables", ColumnType.String) .setLabel(message("Variables"))); addColumn(new ColumnDefinition("expression", ColumnType.Clob) .setLabel(message("Expression"))); addColumn(new ColumnDefinition("domain", ColumnType.Clob) .setLabel(message("FunctionDomain"))); 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/table/TablePathConnection.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TablePathConnection.java
package mara.mybox.db.table; import java.sql.Connection; import java.sql.PreparedStatement; 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.data.PathConnection; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2023-3-17 * @License Apache License Version 2.0 */ public class TablePathConnection extends BaseTable<PathConnection> { public TablePathConnection() { tableName = "Path_Connection"; defineColumns(); } public TablePathConnection(boolean defineColumns) { tableName = "Path_Connection"; if (defineColumns) { defineColumns(); } } public final TablePathConnection defineColumns() { addColumn(new ColumnDefinition("pcnid", ColumnType.Long, true, true).setAuto(true)); addColumn(new ColumnDefinition("type", ColumnType.String, true)); addColumn(new ColumnDefinition("title", ColumnType.String)); addColumn(new ColumnDefinition("host", ColumnType.String)); addColumn(new ColumnDefinition("username", ColumnType.String)); addColumn(new ColumnDefinition("password", ColumnType.String)); addColumn(new ColumnDefinition("path", ColumnType.String)); addColumn(new ColumnDefinition("rootpath", ColumnType.String)); addColumn(new ColumnDefinition("port", ColumnType.Integer)); addColumn(new ColumnDefinition("timeout", ColumnType.Integer)); addColumn(new ColumnDefinition("retry", ColumnType.Integer)); addColumn(new ColumnDefinition("host_key_check", ColumnType.Boolean)); addColumn(new ColumnDefinition("modify_time", ColumnType.Datetime)); addColumn(new ColumnDefinition("comments", ColumnType.String).setLength(StringMaxLength)); orderColumns = "modify_time DESC"; return this; } public static final String Query_Type = "SELECT * FROM Path_Connection WHERE type=?"; public static final String Clear_Type = "DELETE * FROM Path_Connection WHERE type=?"; @Override public boolean setValue(PathConnection data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(PathConnection data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(PathConnection data) { if (data == null) { return false; } return data.valid(); } /* local methods */ public List<PathConnection> read(PathConnection.Type type, int max) { if (type == null) { return null; } try (Connection conn = DerbyBase.getConnection();) { return read(conn, type, max); } catch (Exception e) { MyBoxLog.error(e); return null; } } public List<PathConnection> read(Connection conn, PathConnection.Type type, int max) { if (conn == null || type == null) { return null; } try (PreparedStatement statement = conn.prepareStatement(Query_Type)) { if (max > 0) { statement.setMaxRows(max); } statement.setString(1, type.name()); return query(statement); } catch (Exception e) { MyBoxLog.error(e); return null; } } public int clear(PathConnection.Type type) { if (type == null) { return -1; } try (Connection conn = DerbyBase.getConnection(); PreparedStatement statement = conn.prepareStatement(Clear_Type)) { statement.setString(1, type.name()); return statement.executeUpdate(); } catch (Exception e) { MyBoxLog.error(e); return -2; } } }
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/table/TableNodeHtml.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableNodeHtml.java
package mara.mybox.db.table; import java.sql.Connection; import mara.mybox.controller.BaseController; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.DataNode; import mara.mybox.fxml.FxTask; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2021-4-23 * @License Apache License Version 2.0 */ public class TableNodeHtml extends BaseNodeTable { public TableNodeHtml() { tableName = "Node_Html"; treeName = message("HtmlTree"); dataName = message("Html"); dataFxml = Fxmls.ControlDataHtmlFxml; examplesFileName = "HtmlTree"; majorColumnName = "html"; defineColumns(); } public final TableNodeHtml defineColumns() { defineNodeColumns(); addColumn(new ColumnDefinition("html", ColumnType.Clob) .setLabel(message("Html"))); return this; } @Override public String valuesHtml(FxTask task, Connection conn, BaseController controller, DataNode node) { try { return node.getStringValue("html"); } catch (Exception e) { return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/db/table/TableMyBoxLog.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableMyBoxLog.java
package mara.mybox.db.table; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2020-11-25 * @License Apache License Version 2.0 */ public class TableMyBoxLog extends BaseTable<MyBoxLog> { public TableMyBoxLog() { tableName = "MyBox_Log"; defineColumns(); } public TableMyBoxLog(boolean defineColumns) { tableName = "MyBox_Log"; if (defineColumns) { defineColumns(); } } public final TableMyBoxLog defineColumns() { addColumn(new ColumnDefinition("mblid", ColumnType.Long, true, true).setAuto(true)); addColumn(new ColumnDefinition("time", ColumnType.Datetime, true)); addColumn(new ColumnDefinition("log_type", ColumnType.Short, true)); addColumn(new ColumnDefinition("log", ColumnType.String, true).setLength(StringMaxLength)); addColumn(new ColumnDefinition("file_name", ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("class_name", ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("method_name", ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("line", ColumnType.Integer)); addColumn(new ColumnDefinition("callers", ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("comments", ColumnType.String).setLength(StringMaxLength)); orderColumns = "time DESC"; return this; } public static final String Create_Index = "CREATE INDEX MyBox_Log_index on MyBox_Log (time, log_type)"; public static final String AllQuery = " SELECT * FROM MyBox_Log ORDER BY time DESC "; public static final String TypeQuery = " SELECT * FROM MyBox_Log WHERE log_type=? ORDER BY time DESC "; @Override public boolean setValue(MyBoxLog data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(MyBoxLog data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(MyBoxLog data) { if (data == null) { return false; } return data.valid(); } }
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/table/TableNodeRowExpression.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableNodeRowExpression.java
package mara.mybox.db.table; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2021-4-23 * @License Apache License Version 2.0 */ public class TableNodeRowExpression extends BaseNodeTable { public TableNodeRowExpression() { tableName = "Node_Row_Expression"; treeName = message("RowExpression"); dataName = message("RowExpression"); dataFxml = Fxmls.ControlDataRowExpressionFxml; examplesFileName = "RowExpression"; majorColumnName = "script"; defineColumns(); } public final TableNodeRowExpression defineColumns() { defineNodeColumns(); addColumn(new ColumnDefinition("script", ColumnType.Clob) .setLabel(message("RowExpression"))); 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/table/TableNodeText.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableNodeText.java
package mara.mybox.db.table; import java.sql.Connection; import mara.mybox.controller.BaseController; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.DataNode; import mara.mybox.fxml.FxTask; import mara.mybox.tools.HtmlWriteTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2021-4-23 * @License Apache License Version 2.0 */ public class TableNodeText extends BaseNodeTable { public TableNodeText() { tableName = "Node_Text"; treeName = message("TextTree"); dataName = message("Texts"); dataFxml = Fxmls.ControlDataTextFxml; examplesFileName = "TextTree"; majorColumnName = "text"; defineColumns(); } public final TableNodeText defineColumns() { defineNodeColumns(); addColumn(new ColumnDefinition("text", ColumnType.Clob) .setLabel(message("Texts"))); return this; } @Override public String valuesHtml(FxTask task, Connection conn, BaseController controller, DataNode node) { try { String text = node.getStringValue("text"); return text == null || text.isBlank() ? null : HtmlWriteTools.codeToHtml(text); } catch (Exception e) { return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/db/table/TableWebHistory.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableWebHistory.java
package mara.mybox.db.table; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Date; import java.util.List; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.WebHistory; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2021-5-4 * @License Apache License Version 2.0 */ public class TableWebHistory extends BaseTable<WebHistory> { public TableWebHistory() { tableName = "Web_History"; defineColumns(); } public TableWebHistory(boolean defineColumns) { tableName = "Web_History"; if (defineColumns) { defineColumns(); } } public final TableWebHistory defineColumns() { addColumn(new ColumnDefinition("whid", ColumnType.Long, true, true).setAuto(true)); addColumn(new ColumnDefinition("address", ColumnType.String, true).setLength(StringMaxLength)); addColumn(new ColumnDefinition("visit_time", ColumnType.Datetime, true)); addColumn(new ColumnDefinition("title", ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("icon", ColumnType.String).setLength(StringMaxLength)); orderColumns = "visit_time DESC"; return this; } public static final String Create_Time_Index = "CREATE INDEX Web_History_time_index on Web_History ( visit_time )"; public static final String QueryID = "SELECT * FROM Web_History WHERE whid=?"; public static final String QueryAddresses = "SELECT address FROM Web_History ORDER BY visit_time DESC"; public static final String Times = "SELECT DISTINCT visit_time FROM Web_History ORDER BY visit_time DESC"; @Override public boolean setValue(WebHistory data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(WebHistory data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(WebHistory data) { if (data == null) { return false; } return data.valid(); } public List<String> recent(int number) { try (Connection conn = DerbyBase.getConnection()) { return recent(conn, number); } catch (Exception e) { MyBoxLog.error(e); return null; } } public List<String> recent(Connection conn, int number) { List<String> recent = new ArrayList<>(); if (conn == null) { return recent; } try { conn.setAutoCommit(true); try (PreparedStatement statement = conn.prepareStatement(QueryAddresses); ResultSet results = statement.executeQuery()) { while (results.next()) { String address = results.getString("address"); if (!recent.contains(address)) { recent.add(address); } if (recent.size() >= number) { break; } } } catch (Exception e) { MyBoxLog.error(e); } } catch (Exception e) { MyBoxLog.error(e); } return recent; } /* Static methods */ public static List<Date> times() { try (Connection conn = DerbyBase.getConnection()) { conn.setReadOnly(true); return times(conn); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static List<Date> times(Connection conn) { List<Date> times = new ArrayList(); if (conn == null) { return times; } try { conn.setAutoCommit(true); try (PreparedStatement statement = conn.prepareStatement(Times); ResultSet results = statement.executeQuery()) { while (results.next()) { Date time = results.getTimestamp("visit_time"); if (time != null) { times.add(time); } } } catch (Exception e) { MyBoxLog.error(e); } } catch (Exception e) { MyBoxLog.error(e); } return times; } }
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/table/TableDataNodeTag.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableDataNodeTag.java
package mara.mybox.db.table; 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.data.DataNode; import mara.mybox.db.data.DataNodeTag; import mara.mybox.db.data.DataTag; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2021-3-3 * @License Apache License Version 2.0 */ public class TableDataNodeTag extends BaseTable<DataNodeTag> { public static final String TableNameSuffix = "_Node_Tag"; protected BaseNodeTable nodeTable; protected TableDataTag tagTable; public TableDataNodeTag(BaseNodeTable table) { if (table == null) { return; } nodeTable = table; tagTable = new TableDataTag(nodeTable); init(); } public TableDataNodeTag(BaseNodeTable data, TableDataTag tag) { nodeTable = data; tagTable = tag; init(); } public final void init() { if (nodeTable == null || tagTable == null) { return; } tableName = nodeTable.tableName + TableNameSuffix; defineColumns(); } public final TableDataNodeTag defineColumns() { addColumn(new ColumnDefinition("tnodeid", ColumnType.Long, true, true) .setReferName(tableName + "_nodeid_fk") .setReferTable(nodeTable.tableName).setReferColumn(nodeTable.idColumnName) .setOnDelete(ColumnDefinition.OnDelete.Cascade) ); addColumn(new ColumnDefinition("ttagid", ColumnType.Long, true, true) .setReferName(tableName + "_tagid_fk") .setReferTable(tagTable.tableName).setReferColumn(tagTable.idColumnName) .setOnDelete(ColumnDefinition.OnDelete.Cascade) ); return this; } @Override public boolean setValue(DataNodeTag data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(DataNodeTag data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(DataNodeTag data) { if (data == null) { return false; } return data.valid(); } @Override public Object readForeignValue(ResultSet results, String column) { if (results == null || column == null || nodeTable == null || tagTable == null) { return null; } try { if ("tnodeid".equals(column) && results.findColumn("nodeid") > 0) { return nodeTable.readData(results); } if ("ttagid".equals(column) && results.findColumn("tagid") > 0) { return tagTable.readData(results); } } catch (Exception e) { } return null; } @Override public boolean setForeignValue(DataNodeTag data, String column, Object value) { if (data == null || column == null || value == null) { return true; } if ("tnodeid".equals(column) && value instanceof DataNode) { data.setNode((DataNode) value); } if ("ttagid".equals(column) && value instanceof DataTag) { data.setTag((DataTag) value); } return true; } public List<DataNodeTag> nodeTags(long nodeid) { List<DataNodeTag> tags = new ArrayList<>(); if (nodeid < 0) { return tags; } try (Connection conn = DerbyBase.getConnection()) { tags = nodeTags(conn, nodeid); } catch (Exception e) { MyBoxLog.error(e); } return tags; } public List<DataNodeTag> nodeTags(Connection conn, long nodeid) { List<DataNodeTag> tags = new ArrayList<>(); if (conn == null || nodeid < 0) { return tags; } String sql = "SELECT * FROM " + tableName + ", " + nodeTable.tableName + "_Tag" + " WHERE tnodeid=? AND ttagid=tagid"; try (PreparedStatement statement = conn.prepareStatement(sql)) { statement.setLong(1, nodeid); conn.setAutoCommit(true); ResultSet results = statement.executeQuery(); while (results.next()) { DataNodeTag tag = readData(results); if (tag != null) { tags.add(tag); } } } catch (Exception e) { MyBoxLog.error(e); } return tags; } public int setAll(Connection conn, long nodeid, List<DataTag> tags) { if (nodeTable == null || conn == null || nodeid < 0) { return -1; } removeTags(conn, nodeid); if (tags == null || tags.isEmpty()) { return 0; } int count = 0; try { for (DataTag dataTag : tags) { DataNodeTag nodeTag = DataNodeTag.create() .setTnodeid(nodeid).setTtagid(dataTag.getTagid()); count += insertData(conn, nodeTag) == null ? 0 : 1; } } catch (Exception e) { MyBoxLog.error(e); return -1; } return count; } public int removeTag(Connection conn, long nodeid, long tagid) { if (conn == null || nodeid < 0 || tagid < 0) { return -1; } String sql = "DELETE FROM " + tableName + " WHERE " + "tnodeid=" + nodeid + " AND tagid=" + tagid; try (PreparedStatement statement = conn.prepareStatement(sql)) { return statement.executeUpdate(); } catch (Exception e) { MyBoxLog.error(e); return -1; } } public int removeTags(Connection conn, long nodeid) { if (conn == null || nodeid < 0) { return -1; } String sql = "DELETE FROM " + tableName + " WHERE tnodeid=?"; try (PreparedStatement statement = conn.prepareStatement(sql)) { statement.setLong(1, nodeid); return statement.executeUpdate(); } catch (Exception e) { MyBoxLog.error(e); return -1; } } }
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/table/TableDataTag.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableDataTag.java
package mara.mybox.db.table; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.DataTag; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2021-3-3 * @License Apache License Version 2.0 */ public class TableDataTag extends BaseTable<DataTag> { public static final String TableNameSuffix = "_Tag"; protected BaseNodeTable nodeTable; public TableDataTag(BaseNodeTable table) { if (table == null) { return; } nodeTable = table; tableName = nodeTable.tableName + TableNameSuffix; idColumnName = "tagid"; defineColumns(); } public final TableDataTag defineColumns() { addColumn(new ColumnDefinition("tagid", ColumnType.Long, true, true).setAuto(true)); addColumn(new ColumnDefinition("tag", ColumnType.String, true).setLength(StringMaxLength)); addColumn(new ColumnDefinition("color", ColumnType.Color, true)); orderColumns = "tagid ASC"; return this; } @Override public boolean setValue(DataTag data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(DataTag data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(DataTag data) { if (data == null) { return false; } return data.valid(); } public DataTag queryTag(Connection conn, String tag) { if (conn == null || tag == null || tag.isBlank()) { return null; } DataTag dataTag = null; String sql = "SELECT * FROM " + tableName + " WHERE tag=? FETCH FIRST ROW ONLY"; try (PreparedStatement statement = conn.prepareStatement(sql)) { statement.setString(1, tag); ResultSet results = statement.executeQuery(); if (results.next()) { dataTag = readData(results); } } catch (Exception e) { MyBoxLog.error(e); } return dataTag; } }
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/table/TableColor.java
alpha/MyBox/src/main/java/mara/mybox/db/table/TableColor.java
package mara.mybox.db.table; 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 javafx.scene.paint.Color; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColorData; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.image.FxColorTools; import mara.mybox.value.AppValues; /** * @Author Mara * @CreateDate 2019-9-28 * @License Apache License Version 2.0 */ public class TableColor extends BaseTable<ColorData> { public TableColor() { tableName = "Color"; defineColumns(); } public TableColor(boolean defineColumns) { tableName = "Color"; if (defineColumns) { defineColumns(); } } public final TableColor defineColumns() { addColumn(new ColumnDefinition("color_value", ColumnType.Integer, true, true)); addColumn(new ColumnDefinition("rgba", ColumnType.Color, true).setLength(16)); addColumn(new ColumnDefinition("color_name", ColumnType.String).setLength(StringMaxLength)); addColumn(new ColumnDefinition("rgb", ColumnType.Color, true).setLength(16)); addColumn(new ColumnDefinition("srgb", ColumnType.String).setLength(128)); addColumn(new ColumnDefinition("hsb", ColumnType.String).setLength(128)); addColumn(new ColumnDefinition("ryb", ColumnType.Float)); addColumn(new ColumnDefinition("adobeRGB", ColumnType.String).setLength(128)); addColumn(new ColumnDefinition("appleRGB", ColumnType.String).setLength(128)); addColumn(new ColumnDefinition("eciRGB", ColumnType.String).setLength(128)); addColumn(new ColumnDefinition("sRGBLinear", ColumnType.String).setLength(128)); addColumn(new ColumnDefinition("adobeRGBLinear", ColumnType.String).setLength(128)); addColumn(new ColumnDefinition("appleRGBLinear", ColumnType.String).setLength(128)); addColumn(new ColumnDefinition("calculatedCMYK", ColumnType.String).setLength(128)); addColumn(new ColumnDefinition("eciCMYK", ColumnType.String).setLength(128)); addColumn(new ColumnDefinition("adobeCMYK", ColumnType.String).setLength(128)); addColumn(new ColumnDefinition("xyz", ColumnType.String).setLength(128)); addColumn(new ColumnDefinition("cieLab", ColumnType.String).setLength(128)); addColumn(new ColumnDefinition("lchab", ColumnType.String).setLength(128)); addColumn(new ColumnDefinition("cieLuv", ColumnType.String).setLength(128)); addColumn(new ColumnDefinition("lchuv", ColumnType.String).setLength(128)); orderColumns = "color_value DESC"; return this; } public static final String Create_RGBA_Unique_Index = "CREATE UNIQUE INDEX Color_rgba_unique_index on Color ( rgba )"; public static final String QueryRGBA = "SELECT * FROM Color WHERE rgba=?"; public static final String QueryValue = "SELECT * FROM Color WHERE color_value=?"; public static final String Delete = "DELETE FROM Color WHERE color_value=?"; @Override public boolean setValue(ColorData data, String column, Object value) { if (data == null || column == null) { return false; } return data.setValue(column, value); } @Override public Object getValue(ColorData data, String column) { if (data == null || column == null) { return null; } return data.getValue(column); } @Override public boolean valid(ColorData data) { if (data == null) { return false; } return data.valid(); } public ColorData read(int value) { ColorData data = null; try (Connection conn = DerbyBase.getConnection()) { conn.setReadOnly(true); data = read(conn, value); } catch (Exception e) { MyBoxLog.error(e); } return data; } public ColorData read(Connection conn, int value) { if (conn == null) { return null; } ColorData data = null; try (PreparedStatement statement = conn.prepareStatement(QueryValue)) { statement.setInt(1, value); statement.setMaxRows(1); conn.setAutoCommit(true); try (ResultSet results = statement.executeQuery()) { if (results != null && results.next()) { data = readData(results); } } catch (Exception e) { MyBoxLog.error(e); } } catch (Exception e) { MyBoxLog.error(e); } return data; } public ColorData read(String web) { try { int value = FxColorTools.web2Value(web); if (value == AppValues.InvalidInteger) { return null; } return read(value); } catch (Exception e) { return null; } } public ColorData read(Connection conn, String web) { try { int value = FxColorTools.web2Value(web); if (value == AppValues.InvalidInteger) { return null; } return read(conn, value); } catch (Exception e) { return null; } } public ColorData read(Color color) { if (color == null) { return null; } return read(FxColorTools.color2rgba(color)); } public ColorData findAndCreate(int value, String name) { ColorData data = null; try (Connection conn = DerbyBase.getConnection()) { data = findAndCreate(conn, value, name); } catch (Exception e) { MyBoxLog.error(e); } return data; } public ColorData findAndCreate(Connection conn, int value, String name) { try { boolean ac = conn.getAutoCommit(); ColorData data = read(conn, value); if (data == null) { data = new ColorData(value).calculate().setColorName(name); insertData(conn, data); } else if (name != null && !name.equals(data.getColorName())) { data.setColorName(name); updateData(conn, data.calculate()); } else if (data.needCalculate()) { updateData(conn, data.calculate()); } conn.setAutoCommit(ac); return data; } catch (Exception e) { MyBoxLog.error(e, value + ""); return null; } } public ColorData findAndCreate(String web, String name) { try (Connection conn = DerbyBase.getConnection()) { return findAndCreate(conn, web, name); } catch (Exception e) { MyBoxLog.error(e); return null; } } public ColorData findAndCreate(Connection conn, String web, String name) { try { int value = FxColorTools.web2Value(web); if (value == AppValues.InvalidInteger) { return null; } return findAndCreate(conn, value, name); } catch (Exception e) { MyBoxLog.error(e, web); return null; } } public ColorData write(String rgba, boolean replace) { try (Connection conn = DerbyBase.getConnection();) { return write(conn, rgba, null, replace); } catch (Exception e) { MyBoxLog.error(e); return null; } } public ColorData write(Connection conn, String rgba, String name, boolean replace) { if (conn == null || rgba == null) { return null; } ColorData exist = read(conn, rgba); if (exist != null) { if (replace) { ColorData data = new ColorData(rgba, name).calculate(); return updateData(conn, data); } else { return exist; } } else { ColorData data = new ColorData(rgba, name).calculate(); return insertData(conn, data); } } public ColorData write(Connection conn, String rgba, boolean replace) { return write(conn, rgba, null, replace); } public ColorData write(Color color, boolean replace) { try { return write(new ColorData(color), replace); } catch (Exception e) { return null; } } public ColorData write(ColorData data, boolean replace) { if (data == null) { return null; } try (Connection conn = DerbyBase.getConnection();) { return write(conn, data, replace); } catch (Exception e) { MyBoxLog.error(e); return null; } } public ColorData write(Connection conn, ColorData data, boolean replace) { if (conn == null || data == null) { return null; } ColorData exist = read(conn, data.getColorValue()); if (exist != null) { if (replace || data.needCalculate()) { return updateData(conn, data.calculate()); } else { return exist; } } else { return insertData(conn, data.calculate()); } } public List<ColorData> writeColors(List<Color> colors, boolean replace) { if (colors == null || colors.isEmpty()) { return null; } try (Connection conn = DerbyBase.getConnection()) { return writeColors(conn, colors, replace); } catch (Exception e) { MyBoxLog.error(e); return null; } } public List<ColorData> writeColors(Connection conn, List<Color> colors, boolean replace) { if (conn == null || colors == null || colors.isEmpty()) { return null; } List<ColorData> updateList = new ArrayList<>(); try { boolean ac = conn.getAutoCommit(); conn.setAutoCommit(false); for (Color color : colors) { ColorData data = new ColorData(color); data = write(conn, data, replace); if (data != null) { updateList.add(data); } } conn.commit(); conn.setAutoCommit(ac); } catch (Exception e) { MyBoxLog.error(e); } return updateList; } public List<ColorData> writeData(List<ColorData> dataList, boolean replace) { if (dataList == null) { return null; } try (Connection conn = DerbyBase.getConnection();) { return writeData(conn, dataList, replace); } catch (Exception e) { MyBoxLog.error(e); return null; } } public List<ColorData> writeData(Connection conn, List<ColorData> dataList, boolean replace) { if (conn == null || dataList == null) { return null; } List<ColorData> updateList = new ArrayList<>(); try { boolean ac = conn.getAutoCommit(); conn.setAutoCommit(false); for (ColorData data : dataList) { ColorData updated = write(conn, data, replace); if (updated != null) { updateList.add(updated); } } conn.commit(); conn.setAutoCommit(ac); } catch (Exception e) { MyBoxLog.error(e); } return updateList; } public boolean setName(Color color, String name) { if (color == null || name == null) { return false; } return setName(FxColorTools.color2Value(color), name); } public boolean setName(String rgba, String name) { if (name == null || rgba == null) { return false; } return setName(Color.web(rgba), name); } public boolean setName(int value, String name) { if (name == null) { return false; } try (Connection conn = DerbyBase.getConnection(); Statement statement = conn.createStatement()) { ColorData exist = read(conn, value); if (exist != null) { String sql = "UPDATE Color SET " + " color_name='" + DerbyBase.stringValue(name) + "' " + " WHERE color_value=" + value; return statement.executeUpdate(sql) > 0; } else { ColorData data = new ColorData(value).calculate(); data.setColorName(name); return insertData(conn, data) != null; } } catch (Exception e) { MyBoxLog.error(e); return false; } } /* static methods */ public static boolean delete(String web) { if (web == null) { return false; } try (Connection conn = DerbyBase.getConnection();) { return delete(conn, web); } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean delete(Connection conn, String web) { if (conn == null || web == null) { return false; } try (PreparedStatement delete = conn.prepareStatement(Delete)) { int value = FxColorTools.web2Value(web); if (value == AppValues.InvalidInteger) { return false; } delete.setInt(1, value); return delete.executeUpdate() >= 0; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static int delete(List<String> webList) { int count = 0; if (webList == null || webList.isEmpty()) { return count; } try (Connection conn = DerbyBase.getConnection(); PreparedStatement delete = conn.prepareStatement(Delete)) { boolean ac = conn.getAutoCommit(); conn.setAutoCommit(false); for (String web : webList) { int value = FxColorTools.web2Value(web); if (value == AppValues.InvalidInteger) { continue; } delete.setInt(1, value); int ret = delete.executeUpdate(); if (ret > 0) { count += ret; } } conn.commit(); conn.setAutoCommit(ac); } catch (Exception e) { MyBoxLog.error(e); } return 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/value/AppVariables.java
alpha/MyBox/src/main/java/mara/mybox/value/AppVariables.java
package mara.mybox.value; import java.awt.RenderingHints; import java.awt.Toolkit; import java.io.File; import java.sql.Connection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import mara.mybox.controller.AlarmClockController; import mara.mybox.controller.AutoTestingExecutionController; import mara.mybox.db.Database; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.VisitHistory; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.ImageClipboardMonitor; import mara.mybox.fxml.TextClipboardMonitor; import mara.mybox.fxml.WindowTools; import mara.mybox.fxml.style.StyleData; import mara.mybox.fxml.style.StyleTools; import static mara.mybox.value.Languages.isChinese; import static mara.mybox.value.Languages.sysDefaultLanguage; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class AppVariables { public static String[] AppArgs; public static File MyboxConfigFile, MyBoxLogsPath; public static String MyboxDataPath, AlarmClocksFile, CurrentLangName; public static File MyBoxTempPath, MyBoxDerbyPath, MyBoxLanguagesPath; public static List<File> MyBoxReservePaths; public static ResourceBundle CurrentBundle; public static Map<String, String> UserConfigValues = new HashMap<>(); public static Map<String, String> SystemConfigValues = new HashMap<>(); public static ScheduledExecutorService ExecutorService; public static Map<String, ScheduledFuture<?>> ScheduledTasks; public static AlarmClockController AlarmClockController; public static int sceneFontSize, fileRecentNumber, iconSize, thumbnailWidth, titleTrimSize, menuMaxLen, blockMatrixThreshold; public static long maxDemoImage; public static float sparseMatrixThreshold; public static boolean handlingExit, ShortcutsCanNotOmitCtrlAlt, icons40px, closeCurrentWhenOpenTool, operationWindowIconifyParent, recordWindowsSizeLocation, controlDisplayText, commitModificationWhenDataCellLoseFocus, ignoreDbUnavailable, popErrorLogs, saveDebugLogs, detailedDebugLogs, rejectInvalidValueWhenEdit, rejectInvalidValueWhenSave, useChineseWhenBlankTranslation; public static TextClipboardMonitor TextClipMonitor; public static ImageClipboardMonitor ImageClipMonitor; public static Timer ExitTimer; public static Map<RenderingHints.Key, Object> ImageHints; public static StyleData.StyleColor ControlColor; public static AutoTestingExecutionController autoTestingController; public static void initAppVaribles() { try { UserConfigValues.clear(); SystemConfigValues.clear(); CurrentLangName = Languages.getLangName(); CurrentBundle = Languages.getBundle(); ignoreDbUnavailable = false; autoTestingController = null; loadAppVaribles(); if (ExitTimer != null) { ExitTimer.cancel(); } ExitTimer = new Timer(); ExitTimer.schedule(new TimerTask() { @Override public void run() { if (handlingExit) { return; } System.gc(); WindowTools.checkExit(); } }, 0, 3000); } catch (Exception e) { MyBoxLog.error(e.toString()); } } public static void loadAppVaribles() { try { Connection conn = null; try { conn = DerbyBase.getConnection(); } catch (Exception e) { MyBoxLog.console(e.toString()); } closeCurrentWhenOpenTool = UserConfig.getBoolean(conn, "CloseCurrentWhenOpenTool", false); operationWindowIconifyParent = UserConfig.getBoolean(conn, "OperationWindowIconifyParent", true); recordWindowsSizeLocation = UserConfig.getBoolean(conn, "RecordWindowsSizeLocation", true); sceneFontSize = UserConfig.getInt(conn, "SceneFontSize", 15); fileRecentNumber = UserConfig.getInt(conn, "FileRecentNumber", VisitHistory.Default_Max_Histories); iconSize = UserConfig.getInt(conn, "IconSize", 20); ControlColor = StyleTools.getColorStyle(UserConfig.getString(conn, "ControlColor", "red")); controlDisplayText = UserConfig.getBoolean(conn, "ControlDisplayText", false); icons40px = UserConfig.getBoolean(conn, "Icons40px", Toolkit.getDefaultToolkit().getScreenResolution() <= 120); thumbnailWidth = UserConfig.getInt(conn, "ThumbnailWidth", 100); maxDemoImage = UserConfig.getLong(conn, "MaxDemoImage", 1000000); titleTrimSize = UserConfig.getInt(conn, "TitleTrimSize", 60); menuMaxLen = UserConfig.getInt(conn, "MenuMaxLen", 80); sparseMatrixThreshold = UserConfig.getFloat(conn, "SparseMatrixThreshold", 0.05f); blockMatrixThreshold = UserConfig.getInt(conn, "BlockMatrixThreshold", 30); ShortcutsCanNotOmitCtrlAlt = UserConfig.getBoolean(conn, "ShortcutsCanNotOmitCtrlAlt", false); useChineseWhenBlankTranslation = UserConfig.getBoolean(conn, "UseChineseWhenBlankTranslation", isChinese(sysDefaultLanguage())); commitModificationWhenDataCellLoseFocus = UserConfig.getBoolean(conn, "CommitModificationWhenDataCellLoseFocus", true); rejectInvalidValueWhenEdit = UserConfig.getBoolean(conn, "Data2DValidateEdit", false); rejectInvalidValueWhenSave = UserConfig.getBoolean(conn, "Data2DValidateSave", true); saveDebugLogs = UserConfig.getBoolean(conn, "SaveDebugLogs", false); detailedDebugLogs = UserConfig.getBoolean(conn, "DetailedDebugLogs", false); popErrorLogs = UserConfig.getBoolean(conn, "PopErrorLogs", true); Database.BatchSize = UserConfig.getLong(conn, "DatabaseBatchSize", 500); if (Database.BatchSize <= 0) { Database.BatchSize = 500; UserConfig.setLong(conn, "DatabaseBatchSize", 500); } ImageRenderHints.loadImageRenderHints(conn); if (conn != null) { conn.close(); } } catch (Exception e) { MyBoxLog.error(e.toString()); } } public static void lostFocusCommitData(boolean auto) { AppVariables.commitModificationWhenDataCellLoseFocus = auto; UserConfig.setBoolean("CommitModificationWhenDataCellLoseFocus", auto); } }
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/value/TimeFormats.java
alpha/MyBox/src/main/java/mara/mybox/value/TimeFormats.java
package mara.mybox.value; import java.util.TimeZone; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class TimeFormats { public static final TimeZone zoneUTC = TimeZone.getTimeZone("GMT+0"); // UTC public static final TimeZone zoneZhCN = TimeZone.getTimeZone("GMT+8"); // Beijing zone, UTC+0800 public static final String Datetime = "yyyy-MM-dd HH:mm:ss"; public static final String Date = "yyyy-MM-dd"; public static final String Month = "yyyy-MM"; public static final String Year = "yyyy"; public static final String Time = "HH:mm:ss"; public static final String TimeMs = "HH:mm:ss.SSS"; public static final String DatetimeMs = "yyyy-MM-dd HH:mm:ss.SSS"; public static final String DatetimeZone = "yyyy-MM-dd HH:mm:ss Z"; public static final String DatetimeMsZone = "yyyy-MM-dd HH:mm:ss.SSS Z"; public static final String Datetime2 = "yyyy-MM-dd_HH-mm-ss-SSS"; public static final String Datetime3 = "yyyyMMddHHmmssSSS"; public static final String Datetime4 = "yyyy-MM-dd_HH-mm-ss"; public static final String DatetimeFormat5 = "yyyy.MM.dd HH:mm:ss"; public static final String DatetimeA = "y-MM-dd HH:mm:ss"; public static final String DatetimeMsA = "y-MM-dd HH:mm:ss.SSS"; public static final String DateA = "y-MM-dd"; public static final String MonthA = "y-MM"; public static final String YearA = "y"; public static final String TimeA = "HH:mm:ss"; public static final String TimeMsA = "HH:mm:ss.SSS"; public static final String DatetimeB = "MM/dd/y HH:mm:ss"; public static final String DatetimeMsB = "MM/dd/y HH:mm:ss.SSS"; public static final String DateB = "MM/dd/y"; public static final String MonthB = "MM/y"; public static final String DatetimeC = "yyyy/MM/dd HH:mm:ss"; public static final String DatetimeMsC = "yyyy/MM/dd HH:mm:ss.SSS"; public static final String DateC = "yyyy/MM/dd"; public static final String MonthC = "yyyy/MM"; public static final String DatetimeZoneC = "yyyy/MM/dd HH:mm:ss Z"; public static final String DatetimeE = "MM/dd/yyyy HH:mm:ss"; public static final String DateE = "MM/dd/yyyy"; public static final String MonthE = "MM/yyyy"; public static final String DatetimeMsE = "MM/dd/yyyy HH:mm:ss.SSS"; public static final String DatetimeZoneE = "MM/dd/yyyy HH:mm:ss Z"; }
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/value/SystemConfig.java
alpha/MyBox/src/main/java/mara/mybox/value/SystemConfig.java
package mara.mybox.value; import java.sql.Connection; import mara.mybox.db.DerbyBase; import mara.mybox.db.table.TableSystemConf; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class SystemConfig { public static boolean setString(String key, String value) { try (Connection conn = DerbyBase.getConnection()) { return setString(conn, key, value); } catch (Exception e) { // MyBoxLog.error(e); return false; } } public static boolean setString(Connection conn, String key, String value) { AppVariables.SystemConfigValues.put(key, value); if (TableSystemConf.writeString(conn, key, value) >= 0) { return true; } else { return false; } } public static String getString(String key, String defaultValue) { try { // MyBoxLog.debug("getSystemConfigString:" + key); String value; if (AppVariables.SystemConfigValues.containsKey(key)) { value = AppVariables.SystemConfigValues.get(key); } else { value = TableSystemConf.readString(key, defaultValue); AppVariables.SystemConfigValues.put(key, value); } return value; } catch (Exception e) { // MyBoxLog.error(e.toString()); return null; } } public static boolean setInt(String key, int value) { AppVariables.SystemConfigValues.put(key, value + ""); if (TableSystemConf.writeInt(key, value) >= 0) { return true; } else { return false; } } public static int getInt(String key, int defaultValue) { try { int v; if (AppVariables.SystemConfigValues.containsKey(key)) { v = Integer.parseInt(AppVariables.SystemConfigValues.get(key)); } else { v = TableSystemConf.readInt(key, defaultValue); AppVariables.SystemConfigValues.put(key, v + ""); } return v; } catch (Exception e) { // MyBoxLog.error(e.toString()); return defaultValue; } } public static boolean setBoolean(String key, boolean value) { try (Connection conn = DerbyBase.getConnection()) { return setBoolean(conn, key, value); } catch (Exception e) { // MyBoxLog.error(e); return false; } } public static boolean setBoolean(Connection conn, String key, boolean value) { AppVariables.SystemConfigValues.put(key, value ? "true" : "false"); if (TableSystemConf.writeBoolean(conn, key, value) >= 0) { return true; } else { return false; } } public static boolean getBoolean(String key, boolean defaultValue) { try { boolean v; if (AppVariables.SystemConfigValues.containsKey(key)) { v = AppVariables.SystemConfigValues.get(key).equals("true"); } else { v = TableSystemConf.readBoolean(key, defaultValue); AppVariables.SystemConfigValues.put(key, v ? "true" : "false"); } return v; } catch (Exception e) { // MyBoxLog.error(e.toString()); return defaultValue; } } public static boolean getBoolean(String key) { return getBoolean(key, true); } public static boolean deleteValue(String key) { if (TableSystemConf.delete(key)) { AppVariables.SystemConfigValues.remove(key); return true; } else { 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/value/Fxmls.java
alpha/MyBox/src/main/java/mara/mybox/value/Fxmls.java
package mara.mybox.value; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class Fxmls { public static final String MyboxFxml = "/fxml/MyBox.fxml"; public static final String MyBoxLoadingFxml = "/fxml/MyBoxLoading.fxml"; public static final String MyBoxSetupFxml = "/fxml/MyBoxSetup.fxml"; /* document */ public static final String PdfViewFxml = "/fxml/PdfView.fxml"; public static final String PdfAttributesFxml = "/fxml/PdfAttributes.fxml"; public static final String PdfAttributesBatchFxml = "/fxml/PdfAttributesBatch.fxml"; public static final String PdfExtractImagesBatchFxml = "/fxml/PdfExtractImagesBatch.fxml"; public static final String PdfExtractTextsBatchFxml = "/fxml/PdfExtractTextsBatch.fxml"; public static final String PdfConvertHtmlsBatchFxml = "/fxml/PdfConvertHtmlsBatch.fxml"; public static final String PdfConvertImagesBatchFxml = "/fxml/PdfConvertImagesBatch.fxml"; public static final String PdfCompressImagesBatchFxml = "/fxml/PdfCompressImagesBatch.fxml"; public static final String PdfImagesConvertBatchFxml = "/fxml/PdfImagesConvertBatch.fxml"; public static final String PdfInformationFxml = "/fxml/PdfInformation.fxml"; public static final String PdfOCRBatchFxml = "/fxml/PdfOCRBatch.fxml"; public static final String PdfMergeFxml = "/fxml/PdfMerge.fxml"; public static final String PdfSplitBatchFxml = "/fxml/PdfSplitBatch.fxml"; public static final String PdfAddWatermarkBatchFxml = "/fxml/PdfAddWatermarkBatch.fxml"; public static final String HtmlEditorFxml = "/fxml/HtmlEditor.fxml"; public static final String HtmlDomCopyFxml = "/fxml/HtmlDomCopy.fxml"; public static final String HtmlDomAddFxml = "/fxml/HtmlDomAdd.fxml"; public static final String HtmlDomMoveFxml = "/fxml/HtmlDomMove.fxml"; public static final String HtmlDomDeleteFxml = "/fxml/HtmlDomDelete.fxml"; public static final String HtmlToMarkdownFxml = "/fxml/HtmlToMarkdown.fxml"; public static final String HtmlToTextFxml = "/fxml/HtmlToText.fxml"; public static final String HtmlToPdfFxml = "/fxml/HtmlToPdf.fxml"; public static final String HtmlSetCharsetFxml = "/fxml/HtmlSetCharset.fxml"; public static final String HtmlSetStyleFxml = "/fxml/HtmlSetStyle.fxml"; public static final String HtmlSetEquivFxml = "/fxml/HtmlSetEquiv.fxml"; public static final String HtmlSnapFxml = "/fxml/HtmlSnap.fxml"; public static final String HtmlTypesettingFxml = "/fxml/HtmlTypesetting.fxml"; public static final String HtmlExtractTablesFxml = "/fxml/HtmlExtractTables.fxml"; public static final String HtmlMergeAsHtmlFxml = "/fxml/HtmlMergeAsHtml.fxml"; public static final String HtmlMergeAsMarkdownFxml = "/fxml/HtmlMergeAsMarkdown.fxml"; public static final String HtmlMergeAsPDFFxml = "/fxml/HtmlMergeAsPDF.fxml"; public static final String HtmlMergeAsTextFxml = "/fxml/HtmlMergeAsText.fxml"; public static final String HtmlFramesetFxml = "/fxml/HtmlFrameset.fxml"; public static final String HtmlFindFxml = "/fxml/HtmlFind.fxml"; public static final String HtmlElementsFxml = "/fxml/HtmlElements.fxml"; public static final String HtmlTableFxml = "/fxml/HtmlTable.fxml"; public static final String HtmlPopFxml = "/fxml/HtmlPop.fxml"; public static final String HtmlCodesPopFxml = "/fxml/HtmlCodesPop.fxml"; public static final String WebAddressFxml = "/fxml/WebAddress.fxml"; public static final String MarkdownEditorFxml = "/fxml/MarkdownEditor.fxml"; public static final String MarkdownToHtmlFxml = "/fxml/MarkdownToHtml.fxml"; public static final String MarkdownToTextFxml = "/fxml/MarkdownToText.fxml"; public static final String MarkdownToPdfFxml = "/fxml/MarkdownToPdf.fxml"; public static final String MarkdownPopFxml = "/fxml/MarkdownPop.fxml"; public static final String MarkdownTypesettingFxml = "/fxml/MarkdownTypesetting.fxml"; public static final String MarkdownOptionsFxml = "/fxml/MarkdownOptions.fxml"; public static final String JsonEditorFxml = "/fxml/JsonEditor.fxml"; public static final String JsonAddFieldFxml = "/fxml/JsonAddField.fxml"; public static final String JsonAddElementFxml = "/fxml/JsonAddElement.fxml"; public static final String JsonTypesettingFxml = "/fxml/JsonTypesetting.fxml"; public static final String JsonOptionsFxml = "/fxml/JsonOptions.fxml"; public static final String XmlEditorFxml = "/fxml/XmlEditor.fxml"; public static final String XmlAddNodeFxml = "/fxml/XmlAddNode.fxml"; public static final String XmlTypesettingFxml = "/fxml/XmlTypesetting.fxml"; public static final String XmlOptionsFxml = "/fxml/XmlOptions.fxml"; public static final String TextEditorFxml = "/fxml/TextEditor.fxml"; public static final String TextEditorSaveAsFxml = "/fxml/TextEditorSaveAs.fxml"; public static final String TextEditorFormatFxml = "/fxml/TextEditorFormat.fxml"; public static final String TextLocateFxml = "/fxml/TextLocate.fxml"; public static final String TextFilterFxml = "/fxml/TextFilter.fxml"; public static final String TextIntervalInputFxml = "/fxml/TextIntervalInput.fxml"; public static final String TextFilesConvertFxml = "/fxml/TextFilesConvert.fxml"; public static final String TextFilesMergeFxml = "/fxml/TextFilesMerge.fxml"; public static final String TextFindBatchFxml = "/fxml/TextFindBatch.fxml"; public static final String TextReplaceBatchFxml = "/fxml/TextReplaceBatch.fxml"; public static final String TextFilterBatchFxml = "/fxml/TextFilterBatch.fxml"; public static final String TextToHtmlFxml = "/fxml/TextToHtml.fxml"; public static final String TextToPdfFxml = "/fxml/TextToPdf.fxml"; public static final String TextInSystemClipboardFxml = "/fxml/TextInSystemClipboard.fxml"; public static final String TextInMyBoxClipboardFxml = "/fxml/TextInMyBoxClipboard.fxml"; public static final String TextPopFxml = "/fxml/TextPop.fxml"; public static final String BytesEditorFxml = "/fxml/BytesEditor.fxml"; public static final String BytesEditorFormatFxml = "/fxml/BytesEditorFormat.fxml"; public static final String BytesFindBatchFxml = "/fxml/BytesFindBatch.fxml"; public static final String BytesPopFxml = "/fxml/BytesPop.fxml"; public static final String WordViewFxml = "/fxml/WordView.fxml"; public static final String WordToHtmlFxml = "/fxml/WordToHtml.fxml"; public static final String WordToPdfFxml = "/fxml/WordToPdf.fxml"; public static final String PptViewFxml = "/fxml/PptView.fxml"; public static final String PptToImagesFxml = "/fxml/PptToImages.fxml"; public static final String PptToPdfFxml = "/fxml/PptToPdf.fxml"; public static final String PptExtractFxml = "/fxml/PptExtract.fxml"; public static final String PptxMergeFxml = "/fxml/PptxMerge.fxml"; public static final String PptSplitFxml = "/fxml/PptSplit.fxml"; public static final String ExtractTextsFromMSFxml = "/fxml/ExtractTextsFromMS.fxml"; /* image */ public static final String ImageAnalyseFxml = "/fxml/ImageAnalyse.fxml"; public static final String ImagesBrowserFxml = "/fxml/ImagesBrowser.fxml"; public static final String ImageConverterFxml = "/fxml/ImageConverter.fxml"; public static final String ImageEditorFxml = "/fxml/ImageEditor.fxml"; public static final String ImageSelectPixelsFxml = "/fxml/ImageSelectPixels.fxml"; public static final String ImageCopyFxml = "/fxml/ImageCopy.fxml"; public static final String ImageCropFxml = "/fxml/ImageCrop.fxml"; public static final String ImagePasteFxml = "/fxml/ImagePaste.fxml"; public static final String ImageMarginsFxml = "/fxml/ImageMargins.fxml"; public static final String ImageSizeFxml = "/fxml/ImageSize.fxml"; public static final String ImageReplaceColorFxml = "/fxml/ImageReplaceColor.fxml"; public static final String ImageBlendColorFxml = "/fxml/ImageBlendColor.fxml"; public static final String ImageAdjustColorFxml = "/fxml/ImageAdjustColor.fxml"; public static final String ImageThresholdingFxml = "/fxml/ImageThresholding.fxml"; public static final String ImageEdgeFxml = "/fxml/ImageEdge.fxml"; public static final String ImageEmbossFxml = "/fxml/ImageEmboss.fxml"; public static final String ImageBlackWhiteFxml = "/fxml/ImageBlackWhite.fxml"; public static final String ImageGreyFxml = "/fxml/ImageGrey.fxml"; public static final String ImageSepiaFxml = "/fxml/ImageSepia.fxml"; public static final String ImageMosaicFxml = "/fxml/ImageMosaic.fxml"; public static final String ImageGlassFxml = "/fxml/ImageGlass.fxml"; public static final String ImageReduceColorsFxml = "/fxml/ImageReduceColors.fxml"; public static final String ImageRotateFxml = "/fxml/ImageRotate.fxml"; public static final String ImageMirrorFxml = "/fxml/ImageMirror.fxml"; public static final String ImageShearFxml = "/fxml/ImageShear.fxml"; public static final String ImageRoundFxml = "/fxml/ImageRound.fxml"; public static final String ImageShadowFxml = "/fxml/ImageShadow.fxml"; public static final String ImageEraserFxml = "/fxml/ImageEraser.fxml"; public static final String ImageSmoothFxml = "/fxml/ImageSmooth.fxml"; public static final String ImageSharpenFxml = "/fxml/ImageSharpen.fxml"; public static final String ImageContrastFxml = "/fxml/ImageContrast.fxml"; public static final String ImageConvolutionFxml = "/fxml/ImageConvolution.fxml"; public static final String ImageLineFxml = "/fxml/ImageLine.fxml"; public static final String ImagePolylinesFxml = "/fxml/ImagePolylines.fxml"; public static final String ImageRectangleFxml = "/fxml/ImageRectangle.fxml"; public static final String ImageCircleFxml = "/fxml/ImageCircle.fxml"; public static final String ImageEllipseFxml = "/fxml/ImageEllipse.fxml"; public static final String ImagePolylineFxml = "/fxml/ImagePolyline.fxml"; public static final String ImagePolygonFxml = "/fxml/ImagePolygon.fxml"; public static final String ImageArcFxml = "/fxml/ImageArc.fxml"; public static final String ImageQuadraticFxml = "/fxml/ImageQuadratic.fxml"; public static final String ImageCubicFxml = "/fxml/ImageCubic.fxml"; public static final String ImageSVGPathFxml = "/fxml/ImageSVGPath.fxml"; public static final String ImageTextFxml = "/fxml/ImageText.fxml"; public static final String ImageCanvasInputFxml = "/fxml/ImageCanvasInput.fxml"; public static final String ImageHistoriesFxml = "/fxml/ImageHistories.fxml"; public static final String ImageScopeViewsFxml = "/fxml/ImageScopeViews.fxml"; public static final String ImageClipSelectFxml = "/fxml/ImageClipSelect.fxml"; public static final String ImageCropBatchFxml = "/fxml/ImageCropBatch.fxml"; public static final String ImageAdjustColorBatchFxml = "/fxml/ImageAdjustColorBatch.fxml"; public static final String ImageReplaceColorBatchFxml = "/fxml/ImageReplaceColorBatch.fxml"; public static final String ImageBlendColorBatchFxml = "/fxml/ImageBlendColorBatch.fxml"; public static final String ImageReduceColorsBatchFxml = "/fxml/ImageReduceColorsBatch.fxml"; public static final String ImageGreyBatchFxml = "/fxml/ImageGreyBatch.fxml"; public static final String ImageBlackWhiteBatchFxml = "/fxml/ImageBlackWhiteBatch.fxml"; public static final String ImageSepiaBatchFxml = "/fxml/ImageSepiaBatch.fxml"; public static final String ImageThresholdingBatchFxml = "/fxml/ImageThresholdingBatch.fxml"; public static final String ImageTextBatchFxml = "/fxml/ImageTextBatch.fxml"; public static final String ImageEdgeBatchFxml = "/fxml/ImageEdgeBatch.fxml"; public static final String ImageEmbossBatchFxml = "/fxml/ImageEmbossBatch.fxml"; public static final String ImageSharpenBatchFxml = "/fxml/ImageSharpenBatch.fxml"; public static final String ImageSmoothBatchFxml = "/fxml/ImageSmoothBatch.fxml"; public static final String ImageShadowBatchFxml = "/fxml/ImageShadowBatch.fxml"; public static final String ImageRoundBatchFxml = "/fxml/ImageRoundBatch.fxml"; public static final String ImageMarginsBatchFxml = "/fxml/ImageMarginsBatch.fxml"; public static final String ImageSizeBatchFxml = "/fxml/ImageSizeBatch.fxml"; public static final String ImageMirrorBatchFxml = "/fxml/ImageMirrorBatch.fxml"; public static final String ImageShearBatchFxml = "/fxml/ImageShearBatch.fxml"; public static final String ImageRotateBatchFxml = "/fxml/ImageRotateBatch.fxml"; public static final String ImagePasteBatchFxml = "/fxml/ImagePasteBatch.fxml"; public static final String ImageMosaicBatchFxml = "/fxml/ImageMosaicBatch.fxml"; public static final String ImageGlassBatchFxml = "/fxml/ImageGlassBatch.fxml"; public static final String ImageContrastBatchFxml = "/fxml/ImageContrastBatch.fxml"; public static final String ImageConvolutionBatchFxml = "/fxml/ImageConvolutionBatch.fxml"; public static final String SvgEditorFxml = "/fxml/SvgEditor.fxml"; public static final String SvgTypesettingFxml = "/fxml/SvgTypesetting.fxml"; public static final String SvgToImageFxml = "/fxml/SvgToImage.fxml"; public static final String SvgToPDFFxml = "/fxml/SvgToPDF.fxml"; public static final String SvgFromImageFxml = "/fxml/SvgFromImage.fxml"; public static final String SvgFromImageBatchFxml = "/fxml/SvgFromImageBatch.fxml"; public static final String SvgCircleFxml = "/fxml/SvgCircle.fxml"; public static final String SvgRectangleFxml = "/fxml/SvgRectangle.fxml"; public static final String SvgEllipseFxml = "/fxml/SvgEllipse.fxml"; public static final String SvgLineFxml = "/fxml/SvgLine.fxml"; public static final String SvgPolylineFxml = "/fxml/SvgPolyline.fxml"; public static final String SvgPolygonFxml = "/fxml/SvgPolygon.fxml"; public static final String SvgQuadraticFxml = "/fxml/SvgQuadratic.fxml"; public static final String SvgCubicFxml = "/fxml/SvgCubic.fxml"; public static final String SvgArcFxml = "/fxml/SvgArc.fxml"; public static final String SvgPolylinesFxml = "/fxml/SvgPolylines.fxml"; public static final String SvgPathFxml = "/fxml/SvgPath.fxml"; public static final String PointInputFxml = "/fxml/PointInput.fxml"; public static final String LineInputFxml = "/fxml/LineInput.fxml"; public static final String ShapeTranslateInputFxml = "/fxml/ShapeTranslateInput.fxml"; public static final String ShapeScaleInputFxml = "/fxml/ShapeScaleInput.fxml"; public static final String ShapeShearInputFxml = "/fxml/ShapeShearInput.fxml"; public static final String ShapeRotateInputFxml = "/fxml/ShapeRotateInput.fxml"; public static final String ShapePathSegmentEditFxml = "/fxml/ShapePathSegmentEdit.fxml"; public static final String ImageConverterBatchFxml = "/fxml/ImageConverterBatch.fxml"; public static final String ImagesSpliceFxml = "/fxml/ImagesSplice.fxml"; public static final String ImageSplitFxml = "/fxml/ImageSplit.fxml"; public static final String ImageSampleFxml = "/fxml/ImageSample.fxml"; public static final String ImagesEditorFxml = "/fxml/ImagesEditor.fxml"; public static final String ImagesSaveFxml = "/fxml/ImagesSave.fxml"; public static final String ImagesPlayFxml = "/fxml/ImagesPlay.fxml"; public static final String ImageAlphaExtractBatchFxml = "/fxml/ImageAlphaExtractBatch.fxml"; public static final String ImageAlphaAddBatchFxml = "/fxml/ImageAlphaAddBatch.fxml"; public static final String ImageOCRFxml = "/fxml/ImageOCR.fxml"; public static final String ImageOCRBatchFxml = "/fxml/ImageOCRBatch.fxml"; public static final String ImageRepeatFxml = "/fxml/ImageRepeat.fxml"; public static final String ColorsManageFxml = "/fxml/ColorsManage.fxml"; public static final String ColorPalettePopupFxml = "/fxml/ColorPalettePopup.fxml"; public static final String ColorsInputFxml = "/fxml/ColorsInput.fxml"; public static final String ColorCopyFxml = "/fxml/ColorCopy.fxml"; public static final String ColorQueryFxml = "/fxml/ColorQuery.fxml"; public static final String ColorsBlendFxml = "/fxml/ColorsBlend.fxml"; public static final String ColorPaletteInputFxml = "/fxml/ColorPaletteInput.fxml"; public static final String ColorPaletteSelectorFxml = "/fxml/ColorPaletteSelector.fxml"; public static final String ColorsCustomizeFxml = "/fxml/ColorsCustomize.fxml"; public static final String IccProfileEditorFxml = "/fxml/IccProfileEditor.fxml"; public static final String ChromaticityDiagramFxml = "/fxml/ChromaticityDiagram.fxml"; public static final String ChromaticAdaptationMatrixFxml = "/fxml/ChromaticAdaptationMatrix.fxml"; public static final String ColorConversionFxml = "/fxml/ColorConversion.fxml"; public static final String RGBColorSpacesFxml = "/fxml/RGBColorSpaces.fxml"; public static final String RGB2XYZConversionMatrixFxml = "/fxml/RGB2XYZConversionMatrix.fxml"; public static final String RGB2RGBConversionMatrixFxml = "/fxml/RGB2RGBConversionMatrix.fxml"; public static final String IlluminantsFxml = "/fxml/Illuminants.fxml"; public static final String ImageInMyBoxClipboardFxml = "/fxml/ImageInMyBoxClipboard.fxml"; public static final String ImageInSystemClipboardFxml = "/fxml/ImageInSystemClipboard.fxml"; public static final String PixelsCalculatorFxml = "/fxml/PixelsCalculator.fxml"; public static final String ConvolutionKernelManagerFxml = "/fxml/ConvolutionKernelManager.fxml"; public static final String ImageBase64Fxml = "/fxml/ImageBase64.fxml"; public static final String ImageLoadWidthFxml = "/fxml/ImageLoadWidth.fxml"; public static final String ImageFramesFxml = "/fxml/ImageFrames.fxml"; public static final String ImageOptionsFxml = "/fxml/ImageOptions.fxml"; public static final String ImageShapeOptionsFxml = "/fxml/ImageShapeOptions.fxml"; public static final String ImagePopFxml = "/fxml/ImagePop.fxml"; public static final String ImageInformationFxml = "/fxml/ImageInformation.fxml"; public static final String ImageMetaDataFxml = "/fxml/ImageMetaData.fxml"; public static final String ImageTooLargeFxml = "/fxml/ImageTooLarge.fxml"; /* tree */ public static final String DataTreeFxml = "/fxml/DataTree.fxml"; public static final String ControlDataTextFxml = "/fxml/ControlDataText.fxml"; public static final String ControlDataHtmlFxml = "/fxml/ControlDataHtml.fxml"; public static final String ControlDataMathFunctionFxml = "/fxml/ControlDataMathFunction.fxml"; public static final String ControlDataWebFavoriteFxml = "/fxml/ControlDataWebFavorite.fxml"; public static final String ControlDataSQLFxml = "/fxml/ControlDataSQL.fxml"; public static final String ControlDataJShellFxml = "/fxml/ControlDataJShell.fxml"; public static final String ControlDataJEXLFxml = "/fxml/ControlDataJEXL.fxml"; public static final String ControlDataJavaScriptFxml = "/fxml/ControlDataJavaScript.fxml"; public static final String ControlDataImageScopeFxml = "/fxml/ControlDataImageScope.fxml"; public static final String ControlDataDataColumnFxml = "/fxml/ControlDataDataColumn.fxml"; public static final String ControlDataRowExpressionFxml = "/fxml/ControlDataRowExpression.fxml"; public static final String ControlDataGeographyCodeFxml = "/fxml/ControlDataGeographyCode.fxml"; public static final String ControlDataMacroFxml = "/fxml/ControlDataMacro.fxml"; public static final String DataTreeNodeEditorFxml = "/fxml/DataTreeNodeEditor.fxml"; public static final String DataTreeTagsFxml = "/fxml/DataTreeTags.fxml"; public static final String DataTreeExportFxml = "/fxml/DataTreeExport.fxml"; public static final String DataTreeImportFxml = "/fxml/DataTreeImport.fxml"; public static final String DataTreeCopyFxml = "/fxml/DataTreeCopy.fxml"; public static final String DataTreeMoveFxml = "/fxml/DataTreeMove.fxml"; public static final String DataTreeDeleteFxml = "/fxml/DataTreeDelete.fxml"; public static final String DataTreeQueryByConditionsFxml = "/fxml/DataTreeQueryByConditions.fxml"; public static final String DataTreeQueryByTagsFxml = "/fxml/DataTreeQueryByTags.fxml"; public static final String DataTreeQueryDescendantsFxml = "/fxml/DataTreeQueryDescendants.fxml"; public static final String DataTreeQueryResultsFxml = "/fxml/DataTreeQueryResults.fxml"; public static final String DataSelectParentFxml = "/fxml/DataSelectParent.fxml"; public static final String DataSelectRowExpressionFxml = "/fxml/DataSelectRowExpression.fxml"; public static final String DataSelectJavaScriptFxml = "/fxml/DataSelectJavaScript.fxml"; public static final String DataSelectDataColumnFxml = "/fxml/DataSelectDataColumn.fxml"; public static final String DataSelectImageScopeFxml = "/fxml/DataSelectImageScope.fxml"; public static final String DataSelectSQLFxml = "/fxml/DataSelectSQL.fxml"; /* data */ public static final String Data2DManufactureFxml = "/fxml/Data2DManufacture.fxml"; public static final String Data2DManageFxml = "/fxml/Data2DManage.fxml"; public static final String Data2DManageQueryFxml = "/fxml/Data2DManageQuery.fxml"; public static final String DataInSystemClipboardFxml = "/fxml/DataInSystemClipboard.fxml"; public static final String DataInMyBoxClipboardFxml = "/fxml/DataInMyBoxClipboard.fxml"; public static final String Data2DSaveAsFxml = "/fxml/Data2DSaveAs.fxml"; public static final String Data2DSaveDataFxml = "/fxml/Data2DSaveData.fxml"; public static final String Data2DSaveRowsFxml = "/fxml/Data2DSaveRows.fxml"; public static final String Data2DSpliceFxml = "/fxml/Data2DSplice.fxml"; public static final String Data2DCreateFxml = "/fxml/Data2DCreate.fxml"; public static final String Data2DSelectFxml = "/fxml/Data2DSelect.fxml"; public static final String Data2DAttributesFxml = "/fxml/Data2DAttributes.fxml"; public static final String Data2DColumnsFxml = "/fxml/Data2DColumns.fxml"; public static final String Data2DAddRowsFxml = "/fxml/Data2DAddRows.fxml"; public static final String Data2DRowEditFxml = "/fxml/Data2DRowEdit.fxml"; public static final String Data2DColumnEditFxml = "/fxml/Data2DColumnEdit.fxml"; public static final String Data2DSetValuesFxml = "/fxml/Data2DSetValues.fxml"; public static final String Data2DCopyFxml = "/fxml/Data2DCopy.fxml"; public static final String Data2DLoadContentInSystemClipboardFxml = "/fxml/Data2DLoadContentInSystemClipboard.fxml"; public static final String Data2DPasteContentInSystemClipboardFxml = "/fxml/Data2DPasteContentInSystemClipboard.fxml"; public static final String Data2DPasteContentInMyBoxClipboardFxml = "/fxml/Data2DPasteContentInMyBoxClipboard.fxml"; public static final String Data2DDeleteFxml = "/fxml/Data2DDelete.fxml"; public static final String Data2DExportFxml = "/fxml/Data2DExport.fxml"; public static final String Data2DTransposeFxml = "/fxml/Data2DTranspose.fxml"; public static final String Data2DRowExpressionFxml = "/fxml/Data2DRowExpression.fxml"; public static final String Data2DStatisticFxml = "/fxml/Data2DStatistic.fxml"; public static final String Data2DPercentageFxml = "/fxml/Data2DPercentage.fxml"; public static final String Data2DSortFxml = "/fxml/Data2DSort.fxml"; public static final String Data2DNormalizeFxml = "/fxml/Data2DNormalize.fxml"; public static final String Data2DFrequencyFxml = "/fxml/Data2DFrequency.fxml"; public static final String Data2DChartPieFxml = "/fxml/Data2DChartPie.fxml"; public static final String Data2DChartXYFxml = "/fxml/Data2DChartXY.fxml"; public static final String Data2DChartBubbleFxml = "/fxml/Data2DChartBubble.fxml"; public static final String Data2DChartXYZFxml = "/fxml/Data2DChartXYZ.fxml"; public static final String Data2DChartBoxWhiskerFxml = "/fxml/Data2DChartBoxWhisker.fxml"; public static final String Data2DChartSelfComparisonBarsFxml = "/fxml/Data2DChartSelfComparisonBars.fxml"; public static final String Data2DChartComparisonBarsFxml = "/fxml/Data2DChartComparisonBars.fxml"; public static final String Data2DColumnCreateFxml = "/fxml/Data2DColumnCreate.fxml"; public static final String Data2DTableCreateFxml = "/fxml/Data2DTableCreate.fxml"; public static final String DataTableQueryFxml = "/fxml/DataTableQuery.fxml"; public static final String Data2DSimpleLinearRegressionFxml = "/fxml/Data2DSimpleLinearRegression.fxml"; public static final String Data2DSimpleLinearRegressionCombinationFxml = "/fxml/Data2DSimpleLinearRegressionCombination.fxml"; public static final String Data2DMultipleLinearRegressionFxml = "/fxml/Data2DMultipleLinearRegression.fxml"; public static final String Data2DMultipleLinearRegressionCombinationFxml = "/fxml/Data2DMultipleLinearRegressionCombination.fxml"; public static final String Data2DChartXYOptionsFxml = "/fxml/Data2DChartXYOptions.fxml"; public static final String Data2DChartPieOptionsFxml = "/fxml/Data2DChartPieOptions.fxml"; public static final String Data2DSetStylesFxml = "/fxml/Data2DSetStyles.fxml"; public static final String Data2DGroupStatisticFxml = "/fxml/Data2DGroupStatistic.fxml"; public static final String Data2DGroupFxml = "/fxml/Data2DGroup.fxml"; public static final String Data2DLocationDistributionFxml = "/fxml/Data2DLocationDistribution.fxml"; public static final String Data2DRowFilterEditFxml = "/fxml/Data2DRowFilterEdit.fxml"; public static final String Data2DChartGroupXYFxml = "/fxml/Data2DChartGroupXY.fxml"; public static final String Data2DChartGroupBubbleFxml = "/fxml/Data2DChartGroupBubble.fxml"; public static final String Data2DChartGroupPieFxml = "/fxml/Data2DChartGroupPie.fxml"; public static final String Data2DChartGroupComparisonBarsFxml = "/fxml/Data2DChartGroupComparisonBars.fxml"; public static final String Data2DChartGroupSelfComparisonBarsFxml = "/fxml/Data2DChartGroupSelfComparisonBars.fxml"; public static final String Data2DChartGroupBoxWhiskerFxml = "/fxml/Data2DChartGroupBoxWhisker.fxml"; public static final String ValueRangeInputFxml = "/fxml/ValueRangeInput.fxml"; public static final String MathFunctionDataFxml = "/fxml/MathFunctionData.fxml"; public static final String MathFunctionChartFxml = "/fxml/MathFunctionChart.fxml"; public static final String MathFunctionXYChartFxml = "/fxml/MathFunctionXYChart.fxml"; public static final String ControlDataSplitFxml = "/fxml/ControlDataSplit.fxml"; public static final String DataFileCSVFormatFxml = "/fxml/DataFileCSVFormat.fxml"; public static final String DataFileCSVConvertFxml = "/fxml/DataFileCSVConvert.fxml"; public static final String DataFileCSVMergeFxml = "/fxml/DataFileCSVMerge.fxml"; public static final String DataFileExcelSheetsFxml = "/fxml/DataFileExcelSheets.fxml"; public static final String DataFileExcelFormatFxml = "/fxml/DataFileExcelFormat.fxml"; public static final String DataFileExcelConvertFxml = "/fxml/DataFileExcelConvert.fxml"; public static final String DataFileExcelMergeFxml = "/fxml/DataFileExcelMerge.fxml"; public static final String DataFileTextFormatFxml = "/fxml/DataFileTextFormat.fxml"; public static final String DataFileTextConvertFxml = "/fxml/DataFileTextConvert.fxml"; public static final String DataFileTextMergeFxml = "/fxml/DataFileTextMerge.fxml"; public static final String MatricesManageFxml = "/fxml/MatricesManage.fxml"; public static final String MatrixUnaryCalculationFxml = "/fxml/MatrixUnaryCalculation.fxml"; public static final String MatricesBinaryCalculationFxml = "/fxml/MatricesBinaryCalculation.fxml"; public static final String DatabaseTableDefinitionFxml = "/fxml/DatabaseTableDefinition.fxml"; public static final String DataTablesFxml = "/fxml/DataTables.fxml"; public static final String Data2DTableQueryFxml = "/fxml/Data2DTableQuery.fxml"; public static final String BarcodeCreatorFxml = "/fxml/BarcodeCreator.fxml"; public static final String BarcodeDecoderFxml = "/fxml/BarcodeDecoder.fxml"; public static final String MessageDigestFxml = "/fxml/MessageDigest.fxml"; public static final String Base64Fxml = "/fxml/Base64.fxml"; public static final String FileTTC2TTFFxml = "/fxml/FileTTC2TTF.fxml"; public static final String GeographyCodeFxml = "/fxml/GeographyCode.fxml"; public static final String MapOptionsFxml = "/fxml/MapOptions.fxml"; public static final String LocationInMapFxml = "/fxml/LocationInMap.fxml"; public static final String CoordinatePickerFxml = "/fxml/CoordinatePicker.fxml"; public static final String ConvertCoordinateFxml = "/fxml/ConvertCoordinate.fxml"; public static final String Data2DCoordinatePickerFxml = "/fxml/Data2DCoordinatePicker.fxml"; /* file */ public static final String FilesRenameFxml = "/fxml/FilesRename.fxml"; public static final String FilesRenameResultsFxml = "/fxml/FilesRenameResults.fxml"; public static final String DirectorySynchronizeFxml = "/fxml/DirectorySynchronize.fxml"; public static final String FilesArrangementFxml = "/fxml/FilesArrange.fxml"; public static final String FilesDeleteEmptyDirFxml = "/fxml/FilesDeleteEmptyDir.fxml"; public static final String FilesDeleteJavaTempFxml = "/fxml/FilesDeleteJavaTemp.fxml"; public static final String FilesDeleteNestedDirFxml = "/fxml/FilesDeleteNestedDir.fxml"; public static final String FileCutFxml = "/fxml/FileCut.fxml"; public static final String FileRenameFxml = "/fxml/FileRename.fxml"; public static final String FilesMergeFxml = "/fxml/FilesMerge.fxml"; public static final String FilesDeleteFxml = "/fxml/FilesDelete.fxml"; public static final String FilesCopyFxml = "/fxml/FilesCopy.fxml"; public static final String FilesMoveFxml = "/fxml/FilesMove.fxml"; public static final String FilesFindFxml = "/fxml/FilesFind.fxml"; public static final String FilesCompareFxml = "/fxml/FilesCompare.fxml"; public static final String FilesRedundancyFxml = "/fxml/FilesRedundancy.fxml"; public static final String FilesRedundancyResultsFxml = "/fxml/FilesRedundancyResults.fxml"; public static final String FilesArchiveCompressFxml = "/fxml/FilesArchiveCompress.fxml"; public static final String FilesCompressBatchFxml = "/fxml/FilesCompressBatch.fxml"; public static final String FileDecompressUnarchiveFxml = "/fxml/FileDecompressUnarchive.fxml"; public static final String FilesDecompressUnarchiveBatchFxml = "/fxml/FilesDecompressUnarchiveBatch.fxml"; /* media */ public static final String MediaPlayerFxml = "/fxml/MediaPlayer.fxml"; public static final String MediaListFxml = "/fxml/MediaList.fxml"; public static final String FFmpegInformationFxml = "/fxml/FFmpegInformation.fxml"; public static final String FFmpegProbeMediaInformationFxml = "/fxml/FFmpegProbeMediaInformation.fxml"; public static final String FFmpegConvertMediaFilesFxml = "/fxml/FFmpegConvertMediaFiles.fxml"; public static final String FFmpegConvertMediaStreamsFxml = "/fxml/FFmpegConvertMediaStreams.fxml"; public static final String FFmpegMergeImagesFxml = "/fxml/FFmpegMergeImages.fxml"; public static final String FFmpegMergeImageFilesFxml = "/fxml/FFmpegMergeImageFiles.fxml"; public static final String FFmpegScreenRecorderFxml = "/fxml/FFmpegScreenRecorder.fxml"; public static final String AlarmClockFxml = "/fxml/AlarmClock.fxml"; public static final String AlarmClockRunFxml = "/fxml/AlarmClockRun.fxml"; public static final String GameElimniationFxml = "/fxml/GameElimination.fxml"; public static final String GameMineFxml = "/fxml/GameMine.fxml"; /* network */ public static final String WeiboSnapFxml = "/fxml/WeiboSnap.fxml"; public static final String WeiboSnapPostsFxml = "/fxml/WeiboSnapPosts.fxml"; public static final String WeiboSnapLikeFxml = "/fxml/WeiboSnapLike.fxml"; public static final String WeiboSnapingInfoFxml = "/fxml/WeiboSnapingInfo.fxml"; public static final String WebBrowserFxml = "/fxml/WebBrowser.fxml"; public static final String WebHistoriesFxml = "/fxml/WebHistories.fxml"; public static final String NetworkConvertUrlFxml = "/fxml/NetworkConvertUrl.fxml";
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/value/FileExtensions.java
alpha/MyBox/src/main/java/mara/mybox/value/FileExtensions.java
package mara.mybox.value; import java.util.Arrays; import java.util.List; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class FileExtensions { public static List<String> SupportedImages = Arrays.asList( "png", "jpg", "jpeg", "bmp", "tif", "tiff", "gif", "pcx", "pnm", "wbmp", "ico", "icon", "webp" ); public static List<String> NoAlphaImages = Arrays.asList( "jpg", "jpeg", "bmp", "pnm", "gif", "wbmp", "pcx" ); public static List<String> AlphaImages = Arrays.asList( "png", "tif", "tiff", "ico", "icon", "webp" ); // PNG does not support premultiplyAlpha // https://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8229013 public static List<String> PremultiplyAlphaImages = Arrays.asList( "tif", "tiff" ); public static List<String> CMYKImages = Arrays.asList( "tif", "tiff" ); public static List<String> MultiFramesImages = Arrays.asList( "gif", "tif", "tiff" ); public static String[] TextFileSuffix = {"txt", "java", "fxml", "xml", "json", "log", "js", "css", "csv", "pom", "ini", "del", "svg", "html", "htm", "c", "cpp", "cxx", "cc", "c++", "h", "php", "py", "perl", "iml", "sh", "bat", "tcl", "mf", "md", "properties", "env", "cfg", "conf"}; public static String[] MediaPlayerSupports = {"mp4", "m4a", "mp3", "wav", "aif", "aiff", "m3u8"}; }
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/value/Colors.java
alpha/MyBox/src/main/java/mara/mybox/value/Colors.java
package mara.mybox.value; import java.awt.Color; import mara.mybox.fxml.style.StyleData.StyleColor; import static mara.mybox.fxml.style.StyleData.StyleColor.Blue; import static mara.mybox.fxml.style.StyleData.StyleColor.Customize; import static mara.mybox.fxml.style.StyleData.StyleColor.Green; import static mara.mybox.fxml.style.StyleData.StyleColor.LightBlue; import static mara.mybox.fxml.style.StyleData.StyleColor.Orange; import static mara.mybox.fxml.style.StyleData.StyleColor.Pink; import mara.mybox.image.tools.ColorConvertTools; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class Colors { public static final Color TRANSPARENT = new Color(0, 0, 0, 0); public static Color color(StyleColor inStyle, boolean dark) { return ColorConvertTools.rgba2color("0x" + colorValue(inStyle, dark) + "FF"); } public static String colorValue(StyleColor inStyle, boolean dark) { String color; try { StyleColor style = inStyle; if (style == null) { style = StyleColor.Red; } switch (style) { case Blue: color = dark ? "003472" : "E3F9FD"; break; case LightBlue: color = dark ? "4C8DAE" : "D6ECF0"; break; case Pink: color = dark ? "9E004F" : "FFFFFF"; break; case Orange: color = dark ? "622A1D" : "FFF8D8"; break; case Green: color = dark ? "0D3928" : "E0F0E9"; break; case Customize: color = dark ? customizeColorDarkValue() : customizeColorLightValue(); color = color.substring(2, 8); break; default: color = dark ? "C32136" : "FBD5CF"; } } catch (Exception e) { color = dark ? "C32136" : "FBD5CF"; } return color; } public static String customizeColorDarkValue() { return UserConfig.getString("CustomizeColorDark", "0x8B008BFF"); } public static javafx.scene.paint.Color customizeColorDark() { return javafx.scene.paint.Color.web(customizeColorDarkValue()); } public static String customizeColorLightValue() { return UserConfig.getString("CustomizeColorLight", "0xF8F8FFFF"); } public static javafx.scene.paint.Color customizeColorLight() { return javafx.scene.paint.Color.web(customizeColorLightValue()); } }
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/value/ImageRenderHints.java
alpha/MyBox/src/main/java/mara/mybox/value/ImageRenderHints.java
package mara.mybox.value; import java.awt.RenderingHints; import java.sql.Connection; import java.util.HashMap; import java.util.Map; import mara.mybox.dev.MyBoxLog; import static mara.mybox.value.AppVariables.ImageHints; /** * @Author Mara * @CreateDate 2022-1-17 * @License Apache License Version 2.0 */ public class ImageRenderHints { public static boolean applyHints() { return UserConfig.getBoolean("ApplyImageRenderOptions", false); } public static boolean applyHints(boolean apply) { return UserConfig.setBoolean("ApplyImageRenderOptions", apply); } public static Map<RenderingHints.Key, Object> loadImageRenderHints(Connection conn) { try { if (!applyHints()) { ImageHints = null; return null; } ImageHints = new HashMap<>(); String render = UserConfig.getString(conn, "ImageRenderHint-" + RenderingHints.KEY_RENDERING.toString(), null); if (RenderingHints.VALUE_RENDER_QUALITY.toString().equals(render)) { ImageHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); } else if (RenderingHints.VALUE_RENDER_SPEED.toString().equals(render)) { ImageHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); } else { ImageHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_DEFAULT); } String crender = UserConfig.getString(conn, "ImageRenderHint-" + RenderingHints.KEY_COLOR_RENDERING.toString(), null); if (RenderingHints.VALUE_COLOR_RENDER_QUALITY.toString().equals(crender)) { ImageHints.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); } else if (RenderingHints.VALUE_COLOR_RENDER_SPEED.toString().equals(crender)) { ImageHints.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED); } else { ImageHints.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_DEFAULT); } String inter = UserConfig.getString(conn, "ImageRenderHint-" + RenderingHints.KEY_INTERPOLATION.toString(), null); if (RenderingHints.VALUE_INTERPOLATION_BILINEAR.toString().equals(inter)) { ImageHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); } else if (RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR.toString().equals(inter)) { ImageHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); } else { ImageHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); } String ainter = UserConfig.getString(conn, "ImageRenderHint-" + RenderingHints.KEY_ALPHA_INTERPOLATION.toString(), null); if (RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY.toString().equals(ainter)) { ImageHints.put(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); } else if (RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED.toString().equals(ainter)) { ImageHints.put(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED); } else { ImageHints.put(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT); } String anti = UserConfig.getString(conn, "ImageRenderHint-" + RenderingHints.KEY_ANTIALIASING.toString(), null); if (RenderingHints.VALUE_ANTIALIAS_ON.toString().equals(anti)) { ImageHints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } else if (RenderingHints.VALUE_ANTIALIAS_OFF.toString().equals(anti)) { ImageHints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } else { ImageHints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_DEFAULT); } String tanti = UserConfig.getString(conn, "ImageRenderHint-" + RenderingHints.KEY_TEXT_ANTIALIASING.toString(), null); if (RenderingHints.VALUE_TEXT_ANTIALIAS_ON.toString().equals(tanti)) { ImageHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } else if (RenderingHints.VALUE_TEXT_ANTIALIAS_OFF.toString().equals(tanti)) { ImageHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); } else if (RenderingHints.VALUE_TEXT_ANTIALIAS_GASP.toString().equals(tanti)) { ImageHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); } else if (RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB.toString().equals(tanti)) { ImageHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB); } else if (RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HBGR.toString().equals(tanti)) { ImageHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HBGR); } else if (RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VRGB.toString().equals(tanti)) { ImageHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VRGB); } else if (RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VBGR.toString().equals(tanti)) { ImageHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VBGR); } else { ImageHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT); } String fm = UserConfig.getString(conn, "ImageRenderHint-" + RenderingHints.KEY_FRACTIONALMETRICS.toString(), null); if (RenderingHints.VALUE_FRACTIONALMETRICS_ON.toString().equals(fm)) { ImageHints.put(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); } else if (RenderingHints.VALUE_FRACTIONALMETRICS_OFF.toString().equals(fm)) { ImageHints.put(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_OFF); } else { ImageHints.put(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT); } String stroke = UserConfig.getString(conn, "ImageRenderHint-" + RenderingHints.KEY_STROKE_CONTROL.toString(), null); if (RenderingHints.VALUE_STROKE_NORMALIZE.toString().equals(stroke)) { ImageHints.put(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); } else if (RenderingHints.VALUE_STROKE_PURE.toString().equals(stroke)) { ImageHints.put(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); } else { ImageHints.put(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT); } String dither = UserConfig.getString(conn, "ImageRenderHint-" + RenderingHints.KEY_DITHERING.toString(), null); if (RenderingHints.VALUE_DITHER_ENABLE.toString().equals(dither)) { ImageHints.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE); } else if (RenderingHints.VALUE_DITHER_DISABLE.toString().equals(dither)) { ImageHints.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE); } else { ImageHints.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DEFAULT); } saveImageRenderHints(conn); return ImageHints; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static void saveImageRenderHints(Connection conn) { if (ImageHints == null) { return; } try { for (RenderingHints.Key key : ImageHints.keySet()) { UserConfig.setString(conn, "ImageRenderHint-" + key.toString(), ImageHints.get(key).toString()); } } catch (Exception e) { MyBoxLog.error(e.toString()); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/value/InternalImages.java
alpha/MyBox/src/main/java/mara/mybox/value/InternalImages.java
package mara.mybox.value; import java.io.File; import java.util.ArrayList; import java.util.List; import javafx.scene.image.Image; import mara.mybox.data.ImageItem; import mara.mybox.fxml.FxFileTools; import mara.mybox.fxml.style.StyleTools; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2025-2-22 * @License Apache License Version 2.0 */ public class InternalImages { public static List<ImageItem> all() { return all(AppVariables.CurrentLangName); } public static List<ImageItem> allWithColors() { List<ImageItem> images = all(); images.addAll(colors()); return images; } public static List<ImageItem> all(String lang) { List<ImageItem> images = imgPath(lang); images.addAll(buttonsPath(lang, StyleTools.getIconPath())); images.addAll(buttonsPath(lang, StyleTools.ButtonsSourcePath)); return images; } public static List<ImageItem> imgPath(String lang) { List<ImageItem> images = new ArrayList<>(); try { for (int y = AppValues.AppYear; y >= 2018; y--) { for (int i = 1; i <= (y == 2018 ? 6 : 9); i++) { String name = "cover" + y + "g" + i; ImageItem item = new ImageItem() .setName(name + ".png") .setAddress("img/" + name + ".png") .setComments(y == 2018 ? null : message(lang, name)); images.add(item); } } ImageItem item = new ImageItem() .setName("jade.png").setAddress("img/jade.png") .setComments(message(lang, "jadeImageTips")); images.add(item); item = new ImageItem() .setName("exg1.png").setAddress("img/exg1.png") .setComments(message(lang, "exg1ImageTips")); images.add(item); item = new ImageItem() .setName("exg2.png").setAddress("img/exg2.png") .setComments(message(lang, "exg2ImageTips")); images.add(item); item = new ImageItem() .setName("MyBox.png").setAddress("img/MyBox.png") .setComments(message(lang, "MyBoxImageTips")); images.add(item); images.add(new ImageItem().setName("Gadwalls.png").setAddress("img/Gadwalls.png")); images.add(new ImageItem().setName("SpermWhale.png").setAddress("img/SpermWhale.png")); } catch (Exception e) { } return images; } public static List<ImageItem> buttonsPath(String lang, String path) { List<ImageItem> images = new ArrayList<>(); try { List<String> icons = FxFileTools.getResourceFiles(path); if (icons == null || icons.isEmpty()) { icons = FxFileTools.getResourceFiles(StyleTools.ButtonsSourcePath + "Red/"); } String name, comments; for (String icon : icons) { if (!icon.startsWith("icon") || !icon.endsWith(".png") || icon.contains("_40")) { continue; } name = icon.substring(4, icon.length() - 4); comments = message(lang, "icon" + name); ImageItem item = new ImageItem() .setName("icon" + name + ".png") .setAddress(path + icon) .setWidth(100) .setComments(comments.startsWith("icon") ? null : comments); images.add(item); } } catch (Exception e) { } return images; } public static List<ImageItem> colors() { List<ImageItem> colors = new ArrayList<>(); colors.add(new ImageItem().setAddress("color:#ffccfd")); colors.add(new ImageItem().setAddress("color:#fd98a2")); colors.add(new ImageItem().setAddress("color:#dff0fe")); colors.add(new ImageItem().setAddress("color:#65b4fd")); colors.add(new ImageItem().setAddress("color:#fdba98")); colors.add(new ImageItem().setAddress("color:#8fbc8f")); colors.add(new ImageItem().setAddress("color:#9370db")); colors.add(new ImageItem().setAddress("color:#eee8aa")); return colors; } public static String exampleImageName() { return "img/cover" + AppValues.AppYear + "g5.png"; } public static Image exampleImage() { return new Image(exampleImageName()); } public static File exampleImageFile() { return FxFileTools.getInternalFile("/" + exampleImageName(), "image", "Example.png"); } }
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/value/Languages.java
alpha/MyBox/src/main/java/mara/mybox/value/Languages.java
package mara.mybox.value; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import mara.mybox.data.UserLanguage; import mara.mybox.dev.MyBoxLog; import static mara.mybox.value.AppVariables.CurrentBundle; import static mara.mybox.value.AppVariables.CurrentLangName; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class Languages { public static final Locale LocaleZhCN = Locale.of("zh", "CN"); public static final Locale LocaleEn = Locale.of("en"); // public static final Locale LocaleFrFR = new Locale("fr", "FR"); // public static final Locale LocaleEsES = new Locale("es", "ES"); // public static final Locale LocaleRuRU = new Locale("ru", "RU"); public static final ResourceBundle BundleZhCN = ResourceBundle.getBundle("bundles/Messages", LocaleZhCN); public static final ResourceBundle BundleEn = ResourceBundle.getBundle("bundles/Messages", LocaleEn); // public static final ResourceBundle BundleFrFR = ResourceBundle.getBundle("bundles/Messages", LocaleFrFR); // public static final ResourceBundle BundleEsES = ResourceBundle.getBundle("bundles/Messages", LocaleEsES); // public static final ResourceBundle BundleRuRU = ResourceBundle.getBundle("bundles/Messages", LocaleRuRU); public static String sysDefaultLanguage() { try { return Locale.getDefault().getLanguage().toLowerCase(); } catch (Exception e) { return "en"; } } public static void setLanguage(String lang) { if (lang == null) { lang = sysDefaultLanguage(); } CurrentBundle = getBundle(lang); try { if (CurrentBundle instanceof UserLanguage) { CurrentLangName = ((UserLanguage) CurrentBundle).getLanguage(); } else { CurrentLangName = CurrentBundle.getLocale().getLanguage(); } UserConfig.setString("language", CurrentLangName); } catch (Exception e) { } } public static String getLangName() { if (CurrentLangName == null) { String defaultLang = sysDefaultLanguage(); String lang = null; try { lang = UserConfig.getString("language", defaultLang); } catch (Exception e) { } if (lang != null) { CurrentLangName = lang.toLowerCase(); } else { CurrentLangName = defaultLang; try { UserConfig.setString("language", CurrentLangName); } catch (Exception e) { } } } return CurrentLangName; } public static String embedLangName() { try { String lang = sysDefaultLanguage(); if (isChinese(lang)) { return "zh"; } } catch (Exception e) { } return "en"; } public static String embedFileLang() { try { String lang = CurrentLangName; if (isChinese(lang)) { return "zh"; } else if (isEnglish(lang)) { return "en"; } } catch (Exception e) { } return embedLangName(); } public static boolean isChinese() { return isChinese(getLangName()); } public static boolean isChinese(String lang) { if (lang == null) { return false; } return lang.equals("zh") || lang.startsWith("zh_"); } public static boolean isEnglish(String lang) { if (lang == null) { return false; } return lang.equals("en") || lang.startsWith("en_"); } public static ResourceBundle getBundle() { if (CurrentBundle == null) { CurrentBundle = getBundle(getLangName()); } return CurrentBundle; } public static ResourceBundle getBundle(String language) { String lang = language; if (lang == null) { lang = sysDefaultLanguage(); } ResourceBundle bundle = tryBundle(lang); if (bundle == null) { lang = embedLangName(); if ("zh".equals(lang)) { bundle = BundleZhCN; } else { bundle = BundleEn; } } return bundle; } private static ResourceBundle tryBundle(String language) { String lang = language; if (lang == null) { return null; } ResourceBundle bundle = null; if (lang.equals("en") || lang.startsWith("en_")) { bundle = BundleEn; } else if (lang.equals("zh") || lang.startsWith("zh_")) { bundle = BundleZhCN; } else { File file = interfaceLanguageFile(lang); if (file.exists()) { try { bundle = new UserLanguage(lang); } catch (Exception e) { } } } return bundle; } public static ResourceBundle refreshBundle() { CurrentBundle = getBundle(getLangName()); return CurrentBundle; } public static String message(String language, String msg) { try { if (msg.isBlank()) { return msg; } ResourceBundle bundle = getBundle(language); return bundle.getString(msg); } catch (Exception e) { return msg; } } public static String message(String msg) { try { return getBundle().getString(msg); } catch (Exception e) { return msg; } } public static String messageIgnoreFirstCase(String msg) { try { if (msg == null || msg.isBlank()) { return msg; } return getBundle().getString(msg); } catch (Exception e) { try { return getBundle().getString(msg.substring(0, 1).toUpperCase() + msg.substring(1, msg.length())); } catch (Exception ex) { return msg; } } } public static List<String> userLanguages() { List<String> languages = new ArrayList<>(); try { File[] files = AppVariables.MyBoxLanguagesPath.listFiles(); if (files != null) { for (File file : files) { if (!file.isFile()) { continue; } String name = file.getName(); if (name.endsWith(".properties")) { name = name.substring(0, name.length() - ".properties".length()); } if (name.startsWith("Messages_")) { name = name.substring("Messages_".length()); } if (!languages.contains(name)) { languages.add(name); } } } } catch (Exception e) { } return languages; } public static File interfaceLanguageFile(String langName) { return new File(AppVariables.MyBoxLanguagesPath + File.separator + "Messages_" + langName + ".properties"); } public static Locale locale() { String lang = CurrentLangName; if (lang == null) { return Languages.LocaleEn; } else if (lang.equals("en") || lang.startsWith("en_")) { return Languages.LocaleEn; } else if (lang.equals("zh") || lang.startsWith("zh_")) { return Languages.LocaleZhCN; } else { try { return new Locale.Builder().setLanguage(lang).build(); } catch (Exception e) { return Languages.LocaleEn; } } } public static boolean match(String matchTo, String s) { try { if (matchTo == null || s == null) { return false; } return message("en", matchTo).equals(s) || message("zh", matchTo).equals(s) || message(matchTo).equals(s) || matchTo.equals(s); } catch (Exception e) { return false; } } public static boolean matchIgnoreCase(String matchTo, String s) { try { if (matchTo == null || s == null) { return false; } return message("en", matchTo).equalsIgnoreCase(s) || message("zh", matchTo).equalsIgnoreCase(s) || message(matchTo).equalsIgnoreCase(s) || matchTo.equalsIgnoreCase(s); } catch (Exception e) { return false; } } public static void checkStatus() { MyBoxLog.console("LocaleEn: " + LocaleEn.getDisplayName()); MyBoxLog.console("BundleEn: " + BundleEn.getBaseBundleName()); MyBoxLog.console("LocaleZhCN: " + LocaleZhCN.getDisplayName()); MyBoxLog.console("BundleZhCN: " + BundleZhCN.getBaseBundleName()); MyBoxLog.console("CurrentLangName: " + CurrentLangName); MyBoxLog.console("CurrentBundle: " + CurrentBundle.getBaseBundleName()); MyBoxLog.console("getLangName: " + getLangName()); MyBoxLog.console("embedLangName: " + embedLangName()); MyBoxLog.console("isChinese: " + isChinese()); MyBoxLog.console("getBundle: " + getBundle().getBaseBundleName()); MyBoxLog.console("sysDefaultLanguage();: " + sysDefaultLanguage()); MyBoxLog.console("message(\"en\", \"FileInformation\"): " + message("en", "FileInformation")); MyBoxLog.console("message(\"zh\", \"FileInformation\"): " + message("zh", "FileInformation")); MyBoxLog.console("message( \"FileInformation\"): " + message("FileInformation")); } }
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/value/AppPaths.java
alpha/MyBox/src/main/java/mara/mybox/value/AppPaths.java
package mara.mybox.value; import java.io.File; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @Update 2021-9-1 * @License Apache License Version 2.0 */ public class AppPaths { public static File defaultPath() { return new File(getGeneratedPath()); } public static boolean sysPath(String filename) { if (filename == null || filename.isBlank()) { return false; } return filename.startsWith(AppVariables.MyBoxTempPath.getAbsolutePath() + File.separator) || filename.startsWith(getImageClipboardPath() + File.separator) || filename.startsWith(getDataClipboardPath() + File.separator) || filename.startsWith(getImageHisPath() + File.separator) || filename.startsWith(getImageScopePath() + File.separator) || filename.startsWith(getLanguagesPath() + File.separator) || filename.startsWith(getBackupsPath() + File.separator); } public static String getPath(String name) { try { String pathString = AppVariables.MyboxDataPath + File.separator + name; File path = new File(pathString); if (!path.exists()) { path.mkdirs(); } return path.toString(); } catch (Exception e) { MyBoxLog.console(e); return null; } } public static String getImageClipboardPath() { return getPath("imageClipboard"); } public static String getDataPath() { return getPath("data"); } public static String getDataClipboardPath() { return getPath("dataClipboard"); } public static String getImageHisPath() { return getPath("imageHistories"); } public static String getImageScopePath() { return getPath("imageScopes"); } public static String getLanguagesPath() { return getPath("mybox_languages"); } public static String getBackupsPath() { return getPath("fileBackups"); } public static String getDownloadsPath() { return getPath("downloads"); } public static String getGeneratedPath() { return getPath("generated"); } public static String getIconsPath() { return getPath("icons"); } public static String getMatrixPath() { return getPath("managed" + File.separator + "matrix"); } }
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/value/FileFilters.java
alpha/MyBox/src/main/java/mara/mybox/value/FileFilters.java
package mara.mybox.value; import java.io.File; import java.util.ArrayList; import java.util.List; import javafx.stage.FileChooser; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.FileNameTools; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class FileFilters { public static boolean accept(List<FileChooser.ExtensionFilter> filters, File file) { try { if (filters == null || file == null) { return false; } String suffix = FileNameTools.ext(file.getName()); for (FileChooser.ExtensionFilter filter : filters) { List<String> exts = filter.getExtensions(); for (String ext : exts) { if (ext.equals("*") || ext.equals("*.*")) { return true; } if (suffix == null || suffix.isBlank()) { return false; } if (ext.equalsIgnoreCase("*." + suffix)) { return true; } } } return false; } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } public static List<FileChooser.ExtensionFilter> AllExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("*", "*.*", "*")); } }; public static List<FileChooser.ExtensionFilter> TextExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("*", "*.*", "*")); add(new FileChooser.ExtensionFilter("txt", "*.txt", "*.csv", "*.log", "*.ini", "*.cfg", "*.conf", "*.sh", "*.del", "*.pom", "*.env", "*.properties")); add(new FileChooser.ExtensionFilter("codes", "*.java", "*.c", "*.h", "*.py", "*.php", "*.fxml", "*.cpp", "*.cc", "*.js", "*.css", "*.bat")); add(new FileChooser.ExtensionFilter("csv", "*.csv")); add(new FileChooser.ExtensionFilter("html", "*.html", "*.htm")); add(new FileChooser.ExtensionFilter("xml", "*.xml")); add(new FileChooser.ExtensionFilter("json", "*.json")); add(new FileChooser.ExtensionFilter("markdown", "*.md")); add(new FileChooser.ExtensionFilter("svg", "*.svg")); } }; public static List<FileChooser.ExtensionFilter> ImagesExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("images", "*.png", "*.jpg", "*.jpeg", "*.bmp", "*.tif", "*.tiff", "*.gif", "*.pcx", "*.pnm", "*.wbmp", "*.ico", "*.icon", "*.webp")); } }; public static List<FileChooser.ExtensionFilter> PngExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("png", "*.png")); } }; public static List<FileChooser.ExtensionFilter> JpgExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("jpg", "*.jpg", "*.jpeg")); } }; public static List<FileChooser.ExtensionFilter> Jpg2000ExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("jpeg2000", "*.jp2", "*.jpeg2000", "*.jpx", "*.jpm")); } }; public static List<FileChooser.ExtensionFilter> TiffExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("tif/tiff", "*.tif", "*.tiff")); } }; public static List<FileChooser.ExtensionFilter> GifExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("gif", "*.gif")); } }; public static List<FileChooser.ExtensionFilter> BmpExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("bmp", "*.bmp")); } }; public static List<FileChooser.ExtensionFilter> PcxExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("pcx", "*.pcx")); } }; public static List<FileChooser.ExtensionFilter> PnmExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("pnm", "*.pnm")); } }; public static List<FileChooser.ExtensionFilter> WbmpExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("wbmp", "*.wbmp")); } }; public static List<FileChooser.ExtensionFilter> IcoExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("ico", "*.ico", "*.icon")); } }; public static List<FileChooser.ExtensionFilter> WebpExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("webp", "*.webp")); } }; public static List<FileChooser.ExtensionFilter> ImageExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { addAll(ImagesExtensionFilter); addAll(PngExtensionFilter); addAll(JpgExtensionFilter); addAll(TiffExtensionFilter); addAll(GifExtensionFilter); addAll(IcoExtensionFilter); addAll(WebpExtensionFilter); addAll(BmpExtensionFilter); addAll(PcxExtensionFilter); addAll(PnmExtensionFilter); addAll(WbmpExtensionFilter); } }; public static List<FileChooser.ExtensionFilter> AlphaImageExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("images", "*.png", "*.tif", "*.tiff", "*.ico", "*.icon", "*.webp")); addAll(PngExtensionFilter); addAll(TiffExtensionFilter); addAll(IcoExtensionFilter); addAll(WebpExtensionFilter); } }; public static List<FileChooser.ExtensionFilter> NoAlphaImageExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("images", "*.jpg", "*.jpeg", "*.bmp", "*.gif", "*.pnm", "*.wbmp")); addAll(JpgExtensionFilter); addAll(GifExtensionFilter); addAll(BmpExtensionFilter); addAll(PcxExtensionFilter); addAll(PnmExtensionFilter); addAll(WbmpExtensionFilter); } }; public static List<FileChooser.ExtensionFilter> MultipleFramesImageExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("tif/tiff/gif", "*.tif", "*.tiff", "*.gif")); addAll(TiffExtensionFilter); addAll(GifExtensionFilter); } }; public static List<FileChooser.ExtensionFilter> PdfExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("pdf", "*.pdf", "*.PDF")); } }; public static List<FileChooser.ExtensionFilter> HtmlExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("htm", "*.html", "*.htm", "*.svg")); } }; public static List<FileChooser.ExtensionFilter> MarkdownExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("markdown", "*.md", "*.MD")); } }; public static List<FileChooser.ExtensionFilter> SoundExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("sound", "*.wav", "*.mp3", "*.m4a", "*.*")); add(new FileChooser.ExtensionFilter("wav", "*.wav")); add(new FileChooser.ExtensionFilter("mp3", "*.mp3")); add(new FileChooser.ExtensionFilter("m4a", "*.m4a")); add(new FileChooser.ExtensionFilter("*", "*.*", "*")); } }; public static List<FileChooser.ExtensionFilter> Mp3WavExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("sound", "*.wav", "*.mp3")); add(new FileChooser.ExtensionFilter("wav", "*.wav")); add(new FileChooser.ExtensionFilter("mp3", "*.mp3")); add(new FileChooser.ExtensionFilter("*", "*.*", "*")); } }; public static List<FileChooser.ExtensionFilter> IccProfileExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("icc", "*.icc", "*.icm")); add(new FileChooser.ExtensionFilter("icc", "*.icc")); add(new FileChooser.ExtensionFilter("icm", "*.icm")); } }; public static List<FileChooser.ExtensionFilter> JdkMediaExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("media", "*.mp4", "*.m4a", "*.m4v", "*.mp3", "*.wav", "*.aif", "*.aiff", "*.m3u8", "*.*")); add(new FileChooser.ExtensionFilter("video", "*.mp4", "*.m4v", "*.aif", "*.aiff", "*.m3u8", "*.*")); add(new FileChooser.ExtensionFilter("audio", "*.mp4", "*.m4a", "*.mp3", "*.wav", "*.aif", "*.aiff", "*.*")); add(new FileChooser.ExtensionFilter("mp4", "*.mp4", "*.m4a", "*.m4v")); add(new FileChooser.ExtensionFilter("mp3", "*.mp3")); add(new FileChooser.ExtensionFilter("wav", "*.wav")); add(new FileChooser.ExtensionFilter("aiff", "*.aif", "*.aiff")); add(new FileChooser.ExtensionFilter("hls", "*.m3u8", "*.*")); add(new FileChooser.ExtensionFilter("*", "*.*", "*")); } }; public static List<FileChooser.ExtensionFilter> Mp4ExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("mp4", "*.mp4", "*.m4a", "*.m4v")); } }; public static List<FileChooser.ExtensionFilter> FFmpegMediaExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("media", "*.mp4", "*.m4a", "*.m4v", "*.mp3", "*.flv", "*.mov", "*.wav", "*.aif", "*.aiff", "*.m3u8", "*.*")); add(new FileChooser.ExtensionFilter("video", "*.mp4", "*.m4v", "*.aif", "*.aiff", "*.flv", "*.mov", "*.m3u8", "*.*")); add(new FileChooser.ExtensionFilter("audio", "*.mp4", "*.m4a", "*.mp3", "*.wav", "*.aif", "*.aiff", "*.*")); add(new FileChooser.ExtensionFilter("mp4", "*.mp4", "*.m4a", "*.m4v")); add(new FileChooser.ExtensionFilter("mp3", "*.mp3")); add(new FileChooser.ExtensionFilter("wav", "*.wav")); add(new FileChooser.ExtensionFilter("aiff", "*.aif", "*.aiff")); add(new FileChooser.ExtensionFilter("hls", "*.m3u8", "*.*")); add(new FileChooser.ExtensionFilter("*", "*.*", "*")); } }; public static List<FileChooser.ExtensionFilter> CertificateExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("DER", "*.cer", "*.crt", "*.rsa")); add(new FileChooser.ExtensionFilter("PKCS7", "*.p7b", "*.p7r")); add(new FileChooser.ExtensionFilter("CMS", "*.p7c", "*.p7m", "*.p7s")); add(new FileChooser.ExtensionFilter("PEM", "*.pem")); add(new FileChooser.ExtensionFilter("PKCS10", "*.p10", "*.csr")); add(new FileChooser.ExtensionFilter("SPC", "*.pvk", "*.spc")); add(new FileChooser.ExtensionFilter("*", "*.*", "*")); } }; public static List<FileChooser.ExtensionFilter> KeyStoreExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("*", "*.*", "*")); add(new FileChooser.ExtensionFilter("JKS", "*.jks", "*.ks")); add(new FileChooser.ExtensionFilter("JCEKS", "*.jce")); add(new FileChooser.ExtensionFilter("PKCS12", "*.p12", "*.pfx")); add(new FileChooser.ExtensionFilter("BKS", "*.bks")); add(new FileChooser.ExtensionFilter("UBER", "*.ubr")); } }; public static List<FileChooser.ExtensionFilter> CertExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("X.509", "*.crt")); } }; public static List<FileChooser.ExtensionFilter> TTCExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("ttc", "*.ttc")); } }; public static List<FileChooser.ExtensionFilter> TTFExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("ttf", "*.ttf")); } }; public static List<FileChooser.ExtensionFilter> ExcelExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("excel", "*.xlsx", "*.xls")); } }; public static List<FileChooser.ExtensionFilter> CsvExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("csv", "*.csv")); } }; public static List<FileChooser.ExtensionFilter> DataFileExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("*", "*.csv", "*.xlsx", "*.xls", "*.txt")); add(new FileChooser.ExtensionFilter("csv", "*.csv")); add(new FileChooser.ExtensionFilter("excel", "*.xlsx", "*.xls")); addAll(TextExtensionFilter); } }; public static List<FileChooser.ExtensionFilter> SheetExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("excel", "*.xlsx", "*.xls")); add(new FileChooser.ExtensionFilter("csv", "*.csv")); add(new FileChooser.ExtensionFilter("*", "*.*", "*")); } }; public static List<FileChooser.ExtensionFilter> WordExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("word", "*.doc")); } }; public static List<FileChooser.ExtensionFilter> WordXExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("word", "*.docx")); } }; public static List<FileChooser.ExtensionFilter> WordSExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("word", "*.doc", "*.docx")); } }; public static List<FileChooser.ExtensionFilter> PPTExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("ppt", "*.ppt")); } }; public static List<FileChooser.ExtensionFilter> PPTXExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("pptx", "*.pptx")); } }; public static List<FileChooser.ExtensionFilter> PPTSExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("ppt", "*.ppt", "*.pptx")); } }; public static List<FileChooser.ExtensionFilter> JarExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("jar", "*.jar")); } }; public static List<FileChooser.ExtensionFilter> JSONExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("json", "*.json")); } }; public static List<FileChooser.ExtensionFilter> XMLExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("xml", "*.xml")); } }; public static List<FileChooser.ExtensionFilter> SVGExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("svg", "*.svg")); } }; public static List<FileChooser.ExtensionFilter> JavascriptExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("js", "*.js")); } }; public static List<FileChooser.ExtensionFilter> ImagesListExtensionFilter = new ArrayList<FileChooser.ExtensionFilter>() { { add(new FileChooser.ExtensionFilter("*", "*.png", "*.jpg", "*.jpeg", "*.bmp", "*.tif", "*.tiff", "*.gif", "*.pcx", "*.pnm", "*.wbmp", "*.ico", "*.icon", "*.webp", "*.pdf", "*.ppt", "*.pptx")); addAll(ImageExtensionFilter); addAll(PdfExtensionFilter); addAll(PPTSExtensionFilter); } }; public static List<FileChooser.ExtensionFilter> imageFilter(String suffix) { if (suffix == null || suffix.isBlank()) { return ImageExtensionFilter; } String s = suffix.toLowerCase(); switch (s) { case "png": return PngExtensionFilter; case "jpg": return JpgExtensionFilter; case "tif": case "tiff": return TiffExtensionFilter; case "gif": return GifExtensionFilter; case "ico": case "icon": return IcoExtensionFilter; case "webp": return WebpExtensionFilter; case "bmp": return BmpExtensionFilter; case "pcx": return PcxExtensionFilter; case "pnm": return PnmExtensionFilter; case "wbmp": return WbmpExtensionFilter; default: return ImageExtensionFilter; } } }
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/value/AppValues.java
alpha/MyBox/src/main/java/mara/mybox/value/AppValues.java
package mara.mybox.value; import javafx.scene.image.Image; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class AppValues { public static final boolean Alpha = false; public static final String AppVersion = "6.9.2"; public static final String AppVersionDate = "2025-12-29"; public static final String AppDerbyUser = "mara"; public static final String AppDerbyPassword = "mybox"; public static final int AppYear = 2025; public static final Image AppIcon = new Image("img/MyBox.png"); public static final String JavaVersion = "25"; public static final String MyBoxSeparator = "##MyBox#"; public static final String MyBoxStyle = "/styles/MyBox.css"; public static final String HttpsProtocal = "TLSv1.2"; public static final String FileNameSpecialChars = "[:<>/&%]|\\*|\\?|\\\\|\n|\"|\\s+|\\||&nbsp;|&lt;|&gt;|&amp;|&quot;"; public static final String Indent = " "; public static final int IOBufferLength = 8024; public static final short InvalidShort = Short.MAX_VALUE; public static final long InvalidLong = Long.MAX_VALUE; public static final float InvalidFloat = Float.MAX_VALUE; public static final int InvalidInteger = Integer.MAX_VALUE; public static final double InvalidDouble = Double.MAX_VALUE; public static final double TinyDouble = Float.MIN_VALUE; public static final String InvalidString = "MyBox%$#@^&Invalid)(*&!~`String=-+_<>MyBox"; public static final String GaoDeMapJavascriptKey = "9a05f3a33dbf64b70f6e1ac3988d9cdd"; public static final String GaoDeMapWebServiceKey = "a389d47ae369e57e0c2c7e32e845d1b0"; public static final String TianDiTuWebKey = "0ddeb917def62b4691500526cc30a9b1"; }
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/value/UserConfig.java
alpha/MyBox/src/main/java/mara/mybox/value/UserConfig.java
package mara.mybox.value; import java.io.File; import java.sql.Connection; import javafx.scene.paint.Color; import mara.mybox.db.table.TableUserConf; import static mara.mybox.value.AppVariables.UserConfigValues; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class UserConfig { public static boolean setString(String key, String value) { UserConfigValues.put(key, value); if (TableUserConf.writeString(key, value) >= 0) { return true; } else { // MyBoxLog.console(key + " " + value); return false; } } public static boolean setString(Connection conn, String key, String value) { UserConfigValues.put(key, value); return TableUserConf.writeString(conn, key, value) >= 0; } public static String getString(String key, String defaultValue) { try { String value; if (UserConfigValues.containsKey(key)) { value = UserConfigValues.get(key); } else { value = TableUserConf.readString(key, defaultValue); if (value == null) { return defaultValue; } UserConfigValues.put(key, value); } return value; } catch (Exception e) { // MyBoxLog.error(e.toString()); return defaultValue; } } public static String getString(Connection conn, String key, String defaultValue) { try { if (conn == null) { return getString(key, defaultValue); } String value; if (UserConfigValues.containsKey(key)) { value = UserConfigValues.get(key); } else { value = TableUserConf.readString(conn, key, defaultValue); if (value == null) { return defaultValue; } UserConfigValues.put(key, value); } return value; } catch (Exception e) { // MyBoxLog.error(e.toString()); return defaultValue; } } public static boolean setInt(String key, int value) { UserConfigValues.put(key, value + ""); if (TableUserConf.writeInt(key, value) > 0) { return true; } else { return false; } } public static boolean setInt(Connection conn, String key, int value) { UserConfigValues.put(key, value + ""); if (TableUserConf.writeInt(conn, key, value) > 0) { return true; } else { return false; } } public static int getInt(String key, int defaultValue) { if (UserConfigValues.containsKey(key)) { try { int v = Integer.parseInt(UserConfigValues.get(key)); return v; } catch (Exception e) { // MyBoxLog.console(e.toString()); } } try { int v = TableUserConf.readInt(key, defaultValue); if (v == AppValues.InvalidInteger) { return defaultValue; } UserConfigValues.put(key, v + ""); return v; } catch (Exception e) { // MyBoxLog.error(e.toString()); return defaultValue; } } public static int getInt(Connection conn, String key, int defaultValue) { if (conn == null) { return getInt(key, defaultValue); } if (UserConfigValues.containsKey(key)) { try { int v = Integer.parseInt(UserConfigValues.get(key)); return v; } catch (Exception e) { // MyBoxLog.console(e.toString()); } } try { int v = TableUserConf.readInt(conn, key, defaultValue); if (v == AppValues.InvalidInteger) { return defaultValue; } UserConfigValues.put(key, v + ""); return v; } catch (Exception e) { // MyBoxLog.error(e.toString()); return defaultValue; } } public static boolean getBoolean(String key) { return getBoolean(key, true); } public static boolean getBoolean(String key, boolean defaultValue) { if (UserConfigValues.containsKey(key)) { try { boolean v = UserConfigValues.get(key).equals("true"); return v; } catch (Exception e) { } } try { boolean v = TableUserConf.readBoolean(key, defaultValue); UserConfigValues.put(key, v ? "true" : "false"); return v; } catch (Exception e) { // MyBoxLog.error(e.toString()); return defaultValue; } } public static boolean getBoolean(Connection conn, String key, boolean defaultValue) { if (conn == null) { return getBoolean(key, defaultValue); } if (UserConfigValues.containsKey(key)) { try { boolean v = UserConfigValues.get(key).equals("true"); return v; } catch (Exception e) { } } try { boolean v = TableUserConf.readBoolean(conn, key, defaultValue); UserConfigValues.put(key, v ? "true" : "false"); return v; } catch (Exception e) { // MyBoxLog.error(e.toString()); return defaultValue; } } public static boolean setBoolean(String key, boolean value) { UserConfigValues.put(key, value ? "true" : "false"); if (TableUserConf.writeBoolean(key, value) > 0) { return true; } else { return false; } } public static boolean setBoolean(Connection conn, String key, boolean value) { UserConfigValues.put(key, value ? "true" : "false"); if (TableUserConf.writeBoolean(conn, key, value) > 0) { return true; } else { return false; } } public static boolean setDouble(String key, double value) { UserConfigValues.put(key, value + ""); if (TableUserConf.writeString(key, value + "") > 0) { return true; } else { return false; } } public static boolean setDouble(Connection conn, String key, double value) { UserConfigValues.put(key, value + ""); if (TableUserConf.writeString(conn, key, value + "") > 0) { return true; } else { return false; } } public static double getDouble(String key, double defaultValue) { if (UserConfigValues.containsKey(key)) { try { double v = Double.parseDouble(UserConfigValues.get(key)); return v; } catch (Exception e) { // MyBoxLog.console(e.toString()); } } try { String v = TableUserConf.readString(key, defaultValue + ""); if (v == null) { return defaultValue; } double d = Double.parseDouble(v); UserConfigValues.put(key, v); return d; } catch (Exception e) { // MyBoxLog.error(e.toString()); return defaultValue; } } public static double getDouble(Connection conn, String key, double defaultValue) { if (conn == null) { return getDouble(key, defaultValue); } if (UserConfigValues.containsKey(key)) { try { double v = Double.parseDouble(UserConfigValues.get(key)); return v; } catch (Exception e) { // MyBoxLog.console(e.toString()); } } try { String v = TableUserConf.readString(conn, key, defaultValue + ""); if (v == null) { return defaultValue; } double d = Double.parseDouble(v); UserConfigValues.put(key, v); return d; } catch (Exception e) { // MyBoxLog.error(e.toString()); return defaultValue; } } public static boolean setLong(String key, long value) { UserConfigValues.put(key, value + ""); if (TableUserConf.writeString(key, value + "") > 0) { return true; } else { return false; } } public static boolean setLong(Connection conn, String key, long value) { UserConfigValues.put(key, value + ""); if (TableUserConf.writeString(conn, key, value + "") > 0) { return true; } else { return false; } } public static long getLong(String key, long defaultValue) { if (UserConfigValues.containsKey(key)) { try { long v = Long.parseLong(UserConfigValues.get(key)); return v; } catch (Exception e) { // MyBoxLog.console(e.toString()); } } try { String v = TableUserConf.readString(key, defaultValue + ""); if (v == null) { return defaultValue; } long d = Long.parseLong(v); UserConfigValues.put(key, v); return d; } catch (Exception e) { // MyBoxLog.error(e.toString()); return defaultValue; } } public static long getLong(Connection conn, String key, long defaultValue) { if (conn == null) { return getLong(key, defaultValue); } if (UserConfigValues.containsKey(key)) { try { long v = Long.parseLong(UserConfigValues.get(key)); return v; } catch (Exception e) { // MyBoxLog.console(e.toString()); } } try { String v = TableUserConf.readString(conn, key, defaultValue + ""); if (v == null) { return defaultValue; } long d = Long.parseLong(v); UserConfigValues.put(key, v); return d; } catch (Exception e) { // MyBoxLog.error(e.toString()); return defaultValue; } } public static boolean setFloat(String key, float value) { UserConfigValues.put(key, value + ""); if (TableUserConf.writeString(key, value + "") > 0) { return true; } else { return false; } } public static boolean setFloat(Connection conn, String key, float value) { UserConfigValues.put(key, value + ""); if (TableUserConf.writeString(conn, key, value + "") > 0) { return true; } else { return false; } } public static float getFloat(String key, float defaultValue) { if (UserConfigValues.containsKey(key)) { try { float v = Float.parseFloat(UserConfigValues.get(key)); return v; } catch (Exception e) { // MyBoxLog.console(e.toString()); } } try { String v = TableUserConf.readString(key, defaultValue + ""); if (v == null) { return defaultValue; } float d = Float.parseFloat(v); UserConfigValues.put(key, v); return d; } catch (Exception e) { // MyBoxLog.error(e.toString()); return defaultValue; } } public static float getFloat(Connection conn, String key, float defaultValue) { if (conn == null) { return getFloat(key, defaultValue); } if (UserConfigValues.containsKey(key)) { try { float v = Float.parseFloat(UserConfigValues.get(key)); return v; } catch (Exception e) { // MyBoxLog.console(e.toString()); } } try { String v = TableUserConf.readString(conn, key, defaultValue + ""); if (v == null) { return defaultValue; } float d = Float.parseFloat(v); UserConfigValues.put(key, v); return d; } catch (Exception e) { // MyBoxLog.error(e.toString()); return defaultValue; } } public static boolean deleteValue(String key) { if (TableUserConf.delete(key)) { UserConfigValues.remove(key); return true; } else { return false; } } public static File getPath(String key) { return getPath(key, AppPaths.getGeneratedPath()); } public static File getPath(String key, String defaultValue) { try { String pathString; if (UserConfigValues.containsKey(key)) { pathString = UserConfigValues.get(key); } else { pathString = TableUserConf.readString(key, defaultValue); } if (pathString == null) { pathString = defaultValue; } File path = new File(pathString); if (!path.exists() || !path.isDirectory()) { deleteValue(key); path = new File(AppPaths.getGeneratedPath()); if (!path.exists()) { path.mkdirs(); } } UserConfigValues.put(key, path.getAbsolutePath()); return path; } catch (Exception e) { // MyBoxLog.error(e.toString()); return null; } } public static String infoColor() { String v = getString("PopInfoColor", "white"); return v != null && v.startsWith("#") ? v : "white"; } public static String textSize() { return getString("PopTextSize", "1.5") + "em"; } public static String textBgColor() { String v = getString("PopTextBgColor", "black"); return v != null && v.startsWith("#") ? v : "black"; } public static Color alphaColor() { String color = getString("AlphaAsColor", Color.WHITE.toString()); Color c = Color.web(color); return new Color(c.getRed(), c.getGreen(), c.getBlue(), 1d); } public static String errorColor() { String v = getString("PopErrorColor", "aqua"); return v != null && v.startsWith("#") ? v : "aqua"; } public static String warnColor() { String v = getString("PopWarnColor", "orange"); return v != null && v.startsWith("#") ? v : "orange"; } public static int textDuration() { return getInt("PopTextDuration", 3000); } public static String getStyle() { return UserConfig.getString("InterfaceStyle", AppValues.MyBoxStyle); } public static String badStyle() { String c = errorColor(); return "-fx-text-box-border: " + c + "; -fx-text-fill: " + c + ";"; } public static String warnStyle() { String c = warnColor(); return "-fx-text-box-border: " + c + "; -fx-text-fill: " + c + ";"; } public static int imageScale() { return UserConfig.getInt("ImageDecimal", 3); } public static int selectorScrollSize() { int size = getInt("SelectorScrollSize", 100); if (size <= 0) { size = 100; } return size; } public static boolean setSceneFontSize(int size) { AppVariables.sceneFontSize = size; if (UserConfig.setInt("SceneFontSize", size)) { return true; } else { return false; } } public static boolean setIconSize(int size) { AppVariables.iconSize = size; if (UserConfig.setInt("IconSize", size)) { return true; } else { return false; } } public static void clear() { new TableUserConf().clearData(); AppVariables.initAppVaribles(); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/DataTableGroupStatistic.java
alpha/MyBox/src/main/java/mara/mybox/data2d/DataTableGroupStatistic.java
package mara.mybox.data2d; import java.io.File; import java.nio.charset.Charset; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import mara.mybox.calculation.DescriptiveStatistic; import mara.mybox.calculation.DescriptiveStatistic.StatisticType; import mara.mybox.calculation.DoubleStatistic; import mara.mybox.data2d.tools.Data2DTableTools; import mara.mybox.db.Database; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.Data2DColumn; import mara.mybox.db.data.Data2DRow; import mara.mybox.db.table.TableData2D; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.tools.CsvTools; import mara.mybox.tools.DoubleTools; import static mara.mybox.tools.FileTmpTools.generateFile; import static mara.mybox.value.Languages.message; import org.apache.commons.csv.CSVPrinter; /** * @Author Mara * @CreateDate 2022-10-16 * @License Apache License Version 2.0 */ public class DataTableGroupStatistic { protected DataTableGroup groups; protected DataTable groupResults; protected List<String> calNames; protected DescriptiveStatistic calculation; protected short scale; protected Connection conn; protected List<Data2DColumn> groupColumns; protected String idColName, parameterName, parameterValue; protected DataTable groupData, statisticData; protected TableData2D tableGroup, tableStatistic; protected long groupid, chartRowsCount, statisticRowsCount; protected PreparedStatement statisticInsert; protected FxTask task; protected boolean countChart, ok; protected File chartFile; protected CSVPrinter chartPrinter; protected DataFileCSV chartData; public boolean run() { if (groups == null || calNames == null || calculation == null || !calculation.need()) { return false; } groupResults = groups.getTargetData(); if (groupResults == null) { return false; } ok = false; try (Connection dconn = DerbyBase.getConnection()) { conn = dconn; init(); String currentParameterValue; long currentGroupid, count = 0; String mappedIdColName = groupResults.columnName(1); String sql = "SELECT * FROM " + groupResults.getSheet() + " ORDER BY " + mappedIdColName; String mappedParameterName = groupResults.columnName(2); if (task != null) { task.setInfo(sql); } try (ResultSet query = conn.prepareStatement(sql).executeQuery(); PreparedStatement insert = conn.prepareStatement(tableGroup.insertStatement());) { String sIdColName = DerbyBase.savedName(mappedIdColName); String sParameterName = DerbyBase.savedName(mappedParameterName); while (query.next()) { if (task == null || task.isCancelled()) { query.close(); chartPrinter.close(); conn.close(); return false; } currentGroupid = query.getLong(sIdColName); currentParameterValue = query.getString(sParameterName); Data2DRow data2DRow = tableGroup.newRow(); for (String name : calNames) { Object v = groupColumn(name).value(query); data2DRow.setValue(groupColumnName(name), v); } if (groupid > 0 && groupid != currentGroupid) { insert.executeBatch(); conn.commit(); statistic(); tableGroup.clearData(conn); count = 0; } if (tableGroup.setInsertStatement(conn, insert, data2DRow)) { insert.addBatch(); if (++count % Database.BatchSize == 0) { insert.executeBatch(); conn.commit(); if (task != null) { task.setInfo(message("Inserted") + ": " + count); } } } groupid = currentGroupid; parameterValue = currentParameterValue; } insert.executeBatch(); conn.commit(); statistic(); } ok = finish(); conn.commit(); conn = null; } catch (Exception e) { MyBoxLog.error(e); if (task != null) { task.setError(e.toString()); } ok = false; } return ok; } private boolean init() { try { idColName = groups.getIdColName(); parameterName = groups.getParameterName(); scale = groups.getScale(); List<Data2DColumn> valuesColumns = new ArrayList<>(); valuesColumns.add(new Data2DColumn(idColName, ColumnType.Long)); valuesColumns.add(new Data2DColumn(parameterName, ColumnType.String, 200)); valuesColumns.add(new Data2DColumn(message("ColumnName"), ColumnType.String, 200)); for (StatisticType type : calculation.types) { valuesColumns.add(new Data2DColumn(message("Group") + "_" + message(type.name()), ColumnType.Double, 150)); } String dname = DerbyBase.appendIdentifier(groupResults.getName(), "_" + message("Statistic")); statisticData = Data2DTableTools.createTable(task, conn, dname, valuesColumns); statisticData.setDataName(dname).setScale(scale); tableStatistic = statisticData.getTableData2D(); statisticInsert = conn.prepareStatement(tableStatistic.insertStatement()); if (countChart) { chartData = new DataFileCSV(); List<Data2DColumn> chartColumns = new ArrayList<>(); chartColumns.add(new Data2DColumn(idColName, ColumnType.Long)); chartColumns.add(new Data2DColumn(parameterName, ColumnType.String, 200)); chartColumns.add(new Data2DColumn(message("Group") + "_" + message("Count"), ColumnType.Long)); for (String name : calNames) { for (StatisticType type : calculation.types) { if (type == StatisticType.Count) { continue; } chartColumns.add(new Data2DColumn(name + "_" + message(type.name()), ColumnType.Double, 200)); } } String chartname = dname + "_Chart"; chartFile = generateFile(chartname, "csv"); chartData.setColumns(chartColumns).setDataName(chartname) .setFile(chartFile).setCharset(Charset.forName("UTF-8")) .setDelimiter(",").setHasHeader(true) .setColsNumber(chartColumns.size()).setScale(scale); chartPrinter = CsvTools.csvPrinter(chartFile); chartPrinter.printRecord(chartData.columnNames()); } groupColumns = new ArrayList<>(); for (String name : calNames) { Data2DColumn c = groupColumn(name).copy(); c.setColumnName(name); groupColumns.add(c); } String gname = DerbyBase.appendIdentifier(groupResults.getName(), "_" + message("Group")); groupData = Data2DTableTools.createTable(task, conn, gname, groupColumns); tableGroup = groupData.getTableData2D(); groupid = 0; chartRowsCount = 0; statisticRowsCount = 0; return true; } catch (Exception e) { MyBoxLog.error(e); if (task != null) { task.setError(e.toString()); } return false; } } public Data2DColumn groupColumn(String sourceName) { if (sourceName == null) { return null; } for (int i = 0; i < groups.tmpData.getSourcePickIndice().size(); i++) { int col = groups.tmpData.getSourcePickIndice().get(i); if (sourceName.equals(groups.originalData.columnName(col))) { return groupResults.column(i + 3); } } return null; } public String groupColumnName(String sourceName) { Data2DColumn column = groupColumn(sourceName); return column == null ? null : column.getColumnName(); } private void statistic() { try { groupData.resetStatistic(); groupData.setTask(task).setScale(groups.getScale()); int colSize = calNames.size(); List<Integer> cols = new ArrayList<>(); for (int i = 1; i <= colSize; i++) { cols.add(i); } if (task != null) { task.setInfo(parameterName + ": " + parameterValue + "\n" + message("Statistic") + ": " + calculation.names()); } DoubleStatistic[] sData = null; if (calculation.needNonStored()) { sData = groupData.statisticByColumnsWithoutStored(cols, calculation); } if (calculation.needStored()) { sData = groupData.statisticByColumnsForStored(cols, calculation); } if (sData == null) { return; } for (int i = 0; i < colSize; i++) { Data2DRow data2DRow = tableStatistic.newRow(); data2DRow.setValue(statisticData.columnName(1), groupid); data2DRow.setValue(statisticData.columnName(2), parameterValue); data2DRow.setValue(statisticData.columnName(3), calNames.get(i)); DoubleStatistic s = sData[i]; for (int k = 0; k < calculation.types.size(); k++) { StatisticType type = calculation.types.get(k); data2DRow.setValue(statisticData.columnName(k + 4), DoubleTools.scale(s.value(type), scale)); } if (tableStatistic.setInsertStatement(conn, statisticInsert, data2DRow)) { statisticInsert.addBatch(); if (++statisticRowsCount % Database.BatchSize == 0) { statisticInsert.executeBatch(); conn.commit(); if (task != null) { task.setInfo(message("Inserted") + ": " + statisticRowsCount); } } } } statisticInsert.executeBatch(); conn.commit(); if (task != null) { task.setInfo(message("Inserted") + ": " + statisticRowsCount); } if (countChart) { List<String> row = new ArrayList<>(); row.add(groupid + ""); row.add(parameterValue); row.add(sData[0].count + ""); for (DoubleStatistic s : sData) { List<String> vs = s.toStringList(); int size = vs.size(); if (size > 1) { row.addAll(vs.subList(1, size)); } } chartPrinter.printRecord(row); chartRowsCount++; } } catch (Exception e) { MyBoxLog.error(e); if (task != null) { task.setError(e.toString()); } } } private boolean finish() { try { statisticInsert.executeBatch(); conn.commit(); groupData.drop(conn); statisticData.setRowsNumber(statisticRowsCount); Data2D.saveAttributes(conn, statisticData, statisticData.getColumns()); if (countChart) { chartPrinter.flush(); chartPrinter.close(); chartData.setRowsNumber(chartRowsCount); Data2D.saveAttributes(conn, chartData, chartData.getColumns()); } ok = true; } catch (Exception e) { MyBoxLog.error(e); if (task != null) { task.setError(e.toString()); } ok = false; } return ok; } // groupid is 1-based public List<List<String>> groupData(Connection qconn, long groupid) { if (statisticData == null || qconn == null || groupid < 1 || groupid > statisticRowsCount) { return null; } List<List<String>> data = new ArrayList<>(); String sql = "SELECT * FROM " + statisticData.getSheet() + " WHERE " + statisticData.columnName(1) + "=" + groupid; if (task != null) { task.setInfo(sql); } try (ResultSet query = qconn.prepareStatement(sql).executeQuery()) { while (query.next() && qconn != null && !qconn.isClosed()) { List<String> vrow = new ArrayList<>(); for (int i = 3; i < statisticData.getColumns().size(); i++) { Data2DColumn column = statisticData.getColumns().get(i); String s = column.toString(column.value(query)); vrow.add(s); } data.add(vrow); } return data; } catch (Exception e) { MyBoxLog.error(e); return null; } } /* get */ public DataFileCSV getChartData() { return chartData; } public DataTable getStatisticData() { return statisticData; } /* set */ public DataTableGroupStatistic setGroups(DataTableGroup groups) { this.groups = groups; return this; } public DataTableGroupStatistic setTask(FxTask task) { this.task = task; return this; } public DataTableGroupStatistic setCalNames(List<String> calNames) { this.calNames = calNames; return this; } public DataTableGroupStatistic setCalculation(DescriptiveStatistic calculation) { this.calculation = calculation; return this; } public DataTableGroupStatistic setCountChart(boolean countChart) { this.countChart = countChart; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/Data2D_Data.java
alpha/MyBox/src/main/java/mara/mybox/data2d/Data2D_Data.java
package mara.mybox.data2d; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import javafx.collections.ObservableList; import javafx.scene.control.CheckBox; import javafx.scene.control.TableColumn; import mara.mybox.data.StringTable; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.ColumnDefinition.InvalidAs; import mara.mybox.db.data.Data2DColumn; import static mara.mybox.db.data.Data2DDefinition.DataType.Texts; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.image.FxColorTools; import mara.mybox.tools.DoubleTools; import mara.mybox.tools.FileTmpTools; import mara.mybox.tools.NumberTools; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2021-10-18 * @License Apache License Version 2.0 */ public abstract class Data2D_Data extends Data2D_Attributes { public Data2D_Data initData(File file, String sheet, long dataSize, long currentPage) { resetData(); this.file = file; this.sheet = sheet; pagination.rowsNumber = dataSize; pagination.currentPage = currentPage; return this; } public File tmpFile(String name, String operation, String ext) { return tmpFile(name, operation, ext, UserConfig.getBoolean("Data2DTmpDataUnderGeneratedPath", false)); } public File tmpFile(String name, String operation, String ext, boolean underGeneratedPath) { String prefix; if (name != null && !name.isBlank()) { prefix = name; } else { prefix = shortName(); } if (prefix.startsWith(TmpTable.TmpTablePrefix) || prefix.startsWith(TmpTable.TmpTablePrefix.toLowerCase())) { prefix = prefix.substring(TmpTable.TmpTablePrefix.length()); } if (operation != null && !operation.isBlank()) { if (prefix != null && !prefix.isBlank()) { prefix += "_" + operation; } else { prefix = operation; } } if (underGeneratedPath) { return FileTmpTools.generateFile(prefix, ext); } else { return FileTmpTools.tmpFile(prefix, ext); } } /* file */ public Data2D_Data initFile(File file) { if (file != null && file.equals(this.file)) { return initData(file, sheet, pagination.rowsNumber, pagination.currentPage); } else { return initData(file, null, 0, 0); } } public boolean isMutiplePages() { return dataLoaded && pagination.pagesNumber > 1; } public boolean isDataLoaded() { return dataLoaded; } public Data2D_Data setDataLoaded(boolean dataLoaded) { this.dataLoaded = dataLoaded; return this; } // file columns are not necessary in order of columns definition. // column's index remembers the order of columns // when index is less than 0, it is new column public List<String> fileRow(List<String> fileRow) { try { if (fileRow == null) { return null; } List<String> row = new ArrayList<>(); int len = fileRow.size(); for (int i = 0; i < columns.size(); i++) { String value = null; int index = columns.get(i).getIndex(); if (index >= 0 && index < len) { value = fileRow.get(index); } row.add(value); } return row; } catch (Exception e) { return null; } } public boolean supportMultipleLine() { return dataType != DataType.Texts && dataType != DataType.Matrix; } /* values */ public String randomString(Random random, boolean nonNegative) { return NumberTools.format(DoubleTools.random(random, maxRandom, nonNegative), scale); // return (char) ('a' + random.nextInt(25)) + ""; } public List<String> dummyRow() { if (columns == null) { return null; } List<String> row = new ArrayList<>(); for (Data2DColumn column : columns) { row.add(column.dummyValue()); } return row; } /* table data */ public int tableRowsNumber() { return pageData == null ? 0 : pageData.size(); } public int tableColsNumber() { return columns == null ? 0 : columns.size(); } public int colOrder(String name) { try { if (name == null || name.isBlank()) { return -1; } for (int i = 0; i < columns.size(); i++) { Data2DColumn c = columns.get(i); if (name.equals(c.getColumnName()) || name.equals(c.getLabel())) { return i; } } } catch (Exception e) { } return -1; } public int colOrderInTable(TableColumn tc) { if (tc == null) { return -1; } String name; try { Data2DColumn col = (Data2DColumn) tc.getUserData(); name = col.getColumnName(); } catch (Exception e) { name = tc.getText(); } return colOrder(name); } public int colOrderInCheckBox(CheckBox cb) { if (cb == null) { return -1; } String name; try { Data2DColumn col = (Data2DColumn) cb.getUserData(); name = col.getColumnName(); } catch (Exception e) { name = cb.getText(); } return colOrder(name); } public int idOrder() { try { for (int i = 0; i < columns.size(); i++) { Data2DColumn c = columns.get(i); if (c.isIsPrimaryKey() && c.isAuto()) { return i; } } } catch (Exception e) { } return -1; } // table data are formatted by this method public void setPageData(ObservableList<List<String>> sourceData) { try { if (sourceData == null) { pageData = null; return; } for (int i = 0; i < sourceData.size(); i++) { List<String> sourceRow = sourceData.get(i); List<String> formatedRow = new ArrayList<>(); formatedRow.add(sourceRow.get(0)); for (int j = 0; j < columns.size(); j++) { String v = sourceRow.get(j + 1); formatedRow.add(columns.get(j).formatString(v)); } sourceData.set(i, formatedRow); } pageData = sourceData; } catch (Exception e) { MyBoxLog.debug(e); } } // without data row number public List<String> dataRow(int rowIndex) { return dataRow(rowIndex, false); } public List<String> dataRow(int rowIndex, boolean formatData) { try { List<String> pageRow = pageData.get(rowIndex); List<String> dataRow = new ArrayList<>(); for (int i = 0; i < columns.size(); i++) { String v = pageRow.get(i + 1); v = formatData ? v : columns.get(i).removeFormat(v); dataRow.add(v); } return dataRow; } catch (Exception e) { return null; } } // with data row number public List<String> pageRow(int rowIndex, boolean formatData) { try { List<String> trow = pageData.get(rowIndex); List<String> row = new ArrayList<>(); String rindex = trow.get(0); // data row number row.add(rindex != null && rindex.startsWith("-1") ? null : rindex); row.addAll(dataRow(rowIndex, formatData)); return row; } catch (Exception e) { return null; } } public List<List<String>> pageRows(boolean showPageRowNumber, boolean formatData) { try { List<List<String>> rows = new ArrayList<>(); for (int i = 0; i < pageData.size(); i++) { List<String> row = new ArrayList<>(); if (showPageRowNumber) { row.add("" + (i + 1)); row.addAll(pageRow(i, formatData)); } else { row.addAll(dataRow(i, formatData)); } rows.add(row); } return rows; } catch (Exception e) { return null; } } // row data without format public List<List<String>> pageData() { return pageRows(false, false); } public List<String> newRow() { try { List<String> newRow = new ArrayList<>(); newRow.add("-1"); for (Data2DColumn column : columns) { String v = column.getDefaultValue() != null ? column.getDefaultValue() : defaultColValue(); newRow.add(column.formatString(v)); } return newRow; } catch (Exception e) { return null; } } public List<String> copyRow(List<String> row) { if (row == null) { return null; } List<String> newRow = new ArrayList<>(); newRow.addAll(row); newRow.set(0, "-1"); return newRow; } public boolean hasPage() { return hasColumns() && pageData != null; } public boolean hasPageData() { return hasColumns() && pageData != null && !pageData.isEmpty(); } public boolean isPagesChanged() { return isMutiplePages() && isTableChanged(); } public boolean isTmpData() { switch (dataType) { case CSV: case Excel: case Texts: case Matrix: return file == null; case DatabaseTable: case InternalTable: return sheet == null; default: return dataID < 0; } } public boolean isTmpFile() { return FileTmpTools.isTmpFile(file); } public boolean needBackup() { return file != null && isDataFile() && !isTmpFile() && UserConfig.getBoolean("Data2DFileBackupWhenSave", true); } public List<List<String>> tmpData(int rows, int cols) { Random random = new Random(); List<List<String>> data = new ArrayList<>(); for (int i = 0; i < rows; i++) { List<String> row = new ArrayList<>(); for (int j = 0; j < cols; j++) { row.add(randomString(random, false)); } data.add(row); } return data; } public String random(Random random, int col, boolean nonNegative) { return random(random, column(col), nonNegative); } public String random(Random random, Data2DColumn column, boolean nonNegative) { try { return column.random(random, maxRandom, scale, nonNegative); } catch (Exception e) { return null; } } public boolean verifyData() { try { if (pageData == null || pageData.isEmpty()) { return true; } List<String> names = new ArrayList<>(); names.addAll(Arrays.asList(message("Row"), message("Column"), message("Invalid"))); StringTable stringTable = new StringTable(names, labelName()); for (int r = 0; r < pageData.size(); r++) { List<String> dataRow = pageData.get(r); for (int c = 0; c < columns.size(); c++) { Data2DColumn column = columns.get(c); String value = dataRow.get(c + 1); String item = null; if (column.isNotNull() && (value == null || value.isBlank())) { item = message("Null"); } else if (column.validValue(value)) { item = message("DataType"); } else if (validValue(value)) { item = message("TextDataComments"); } if (item == null) { continue; } List<String> invalid = new ArrayList<>(); invalid.addAll(Arrays.asList((r + 1) + "", (c + 1) + "", item)); stringTable.add(invalid); } } return true; } catch (Exception e) { error = e.toString(); return false; } } /* columns */ public String defaultColValue() { return ""; } public ColumnType defaultColumnType() { return ColumnType.String; } public String colPrefix() { return message("Column"); } public boolean defaultColNotNull() { return false; } public Data2DColumn column(int col) { try { return columns.get(col); } catch (Exception e) { return null; } } public int columnsNumber() { if (columns == null) { return 0; } else { return columns.size(); } } public List<String> columnNames() { try { if (!hasColumns()) { return null; } List<String> names = new ArrayList<>(); for (Data2DColumn column : columns) { names.add(column.getColumnName()); } return names; } catch (Exception e) { return null; } } public List<String> columnNames(List<Integer> indices) { try { if (indices == null || columns == null || columns.isEmpty()) { return null; } List<String> names = new ArrayList<>(); int len = columns.size(); for (Integer i : indices) { if (i >= 0 && i < len) { names.add(columns.get(i).getColumnName()); } } return names; } catch (Exception e) { return null; } } public List<String> columnLabels() { try { if (!hasColumns()) { return null; } List<String> names = new ArrayList<>(); for (Data2DColumn column : columns) { names.add(column.getLabel()); } return names; } catch (Exception e) { return null; } } public List<Data2DColumn> makeColumns(List<Integer> indices, boolean rowNumber) { return makeColumns(columns, indices, rowNumber); } public static List<Data2DColumn> makeColumns(List<Data2DColumn> sourceColumns, List<Integer> indices, boolean rowNumber) { try { if (indices == null || sourceColumns == null || sourceColumns.isEmpty()) { return null; } List<Data2DColumn> targetCcolumns = new ArrayList<>(); if (rowNumber) { targetCcolumns.add(new Data2DColumn(message("SourceRowNumber"), ColumnDefinition.ColumnType.Long)); } for (Integer i : indices) { Data2DColumn column = sourceColumns.get(i).copy(); String name = column.getColumnName(); column.setColumnName(name); targetCcolumns.add(column); } return targetCcolumns; } catch (Exception e) { MyBoxLog.error(e); return null; } } public List<Integer> columnIndices() { try { if (!hasColumns()) { return null; } List<Integer> indices = new ArrayList<>(); for (int i = 0; i < columns.size(); i++) { indices.add(i); } return indices; } catch (Exception e) { return null; } } public Data2DColumn columnByName(String name) { try { if (name == null || name.isBlank()) { return null; } for (Data2DColumn c : columns) { if (name.equals(c.getColumnName()) || name.equals(c.getLabel())) { return c; } } } catch (Exception e) { } return null; } public String columnName(int col) { try { return column(col).getColumnName(); } catch (Exception e) { return null; } } public String columnLabel(int col) { try { return column(col).getLabel(); } catch (Exception e) { return null; } } public String formatValue(int col, String value) { try { return column(col).formatString(value); } catch (Exception e) { return null; } } public String removeFormat(int col, String value) { try { return column(col).removeFormat(value, InvalidAs.Use); } catch (Exception e) { return null; } } public boolean hasColumns() { return isValidDefinition() && columns != null && !columns.isEmpty(); } public int newColumnIndex() { return --newColumnIndex; } public List<String> timeColumnNames() { if (columns == null) { return null; } List<String> names = new ArrayList<>(); for (Data2DColumn col : columns) { if (col.isTimeType()) { names.add(col.getColumnName()); } } return names; } public List<Data2DColumn> toColumns(List<String> names) { try { if (names == null) { return null; } List<Data2DColumn> cols = new ArrayList<>(); Random random = new Random(); for (String c : names) { Data2DColumn col = new Data2DColumn(c, defaultColumnType()); col.setIndex(newColumnIndex()); col.setColor(FxColorTools.randomColor(random)); cols.add(col); } return cols; } catch (Exception e) { MyBoxLog.error(e); return null; } } public List<Data2DColumn> tmpColumns(int cols) { List<String> names = new ArrayList<>(); for (int c = 1; c <= cols; c++) { names.add(colPrefix() + c); } return toColumns(names); } public List<Data2DColumn> fixColumnNames(List<Data2DColumn> inColumns) { if (inColumns == null || inColumns.isEmpty()) { return inColumns; } List<String> validNames = new ArrayList<>(); List<Data2DColumn> targetColumns = new ArrayList<>(); for (Data2DColumn column : inColumns) { Data2DColumn tcolumn = column.copy(); String name = DerbyBase.checkIdentifier(validNames, tcolumn.getColumnName(), true); tcolumn.setColumnName(name); targetColumns.add(tcolumn); } return targetColumns; } public void resetStatistic() { if (!hasColumns()) { return; } for (Data2DColumn column : columns) { column.setStatistic(null); } } public boolean includeCoordinate() { if (columns == null) { return false; } boolean hasLongitude = false, haslatitude = false; for (Data2DColumn column : columns) { if (column.getType() == ColumnType.Longitude) { hasLongitude = true; } else if (column.getType() == ColumnType.Latitude) { haslatitude = true; } } return hasLongitude && haslatitude; } public List<String> placeholders(boolean allStatistic) { try { if (!hasColumns()) { return null; } List<String> list = new ArrayList<>(); list.add("#{" + message("TableRowNumber") + "}"); list.add("#{" + message("DataRowNumber") + "}"); for (Data2DColumn column : columns) { String name = column.getColumnName(); list.add("#{" + name + "}"); } for (Data2DColumn column : columns) { String name = column.getColumnName(); if (allStatistic || column.isDBNumberType()) { list.add("#{" + name + "-" + message("Mean") + "}"); list.add("#{" + name + "-" + message("Median") + "}"); list.add("#{" + name + "-" + message("Mode") + "}"); list.add("#{" + name + "-" + message("MinimumQ0") + "}"); list.add("#{" + name + "-" + message("LowerQuartile") + "}"); list.add("#{" + name + "-" + message("UpperQuartile") + "}"); list.add("#{" + name + "-" + message("MaximumQ4") + "}"); list.add("#{" + name + "-" + message("LowerExtremeOutlierLine") + "}"); list.add("#{" + name + "-" + message("LowerMildOutlierLine") + "}"); list.add("#{" + name + "-" + message("UpperMildOutlierLine") + "}"); list.add("#{" + name + "-" + message("UpperExtremeOutlierLine") + "}"); } } return list; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/data2d/DataTableGroup.java
alpha/MyBox/src/main/java/mara/mybox/data2d/DataTableGroup.java
package mara.mybox.data2d; import java.io.File; import java.nio.charset.Charset; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import javafx.scene.control.IndexRange; import mara.mybox.controller.ControlData2DGroup; import mara.mybox.data.DataSort; import mara.mybox.data.ValueRange; import mara.mybox.data2d.tools.Data2DRowTools; import mara.mybox.data2d.tools.Data2DTableTools; import mara.mybox.db.Database; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.ColumnDefinition.InvalidAs; import mara.mybox.db.data.Data2DColumn; import mara.mybox.db.data.Data2DRow; import mara.mybox.db.table.TableData2D; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.tools.CsvTools; import mara.mybox.tools.DateTools; import mara.mybox.tools.DoubleTools; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; import org.apache.commons.csv.CSVPrinter; /** * @Author Mara * @CreateDate 2022-10-17 * @License Apache License Version 2.0 */ public class DataTableGroup { protected ControlData2DGroup groupController; protected GroupType groupType; protected Data2D originalData; protected TmpTable tmpData; protected String groupName, timeName; protected TimeType timeType; protected List<String> groupNames, orders; protected InvalidAs invalidAs; protected short scale; protected long max; protected TargetType targetType; protected FxTask task; protected boolean includeRowNumber, ok; protected List<Integer> sourcePickIndice; protected String tmpSheet, idColName, parameterName, parameterValue, parameterValueForFilename; protected String tmpOrderby, groupOrderby, mappedIdColName, mappedParameterName, dataComments; protected List<Data2DColumn> tmpColumns; protected long count, groupid, groupCurrentSize; protected int tmpValueOffset, targetValueOffset; protected Connection conn; protected List<String> targetColNames; protected List<Data2DColumn> targetColumns, finalColumns; protected DataTable targetData, groupParameters; protected TableData2D tableTmpData, tableTarget, tableGroupParameters; protected PreparedStatement insert; protected File csvFile; protected CSVPrinter csvPrinter; protected DataFileCSV targetFile; protected List<File> csvFiles; public enum GroupType { EqualValues, Time, Expression, ValueSplitInterval, ValueSplitNumber, ValueSplitList, RowsSplitInterval, RowsSplitNumber, RowsSplitList, Conditions } public enum TimeType { Century, Year, Month, Day, Hour, Minute, Second } public enum TargetType { SingleFile, MultipleFiles, Table, TmpTable } // This class is based on results of "Data2D_Convert.toTmpTable(...)" public DataTableGroup(Data2D originalData, ControlData2DGroup groupController, TmpTable tmpData) { this.originalData = originalData; this.groupController = groupController; this.tmpData = tmpData; } public boolean run() { if (originalData == null || groupController == null || tmpData == null || targetType == null || sourcePickIndice == null || sourcePickIndice.isEmpty()) { return false; } groupType = groupController.groupType(); if (null == groupType) { return false; } groupName = groupController.groupName(); groupNames = groupController.groupNames(); timeName = groupController.timeName(); timeType = groupController.timeType(); tmpSheet = tmpData.getSheet(); tmpColumns = tmpData.getColumns(); if (tmpSheet == null || tmpColumns == null) { return false; } tmpOrderby = tmpData.getTmpOrderby(); tmpValueOffset = tmpData.getValueIndexOffset(); tableTmpData = tmpData.getTableData2D(); ok = false; if (conn == null) { try (Connection dconn = DerbyBase.getConnection()) { conn = dconn; ok = scan(); stopScan(); if (ok) { ok = finishGroup(); } dconn.commit(); dconn.close(); conn = null; } catch (Exception e) { MyBoxLog.error(e); if (task != null) { task.setError(e.toString()); } ok = false; } } else { ok = scan(); stopScan(); if (ok) { finishGroup(); } } if (!ok) { if (groupParameters != null) { groupParameters.drop(); groupParameters = null; } } return ok; } private boolean scan() { try { switch (groupType) { case RowsSplitInterval: case RowsSplitNumber: case RowsSplitList: parameterName = message("DataRowNumber"); break; case Conditions: if (groupController.groupConditions() == null || groupController.groupConditions().isEmpty()) { return false; } parameterName = message("Condition"); break; case ValueSplitInterval: case ValueSplitNumber: case ValueSplitList: if (groupName == null || groupName.isBlank()) { return false; } parameterName = message("Range") + "_" + groupName; break; case EqualValues: if (groupNames == null || groupNames.isEmpty()) { return false; } parameterName = message("EqualValues"); for (String name : groupNames) { parameterName += "_" + name; } break; case Time: if (timeName == null || timeName.isBlank()) { return false; } parameterName = message(timeType.name()) + "_" + timeName; break; case Expression: parameterName = message("Expression"); break; default: return false; } groupid = 0; groupCurrentSize = 0; count = 0; idColName = message("GroupID"); targetData = null; insert = null; csvPrinter = null; csvFiles = new ArrayList<>(); groupOrderby = null; dataComments = null; targetColNames = new ArrayList<>(); targetColNames.add(idColName); targetColNames.add(parameterName); targetColumns = new ArrayList<>(); targetColumns.add(new Data2DColumn(idColName, ColumnType.Long)); targetColumns.add(new Data2DColumn(parameterName, ColumnType.String, 200)); targetValueOffset = 2; if (includeRowNumber) { targetColumns.add(new Data2DColumn(message("SourceRowNumber"), ColumnType.Long)); targetValueOffset++; } for (int c : sourcePickIndice) { Data2DColumn column = originalData.column(c).copy(); targetColumns.add(column); targetColNames.add(column.getColumnName()); } List<Data2DColumn> parametersColumns = new ArrayList<>(); parametersColumns.add(new Data2DColumn("group_index", ColumnType.Long)); parametersColumns.add(new Data2DColumn("group_parameters", ColumnType.String)); groupParameters = Data2DTableTools.createTable(task, conn, null, parametersColumns); tableGroupParameters = groupParameters.getTableData2D(); dataComments = message("GroupBy") + ": " + message(groupType.name()) + "\n"; switch (groupType) { case EqualValues: dataComments += message("Columns") + ": " + groupNames.toString(); return byEqualValues(); case ValueSplitInterval: dataComments += message("Column") + ": " + groupName + "\n" + message("Inteval") + ": " + groupController.valueSplitInterval(); return byValueInteval(); case ValueSplitNumber: dataComments += message("Column") + ": " + groupName + "\n" + message("NumberOfSplit") + ": " + groupController.valueSplitNumber(); return byValueInteval(); case ValueSplitList: dataComments += message("Column") + ": " + groupName + "\n" + message("List") + ":\n"; for (ValueRange range : groupController.valueSplitList()) { dataComments += range.toString() + "\n"; } return byValueList(); case RowsSplitInterval: dataComments += message("Interval") + ": " + groupController.rowsSplitInterval(); return byRowsInteval(); case RowsSplitNumber: dataComments += message("NumberOfSplit") + ": " + groupController.rowsSplitNumber(); return byRowsInteval(); case RowsSplitList: dataComments += message("List") + ":\n"; List<Integer> splitList = groupController.rowsSplitList(); for (int i = 0; i < splitList.size();) { dataComments += "[" + splitList.get(i++) + "," + splitList.get(i++) + "]" + "\n"; } return byRowsList(); case Conditions: dataComments += message("List") + ":\n"; for (DataFilter filter : groupController.groupConditions()) { dataComments += filter.toString() + "\n"; } return byConditions(); case Time: dataComments += message("Column") + ": " + timeName + "\n" + message("Same") + ": " + timeType.name(); return byTime(); case Expression: dataComments += message("RowExpression") + ": " + "\n" + tmpData.getGroupExpression(); return byExpression(); } return false; } catch (Exception e) { MyBoxLog.error(e); if (task != null) { task.setError(e.toString()); } return false; } } private int parametersOffset() { return tmpData.parametersOffset(); } private boolean byEqualValues() { try { if (groupType != GroupType.EqualValues || groupNames == null || groupNames.isEmpty()) { return false; } String finalOrderBy = null; List<String> mappedGroupNames = new ArrayList<>(); int offset = parametersOffset(); for (int i = 0; i < groupNames.size(); i++) { String name = tmpData.columnName(i + offset); if (finalOrderBy == null) { finalOrderBy = name; } else { finalOrderBy += ", " + name; } mappedGroupNames.add(name); } if (tmpOrderby != null && !tmpOrderby.isBlank()) { finalOrderBy += "," + tmpOrderby; } String sql = "SELECT * FROM " + tmpSheet + " ORDER BY " + finalOrderBy; if (task != null) { task.setInfo(sql); } try (ResultSet query = conn.prepareStatement(sql).executeQuery()) { Data2DRow tmpRow, lastRow = null; Map<String, Object> groupMap = new HashMap<>(); boolean groupChanged; conn.setAutoCommit(false); while (query.next() && task != null && !task.isCancelled()) { if (task == null || task.isCancelled()) { query.close(); return false; } try { tmpRow = tableTmpData.readData(query); if (lastRow == null) { groupChanged = true; } else { groupChanged = false; for (String group : mappedGroupNames) { Object tv = tmpRow.getValue(group); Object lv = lastRow.getValue(group); if (tv == null) { if (lv != null) { groupChanged = true; break; } } else { if (!tv.equals(lv)) { groupChanged = true; break; } } } } if (groupChanged) { groupChanged(); parameterValueForFilename = idColName + groupid; parameterValue = null; groupMap.clear(); for (int i = 0; i < groupNames.size(); i++) { groupMap.put(groupNames.get(i), tmpRow.getValue(mappedGroupNames.get(i))); } parameterValue = groupMap.toString(); recordGroup(groupid, parameterValue); } if (++groupCurrentSize <= max || max <= 0) { writeRow(tmpRow); } lastRow = tmpRow; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } } } } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } } return true; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } return false; } } private boolean byValueInteval() { try { if (groupName == null || groupName.isBlank()) { return false; } Data2DColumn rangeColumn = tmpData.column(parametersOffset()); String rangeColumnName = rangeColumn.getColumnName(); double maxValue = Double.NaN, minValue = Double.NaN; String sql = "SELECT MAX(" + rangeColumnName + ") AS dmax, MIN(" + rangeColumnName + ") AS dmin FROM " + tmpSheet; if (task != null) { task.setInfo(sql); } try (ResultSet results = conn.prepareStatement(sql).executeQuery()) { if (results.next()) { maxValue = results.getDouble("dmax"); minValue = results.getDouble("dmin"); } } catch (Exception e) { if (task != null) { task.setError(e.toString()); } MyBoxLog.error(e.toString()); } if (DoubleTools.invalidDouble(maxValue) || DoubleTools.invalidDouble(minValue) || task == null || task.isCancelled()) { if (task != null) { task.setError(message("NoData")); } return false; } if (task != null) { task.setInfo("max: " + maxValue + " min: " + minValue); } long maxGroup = Long.MAX_VALUE; double interval = groupController.valueSplitInterval(); if (groupType == GroupType.ValueSplitNumber) { int splitNumber = groupController.valueSplitNumber(); if (splitNumber == 0) { return false; } interval = (maxValue - minValue) / splitNumber; maxGroup = splitNumber; } double start = minValue, end; Data2DColumn rangeSourceColumn = tmpData.parameterSourceColumn(); int rscale = rangeSourceColumn.needScale() ? groupController.splitScale() : 0; boolean isDate = rangeSourceColumn.isTimeType(); String condition; conn.setAutoCommit(false); while (start <= maxValue) { if (task == null || task.isCancelled()) { return false; } end = start + interval; if (groupid < maxGroup) { groupChanged(); } if (end >= maxValue || groupid >= maxGroup) { String startName = isDate ? DateTools.textEra(Math.round(start)) : DoubleTools.scaleString(start, rscale); String endName = isDate ? DateTools.textEra(Math.round(maxValue)) : DoubleTools.scaleString(maxValue, rscale); parameterValue = "[" + startName + "," + endName + "]"; parameterValueForFilename = startName + "-" + endName; condition = rangeColumnName + " >= " + start; start = maxValue + 1; } else { String startName = isDate ? DateTools.textEra(Math.round(start)) : DoubleTools.scaleString(start, rscale); String endName = isDate ? DateTools.textEra(Math.round(end)) : DoubleTools.scaleString(end, rscale); parameterValue = "[" + startName + "," + endName + ")"; parameterValueForFilename = startName + "-" + endName; end = DoubleTools.scale(end, rscale); condition = rangeColumnName + " >= " + start + " AND " + rangeColumnName + " < " + end; start = end; } recordGroup(groupid, parameterValue); sql = "SELECT * FROM " + tmpSheet + " WHERE " + condition + (tmpOrderby != null && !tmpOrderby.isBlank() ? " ORDER BY " + tmpOrderby : ""); valueQeury(sql); } return true; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } return false; } } private boolean byValueList() { try { if (groupName == null || groupName.isBlank() || groupController == null) { return false; } Data2DColumn rangeColumn = tmpData.column(parametersOffset()); String rangeColumnName = rangeColumn.getColumnName(); List<ValueRange> splitList = groupController.valueSplitList(); if (splitList == null || splitList.isEmpty()) { return false; } String condition; conn.setAutoCommit(false); double start, end; Data2DColumn rangeSourceColumn = tmpData.parameterSourceColumn(); int rscale = rangeSourceColumn.needScale() ? groupController.splitScale() : 0; boolean isDate = rangeSourceColumn.isTimeType(); for (ValueRange range : splitList) { if (task == null || task.isCancelled()) { return false; } try { if (isDate) { start = DateTools.encodeDate((String) range.getStart()).getTime(); } else { start = (double) range.getStart(); } } catch (Exception e) { continue; } try { if (isDate) { end = DateTools.encodeDate((String) range.getEnd()).getTime(); } else { end = (double) range.getEnd(); } } catch (Exception e) { continue; } if (start > end) { continue; } groupChanged(); condition = rangeColumnName + (range.isIncludeStart() ? " >= " : " > ") + start + " AND " + rangeColumnName + (range.isIncludeEnd() ? " <= " : " < ") + end; String startName = isDate ? DateTools.textEra(Math.round(start)) : DoubleTools.scaleString(start, rscale); String endName = isDate ? DateTools.textEra(Math.round(end)) : DoubleTools.scaleString(end, rscale); parameterValue = (range.isIncludeStart() ? "[" : "(") + startName + "," + endName + (range.isIncludeEnd() ? "]" : ")"); parameterValueForFilename = startName + "-" + endName; recordGroup(groupid, parameterValue); String sql = "SELECT * FROM " + tmpSheet + " WHERE " + condition + (tmpOrderby != null && !tmpOrderby.isBlank() ? " ORDER BY " + tmpOrderby : ""); valueQeury(sql); } return true; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } return false; } } private void valueQeury(String sql) { if (task != null) { task.setInfo(sql); } try (ResultSet query = conn.prepareStatement(sql).executeQuery()) { Data2DRow tmpRow; while (query.next()) { if (task == null || task.isCancelled()) { query.close(); return; } try { tmpRow = tableTmpData.readData(query); if (++groupCurrentSize <= max || max <= 0) { writeRow(tmpRow); } else { break; } } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } } } if (insert != null) { insert.executeBatch(); } conn.commit(); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } MyBoxLog.error(e.toString()); } } private boolean byTime() { try { if (timeName == null || timeName.isBlank()) { return false; } Data2DColumn timeColumn = tmpData.column(parametersOffset()); String tmpTimeName = timeColumn.getColumnName(); String finalOrderBy = tmpTimeName; if (tmpOrderby != null && !tmpOrderby.isBlank()) { finalOrderBy += "," + tmpOrderby; } String sql = "SELECT * FROM " + tmpSheet + " ORDER BY " + finalOrderBy; if (task != null) { task.setInfo(sql); } try (ResultSet query = conn.prepareStatement(sql).executeQuery()) { long timeValue, lastTimeValue = Long.MAX_VALUE; boolean groupChanged, isChinese = Languages.isChinese(); long zeroYear = DateTools.zeroYear(); Calendar calendar = Calendar.getInstance(); conn.setAutoCommit(false); while (query.next() && task != null && !task.isCancelled()) { if (task == null || task.isCancelled()) { query.close(); return false; } try { Data2DRow tmpRow = tableTmpData.readData(query); Object tv = tmpRow.getValue(tmpTimeName); timeValue = tv == null ? null : (long) tv; groupChanged = lastTimeValue == Long.MAX_VALUE || lastTimeValue != timeValue; if (groupChanged) { groupChanged(); parameterValueForFilename = idColName + groupid; boolean isBC = timeValue < zeroYear; if (timeType == TimeType.Century) { calendar.setTimeInMillis(timeValue); int v = calendar.get(Calendar.YEAR); if (v % 100 == 0) { v = v / 100; } else { v = (v / 100) + 1; } if (isChinese) { parameterValue = (isBC ? "公元前" : "") + v + "世纪"; } else { parameterValue = v + "th century" + (isBC ? " BC" : ""); } } else { String format = ""; switch (timeType) { case Year: format = "y"; break; case Month: format = "y-MM"; break; case Day: format = "y-MM-dd"; break; case Hour: format = "y-MM-dd HH"; break; case Minute: format = "y-MM-dd HH:mm"; break; case Second: format = "y-MM-dd HH:mm:ss"; break; } if (isChinese) { parameterValue = new SimpleDateFormat((isBC ? "G" : "") + format, Languages.LocaleZhCN) .format(timeValue); } else { parameterValue = new SimpleDateFormat(format + (isBC ? " G" : ""), Languages.LocaleEn) .format(timeValue); } } recordGroup(groupid, parameterValue); } if (++groupCurrentSize <= max || max <= 0) { writeRow(tmpRow); } lastTimeValue = timeValue; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } } } } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } } return true; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } return false; } } private boolean byExpression() { try { Data2DColumn expColumn = tmpData.column(parametersOffset()); String tmpExpName = expColumn.getColumnName(); String finalOrderBy = tmpExpName; if (tmpOrderby != null && !tmpOrderby.isBlank()) { finalOrderBy += "," + tmpOrderby; } String sql = "SELECT * FROM " + tmpSheet + " ORDER BY " + finalOrderBy; if (task != null) { task.setInfo(sql); } try (ResultSet query = conn.prepareStatement(sql).executeQuery()) { Object expValue, lastExpValue = null; boolean groupChanged; conn.setAutoCommit(false); while (query.next() && task != null && !task.isCancelled()) { if (task == null || task.isCancelled()) { query.close(); return false; } try { Data2DRow tmpRow = tableTmpData.readData(query); expValue = tmpRow.getValue(tmpExpName); groupChanged = expColumn.compare(lastExpValue, expValue) != 0; if (groupChanged) { groupChanged(); parameterValueForFilename = idColName + groupid; parameterValue = expColumn.toString(expValue); recordGroup(groupid, parameterValue); } if (++groupCurrentSize <= max || max <= 0) { writeRow(tmpRow); } lastExpValue = expValue; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } } } } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } } return true; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e.toString()); } return false; } } private boolean byRowsInteval() { try { long total = 0; String sql = "SELECT COUNT(*) FROM " + tmpSheet; if (task != null) { task.setInfo(sql); } try (ResultSet query = conn.prepareStatement(sql).executeQuery()) { if (query.next()) { total = query.getLong(1); } } if (total <= 0) { return false; } long maxGroup = total; int splitInterval = groupController.rowsSplitInterval();
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
true