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/released/MyBox/src/main/java/mara/mybox/data/ShapeStyle.java | released/MyBox/src/main/java/mara/mybox/data/ShapeStyle.java | package mara.mybox.data;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import javafx.scene.paint.Color;
import javafx.scene.shape.StrokeLineCap;
import static javafx.scene.shape.StrokeLineCap.ROUND;
import static javafx.scene.shape.StrokeLineCap.SQUARE;
import javafx.scene.shape.StrokeLineJoin;
import mara.mybox.db.DerbyBase;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.image.FxColorTools;
import static mara.mybox.fxml.image.FxColorTools.toAwtColor;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2023-7-11
* @License Apache License Version 2.0
*/
public class ShapeStyle {
public final static String DefaultStrokeColor = "#c94d58", DefaultAnchorColor = "#0066cc";
private String name, more;
private Color strokeColor, fillColor, anchorColor;
private float strokeWidth, strokeOpacity, fillOpacity, anchorSize, strokeLineLimit, dashOffset;
private boolean isFillColor, isStrokeDash;
private List<Double> strokeDash;
private StrokeLineCap strokeLineCap;
private StrokeLineJoin strokeLineJoin;
public ShapeStyle() {
init("");
}
public ShapeStyle(String name) {
init(name);
}
public ShapeStyle(Connection conn, String name) {
init(conn, name);
}
final public void init(String name) {
try (Connection conn = DerbyBase.getConnection()) {
init(conn, name);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
final public void init(Connection conn, String inName) {
try {
name = inName != null ? inName : "";
try {
strokeColor = Color.web(UserConfig.getString(conn, name + "StrokeColor", DefaultStrokeColor));
} catch (Exception e) {
strokeColor = Color.web(DefaultStrokeColor);
}
try {
fillColor = Color.web(UserConfig.getString(conn, name + "FillColor", "0xFFFFFFFF"));
} catch (Exception e) {
fillColor = Color.TRANSPARENT;
}
try {
anchorColor = Color.web(UserConfig.getString(conn, name + "AnchorColor", DefaultAnchorColor));
} catch (Exception e) {
anchorColor = Color.web(DefaultAnchorColor);
}
strokeWidth = UserConfig.getFloat(conn, name + "StrokeWidth", 10);
if (strokeWidth < 0) {
strokeWidth = 10f;
}
strokeOpacity = UserConfig.getFloat(conn, name + "StrokeOpacity", 1);
if (strokeOpacity < 0) {
strokeOpacity = 1;
}
fillOpacity = UserConfig.getFloat(conn, name + "FillOpacity", 1f);
if (fillOpacity < 0) {
fillOpacity = 1f;
}
isFillColor = UserConfig.getBoolean(conn, name + "IsFillColor", false);
isStrokeDash = UserConfig.getBoolean(conn, name + "IsStrokeDash", false);
anchorSize = UserConfig.getFloat(conn, name + "AnchorSize", 10);
if (anchorSize < 0) {
anchorSize = 10;
}
String text = UserConfig.getString(conn, name + "StrokeDash", null);
strokeDash = text2StrokeDash(text);
text = UserConfig.getString(conn, name + "StrokeLineCap", "BUTT");
strokeLineCap = strokeLineCap(text);
text = UserConfig.getString(conn, name + "StrokeLineJoin", "MITER");
strokeLineJoin = strokeLineJoin(text);
strokeLineLimit = UserConfig.getFloat(conn, name + "StrokeLineLimit", 10f);
dashOffset = UserConfig.getFloat(conn, name + "DashOffset", 0f);
more = null;
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public ShapeStyle save() {
try (Connection conn = DerbyBase.getConnection()) {
UserConfig.setString(conn, name + "StrokeColor", strokeColor != null ? strokeColor.toString() : null);
UserConfig.setString(conn, name + "AnchorColor", anchorColor != null ? anchorColor.toString() : null);
UserConfig.setBoolean(conn, name + "IsFillColor", isFillColor);
UserConfig.setString(conn, name + "FillColor", fillColor != null ? fillColor.toString() : null);
UserConfig.setFloat(conn, name + "StrokeWidth", strokeWidth);
UserConfig.setFloat(conn, name + "AnchorSize", anchorSize);
UserConfig.setFloat(conn, name + "StrokeOpacity", strokeOpacity);
UserConfig.setFloat(conn, name + "FillOpacity", fillOpacity);
UserConfig.setBoolean(conn, name + "IsStrokeDash", isStrokeDash);
UserConfig.setString(conn, name + "StrokeDash", strokeDash2Text(strokeDash));
UserConfig.setFloat(conn, name + "DashOffset", dashOffset);
UserConfig.setString(conn, name + "StrokeLineCap",
strokeLineCap != null ? strokeLineCap.name() : null);
UserConfig.setFloat(conn, name + "StrokeLineLimit", strokeLineLimit);
UserConfig.setString(conn, name + "StrokeLineJoin",
strokeLineJoin != null ? strokeLineJoin.name() : null);
} catch (Exception e) {
MyBoxLog.debug(e);
}
return this;
}
/*
static
*/
public static List<Double> text2StrokeDash(String text) {
try {
if (text == null || text.isBlank()) {
return null;
}
String[] values = text.split("\\s+");
if (values == null || values.length == 0) {
return null;
}
List<Double> dash = new ArrayList<>();
for (String v : values) {
dash.add(Double.valueOf(v));
}
return dash;
} catch (Exception e) {
return null;
}
}
public static String strokeDash2Text(List<Double> dash) {
try {
if (dash == null || dash.isEmpty()) {
return null;
}
String text = "";
for (Double v : dash) {
text += v + " ";
}
return text;
} catch (Exception e) {
return null;
}
}
public static float[] strokeDashAwt(List<Double> vs) {
try {
if (vs == null || vs.isEmpty()) {
return null;
}
float[] values = new float[vs.size()];
for (int i = 0; i < vs.size(); i++) {
values[i] = vs.get(i).floatValue();
}
return values;
} catch (Exception e) {
return null;
}
}
public static StrokeLineCap strokeLineCap(String text) {
try {
if (text == null || text.isBlank()) {
return StrokeLineCap.BUTT;
}
if ("ROUND".equalsIgnoreCase(text)) {
return StrokeLineCap.ROUND;
} else if ("SQUARE".equalsIgnoreCase(text)) {
return StrokeLineCap.SQUARE;
} else {
return StrokeLineCap.BUTT;
}
} catch (Exception e) {
return StrokeLineCap.BUTT;
}
}
public static int strokeLineCapAwt(StrokeLineCap v) {
try {
if (null == v) {
return java.awt.BasicStroke.CAP_BUTT;
} else {
switch (v) {
case ROUND:
return java.awt.BasicStroke.CAP_ROUND;
case SQUARE:
return java.awt.BasicStroke.CAP_SQUARE;
default:
return java.awt.BasicStroke.CAP_BUTT;
}
}
} catch (Exception e) {
return java.awt.BasicStroke.CAP_BUTT;
}
}
public static StrokeLineJoin strokeLineJoin(String text) {
try {
if (text == null || text.isBlank()) {
return StrokeLineJoin.MITER;
}
if ("ROUND".equalsIgnoreCase(text)) {
return StrokeLineJoin.ROUND;
} else if ("BEVEL".equalsIgnoreCase(text)) {
return StrokeLineJoin.BEVEL;
} else {
return StrokeLineJoin.MITER;
}
} catch (Exception e) {
return StrokeLineJoin.MITER;
}
}
public static int strokeLineJoinAwt(StrokeLineJoin v) {
try {
if (null == v) {
return java.awt.BasicStroke.JOIN_MITER;
} else {
switch (v) {
case ROUND:
return java.awt.BasicStroke.JOIN_ROUND;
case BEVEL:
return java.awt.BasicStroke.JOIN_BEVEL;
default:
return java.awt.BasicStroke.JOIN_MITER;
}
}
} catch (Exception e) {
return java.awt.BasicStroke.JOIN_MITER;
}
}
/*
set
*/
public ShapeStyle setName(String name) {
this.name = name;
return this;
}
public ShapeStyle setStrokeColor(Color strokeColor) {
this.strokeColor = strokeColor;
return this;
}
public ShapeStyle setAnchorColor(Color anchorColor) {
this.anchorColor = anchorColor;
return this;
}
public ShapeStyle setIsFillColor(boolean isFillColor) {
this.isFillColor = isFillColor;
return this;
}
public ShapeStyle setFillColor(Color fillColor) {
this.fillColor = fillColor;
return this;
}
public ShapeStyle setStrokeWidth(float strokeWidth) {
this.strokeWidth = strokeWidth;
return this;
}
public ShapeStyle setAnchorSize(float anchorSize) {
this.anchorSize = anchorSize;
return this;
}
public ShapeStyle setStrokeOpacity(float strokeOpacity) {
this.strokeOpacity = strokeOpacity;
return this;
}
public ShapeStyle setFillOpacity(float fillOpacity) {
this.fillOpacity = fillOpacity;
return this;
}
public ShapeStyle setIsStrokeDash(boolean isStrokeDash) {
this.isStrokeDash = isStrokeDash;
return this;
}
public ShapeStyle setStrokeDashed(boolean dashed) {
setIsStrokeDash(dashed);
if (dashed) {
setStrokeDash(text2StrokeDash(strokeWidth + " " + strokeWidth * 3));
}
return this;
}
public ShapeStyle setStrokeDash(List<Double> strokeDash) {
this.strokeDash = strokeDash;
return this;
}
public ShapeStyle setStrokeDashText(String text) {
setStrokeDash(text2StrokeDash(text));
return this;
}
public ShapeStyle setDashOffset(float dashOffset) {
this.dashOffset = dashOffset;
return this;
}
public ShapeStyle setStrokeLineCap(StrokeLineCap strokeLineCap) {
this.strokeLineCap = strokeLineCap;
return this;
}
public ShapeStyle setStrokeLineLimit(float strokeLineLimit) {
this.strokeLineLimit = strokeLineLimit;
return this;
}
public ShapeStyle setStrokeLineJoin(StrokeLineJoin strokeLineJoin) {
this.strokeLineJoin = strokeLineJoin;
return this;
}
public ShapeStyle setMore(String more) {
this.more = more;
return this;
}
/*
get
*/
public String getName() {
return name;
}
public Color getStrokeColor() {
return strokeColor;
}
public String getStrokeColorCss() {
return FxColorTools.color2css(strokeColor);
}
public java.awt.Color getStrokeColorAwt() {
return toAwtColor(getStrokeColor());
}
public Color getFillColor() {
return fillColor;
}
public java.awt.Color getFillColorAwt() {
return toAwtColor(getFillColor());
}
public String getFilleColorCss() {
return FxColorTools.color2css(fillColor);
}
public Color getAnchorColor() {
return anchorColor;
}
public java.awt.Color getAnchorColorAwt() {
return toAwtColor(getAnchorColor());
}
public float getStrokeWidth() {
return strokeWidth;
}
public float getStrokeOpacity() {
return strokeOpacity;
}
public float getFillOpacity() {
return fillOpacity;
}
public float getAnchorSize() {
return anchorSize;
}
public boolean isIsFillColor() {
return isFillColor;
}
public boolean isIsStrokeDash() {
return isStrokeDash;
}
public List<Double> getStrokeDash() {
return strokeDash;
}
public float[] getStrokeDashAwt() {
return strokeDashAwt(strokeDash);
}
public String getStrokeDashText() {
return strokeDash2Text(strokeDash);
}
public float getDashOffset() {
return dashOffset;
}
public StrokeLineCap getStrokeLineCap() {
return strokeLineCap;
}
public int getStrokeLineCapAwt() {
return strokeLineCapAwt(strokeLineCap);
}
public String getStrokeLineCapText() {
return strokeLineCap != null ? strokeLineCap.name() : null;
}
public float getStrokeLineLimit() {
return strokeLineLimit;
}
public StrokeLineJoin getStrokeLineJoin() {
return strokeLineJoin;
}
public int getStrokeLineJoinAwt() {
return strokeLineJoinAwt(strokeLineJoin);
}
public String getMore() {
return more;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/DoubleArc.java | released/MyBox/src/main/java/mara/mybox/data/DoubleArc.java | package mara.mybox.data;
import java.awt.geom.Arc2D;
import static mara.mybox.tools.DoubleTools.imageScale;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2023-7-31
* @License Apache License Version 2.0
*/
public class DoubleArc implements DoubleShape {
private double centerX, centerY, radiusX, radiusY, startAngle, extentAngle;
private int type;
public DoubleArc() {
}
public static DoubleArc rect(double x1, double y1, double x2, double y2,
double startAngle, double extentAngle, int type) {
DoubleArc a = new DoubleArc();
a.setCenterX((x1 + x2) / 2);
a.setCenterY((y1 + y2) / 2);
a.setRadiusX(Math.abs(x2 - x1) / 2);
a.setRadiusY(Math.abs(y2 - y1) / 2);
a.setStartAngle(startAngle);
a.setExtentAngle(extentAngle);
a.setType(type);
return a;
}
public static DoubleArc arc(double centerX, double centerY, double radiusX, double radiusY,
double startAngle, double extentAngle, int type) {
DoubleArc a = new DoubleArc();
a.setCenterX(centerX);
a.setCenterY(centerY);
a.setRadiusX(radiusX);
a.setRadiusY(radiusY);
a.setStartAngle(startAngle);
a.setExtentAngle(extentAngle);
a.setType(type);
return a;
}
@Override
public String name() {
return message("ArcCurve");
}
public double getX1() {
return centerX - radiusX;
}
public double getY1() {
return centerY - radiusY;
}
public double getX2() {
return centerX + radiusX;
}
public double getY2() {
return centerY + radiusY;
}
@Override
public Arc2D.Double getShape() {
return new Arc2D.Double(getX1(), getY1(), radiusX * 2, radiusY * 2, startAngle, extentAngle, type);
}
@Override
public DoubleArc copy() {
return DoubleArc.arc(centerX, centerY, radiusX, radiusY, startAngle, extentAngle, type);
}
@Override
public boolean isValid() {
return true;
}
@Override
public boolean isEmpty() {
return !isValid();
}
@Override
public boolean translateRel(double offsetX, double offsetY) {
centerX += offsetX;
centerY += offsetY;
return true;
}
@Override
public boolean scale(double scaleX, double scaleY) {
radiusX *= scaleX;
radiusY *= scaleY;
return true;
}
// Calculation is provided by deekseek. Fixed by mara
@Override
public String pathAbs() {
double startRad = Math.toRadians(startAngle);
double endRad = Math.toRadians(startAngle + extentAngle);
double startX = imageScale(centerX + radiusX * Math.cos(startRad));
double startY = imageScale(centerY - radiusY * Math.sin(startRad));
double endX = imageScale(centerX + radiusX * Math.cos(endRad));
double endY = imageScale(centerY - radiusY * Math.sin(endRad));
if (Math.abs(radiusX) < 1e-3 || Math.abs(radiusY) < 1e-3) {
return String.format("M %.2f,%.2f L %.2f,%.2f", startX, startY, endX, endY);
}
int largeArcFlag = computeLargeArcFlag(extentAngle);
int sweepFlag = (extentAngle >= 0) ? 0 : 1;
String arcCmd = String.format(
"A %.2f %.2f 0 %d %d %.2f %.2f",
radiusX, radiusY, largeArcFlag, sweepFlag, endX, endY
);
switch (type) {
case Arc2D.OPEN:
return String.format("M %.2f,%.2f %s", startX, startY, arcCmd);
case Arc2D.CHORD:
return String.format("M %.2f,%.2f %s Z", startX, startY, arcCmd);
case Arc2D.PIE:
return String.format("M %.2f,%.2f L %.2f,%.2f %s Z",
centerX, centerY, startX, startY, arcCmd);
default:
throw new IllegalArgumentException("Unsupported arc type");
}
}
@Override
public String pathRel() {
double startRad = Math.toRadians(startAngle);
double endRad = Math.toRadians(startAngle + extentAngle);
double startX = imageScale(centerX + radiusX * Math.cos(startRad));
double startY = imageScale(centerY - radiusY * Math.sin(startRad));
double endX = imageScale(centerX + radiusX * Math.cos(endRad));
double endY = imageScale(centerY - radiusY * Math.sin(endRad));
if (Math.abs(radiusX) < 1e-3 || Math.abs(radiusY) < 1e-3) {
return String.format("M %.2f,%.2f l %.2f,%.2f",
startX, startY, endX - startX, endY - startY);
}
int largeArcFlag = computeLargeArcFlag(extentAngle);
int sweepFlag = (extentAngle >= 0) ? 0 : 1;
String arcCmd = String.format(
"a %.2f %.2f 0 %d %d %.2f %.2f",
radiusX, radiusY, largeArcFlag, sweepFlag, endX - centerX, endY - centerY
);
switch (type) {
case Arc2D.OPEN:
return String.format("M %.2f,%.2f %s", startX, startY, arcCmd);
case Arc2D.CHORD:
return String.format("M %.2f,%.2f %s Z", startX, startY, arcCmd);
case Arc2D.PIE:
return String.format("M %.2f,%.2f l %.2f,%.2f %s Z",
centerX, centerY, startX - centerX, startY - centerY, arcCmd);
default:
throw new IllegalArgumentException("Unsupported arc type");
}
}
private static int computeLargeArcFlag(double extent) {
double absExtent = Math.abs(extent);
double extentMod = absExtent % 360;
if (extentMod == 0) {
return 1;
}
return (extentMod > 180) ? 1 : 0;
}
@Override
public String elementAbs() {
return "<path d=\"\n" + pathAbs() + "\n\"> ";
}
@Override
public String elementRel() {
return "<path d=\"\n" + pathRel() + "\n\"> ";
}
/*
get
*/
public double getCenterX() {
return centerX;
}
public double getCenterY() {
return centerY;
}
public double getRadiusX() {
return radiusX;
}
public double getRadiusY() {
return radiusY;
}
public double getStartAngle() {
return startAngle;
}
public double getExtentAngle() {
return extentAngle;
}
public int getType() {
return type;
}
/*
set
*/
public void setCenterX(double centerX) {
this.centerX = centerX;
}
public void setCenterY(double centerY) {
this.centerY = centerY;
}
public void setRadiusX(double radiusX) {
this.radiusX = radiusX;
}
public void setRadiusY(double radiusY) {
this.radiusY = radiusY;
}
public void setStartAngle(double startAngle) {
this.startAngle = startAngle;
}
public void setExtentAngle(double extentAngle) {
this.extentAngle = extentAngle;
}
public void setType(int type) {
this.type = type;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/DoubleLine.java | released/MyBox/src/main/java/mara/mybox/data/DoubleLine.java | package mara.mybox.data;
import java.awt.geom.Line2D;
import static mara.mybox.tools.DoubleTools.imageScale;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2023-7-6
* @License Apache License Version 2.0
*/
public class DoubleLine implements DoubleShape {
private double startX, startY, endX, endY;
public DoubleLine() {
}
public DoubleLine(double startX, double startY, double endX, double endY) {
this.startX = startX;
this.startY = startY;
this.endX = endX;
this.endY = endY;
}
@Override
public String name() {
return message("StraightLine");
}
@Override
public Line2D.Double getShape() {
return new Line2D.Double(startX, startY, endX, endY);
}
@Override
public DoubleLine copy() {
return new DoubleLine(startX, startY, endX, endY);
}
@Override
public boolean isValid() {
return true;
}
@Override
public boolean isEmpty() {
return !isValid();
}
@Override
public boolean translateRel(double offsetX, double offsetY) {
startX += offsetX;
startY += offsetY;
endX += offsetX;
endY += offsetY;
return true;
}
@Override
public boolean scale(double scaleX, double scaleY) {
endX *= scaleX;
endY *= scaleY;
return true;
}
@Override
public String pathAbs() {
return "M " + imageScale(startX) + "," + imageScale(startY) + " \n"
+ "L " + imageScale(endX) + "," + imageScale(endY);
}
@Override
public String pathRel() {
return "M " + imageScale(startX) + "," + imageScale(startY) + " \n"
+ "l " + imageScale(endX - startX) + "," + imageScale(endY - startY);
}
@Override
public String elementAbs() {
return "<line x1=\"" + imageScale(startX) + "\""
+ " y1=\"" + imageScale(startY) + "\""
+ " x2=\"" + imageScale(endX) + "\""
+ " y2=\"" + imageScale(endY) + "\"> ";
}
@Override
public String elementRel() {
return elementAbs();
}
public double getStartX() {
return startX;
}
public void setStartX(double startX) {
this.startX = startX;
}
public double getStartY() {
return startY;
}
public void setStartY(double startY) {
this.startY = startY;
}
public double getEndX() {
return endX;
}
public void setEndX(double endX) {
this.endX = endX;
}
public double getEndY() {
return endY;
}
public void setEndY(double endY) {
this.endY = endY;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/DoubleOutline.java | released/MyBox/src/main/java/mara/mybox/data/DoubleOutline.java | package mara.mybox.data;
import java.awt.image.BufferedImage;
import mara.mybox.image.data.ImageScope;
/**
* @Author Mara
* @CreateDate 2018-11-11 12:29:29
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class DoubleOutline extends DoubleRectangle {
private BufferedImage image;
private int insideColor;
public DoubleOutline() {
}
public DoubleOutline(BufferedImage image, int color) {
this.image = image;
x = 0;
y = 0;
width = image.getWidth();
height = image.getHeight();
this.insideColor = color;
}
public DoubleOutline(BufferedImage image, DoubleRectangle rect, int color) {
this.image = image;
this.insideColor = color;
x = rect.getX();
y = rect.getY();
width = rect.getWidth();
height = rect.getHeight();
}
public DoubleOutline(ImageScope scope) {
image = scope.getOutline();
insideColor = scope.isShapeExcluded() ? -1 : 0;
DoubleRectangle rect = scope.getRectangle();
x = rect.getX();
y = rect.getY();
width = rect.getWidth();
height = rect.getHeight();
}
@Override
public boolean isValid() {
return image != null && super.isValid();
}
@Override
public DoubleOutline copy() {
return new DoubleOutline(image, this, insideColor);
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/FunctionsList.java | released/MyBox/src/main/java/mara/mybox/data/FunctionsList.java | package mara.mybox.data;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import mara.mybox.controller.BaseController;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.menu.DevelopmentMenu;
import mara.mybox.fxml.menu.MenuTools;
import mara.mybox.fxml.style.StyleTools;
import mara.mybox.image.file.ImageFileWriters;
import mara.mybox.value.AppVariables;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2023-7-4
* @License Apache License Version 2.0
*/
public class FunctionsList {
public static final int MaxLevel = 4;
protected BaseController controller;
protected List<MenuItem> menus;
protected boolean withLink;
protected int index;
protected StringTable table;
protected String goImageFile, lang;
protected Map<String, MenuItem> map;
public FunctionsList(BaseController controller, boolean withLink, String lang) {
this.controller = controller;
this.withLink = withLink;
this.lang = lang;
}
public StringTable make() {
try {
if (withLink) {
goImageFile = AppVariables.MyboxDataPath + "/icons/iconGo.png";
BufferedImage srcImage = SwingFXUtils.fromFXImage(StyleTools.getIconImage("iconGo.png"), null);
ImageFileWriters.writeImageFile(null, srcImage, "png", goImageFile);
goImageFile = new File(goImageFile).toURI().toString();
}
index = 0;
List<String> names = new ArrayList<>();
names.add(message(lang, "Index"));
names.add(message(lang, "HierarchyNumber"));
for (int i = 1; i <= MaxLevel; i++) {
names.add(message(lang, "Level") + " " + i);
}
if (withLink) {
names.add(message(lang, "Go"));
}
table = new StringTable(names, message(lang, "FunctionsList"));
map = new HashMap<>();
menus = MenuTools.toolsMenu(controller);
Menu devMenu = new Menu(message("Development"));
devMenu.getItems().addAll(DevelopmentMenu.menusList(controller));
menus.add(devMenu);
int number = 0;
for (MenuItem menu : menus) {
menu(menu, 0, ++number + "");
}
return table;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public void menu(MenuItem menu, int level, String number) {
try {
makeRow(menu, level, number);
if (menu instanceof Menu) {
int childIndex = 0;
for (MenuItem menuItem : ((Menu) menu).getItems()) {
String childNumber = number + "." + ++childIndex;
menu(menuItem, level + 1, childNumber);
}
}
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public void makeRow(MenuItem menu, int level, String number) {
try {
String name = menu.getText();
if (name == null || name.isBlank()) {
return;
}
List<String> row = new ArrayList<>();
row.add(++index + "");
row.add(number);
for (int i = 0; i < MaxLevel; i++) {
row.add("");
}
if (withLink) {
String link;
if (menu.getOnAction() != null) {
link = "<a><img src=\"" + goImageFile + "\" "
+ "onclick=\"alert('" + name + "')\" "
+ "alt=\"" + message(lang, "Go") + "\"></a>";
map.put(name, menu);
} else {
link = "";
}
row.add(link);
}
row.set(level + 2, name);
table.add(row);
} catch (Exception e) {
MyBoxLog.error(e);
}
}
/*
get
*/
public static int getMaxLevel() {
return MaxLevel;
}
public StringTable getTable() {
return table;
}
public String getGoImageFile() {
return goImageFile;
}
public Map<String, MenuItem> getMap() {
return map;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/FindReplaceMatch.java | released/MyBox/src/main/java/mara/mybox/data/FindReplaceMatch.java | package mara.mybox.data;
import mara.mybox.tools.StringTools;
/**
* @Author Mara
* @CreateDate 2023-5-7
* @License Apache License Version 2.0
*/
public class FindReplaceMatch {
public final static int MatchedPrefixLength = 100;
protected long line, start, end; // 0-based, exclude end
protected String matchedPrefix;
public FindReplaceMatch() {
line = start = end = -1;
matchedPrefix = null;
}
/*
static
*/
public static FindReplaceMatch create() {
return new FindReplaceMatch();
}
/*
set
*/
public FindReplaceMatch setLine(long line) {
this.line = line;
return this;
}
public FindReplaceMatch setStart(long start) {
this.start = start;
return this;
}
public FindReplaceMatch setEnd(long end) {
this.end = end;
return this;
}
public FindReplaceMatch setMatchedPrefix(String matchedPrefix) {
this.matchedPrefix = StringTools.abbreviate(matchedPrefix, MatchedPrefixLength);
return this;
}
/*
get
*/
public long getLine() {
return line;
}
public long getStart() {
return start;
}
public long getEnd() {
return end;
}
public String getMatchedPrefix() {
return matchedPrefix;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/Direction.java | released/MyBox/src/main/java/mara/mybox/data/Direction.java | package mara.mybox.data;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2020-7-30
* @License Apache License Version 2.0
*/
public class Direction {
protected Name name;
protected int angle; // clockwise
public enum Name {
East, West, North, South, EastNorth, WestNorth, EastSouth, WestSouth, Number
}
public Direction(Name value) {
this.name = value == null ? defaultName() : value;
this.angle = angle(name);
}
public Direction(String name) {
this.name = name(name);
this.angle = angle(this.name);
}
public Direction(int angle) {
this.name = name(angle);
this.angle = angle(angle);
}
public String name() {
if (name == null) {
name = defaultName();
}
return name.name();
}
/*
Static methods
*/
public static Direction defaultDirection() {
return new Direction(defaultName());
}
public static Name defaultName() {
return Name.East;
}
public static Name name(String name) {
if (name == null || name.isBlank()) {
return defaultName();
}
for (Name item : Name.values()) {
if (name.equals(item.name()) || name.equals(Languages.message(item.name()))) {
return item;
}
}
return defaultName();
}
public static int angle(String name) {
return angle(name(name));
}
public static int angle(Name name) {
if (name == null) {
name = defaultName();
}
int angle;
switch (name) {
case West:
angle = 270;
break;
case North:
angle = 0;
break;
case South:
angle = 180;
break;
case EastNorth:
angle = 135;
break;
case WestNorth:
angle = 315;
break;
case EastSouth:
angle = 135;
break;
case WestSouth:
angle = 225;
break;
case East:
default:
angle = 90;
}
return angle;
}
public static int angle(int value) {
int angle = value % 360;
if (angle < 0) {
angle += 360;
}
return angle;
}
public static Name name(int value) {
int angle = angle(value);
Name name;
switch (angle) {
case 90:
name = Name.East;
break;
case 270:
name = Name.West;
break;
case 0:
name = Name.North;
break;
case 180:
name = Name.South;
break;
case 315:
name = Name.EastNorth;
break;
case 45:
name = Name.WestNorth;
break;
case 135:
name = Name.EastSouth;
break;
case 225:
name = Name.WestSouth;
break;
default:
name = Name.Number;
break;
}
return name;
}
/*
get/set
*/
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
public int getAngle() {
return angle;
}
public void setAngle(int angle) {
this.angle = angle;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/MediaList.java | released/MyBox/src/main/java/mara/mybox/data/MediaList.java | /*
* Apache License Version 2.0
*/
package mara.mybox.data;
import java.util.List;
/**
*
* @author mara
*/
public class MediaList {
protected String name;
protected List<MediaInformation> medias;
public MediaList() {
}
public static MediaList create() {
return new MediaList();
}
public MediaList(String name) {
this.name = name;
}
/*
get/set
*/
public String getName() {
return name;
}
public MediaList setName(String name) {
this.name = name;
return this;
}
public List<MediaInformation> getMedias() {
return medias;
}
public MediaList setMedias(List<MediaInformation> medias) {
this.medias = medias;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/HtmlElement.java | released/MyBox/src/main/java/mara/mybox/data/HtmlElement.java | package mara.mybox.data;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.UrlTools;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
/**
* @Author Mara
* @CreateDate 2022-9-7
* @License Apache License Version 2.0
*/
public class HtmlElement {
protected Element element;
protected Charset charset;
protected String tag, href, name, address, decodedHref, decodedAddress;
public HtmlElement(Element element, Charset charset) {
this.element = element;
this.charset = charset;
parse();
}
public final void parse() {
try {
href = null;
decodedHref = null;
tag = null;
name = null;
address = null;
decodedAddress = null;
if (element == null) {
return;
}
tag = element.getTagName();
if (tag == null) {
return;
}
if (tag.equalsIgnoreCase("a")) {
href = element.getAttribute("href");
name = element.getTextContent();
if (href == null) {
NamedNodeMap m = element.getAttributes();
if (m != null) {
for (int k = 0; k < m.getLength(); k++) {
if ("href".equalsIgnoreCase(m.item(k).getNodeName())) {
href = m.item(k).getNodeValue();
} else if ("title".equalsIgnoreCase(m.item(k).getNodeName())) {
name = m.item(k).getNodeValue();
}
}
}
}
} else if (tag.equalsIgnoreCase("img")) {
href = element.getAttribute("src");
name = element.getAttribute("alt");
if (href == null) {
NamedNodeMap m = element.getAttributes();
if (m != null) {
for (int k = 0; k < m.getLength(); k++) {
if ("src".equalsIgnoreCase(m.item(k).getNodeName())) {
href = m.item(k).getNodeValue();
} else if ("alt".equalsIgnoreCase(m.item(k).getNodeName())) {
name = m.item(k).getNodeValue();
}
}
}
}
}
if (href == null) {
return;
}
try {
address = UrlTools.fullAddress(element.getBaseURI(), href);
} catch (Exception e) {
address = href;
}
if (charset != null) {
decodedHref = URLDecoder.decode(href, charset);
decodedAddress = URLDecoder.decode(address, charset);
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public boolean isLink() {
return decodedHref != null && "a".equalsIgnoreCase(tag);
}
public boolean isImage() {
return decodedHref != null && "img".equalsIgnoreCase(tag);
}
/*
get/set
*/
public Element getElement() {
return element;
}
public void setElement(Element element) {
this.element = element;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public Charset getCharset() {
return charset;
}
public void setCharset(Charset charset) {
this.charset = charset;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDecodedAddress() {
return decodedAddress;
}
public void setDecodedAddress(String decodedAddress) {
this.decodedAddress = decodedAddress;
}
public String getDecodedHref() {
return decodedHref;
}
public void setDecodedHref(String decodedHref) {
this.decodedHref = decodedHref;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/FileEditInformation.java | released/MyBox/src/main/java/mara/mybox/data/FileEditInformation.java | package mara.mybox.data;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.tools.ByteTools;
import mara.mybox.tools.StringTools;
import static mara.mybox.tools.TextTools.bomBytes;
import static mara.mybox.tools.TextTools.bomSize;
import static mara.mybox.tools.TextTools.checkCharsetByBom;
import mara.mybox.value.AppValues;
import static mara.mybox.value.Languages.message;
import thridparty.EncodingDetect;
/**
* @Author Mara
* @CreateDate 2018-12-10 13:06:33
* @License Apache License Version 2.0
*/
public abstract class FileEditInformation extends FileInformation implements Cloneable {
protected Edit_Type editType;
protected boolean withBom, totalNumberRead, charsetDetermined;
protected Charset charset;
protected Line_Break lineBreak;
protected String lineBreakValue;
protected int objectUnit, lineBreakWidth;
protected String[] filterStrings;
protected FindReplaceFile findReplace;
protected StringFilterType filterType;
public Pagination pagination;
public enum Edit_Type {
Text, Bytes, Markdown
}
public enum StringFilterType {
IncludeAll, IncludeOne, NotIncludeAll, NotIncludeAny,
MatchRegularExpression, NotMatchRegularExpression,
IncludeRegularExpression, NotIncludeRegularExpression
}
public enum Line_Break {
LF, // Liunx/Unix
CR, // IOS
CRLF, // Windows
Width,
Value,
Auto
}
public FileEditInformation() {
editType = Edit_Type.Text;
}
public FileEditInformation(File file) {
super(file);
}
@Override
public Object clone() throws CloneNotSupportedException {
try {
FileEditInformation newInfo = (FileEditInformation) super.clone();
newInfo.setEditType(editType);
newInfo.setCharset(charset);
newInfo.setLineBreak(lineBreak);
newInfo.setFindReplace(findReplace);
newInfo.setFilterType(filterType);
return newInfo;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
protected final void initValues() {
filterType = StringFilterType.IncludeOne;
withBom = totalNumberRead = charsetDetermined = false;
charset = defaultCharset();
pagination = new Pagination();
pagination.init(editType == Edit_Type.Bytes
? Pagination.ObjectType.Bytes
: Pagination.ObjectType.Text);
findReplace = null;
switch (System.lineSeparator()) {
case "\r\n":
lineBreak = Line_Break.CRLF;
lineBreakValue = "\r\n";
break;
case "\r":
lineBreak = Line_Break.CR;
lineBreakValue = "\r";
break;
default:
lineBreak = Line_Break.LF;
lineBreakValue = "\n";
break;
}
lineBreakWidth = 30;
objectUnit = editType == Edit_Type.Bytes ? 3 : 1;
}
public static Charset defaultCharset() {
// return Charset.defaultCharset();
return Charset.forName("UTF-8");
}
public static FileEditInformation create(Edit_Type type, File file) {
switch (type) {
case Text:
return new TextEditInformation(file);
case Bytes:
return new BytesEditInformation(file);
default:
return new TextEditInformation(file);
}
}
public boolean checkCharset() {
try {
if (file == null) {
return false;
}
String setName;
withBom = false;
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) {
byte[] header = new byte[4];
int bufLen;
if ((bufLen = inputStream.read(header, 0, 4)) > 0) {
header = ByteTools.subBytes(header, 0, bufLen);
setName = checkCharsetByBom(header);
if (setName != null) {
charset = Charset.forName(setName);
withBom = true;
return true;
}
}
}
setName = EncodingDetect.detect(file);
charset = Charset.forName(setName);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public boolean convertCharset(FxTask currentTask, FileEditInformation targetInfo) {
try {
if (file == null || charset == null
|| targetInfo == null || targetInfo.getFile() == null || targetInfo.getCharset() == null) {
return false;
}
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
InputStreamReader reader = new InputStreamReader(inputStream, charset);
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetInfo.getFile()));
OutputStreamWriter writer = new OutputStreamWriter(outputStream, targetInfo.getCharset())) {
if (withBom) {
inputStream.skip(bomSize(charset.name()));
}
if (targetInfo.isWithBom()) {
byte[] bytes = bomBytes(targetInfo.getCharset().name());
outputStream.write(bytes);
}
char[] buf = new char[AppValues.IOBufferLength];
int bufLen;
while ((bufLen = reader.read(buf)) > 0) {
writer.write(new String(buf, 0, bufLen));
}
}
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public abstract boolean readTotalNumbers(FxTask currentTask);
public abstract String readPage(FxTask currentTask, long pageNumber);
public abstract boolean writeObject(FxTask currentTask, String text);
public abstract boolean writePage(FxTask currentTask, FileEditInformation sourceInfo, String text);
public abstract String readLines(FxTask currentTask, long from, long number);
public abstract String readObjects(FxTask currentTask, long from, long number);
public abstract File filter(FxTask currentTask, boolean recordLineNumbers);
public String readLine(FxTask currentTask, long line) {
return readLines(currentTask, line, 1);
}
public String readObject(FxTask currentTask, long index) {
return readObjects(currentTask, index, 1);
}
public boolean isMatchFilters(String string) {
if (string == null || string.isEmpty()) {
return false;
}
switch (filterType) {
case IncludeOne:
return includeOne(string);
case IncludeAll:
return includeAll(string);
case NotIncludeAny:
return notIncludeAny(string);
case NotIncludeAll:
return notIncludeAll(string);
case MatchRegularExpression:
return matchRegularExpression(string);
case NotMatchRegularExpression:
return notMatchRegularExpression(string);
case IncludeRegularExpression:
return includeRegularExpression(string);
case NotIncludeRegularExpression:
return notIncludeRegularExpression(string);
default:
return false;
}
}
public boolean includeOne(String string) {
boolean found;
for (String filter : filterStrings) {
found = string.contains(filter);
if (found) {
return true;
}
}
return false;
}
public boolean includeAll(String string) {
boolean found;
for (String filter : filterStrings) {
found = string.contains(filter);
if (!found) {
return false;
}
}
return true;
}
public boolean notIncludeAny(String string) {
boolean found;
for (String filter : filterStrings) {
found = string.contains(filter);
if (found) {
return false;
}
}
return true;
}
public boolean notIncludeAll(String string) {
boolean found;
for (String filter : filterStrings) {
found = string.contains(filter);
if (!found) {
return true;
}
}
return false;
}
public boolean includeRegularExpression(String string) {
return StringTools.include(string, filterStrings[0], false);
}
public boolean notIncludeRegularExpression(String string) {
return !StringTools.include(string, filterStrings[0], false);
}
public boolean matchRegularExpression(String string) {
return StringTools.match(string, filterStrings[0], false);
}
public boolean notMatchRegularExpression(String string) {
return !StringTools.match(string, filterStrings[0], false);
}
public String filterTypeName() {
return message(filterType.name());
}
public String lineBreakName() {
if (lineBreak == null) {
return "";
}
switch (lineBreak) {
case Width:
return message("BytesNumber") + lineBreakWidth;
case Value:
return message("BytesHex") + lineBreakWidth;
case LF:
return message("LFHex");
case CR:
return message("CRHex");
case CRLF:
return message("CRLFHex");
default:
return "";
}
}
/*
pagination
*/
public long getRowsNumber() {
return pagination != null ? pagination.getRowsNumber() : 0;
}
public void setRowsNumber(long v) {
if (pagination != null) {
pagination.setRowsNumber(v);
}
}
public long getObjectsNumber() {
return pagination != null ? pagination.getObjectsNumber() : 0;
}
public void setObjectsNumber(long v) {
if (pagination != null) {
pagination.setObjectsNumber(v);
}
}
public long getPagesNumber() {
return pagination != null ? pagination.getPagesNumber() : 0;
}
public void setPagesNumber(long v) {
if (pagination != null) {
pagination.setPagesNumber(v);
}
}
public int getPageSize() {
return pagination != null ? pagination.getPageSize() : 0;
}
public void setPageSize(int v) {
if (pagination != null) {
pagination.setPageSize(v);
}
}
public long getCurrentPage() {
return pagination != null ? pagination.getCurrentPage() : 0;
}
public void setCurrentPage(long v) {
if (pagination != null) {
pagination.setCurrentPage(v);
}
}
public long getStartRowOfCurrentPage() {
return pagination != null ? pagination.getStartRowOfCurrentPage() : 0;
}
public void setStartRowOfCurrentPage(long v) {
if (pagination != null) {
pagination.setStartRowOfCurrentPage(v);
}
}
public long getEndRowOfCurrentPage() {
return pagination != null ? pagination.getEndRowOfCurrentPage() : 0;
}
public void setEndRowOfCurrentPage(long v) {
if (pagination != null) {
pagination.setEndRowOfCurrentPage(v);
}
}
public long getStartObjectOfCurrentPage() {
return pagination != null ? pagination.getStartObjectOfCurrentPage() : 0;
}
public void setStartObjectOfCurrentPage(long v) {
if (pagination != null) {
pagination.setStartObjectOfCurrentPage(v);
}
}
public long getEndObjectOfCurrentPage() {
return pagination != null ? pagination.getEndObjectOfCurrentPage() : 0;
}
public void setEndObjectOfCurrentPage(long v) {
if (pagination != null) {
pagination.setEndObjectOfCurrentPage(v);
}
}
/*
get/set
*/
public boolean isWithBom() {
return withBom;
}
public void setWithBom(boolean withBom) {
this.withBom = withBom;
}
public Charset getCharset() {
return charset;
}
public void setCharset(Charset charset) {
this.charset = charset;
}
public Line_Break getLineBreak() {
return lineBreak;
}
public void setLineBreak(Line_Break lineBreak) {
this.lineBreak = lineBreak;
}
public Edit_Type getEditType() {
return editType;
}
public void setEditType(Edit_Type editType) {
this.editType = editType;
}
public String[] getFilterStrings() {
return filterStrings;
}
public void setFilterStrings(String[] filterStrings) {
this.filterStrings = filterStrings;
}
public StringFilterType getFilterType() {
return filterType;
}
public void setFilterType(StringFilterType filterType) {
this.filterType = filterType;
}
public int getLineBreakWidth() {
return lineBreakWidth;
}
public void setLineBreakWidth(int lineBreakWidth) {
this.lineBreakWidth = lineBreakWidth;
}
public String getLineBreakValue() {
return lineBreakValue;
}
public void setLineBreakValue(String lineBreakValue) {
this.lineBreakValue = lineBreakValue;
}
public boolean isTotalNumberRead() {
return totalNumberRead;
}
public void setTotalNumberRead(boolean totalNumberRead) {
this.totalNumberRead = totalNumberRead;
}
public Pagination getPagination() {
return pagination;
}
public void setPagination(Pagination pagination) {
this.pagination = pagination;
}
public FindReplaceFile getFindReplace() {
return findReplace;
}
public void setFindReplace(FindReplaceFile findReplace) {
this.findReplace = findReplace;
}
public int getObjectUnit() {
return objectUnit;
}
public void setObjectUnit(int objectUnit) {
this.objectUnit = objectUnit;
}
public long getSizeWithSubdir() {
return sizeWithSubdir;
}
public void setSizeWithSubdir(long sizeWithSubdir) {
this.sizeWithSubdir = sizeWithSubdir;
}
public long getSizeWithoutSubdir() {
return sizeWithoutSubdir;
}
public void setSizeWithoutSubdir(long sizeWithoutSubdir) {
this.sizeWithoutSubdir = sizeWithoutSubdir;
}
public long getFilesWithSubdir() {
return filesWithSubdir;
}
public void setFilesWithSubdir(long filesWithSubdir) {
this.filesWithSubdir = filesWithSubdir;
}
public long getFilesWithoutSubdir() {
return filesWithoutSubdir;
}
public void setFilesWithoutSubdir(long filesWithoutSubdir) {
this.filesWithoutSubdir = filesWithoutSubdir;
}
public boolean isCharsetDetermined() {
return charsetDetermined;
}
public void setCharsetDetermined(boolean charsetDetermined) {
this.charsetDetermined = charsetDetermined;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/TTC.java | released/MyBox/src/main/java/mara/mybox/data/TTC.java | package mara.mybox.data;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import mara.mybox.dev.MyBoxLog;
import static mara.mybox.tools.ByteTools.bytesToHex;
import static mara.mybox.tools.ByteTools.bytesToUInt;
import static mara.mybox.tools.ByteTools.bytesToUshort;
import static mara.mybox.tools.ByteTools.subBytes;
import static mara.mybox.tools.ByteTools.uIntToBytes;
import mara.mybox.tools.FileNameTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.value.Languages;
/**
* Reference: https://github.com/fermi1981/TTC_TTF
*
* @Author Mara
* @CreateDate 2020-12-03
* @License Apache License Version 2.0
*/
public class TTC {
protected File ttcFile;
protected String tag, sig;
protected long version, ttfCount, sigLength, sigOffset;
protected long[] offsets;
protected List<TTFInfo> ttfInfos;
protected List<List<DataInfo>> dataInfos;
public class TTFInfo {
String tag;
int numTables, searchRange, entrySelector, rangeShift;
}
public class DataInfo {
String tag;
long checkSum, offset, length, writeOffset, writeLength;
}
public TTC(File file) {
ttcFile = file;
}
public void parseFile() {
ttfCount = 0;
ttfInfos = null;
dataInfos = null;
if (ttcFile == null || !ttcFile.exists() || !ttcFile.isFile()) {
return;
}
try ( RandomAccessFile inputStream = new RandomAccessFile(ttcFile, "r")) {
ttfInfos = new ArrayList<>();
dataInfos = new ArrayList<>();
byte[] buf = new byte[4];
int readLen = inputStream.read(buf);
if (readLen != 4) {
return;
}
tag = new String(subBytes(buf, 0, 4));
if (tag.equals("ttcf")) {
parseTTC(inputStream);
} else {
boolean isTTF = false;
if (buf[0] == 0 && buf[1] == 1 && buf[2] == 0 && buf[3] == 0) {
isTTF = true;
} else if (!tag.toLowerCase().equals("otto")) {
isTTF = true;
}
if (isTTF) {
ttfCount = 1;
parseTTF(inputStream, 1);
}
}
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public void parseTTC(RandomAccessFile inputStream) {
try {
byte[] buf = new byte[8];
int readLen = inputStream.read(buf);
if (readLen != 8) {
return;
}
version = bytesToUInt(subBytes(buf, 0, 4));
ttfCount = bytesToUInt(subBytes(buf, 4, 4));
offsets = new long[(int) ttfCount];
buf = new byte[4];
for (int i = 0; i < ttfCount; i++) {
readLen = inputStream.read(buf);
if (readLen != 4) {
return;
}
offsets[i] = bytesToUInt(buf);
}
buf = new byte[12];
readLen = inputStream.read(buf);
if (readLen != 12) {
return;
}
sig = new String(subBytes(buf, 0, 4));
if (sig.equals("DSIG")) {
sigLength = bytesToUInt(subBytes(buf, 4, 4));
sigOffset = bytesToUInt(subBytes(buf, 8, 4));
// MyBoxLog.console(sig + " " + sigOffset + " " + sigLength);
}
for (int i = 0; i < ttfCount; i++) {
parseTTF(inputStream, i);
}
} catch (Exception e) {
MyBoxLog.error(e);
}
}
// Looks working well without alignment.
public long ceil4(long length) {
long mod = length % 4;
if (mod > 0) {
return length + 4 - mod;
} else {
return length;
}
}
public TTFInfo parseTTF(RandomAccessFile inputStream, int index) {
try {
inputStream.seek(offsets[index]);
// MyBoxLog.console("seek:" + offsets[index]);
byte[] buf = new byte[12];
int readLen = inputStream.read(buf);
if (readLen != 12) {
return null;
}
TTFInfo ttfInfo = new TTFInfo();
ttfInfo.tag = bytesToHex(subBytes(buf, 0, 4));
ttfInfo.numTables = bytesToUshort(subBytes(buf, 4, 2));
ttfInfo.searchRange = bytesToUshort(subBytes(buf, 6, 2));
ttfInfo.entrySelector = bytesToUshort(subBytes(buf, 8, 2));
ttfInfo.rangeShift = bytesToUshort(subBytes(buf, 10, 2));
List<DataInfo> ttfData = new ArrayList<>();
long dataOffset = 12 + ttfInfo.numTables * 16;
for (int i = 0; i < ttfInfo.numTables; i++) {
buf = new byte[16];
readLen = inputStream.read(buf);
if (readLen != 16) {
MyBoxLog.error("Invalid");
return null;
}
DataInfo dataInfo = new DataInfo();
dataInfo.tag = new String(subBytes(buf, 0, 4));
dataInfo.checkSum = bytesToUInt(subBytes(buf, 4, 4));
dataInfo.offset = bytesToUInt(subBytes(buf, 8, 4));
dataInfo.length = bytesToUInt(subBytes(buf, 12, 4));
dataInfo.writeOffset = dataOffset;
dataInfo.writeLength = ceil4(dataInfo.length);
dataOffset += dataInfo.writeLength;
ttfData.add(dataInfo);
}
ttfInfos.add(ttfInfo);
dataInfos.add(ttfData);
return ttfInfo;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public String html() {
try {
if (ttcFile == null || ttfInfos == null || ttfInfos.isEmpty()) {
return null;
}
String html = "TTC: " + ttcFile.getAbsolutePath() + "<BR>"
+ Languages.message("Tag") + ":" + tag + " "
+ Languages.message("Count") + ":" + ttfCount + "<BR>";
List<String> names = Arrays.asList("index", Languages.message("Offset"), Languages.message("Tag"),
"numTables", "searchRange", "entrySelector", "rangeShift");
StringTable table = new StringTable(names);
for (int i = 0; i < ttfInfos.size(); i++) {
TTFInfo ttf = ttfInfos.get(i);
List<String> row = Arrays.asList(i + "", offsets[i] + "", ttf.tag,
ttf.numTables + "", ttf.searchRange + "", ttf.entrySelector + "", ttf.rangeShift + "");
table.add(row);
}
html += table.div() + "<BR><HR><BR>";
for (int i = 0; i < ttfInfos.size(); i++) {
html += "<P align=center>TTF " + (i + 1) + "</P><BR>";
List<DataInfo> ttfData = dataInfos.get(i);
names = Arrays.asList("index", Languages.message("Tag"), "checkSum",
"offset", "length", "target offset", "target length");
table = new StringTable(names);
for (int j = 0; j < ttfData.size(); j++) {
DataInfo info = ttfData.get(j);
List<String> row = Arrays.asList(j + "", info.tag, info.checkSum + "",
info.offset + "", info.length + "", info.writeOffset + "", info.writeLength + "");
table.add(row);
}
html += table.div() + "<BR><BR>";
}
return html;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public List<File> extract(File targetPath) {
if (ttcFile == null) {
return null;
}
if (ttfInfos == null || ttfInfos.isEmpty()) {
parseFile();
}
if (ttfInfos == null || ttfInfos.isEmpty()) {
return null;
}
String namePrefix = FileNameTools.prefix(ttcFile.getName());
try ( RandomAccessFile inputStream = new RandomAccessFile(ttcFile, "r")) {
List<File> files = new ArrayList<>();
for (int i = 0; i < ttfInfos.size(); i++) {
long offset = offsets[i];
inputStream.seek(offset);
List<DataInfo> ttfData = dataInfos.get(i);
File ttfFile;
if (targetPath != null) {
ttfFile = new File(targetPath.getAbsoluteFile() + File.separator + namePrefix + "_" + i + ".ttf");
} else {
ttfFile = FileTmpTools.getTempFile(".ttf");
}
try ( BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(ttfFile))) {
int headerLen = 12 + ttfData.size() * 16;
byte[] head = new byte[headerLen];
int readLen = inputStream.read(head);
if (readLen != headerLen) {
MyBoxLog.error(i + " offset:" + offset + " headerLen:" + headerLen + " readLen:" + readLen);
continue;
}
// MyBoxLog.console(bytesToHexFormat(head));
for (int j = 0; j < ttfData.size(); j++) {
DataInfo dataInfo = ttfData.get(j);
byte[] offsetBytes = uIntToBytes(dataInfo.writeOffset);
System.arraycopy(offsetBytes, 0, head, 12 + j * 16 + 8, 4);
byte[] lenBytes = uIntToBytes(dataInfo.writeLength);
System.arraycopy(lenBytes, 0, head, 12 + j * 16 + 12, 4);
// MyBoxLog.console(" dataOffset:" + dataInfo.wOffset + " offsetBytes:" + bytesToHexFormat(offsetBytes)
// + " fixedLength:" + dataInfo.wLength + " lenBytes:" + bytesToHexFormat(lenBytes));
}
// MyBoxLog.console(bytesToHexFormat(head));
outputStream.write(head);
for (int j = 0; j < ttfData.size(); j++) {
DataInfo dataInfo = ttfData.get(j);
inputStream.seek(dataInfo.offset);
byte[] readData = new byte[(int) dataInfo.length]; // Assume length value is smaller than Integer.MAX_VALUE
byte[] writeFata = new byte[(int) dataInfo.writeLength];
readLen = inputStream.read(readData);
if (readLen > 0) {
System.arraycopy(readData, 0, writeFata, 0, readLen);
}
outputStream.write(writeFata);
}
outputStream.flush();
} catch (Exception e) {
MyBoxLog.error(e);
continue;
}
files.add(ttfFile);
}
return files;
} catch (Exception e) {
MyBoxLog.error(e);
}
return null;
}
/*
get/set
*/
public File getTtcFile() {
return ttcFile;
}
public void setTtcFile(File ttcFile) {
this.ttcFile = ttcFile;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getSig() {
return sig;
}
public void setSig(String sig) {
this.sig = sig;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public long getTtfCount() {
return ttfCount;
}
public void setTtfCount(long ttfCount) {
this.ttfCount = ttfCount;
}
public long[] getOffsets() {
return offsets;
}
public void setOffsets(long[] offsets) {
this.offsets = offsets;
}
public long getSigLength() {
return sigLength;
}
public void setSigLength(long sigLength) {
this.sigLength = sigLength;
}
public long getSigOffset() {
return sigOffset;
}
public void setSigOffset(long sigOffset) {
this.sigOffset = sigOffset;
}
public List<TTFInfo> getTtfInfos() {
return ttfInfos;
}
public void setTtfInfos(List<TTFInfo> ttfInfos) {
this.ttfInfos = ttfInfos;
}
public List<List<DataInfo>> getDataInfos() {
return dataInfos;
}
public void setDataInfos(List<List<DataInfo>> dataInfos) {
this.dataInfos = dataInfos;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/DoubleCircle.java | released/MyBox/src/main/java/mara/mybox/data/DoubleCircle.java | package mara.mybox.data;
import java.awt.geom.Ellipse2D;
import static mara.mybox.tools.DoubleTools.imageScale;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2018-11-11 12:29:29
* @License Apache License Version 2.0
*/
public class DoubleCircle implements DoubleShape {
private double centerX, centerY, radius;
public DoubleCircle() {
}
public DoubleCircle(double x, double y, double r) {
centerX = x;
centerY = y;
radius = r;
}
@Override
public String name() {
return message("Circle");
}
@Override
public Ellipse2D.Double getShape() {
return new Ellipse2D.Double(centerX - radius, centerY - radius, 2 * radius, 2 * radius);
}
@Override
public DoubleCircle copy() {
return new DoubleCircle(centerX, centerY, radius);
}
@Override
public boolean isValid() {
return radius > 0;
}
@Override
public boolean isEmpty() {
return !isValid();
}
public boolean same(DoubleCircle circle) {
return centerX == circle.getCenterX() && centerY == circle.getCenterY()
&& radius == circle.getRadius();
}
@Override
public boolean translateRel(double offsetX, double offsetY) {
centerX += offsetX;
centerY += offsetY;
return true;
}
@Override
public boolean scale(double scaleX, double scaleY) {
radius *= Math.min(scaleX, scaleY);
return true;
}
@Override
public String pathAbs() {
double cx = imageScale(centerX);
double cy = imageScale(centerY);
double r = imageScale(radius);
return "M " + (cx - r) + "," + cy + " \n"
+ "A " + r + "," + r + " 0,0,1 " + (cx + r) + "," + cy + " \n"
+ "A " + r + "," + r + " 0,0,1 " + (cx - r) + "," + cy + " \n"
+ "Z";
}
@Override
public String pathRel() {
double cx = imageScale(centerX);
double cy = imageScale(centerY);
double r = imageScale(radius);
double r2 = imageScale(2 * radius);
return "M " + (cx - r) + "," + cy + " \n"
+ "a " + r + "," + r + " 0,0,1 " + r2 + "," + 0 + " \n"
+ "a " + r + "," + r + " 0,0,1 " + (-r2) + "," + 0 + " \n"
+ "z";
}
@Override
public String elementAbs() {
return "<circle cx=\"" + imageScale(centerX) + "\""
+ " cy=\"" + imageScale(centerY) + "\""
+ " r=\"" + imageScale(radius) + "\"> ";
}
@Override
public String elementRel() {
return elementAbs();
}
/*
set
*/
public void setRadius(double radius) {
this.radius = radius;
}
/*
get
*/
public double getCenterX() {
return centerX;
}
public double getCenterY() {
return centerY;
}
public double getRadius() {
return radius;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/XmlTreeNode.java | released/MyBox/src/main/java/mara/mybox/data/XmlTreeNode.java | package mara.mybox.data;
import mara.mybox.tools.XmlTools;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* @Author Mara
* @CreateDate 2023-5-27
* @License Apache License Version 2.0
*/
public class XmlTreeNode {
protected String title, value;
protected NodeType type;
protected Node node;
public static enum NodeType {
Element, Attribute, Text, CDATA, EntityRefrence, Entity, ProcessingInstruction,
Comment, Document, DocumentType, DocumentFragment, Notation, Unknown
}
public XmlTreeNode() {
node = null;
title = null;
value = null;
type = NodeType.Unknown;
}
public XmlTreeNode(Node node) {
this.node = node;
type = XmlTools.type(node);
}
public int childrenSize() {
if (node == null) {
return 0;
}
NodeList children = node.getChildNodes();
if (children == null) {
return 0;
}
return children.getLength();
}
public boolean canAddNode() {
NodeType t = XmlTools.type(node);
return t == NodeType.Document
|| t == NodeType.Element || t == NodeType.Attribute
|| t == NodeType.Entity || t == NodeType.EntityRefrence
|| t == NodeType.DocumentFragment;
}
public boolean isDocWithoutElement() {
if (node == null) {
return false;
}
NodeType t = XmlTools.type(node);
if (t != NodeType.Document) {
return false;
}
NodeList children = node.getChildNodes();
if (children == null) {
return true;
}
for (int i = 0; i < children.getLength(); i++) {
if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
return false;
}
}
return true;
}
public int index() {
return XmlTools.index(node);
}
public String hierarchyNumber() {
return XmlTools.hierarchyNumber(node);
}
public boolean canAddSvgShape() {
if (XmlTools.type(node) != NodeType.Element) {
return false;
}
String tag = node.getNodeName();
return "svg".equalsIgnoreCase(tag)
|| "g".equalsIgnoreCase(tag)
|| "defs".equalsIgnoreCase(tag);
}
public boolean isSvgShape() {
if (XmlTools.type(node) != NodeType.Element) {
return false;
}
String tag = node.getNodeName();
return "rect".equalsIgnoreCase(tag)
|| "circle".equalsIgnoreCase(tag)
|| "ellipse".equalsIgnoreCase(tag)
|| "line".equalsIgnoreCase(tag)
|| "polyline".equalsIgnoreCase(tag)
|| "polygon".equalsIgnoreCase(tag)
|| "path".equalsIgnoreCase(tag);
}
/*
custimized get
*/
public String getTitle() {
return XmlTools.name(node);
}
public String getValue() {
return XmlTools.value(node);
}
public NodeType getType() {
return type;
}
public String getTypename() {
return type == null ? null : type.name();
}
/*
set
*/
public XmlTreeNode setNode(Node node) {
this.node = node;
return this;
}
public XmlTreeNode setTitle(String title) {
this.title = title;
return this;
}
public XmlTreeNode setValue(String value) {
this.value = value;
return this;
}
public XmlTreeNode setType(NodeType type) {
this.type = type;
return this;
}
/*
get
*/
public Node getNode() {
return node;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/FileNode.java | released/MyBox/src/main/java/mara/mybox/data/FileNode.java | package mara.mybox.data;
import java.io.File;
import mara.mybox.tools.FileNameTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2023-03-18
* @License Apache License Version 2.0
*/
public class FileNode extends FileInformation {
public boolean isExisted;
public FileNode parentNode;
public String nodename, permission, separator;
public long accessTime;
public int uid, gid;
public FileNode() {
init();
parentNode = null;
separator = File.separator;
}
public FileNode(File file) {
setFileAttributes(file);
isExisted = file != null && file.exists();
nodename = super.getFullName();
}
public String parentName() {
return parentNode != null ? parentNode.nodeFullName() : "";
}
public String path(boolean endSeparator) {
String pathname;
if (parentNode == null) {
pathname = nodename;
} else if (isDirectory()) {
pathname = nodeFullName();
} else {
pathname = parentNode.nodeFullName();
}
return endSeparator ? pathname + separator : pathname;
}
public String nodeFullName() {
return (parentNode != null ? parentNode.nodeFullName() + separator : "") + nodename;
}
public boolean isExisted() {
return isExisted;
}
public boolean isDirectory() {
return fileType == FileInformation.FileType.Directory;
}
/*
customized get/set
*/
@Override
public String getFileName() {
if (file != null) {
return file.getName();
} else if (nodename != null) {
return FileNameTools.name(nodename, separator);
} else if (data != null) {
return FileNameTools.name(data, separator);
} else {
return null;
}
}
@Override
public String getSuffix() {
if (fileType != null && fileType != FileType.File) {
return message(fileType.name());
}
if (file != null) {
if (file.isDirectory()) {
return null;
} else {
return FileNameTools.ext(file.getName(), separator);
}
} else if (nodename != null) {
return FileNameTools.ext(nodename, separator);
} else if (data != null) {
return FileNameTools.ext(data, separator);
} else {
return null;
}
}
@Override
public void setData(String data) {
this.data = data;
if (nodename == null) {
nodename = data;
}
}
/*
get/set
*/
public FileNode getParentNode() {
return parentNode;
}
public FileNode setParentFile(FileNode parentFile) {
this.parentNode = parentFile;
return this;
}
public String getNodename() {
return nodename;
}
public FileNode setNodename(String nodename) {
this.nodename = nodename;
return this;
}
public String getSeparator() {
return separator;
}
public FileNode setSeparator(String separator) {
this.separator = separator;
return this;
}
public long getAccessTime() {
return accessTime;
}
public FileNode setAccessTime(long accessTime) {
this.accessTime = accessTime;
return this;
}
public String getPermission() {
return permission;
}
public FileNode setPermission(String permission) {
this.permission = permission;
return this;
}
public int getUid() {
return uid;
}
public FileNode setUid(int uid) {
this.uid = uid;
return this;
}
public int getGid() {
return gid;
}
public FileNode setGid(int gid) {
this.gid = gid;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/RGBColorSpace.java | released/MyBox/src/main/java/mara/mybox/color/RGBColorSpace.java | package mara.mybox.color;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mara.mybox.color.ChromaticAdaptation.ChromaticAdaptationAlgorithm;
import static mara.mybox.color.ChromaticAdaptation.matrix;
import mara.mybox.color.Illuminant.IlluminantType;
import mara.mybox.color.Illuminant.Observer;
import mara.mybox.data.StringTable;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.DoubleMatrixTools;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2019-5-21 21:33:50
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*
* Reference:
* http://brucelindbloom.com/index.html?WorkingSpaceInfo.html#Specifications
*/
public class RGBColorSpace extends CIEData {
public String colorSpaceName, colorName, illuminantName, adaptAlgorithm;
public RGBColorSpace(String colorSpace, String color,
String illuminant, double[] values) {
this.colorSpaceName = colorSpace;
this.illuminantName = illuminant;
this.colorName = color;
this.adaptAlgorithm = "";
setxyY(values);
}
public RGBColorSpace(String colorSpace, String color,
String illuminant, String adaptAlgorithm, double[] values) {
this.colorSpaceName = colorSpace;
this.illuminantName = illuminant;
this.adaptAlgorithm = adaptAlgorithm;
this.colorName = color;
setTristimulusValues(values[0], values[1], values[2]);
}
/*
Static methods
*/
public static List<RGBColorSpace> standard() {
List<RGBColorSpace> data = new ArrayList<>();
for (ColorSpaceType cs : ColorSpaceType.values()) {
double[][] p = primaries(cs);
String n = name(cs);
String t = illuminantType(cs) + "";
data.add(new RGBColorSpace(n, "Red", t, p[0]));
data.add(new RGBColorSpace(n, "Green", t, p[1]));
data.add(new RGBColorSpace(n, "Blue", t, p[2]));
}
return data;
}
public static List<RGBColorSpace> adapted() {
List<RGBColorSpace> data = new ArrayList<>();
for (ColorSpaceType cs : ColorSpaceType.values()) {
String name = name(cs);
double[][] primaries = primariesTristimulus(name);
IlluminantType ci = illuminantType(cs);
for (IlluminantType i : IlluminantType.values()) {
for (ChromaticAdaptationAlgorithm a : ChromaticAdaptationAlgorithm.values()) {
if (ci != i) {
data.add(new RGBColorSpace(name, "Red", i + " - " + Observer.CIE1931, a + "",
ChromaticAdaptation.adapt(primaries[0], ci, Observer.CIE1931, i, Observer.CIE1931, a)));
data.add(new RGBColorSpace(name, "Green", i + " - " + Observer.CIE1931, a + "",
ChromaticAdaptation.adapt(primaries[1], ci, Observer.CIE1931, i, Observer.CIE1931, a)));
data.add(new RGBColorSpace(name, "Blue", i + " - " + Observer.CIE1931, a + "",
ChromaticAdaptation.adapt(primaries[2], ci, Observer.CIE1931, i, Observer.CIE1931, a)));
}
data.add(new RGBColorSpace(name, "Red", i + " - " + Observer.CIE1964, a + "",
ChromaticAdaptation.adapt(primaries[0], ci, Observer.CIE1931, i, Observer.CIE1964, a)));
data.add(new RGBColorSpace(name, "Green", i + " - " + Observer.CIE1964, a + "",
ChromaticAdaptation.adapt(primaries[1], ci, Observer.CIE1931, i, Observer.CIE1964, a)));
data.add(new RGBColorSpace(name, "Blue", i + " - " + Observer.CIE1964, a + "",
ChromaticAdaptation.adapt(primaries[2], ci, Observer.CIE1931, i, Observer.CIE1964, a)));
}
}
}
return data;
}
public static List<RGBColorSpace> all() {
List<RGBColorSpace> data = new ArrayList<>();
data.addAll(standard());
data.addAll(adapted());
return data;
}
public static List<RGBColorSpace> all(int scale) {
List<RGBColorSpace> data = RGBColorSpace.all();
for (RGBColorSpace d : data) {
d.scaleValues(scale);
}
return data;
}
public static StringTable allTable() {
try {
List<String> names = new ArrayList<>();
names.addAll(Arrays.asList(Languages.message("ColorSpace"),
Languages.message("Illuminant"), Languages.message("AdaptationAlgorithm"), Languages.message("PrimaryColor"),
Languages.message("TristimulusX"), Languages.message("TristimulusY"), Languages.message("TristimulusZ"),
Languages.message("NormalizedX"), Languages.message("NormalizedY"), Languages.message("NormalizedZ"),
Languages.message("RelativeX"), Languages.message("RelativeY"), Languages.message("RelativeZ")
));
StringTable table = new StringTable(names, Languages.message("RGBPrimaries"));
List<RGBColorSpace> data = all(8);
for (RGBColorSpace d : data) {
List<String> row = new ArrayList<>();
row.addAll(Arrays.asList(
d.colorSpaceName, d.illuminantName, d.adaptAlgorithm, d.colorName,
d.X + "", d.Y + "", d.Z + "",
d.getNormalizedX() + "", d.getNormalizedY() + "", d.getNormalizedZ() + "",
d.getRelativeX() + "", d.getRelativeY() + "", d.getRelativeZ() + ""
));
table.add(row);
}
return table;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static List<String> names() {
List<String> names = new ArrayList<>();
for (ColorSpaceType cs : ColorSpaceType.values()) {
names.add(name(cs));
}
return names;
}
public static String name(ColorSpaceType colorSpaceType) {
try {
switch (colorSpaceType) {
case CIERGB:
return CIERGB;
case ECIRGB:
return ECIRGB;
case AdobeRGB:
return AdobeRGB;
case AppleRGB:
return AppleRGB;
case sRGB:
return sRGB;
case PALRGB:
return PALRGB;
case NTSCRGB:
return NTSCRGB;
case ColorMatchRGB:
return ColorMatchRGB;
case ProPhotoRGB:
return ProPhotoRGB;
case SMPTECRGB:
return SMPTECRGB;
}
} catch (Exception e) {
}
return null;
}
public static ColorSpaceType type(String name) {
try {
if (CIERGB.equals(name)) {
return ColorSpaceType.CIERGB;
} else if (ECIRGB.equals(name)) {
return ColorSpaceType.ECIRGB;
} else if (AdobeRGB.equals(name)) {
return ColorSpaceType.AdobeRGB;
} else if (AppleRGB.equals(name)) {
return ColorSpaceType.AppleRGB;
} else if (sRGB.equals(name)) {
return ColorSpaceType.sRGB;
} else if (PALRGB.equals(name)) {
return ColorSpaceType.PALRGB;
} else if (NTSCRGB.equals(name)) {
return ColorSpaceType.NTSCRGB;
} else if (ColorMatchRGB.equals(name)) {
return ColorSpaceType.ColorMatchRGB;
} else if (ProPhotoRGB.equals(name)) {
return ColorSpaceType.ProPhotoRGB;
} else if (SMPTECRGB.equals(name)) {
return ColorSpaceType.SMPTECRGB;
}
} catch (Exception e) {
}
return null;
}
// Based on CIE 1931 2 degree observer
public static double[][] primariesNormalized(ColorSpaceType cs) {
double[][] p = primaries(cs);
double[][] n = new double[3][3];
n[0][0] = p[0][0];
n[0][1] = p[0][1];
n[0][2] = 1 - p[0][0] - p[0][1];
n[1][0] = p[1][0];
n[1][1] = p[1][1];
n[1][2] = 1 - p[1][0] - p[1][1];
n[2][0] = p[2][0];
n[2][1] = p[2][1];
n[2][2] = 1 - p[2][0] - p[2][1];
return n;
}
public static double[][] primariesNormalized(String csName) {
return primariesNormalized(type(csName));
}
public static double[][] primariesRelative(ColorSpaceType cs) {
double[][] p = primaries(cs);
double[][] n = new double[3][3];
n[0][0] = p[0][0] / p[0][1];
n[0][1] = 1;
n[0][2] = (1 - p[0][0] - p[0][1]) / p[0][1];
n[1][0] = p[1][0] / p[1][1];
n[1][1] = 1;
n[1][2] = (1 - p[1][0] - p[1][1]) / p[1][1];
n[2][0] = p[2][0] / p[2][1];
n[2][1] = 1;
n[2][2] = (1 - p[2][0] - p[2][1]) / p[2][1];
return n;
}
public static double[][] primariesRelative(String csName) {
return primariesRelative(type(csName));
}
public static double[][] primariesTristimulus(ColorSpaceType cs) {
double[][] p = primaries(cs);
double[][] n = new double[3][3];
n[0][0] = p[0][0] * p[0][2] / p[0][1];
n[0][1] = p[0][2];
n[0][2] = (1 - p[0][0] - p[0][1]) * p[0][2] / p[0][1];
n[1][0] = p[1][0] * p[1][2] / p[1][1];
n[1][1] = p[1][2];
n[1][2] = (1 - p[1][0] - p[1][1]) * p[1][2] / p[1][1];
n[2][0] = p[2][0] * p[2][2] / p[2][1];
n[2][1] = p[2][2];
n[2][2] = (1 - p[2][0] - p[2][1]) * p[2][2] / p[2][1];
return n;
}
public static double[][] primariesTristimulus(String csName) {
return primariesTristimulus(type(csName));
}
public static double[][] primaries(String csName) {
return primaries(type(csName));
}
public static double[][] primaries(ColorSpaceType colorSpaceType) {
try {
switch (colorSpaceType) {
case CIERGB:
return CIEPrimariesE;
case ECIRGB:
return ECIPrimariesD50;
case AdobeRGB:
return AdobePrimariesD65;
case AppleRGB:
return ApplePrimariesD65;
case sRGB:
return sRGBPrimariesD65;
case PALRGB:
return PALPrimariesD65;
case NTSCRGB:
return NTSCPrimariesC;
case ColorMatchRGB:
return ColorMatchPrimariesD50;
case ProPhotoRGB:
return ProPhotoPrimariesD50;
case SMPTECRGB:
return SMPTECPrimariesD65;
}
} catch (Exception e) {
}
return null;
}
public static double[] whitePoint(String csName) {
return whitePoint(type(csName));
}
public static double[] whitePoint(ColorSpaceType colorSpaceType) {
double[] xy = whitePointXY(colorSpaceType);
return CIEDataTools.relative(xy[0], xy[1], 1 - xy[0] - xy[1]);
}
public static double[] whitePointXY(ColorSpaceType colorSpaceType) {
try {
switch (colorSpaceType) {
case CIERGB:
return Illuminant.Illuminant1931E;
case ECIRGB:
return Illuminant.Illuminant1931D50;
case AdobeRGB:
return Illuminant.Illuminant1931D65;
case AppleRGB:
return Illuminant.Illuminant1931D65;
case sRGB:
return Illuminant.Illuminant1931D65;
case PALRGB:
return Illuminant.Illuminant1931D65;
case NTSCRGB:
return Illuminant.Illuminant1931C;
case ColorMatchRGB:
return Illuminant.Illuminant1931D50;
case ProPhotoRGB:
return Illuminant.Illuminant1931D50;
case SMPTECRGB:
return Illuminant.Illuminant1931D65;
}
} catch (Exception e) {
}
return null;
}
public static double[][] whitePointMatrix(ColorSpaceType colorSpaceType) {
return DoubleMatrixTools.columnVector(whitePoint(colorSpaceType));
}
public static String illuminantName(String csName) {
return illuminantType(type(csName)) + " - " + Illuminant.Observer.CIE1931;
}
public static IlluminantType illuminantType(String csName) {
return illuminantType(type(csName));
}
public static IlluminantType illuminantType(ColorSpaceType colorSpaceType) {
try {
switch (colorSpaceType) {
case CIERGB:
return IlluminantType.E;
case ECIRGB:
return IlluminantType.D50;
case AdobeRGB:
return IlluminantType.D65;
case AppleRGB:
return IlluminantType.D65;
case sRGB:
return IlluminantType.D65;
case PALRGB:
return IlluminantType.D65;
case NTSCRGB:
return IlluminantType.C;
case ColorMatchRGB:
return IlluminantType.D50;
case ProPhotoRGB:
return IlluminantType.D50;
case SMPTECRGB:
return IlluminantType.D65;
}
} catch (Exception e) {
}
return null;
}
public static double[][] primariesAdapted(ColorSpaceType cs,
IlluminantType targetIlluminantType, Observer targetObserver,
ChromaticAdaptationAlgorithm algorithm) {
double[][] primaries = primariesTristimulus(cs);
IlluminantType ci = illuminantType(cs);
double[] red = ChromaticAdaptation.adapt(primaries[0], ci, Observer.CIE1931,
targetIlluminantType, targetObserver, algorithm);
double[] green = ChromaticAdaptation.adapt(primaries[1], ci, Observer.CIE1931,
targetIlluminantType, targetObserver, algorithm);
double[] blue = ChromaticAdaptation.adapt(primaries[2], ci, Observer.CIE1931,
targetIlluminantType, targetObserver, algorithm);
double[][] adpated = {red, green, blue};
return adpated;
}
public static Object primariesAdapted(ColorSpaceType cs,
double[][] targetWhitePoint, ChromaticAdaptationAlgorithm algorithm,
int scale, boolean isDemo) {
double[][] primaries = primariesTristimulus(cs);
double[][] sourceWhitePoint = whitePointMatrix(cs);
return primariesAdapted(primaries, sourceWhitePoint, targetWhitePoint,
algorithm, scale, isDemo);
}
public static Object primariesAdapted(double[][] primaries,
double[][] sourceWhitePoint, double[][] targetWhitePoint,
ChromaticAdaptationAlgorithm algorithm, int scale, boolean isDemo) {
try {
double[][] adaptMatrix;
String adaptString = null;
Map<String, Object> adapt = null;
if (DoubleMatrixTools.same(sourceWhitePoint, targetWhitePoint, scale)) {
if (isDemo) {
adapt = new HashMap<>();
adapt.put("procedure", Languages.message("NeedNotAdaptChromatic"));
adapt.put("matrix", DoubleMatrixTools.identityDouble(3));
adapt.put("adaptedPrimaries", primaries);
return adapt;
} else {
return primaries;
}
}
Object adaptObject = matrix(sourceWhitePoint, targetWhitePoint, algorithm, scale, isDemo);
if (isDemo) {
adapt = (Map<String, Object>) adaptObject;
adaptMatrix = (double[][]) adapt.get("adpatMatrix");
adaptString = (String) adapt.get("procedure");
} else {
adaptMatrix = (double[][]) adaptObject;
}
double[][] sourceRed = DoubleMatrixTools.columnVector(primaries[0]);
double[][] adaptedRed = DoubleMatrixTools.multiply(adaptMatrix, sourceRed);
double[][] sourceGreen = DoubleMatrixTools.columnVector(primaries[1]);
double[][] adaptedGreen = DoubleMatrixTools.multiply(adaptMatrix, sourceGreen);
double[][] sourceBlue = DoubleMatrixTools.columnVector(primaries[2]);
double[][] adaptedBlue = DoubleMatrixTools.multiply(adaptMatrix, sourceBlue);
double[][] adaptedPrimaries = {
DoubleMatrixTools.columnValues(adaptedRed, 0),
DoubleMatrixTools.columnValues(adaptedGreen, 0),
DoubleMatrixTools.columnValues(adaptedBlue, 0)
};
if (scale >= 0) {
adaptedPrimaries = DoubleMatrixTools.scale(adaptedPrimaries, scale);
} else {
scale = 8;
}
if (isDemo) {
String s = "";
s += "\naaaaaaaaaaaaa " + Languages.message("Step") + " - " + Languages.message("ChromaticAdaptationMatrix") + " aaaaaaaaaaaaa\n\n";
s += adaptString + "\n";
s += "\naaaaaaaaaaaaa " + Languages.message("Step") + " - " + Languages.message("ChromaticAdaptation") + " aaaaaaaaaaaaa\n";
s += "\nsourceRed = \n";
s += DoubleMatrixTools.print(sourceRed, 20, scale);
s += "\nadaptedRed = M * sourceRed = \n";
s += DoubleMatrixTools.print(adaptedRed, 20, scale);
s += "\nsourceGreen = \n";
s += DoubleMatrixTools.print(sourceGreen, 20, scale);
s += "\nadaptedGreen = M * sourceGreen = \n";
s += DoubleMatrixTools.print(adaptedGreen, 20, scale);
s += "\nsourceBlue = \n";
s += DoubleMatrixTools.print(sourceBlue, 20, scale);
s += "\nadaptedBlue = M * sourceBlue = \n";
s += DoubleMatrixTools.print(adaptedBlue, 20, scale);
s += "\nadaptedPrimaries = \n";
s += DoubleMatrixTools.print(adaptedPrimaries, 20, scale);
adapt.put("procedure", s);
adapt.put("adaptedPrimaries", adaptedPrimaries);
return adapt;
} else {
return adaptedPrimaries;
}
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
/*
Gamma
*/
public static GammaType gamma(String csName) {
return gammaType(type(csName));
}
public static GammaType gammaType(ColorSpaceType colorSpaceType) {
try {
switch (colorSpaceType) {
case CIERGB:
case AdobeRGB:
case PALRGB:
case NTSCRGB:
case SMPTECRGB:
return GammaType.Gamma22;
case ECIRGB:
return GammaType.GammaL;
case AppleRGB:
case ColorMatchRGB:
case ProPhotoRGB:
return GammaType.Gamma18;
case sRGB:
return GammaType.GammaSRGB;
}
} catch (Exception e) {
}
return null;
}
public static String gammaName(GammaType gammaType) {
try {
switch (gammaType) {
case GammaSRGB:
return "sRGB";
case Gamma22:
return "2.2";
case Gamma18:
return "1.8";
case GammaL:
return "L*";
}
} catch (Exception e) {
}
return null;
}
public static String gammaName(String colorSpaceName) {
try {
if (RGBColorSpace.sRGB.equals(colorSpaceName)) {
return "sRGB";
} else if (RGBColorSpace.ECIRGB.equals(colorSpaceName)) {
return "L*";
} else if (RGBColorSpace.CIERGB.equals(colorSpaceName)
|| RGBColorSpace.AdobeRGB.equals(colorSpaceName)
|| RGBColorSpace.PALRGB.equals(colorSpaceName)
|| RGBColorSpace.NTSCRGB.equals(colorSpaceName)
|| RGBColorSpace.SMPTECRGB.equals(colorSpaceName)) {
return "2.2";
} else if (RGBColorSpace.AppleRGB.equals(colorSpaceName)
|| RGBColorSpace.ColorMatchRGB.equals(colorSpaceName)
|| RGBColorSpace.ProPhotoRGB.equals(colorSpaceName)) {
return "1.8";
}
} catch (Exception e) {
}
return null;
}
public static double gamma(double Gramma, double v) {
if (v <= 0.0) {
return 0.0;
} else {
return Math.pow(v, 1 / Gramma);
}
}
public static double gamma22(double v) {
return gamma(2.19921875, v);
}
public static double gamma18(double v) {
return gamma(1.8, v);
}
public static double gammaSRGB(double v) {
if (v <= 0.0031308) {
return v * 12.92;
} else {
return 1.055 * Math.pow(v, 1d / 2.4) - 0.055;
}
}
/*
Linear
*/
public static double linearColor(double Gramma, double v) {
if (v <= 0.0) {
return 0.0;
} else {
return Math.pow(v, Gramma);
}
}
public static double linear22(double v) {
return linearColor(2.19921875, v);
}
public static double linear18(double v) {
return linearColor(1.8, v);
}
public static double linearSRGB(double v) {
if (v <= 0.04045) {
return v / 12.92;
} else {
return Math.pow((v + 0.055) / 1.055, 2.4);
}
}
/*
Data
*/
// http://www.eci.org/en/downloads
// {r,g,b}{x, y, Y}
public static enum ColorSpaceType {
CIERGB, ECIRGB, AdobeRGB, AppleRGB, sRGB, PALRGB, NTSCRGB, ColorMatchRGB,
ProPhotoRGB, SMPTECRGB
}
public static enum GammaType {
Linear, Gamma22, Gamma18, GammaSRGB, GammaL
}
public static String CIERGB = "CIE RGB";
public static String ECIRGB = "ECI RGB v2";
public static String AdobeRGB = "Adobe RGB (1998)";
public static String AppleRGB = "Apple RGB";
public static String sRGB = "sRGB";
public static String PALRGB = "PAL/SECAM RGB";
public static String NTSCRGB = "NTSC RGB";
public static String ColorMatchRGB = "ColorMatch RGB";
public static String ProPhotoRGB = "ProPhoto RGB";
public static String SMPTECRGB = "SMPTE-C RGB";
public static double[][] CIEPrimariesE = {
{0.7350, 0.2650, 0.176204},
{0.2740, 0.7170, 0.812985},
{0.1670, 0.0090, 0.010811}
};
public static double[][] ECIPrimariesD50 = {
{0.670000, 0.330000, 0.320250},
{0.210000, 0.710000, 0.602071},
{0.140000, 0.080000, 0.077679}
};
public static double[][] sRGBPrimariesD65 = {
{0.6400, 0.3300, 0.212656},
{0.3000, 0.6000, 0.715158},
{0.1500, 0.0600, 0.072186}
};
public static double[][] AdobePrimariesD65 = {
{0.6400, 0.3300, 0.297361},
{0.2100, 0.7100, 0.627355},
{0.1500, 0.0600, 0.075285}
};
public static double[][] ApplePrimariesD65 = {
{0.6250, 0.3400, 0.244634},
{0.2800, 0.5950, 0.672034},
{0.1550, 0.0700, 0.083332}
};
public static double[][] PALPrimariesD65 = {
{0.6400, 0.3300, 0.222021},
{0.2900, 0.6000, 0.706645},
{0.1500, 0.0600, 0.071334}
};
public static double[][] NTSCPrimariesC = {
{0.6700, 0.3300, 0.298839},
{0.2100, 0.7100, 0.586811},
{0.1400, 0.0800, 0.114350}
};
public static double[][] ProPhotoPrimariesD50 = {
{0.734700, 0.265300, 0.288040},
{0.159600, 0.840400, 0.711874},
{0.036600, 0.000100, 0.000086}
};
public static double[][] ColorMatchPrimariesD50 = {
{0.630000, 0.340000, 0.274884},
{0.295000, 0.605000, 0.658132},
{0.150000, 0.075000, 0.066985}
};
public static double[][] SMPTECPrimariesD65 = {
{0.6300, 0.3400, 0.212395},
{0.3100, 0.5950, 0.701049},
{0.1550, 0.0700, 0.086556}
};
//Extra calculated values
public static double[][] CIEPrimariesD50 = {
{0.737385, 0.264518, 0.174658},
{0.266802, 0.718404, 0.824754},
{0.174329, 0.000599, 0.000588}
};
public static double[][] sRGBPrimariesD50 = {
{0.648431, 0.330856, 0.222491},
{0.321152, 0.597871, 0.716888},
{0.155886, 0.066044, 0.060621}
};
public static double[][] AdobePrimariesD50 = {
{0.648431, 0.330856, 0.311114},
{0.230154, 0.701572, 0.625662},
{0.155886, 0.066044, 0.063224}
};
public static double[][] ApplePrimariesD50 = {
{0.634756, 0.340596, 0.255166},
{0.301775, 0.597511, 0.672578},
{0.162897, 0.079001, 0.072256}
};
public static double[][] NTSCPrimariesD50 = {
{0.671910, 0.329340, 0.310889},
{0.222591, 0.710647, 0.591737},
{0.142783, 0.096145, 0.097374}
};
public static double[][] PALPrimariesD50 = {
{0.648431, 0.330856, 0.232289},
{0.311424, 0.599693, 0.707805},
{0.155886, 0.066044, 0.059906}
};
public static double[][] SMPTECPrimariesD50 = {
{0.638852, 0.340194, 0.221685},
{0.331007, 0.592082, 0.703264},
{0.162897, 0.079001, 0.075052}
};
/*
get/set
*/
public String getColorSpaceName() {
return colorSpaceName;
}
public void setColorSpaceName(String colorSpaceName) {
this.colorSpaceName = colorSpaceName;
}
public String getColorName() {
return colorName;
}
public void setColorName(String colorName) {
this.colorName = colorName;
}
public String getIlluminantName() {
return illuminantName;
}
public void setIlluminantName(String illuminantName) {
this.illuminantName = illuminantName;
}
public String getAdaptAlgorithm() {
return adaptAlgorithm;
}
public void setAdaptAlgorithm(String adaptAlgorithm) {
this.adaptAlgorithm = adaptAlgorithm;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/ChromaticityDiagram.java | released/MyBox/src/main/java/mara/mybox/color/ChromaticityDiagram.java | package mara.mybox.color;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.List;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.value.AppVariables;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2019-5-17 9:57:29
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class ChromaticityDiagram {
private int width = 1300, height = 1300;
private int margins = 60, ruler = 10, each = 5, grid = each * ruler;
private BufferedImage image;
private Color gridColor = new Color(0.9f, 0.9f, 0.9f), rulerColor = Color.LIGHT_GRAY,
textColor, bgColor;
private Graphics2D g;
private int stepH = (height - margins * 2) / grid;
private int stepW = (width - margins * 2) / grid;
private int startH = margins + stepH, startW = margins + stepW;
private int endH = stepH * grid + margins;
private int endW = stepW * grid + margins;
private int fontSize = 20;
private Font dataFont, commentsFont;
private int dotSize = 6;
private boolean isLine, show2Degree, show10Degree, showDataSource;
private File dataSourceFile;
private String dataSourceTexts;
private String title;
private LinkedHashMap<DataType, Boolean> show;
private double calculateX = -1, calculateY = -1;
private Color calculateColor;
public static enum DataType {
Grid, CIE2Degree, CIE10Degree, CIEDataSource, Calculate, Wave, CIELines, ECILines, sRGBLines, AdobeLines, AppleLines,
PALLines, NTSCLines, ColorMatchLines, ProPhotoLines, SMPTECLines, WhitePoints
}
public ChromaticityDiagram() {
show = new LinkedHashMap();
}
public static ChromaticityDiagram create() {
return new ChromaticityDiagram();
}
/*
Diagram
*/
public BufferedImage drawData(LinkedHashMap<DataType, Boolean> show) {
this.show = show;
return drawData();
}
public BufferedImage drawData() {
try {
// MyBoxLog.console(width + " " + height);
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
g = image.createGraphics();
if (AppVariables.ImageHints != null) {
g.addRenderingHints(AppVariables.ImageHints);
}
if (bgColor != null) {
g.setColor(bgColor);
g.fillRect(0, 0, width, height);
}
if (fontSize <= 0) {
fontSize = 20;
}
dataFont = new Font(null, Font.PLAIN, fontSize);
commentsFont = new Font(null, Font.BOLD, fontSize + 8);
if (Color.BLACK.equals(bgColor)) {
textColor = Color.WHITE;
} else {
textColor = Color.BLACK;
}
// Title / Bottom
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setComposite(ac);
if (title == null) {
title = Languages.message("ChromaticityDiagram");
}
g.setFont(commentsFont);
g.setColor(textColor);
g.drawString(title, margins + 400, 50);
g.setFont(dataFont);
g.drawString(Languages.message("ChromaticityDiagramComments"), 20, endH + 55);
backGround();
outlines();
whitePoints();
primariesLines();
calculate();
g.dispose();
return image;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
private void backGround() {
try {
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
g.setComposite(ac);
BasicStroke stroke;
stroke = new BasicStroke(2);
g.setStroke(stroke);
g.setFont(dataFont);
if (show.get(DataType.Grid)) {
g.setColor(gridColor);
for (int i = 0; i < grid; ++i) {
int h = startH + i * stepH;
g.drawLine(margins, h, endW, h);
int w = startW + i * stepW;
g.drawLine(w, margins, w, endH);
}
g.setColor(rulerColor);
for (int i = 0; i < ruler; ++i) {
int h = margins + i * stepH * each;
g.drawLine(margins, h, endW, h);
int w = margins + i * stepW * each;
g.drawLine(w, margins, w, endH);
}
}
g.setColor(textColor);
g.drawLine(margins, margins, margins, endH);
g.drawLine(margins, endH, endW, endH);
for (int i = 0; i < ruler; ++i) {
int h = margins + (i + 1) * stepH * each;
g.drawString("0." + (9 - i), 10, h + 10);
int w = margins + i * stepW * each;
g.drawString("0." + i, w - 10, endH + 30);
}
g.drawString("1.0", endW - 15, endH + 30);
g.drawString("1.0", 10, margins);
} catch (Exception e) {
MyBoxLog.error(e);
}
}
private void outlines() {
try {
List<CIEData> data;
CIEData cieData = new CIEData();
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
if (show.get(DataType.CIE2Degree)) {
data = CIEDataTools.cie1931Observer2Degree1nmData(cs);
outline(data, Languages.message("CIE1931Observer2Degree"), 535, textColor);
}
if (show.get(DataType.CIE10Degree)) {
data = CIEDataTools.cie1964Observer10Degree1nmData(cs);
if (show.get(DataType.CIE2Degree)) {
outline(data, Languages.message("CIE1964Observer10Degree"), 525, Color.BLUE);
} else {
outline(data, Languages.message("CIE1964Observer10Degree"), 525, textColor);
}
}
if (show.get(DataType.CIEDataSource)) {
data = null;
if (dataSourceTexts != null && !dataSourceTexts.isEmpty()) {
data = CIEDataTools.read(dataSourceTexts);
} else if (dataSourceFile != null) {
data = CIEDataTools.read(dataSourceFile, cs);
}
if (data != null) {
if (show.get(DataType.CIE2Degree) || show.get(DataType.CIE10Degree)) {
outline(data, Languages.message("InputtedData"), 520, Color.RED);
} else {
outline(data, Languages.message("InputtedData"), 520, textColor);
}
}
}
} catch (Exception e) {
MyBoxLog.error(e);
}
}
private void outline(List<CIEData> data, String name, int markWave, Color waveColor) {
try {
if (data == null || data.isEmpty()) {
return;
}
Color pColor;
int dotSizeHalf = dotSize / 2;
BasicStroke strokeSized = new BasicStroke(dotSize);
BasicStroke stroke1 = new BasicStroke(1);
int dataW = width - margins * 2, dataH = height - margins * 2;
int x, y, wave, lastx = -1, lasty = -1;
double[] srgb;
for (CIEData d : data) {
wave = d.getWaveLength();
x = (int) Math.round(margins + dataW * d.getNormalizedX());
y = (int) Math.round(endH - dataH * d.getNormalizedY());
srgb = d.getChannels();
if (srgb == null) {
srgb = CIEDataTools.sRGB65(d);
}
pColor = new Color((float) srgb[0], (float) srgb[1], (float) srgb[2]);
g.setColor(pColor);
g.setStroke(stroke1);
if (isLine) {
if (lastx >= 0 && lasty >= 0) {
g.setStroke(strokeSized);
g.drawLine(lastx, lasty, x, y);
} else {
g.fillRect(x - dotSizeHalf, y - dotSizeHalf, dotSize, dotSize);
}
lastx = x;
lasty = y;
} else {
g.fillRect(x - dotSizeHalf, y - dotSizeHalf, dotSize, dotSize);
}
if (wave == markWave) {
g.setColor(waveColor);
g.drawLine(x, y, x + 300, y + markWave - 560);
g.drawString(name, x + 310, y + markWave - 560);
}
if (show.get(DataType.Wave)) {
if (wave == 360 || wave == 830 || wave == 460) {
g.setColor(waveColor);
g.drawString(wave + "nm", x + 10, y);
} else if (wave > 470 && wave < 620) {
if (wave % 5 == 0) {
g.setColor(waveColor);
g.drawString(wave + "nm", x + 10, y);
}
} else if (wave >= 620 && wave <= 640) {
if (wave % 10 == 0) {
g.setColor(waveColor);
g.drawString(wave + "nm", x + 10, y);
}
}
} else {
}
}
// Bottom line
CIEData d1 = data.get(0);
CIEData d2 = data.get(data.size() - 1);
double x1 = d1.getNormalizedX(), x2 = d2.getNormalizedX();
double y1 = d1.getNormalizedY(), y2 = d2.getNormalizedY();
colorLine(x1, y1, x2, y2);
} catch (Exception e) {
MyBoxLog.error(e);
}
}
private void whitePoints() {
if (!show.get(DataType.WhitePoints)) {
return;
}
int dataW = width - margins * 2, dataH = height - margins * 2;
int x, y;
g.setFont(dataFont);
g.setColor(textColor);
BasicStroke stroke1 = new BasicStroke(1);
g.setStroke(stroke1);
double[] xy = Illuminant.Illuminant1931A;
x = (int) Math.round(margins + dataW * xy[0]);
y = (int) Math.round(endH - dataH * xy[1]);
g.drawOval(x - 6, y - 6, 12, 12);
g.drawString("A", x + 10, y + 5);
xy = Illuminant.Illuminant1931D50;
x = (int) Math.round(margins + dataW * xy[0]);
y = (int) Math.round(endH - dataH * xy[1]);
g.drawOval(x - 6, y - 6, 12, 12);
g.drawString("D50", x + 10, y + 5);
xy = Illuminant.Illuminant1931C;
x = (int) Math.round(margins + dataW * xy[0]);
y = (int) Math.round(endH - dataH * xy[1]);
g.drawOval(x - 6, y - 6, 12, 12);
g.drawString("C", x + 10, y + 15);
xy = Illuminant.Illuminant1931E;
x = (int) Math.round(margins + dataW * xy[0]);
y = (int) Math.round(endH - dataH * xy[1]);
g.drawOval(x - 6, y - 6, 12, 12);
g.drawString("E", x + 10, y + 10);
xy = Illuminant.Illuminant1931D65;
x = (int) Math.round(margins + dataW * xy[0]);
y = (int) Math.round(endH - dataH * xy[1]);
g.drawOval(x - 6, y - 6, 12, 12);
g.drawString("D65", x - 40, y);
xy = Illuminant.Illuminant1931D55;
x = (int) Math.round(margins + dataW * xy[0]);
y = (int) Math.round(endH - dataH * xy[1]);
g.drawOval(x - 6, y - 6, 12, 12);
g.drawString("D55", x - 30, y - 10);
}
private void primariesLines() {
if (show == null) {
return;
}
for (DataType name : show.keySet()) {
if (!show.get(name)) {
continue;
}
switch (name) {
case CIELines:
primariesLines(RGBColorSpace.CIERGB, RGBColorSpace.CIEPrimariesD50, 150, 15);
break;
case ECILines:
primariesLines(RGBColorSpace.ECIRGB, RGBColorSpace.ECIPrimariesD50, 150, -40);
break;
case sRGBLines:
primariesLines(RGBColorSpace.sRGB, RGBColorSpace.sRGBPrimariesD50, 260, 0);
break;
case AdobeLines:
primariesLines(RGBColorSpace.AdobeRGB, RGBColorSpace.AdobePrimariesD50, 180, 30);
break;
case AppleLines:
primariesLines(RGBColorSpace.AppleRGB, RGBColorSpace.ApplePrimariesD50, 220, -70);
break;
case PALLines:
primariesLines(RGBColorSpace.PALRGB, RGBColorSpace.PALPrimariesD50, 220, 20);
break;
case NTSCLines:
primariesLines(RGBColorSpace.NTSCRGB, RGBColorSpace.NTSCPrimariesD50, 130, -30);
break;
case ColorMatchLines:
primariesLines(RGBColorSpace.ColorMatchRGB, RGBColorSpace.ColorMatchPrimariesD50, 200, -30);
break;
case ProPhotoLines:
primariesLines(RGBColorSpace.ProPhotoRGB, RGBColorSpace.ProPhotoPrimariesD50, 150, 0);
break;
case SMPTECLines:
primariesLines(RGBColorSpace.SMPTECRGB, RGBColorSpace.SMPTECPrimariesD50, 150, 0);
break;
}
}
}
private void primariesLines(String name, double[][] xy, int xOffset, int yOffset) {
if (image == null || g == null) {
return;
}
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
g.setComposite(ac);
BasicStroke stroke;
stroke = new BasicStroke(3);
g.setStroke(stroke);
g.setFont(dataFont);
int x, y;
int dataW = width - margins * 2, dataH = height - margins * 2;
// vertexes
g.setColor(Color.RED);
x = (int) Math.round(margins + dataW * xy[0][0]);
y = (int) Math.round(endH - dataH * xy[0][1]);
g.drawOval(x - 6, y - 6, 12, 12);
g.setColor(textColor);
// g.drawString(getMessage("Red"), x + 10, y);
g.drawLine(x, y, x + xOffset, y + yOffset);
g.drawString(name, x + xOffset + 10, y + yOffset + 10);
g.setColor(Color.GREEN);
x = (int) Math.round(margins + dataW * xy[1][0]);
y = (int) Math.round(endH - dataH * xy[1][1]);
g.drawOval(x - 6, y - 6, 12, 12);
g.setColor(textColor);
// g.drawString(getMessage("Green"), x + 10, y);
g.drawLine(x, y, x + xOffset, y + yOffset);
g.drawString(name, x + xOffset + 10, y + yOffset + 10);
g.setColor(Color.BLUE);
x = (int) Math.round(margins + dataW * xy[2][0]);
y = (int) Math.round(endH - dataH * xy[2][1]);
g.drawOval(x - 6, y - 6, 12, 12);
g.setColor(textColor);
// g.drawString(getMessage("Blue"), x + 10, y);
// lines
colorLine(xy[1][0], xy[1][1], xy[0][0], xy[0][1]);
colorLine(xy[2][0], xy[2][1], xy[0][0], xy[0][1]);
colorLine(xy[2][0], xy[2][1], xy[1][0], xy[1][1]);
}
private void colorLine(double ix1, double iy1, double ix2, double iy2) {
if (image == null || g == null || ix1 == ix2) {
return;
}
double x1, y1, x2, y2;
if (ix1 < ix2) {
x1 = ix1;
y1 = iy1;
x2 = ix2;
y2 = iy2;
} else {
x1 = ix2;
y1 = iy2;
x2 = ix1;
y2 = iy1;
}
Color pColor;
BasicStroke strokeSized = new BasicStroke(dotSize);
BasicStroke stroke1 = new BasicStroke(1);
int dataW = width - margins * 2, dataH = height - margins * 2;
int x, y, halfDot = dotSize / 2, lastx = -1, lasty = -1;
double ratio = (y2 - y1) / (x2 - x1);
double step = (x2 - x1) / 100;
double[] srgb;
for (double bx = x1 + step; bx < x2; bx += step) {
double by = (bx - x1) * ratio + y1;
double bz = 1 - bx - by;
double[] relativeXYZ = CIEDataTools.relative(bx, by, bz);
srgb = CIEColorSpace.XYZd50toSRGBd65(relativeXYZ);
pColor = new Color((float) srgb[0], (float) srgb[1], (float) srgb[2]);
g.setColor(pColor);
x = (int) Math.round(margins + dataW * bx);
y = (int) Math.round(endH - dataH * by);
if (isLine) {
if (lastx >= 0 && lasty >= 0) {
g.setStroke(strokeSized);
g.drawLine(lastx, lasty, x, y);
} else {
g.setStroke(stroke1);
g.fillRect(x - halfDot, y - halfDot, dotSize, dotSize);
}
lastx = x;
lasty = y;
} else {
g.setStroke(stroke1);
g.fillRect(x - halfDot, y - halfDot, dotSize, dotSize);
}
}
}
private void calculate() {
if (!show.get(DataType.Calculate)
|| calculateX < 0 || calculateX > 1
|| calculateY <= 0 || calculateY > 1) {
return;
}
int dataW = width - margins * 2, dataH = height - margins * 2;
BasicStroke stroke1 = new BasicStroke(1);
g.setStroke(stroke1);
double z = 1 - calculateX - calculateY;
if (z < 0 || z > 1) {
return;
}
Color pColor = calculateColor;
if (pColor == null) {
double[] relativeXYZ = CIEDataTools.relative(calculateX, calculateY, z);
double[] srgb = CIEColorSpace.XYZd50toSRGBd65(relativeXYZ);
pColor = new Color((float) srgb[0], (float) srgb[1], (float) srgb[2]);
}
int x = (int) Math.round(margins + dataW * calculateX);
int y = (int) Math.round(endH - dataH * calculateY);
g.setColor(pColor);
g.fillOval(x - 10, y - 10, 20, 20);
g.setFont(dataFont);
g.setColor(textColor);
g.drawString(Languages.message("CalculatedValues"), x + 15, y + 5);
}
/*
get/set
*/
public int getWidth() {
return width;
}
public ChromaticityDiagram setWidth(int width) {
this.width = width;
return this;
}
public int getHeight() {
return height;
}
public ChromaticityDiagram setHeight(int height) {
this.height = height;
return this;
}
public int getMargins() {
return margins;
}
public void setMargins(int margins) {
this.margins = margins;
}
public int getRuler() {
return ruler;
}
public void setRuler(int ruler) {
this.ruler = ruler;
}
public int getEach() {
return each;
}
public void setEach(int each) {
this.each = each;
}
public int getGrid() {
return grid;
}
public void setGrid(int grid) {
this.grid = grid;
}
public BufferedImage getImage() {
return image;
}
public void setImage(BufferedImage image) {
this.image = image;
}
public Color getGridColor() {
return gridColor;
}
public void setGridColor(Color gridColor) {
this.gridColor = gridColor;
}
public Color getRulerColor() {
return rulerColor;
}
public void setRulerColor(Color rulerColor) {
this.rulerColor = rulerColor;
}
public Color getTextColor() {
return textColor;
}
public void setTextColor(Color textColor) {
this.textColor = textColor;
}
public int getStepH() {
return stepH;
}
public void setStepH(int stepH) {
this.stepH = stepH;
}
public int getStepW() {
return stepW;
}
public void setStepW(int stepW) {
this.stepW = stepW;
}
public int getStartH() {
return startH;
}
public void setStartH(int startH) {
this.startH = startH;
}
public int getStartW() {
return startW;
}
public void setStartW(int startW) {
this.startW = startW;
}
public int getEndH() {
return endH;
}
public void setEndH(int endH) {
this.endH = endH;
}
public int getEndW() {
return endW;
}
public void setEndW(int endW) {
this.endW = endW;
}
public Font getDataFont() {
return dataFont;
}
public void setDataFont(Font dataFont) {
this.dataFont = dataFont;
}
public Graphics2D getG() {
return g;
}
public void setG(Graphics2D g) {
this.g = g;
}
public Font getCommnetsFont() {
return commentsFont;
}
public void setCommnetsFont(Font commnetsFont) {
this.commentsFont = commnetsFont;
}
public int getDotSize() {
return dotSize;
}
public ChromaticityDiagram setDotSize(int dotSize) {
this.dotSize = dotSize;
return this;
}
public boolean isIsLine() {
return isLine;
}
public ChromaticityDiagram setIsLine(boolean isLine) {
this.isLine = isLine;
return this;
}
public boolean isShow2Degree() {
return show2Degree;
}
public void setShow2Degree(boolean show2Degree) {
this.show2Degree = show2Degree;
}
public boolean isShow10Degree() {
return show10Degree;
}
public void setShow10Degree(boolean show10Degree) {
this.show10Degree = show10Degree;
}
public File getDataSourceFile() {
return dataSourceFile;
}
public void setDataSourceFile(File dataSourceFile) {
this.dataSourceFile = dataSourceFile;
}
public boolean isShowDataSource() {
return showDataSource;
}
public void setShowDataSource(boolean showDataSource) {
this.showDataSource = showDataSource;
}
public void setTitle(String title) {
this.title = title;
}
public LinkedHashMap<DataType, Boolean> getShow() {
return show;
}
public void setShow(LinkedHashMap<DataType, Boolean> show) {
this.show = show;
}
public Color getBgColor() {
return bgColor;
}
public ChromaticityDiagram setBgColor(Color bgColor) {
this.bgColor = bgColor;
return this;
}
public double getCalculateX() {
return calculateX;
}
public ChromaticityDiagram setCalculateX(double calculateX) {
this.calculateX = calculateX;
return this;
}
public double getCalculateY() {
return calculateY;
}
public ChromaticityDiagram setCalculateY(double calculateY) {
this.calculateY = calculateY;
return this;
}
public Color getCalculateColor() {
return calculateColor;
}
public ChromaticityDiagram setCalculateColor(Color calculateColor) {
this.calculateColor = calculateColor;
return this;
}
public String getDataSourceTexts() {
return dataSourceTexts;
}
public ChromaticityDiagram setDataSourceTexts(String dataSourceTexts) {
this.dataSourceTexts = dataSourceTexts;
return this;
}
public int getFontSize() {
return fontSize;
}
public ChromaticityDiagram setFontSize(int fontSize) {
this.fontSize = fontSize;
return this;
}
public Font getCommentsFont() {
return commentsFont;
}
public void setCommentsFont(Font commentsFont) {
this.commentsFont = commentsFont;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/Illuminant.java | released/MyBox/src/main/java/mara/mybox/color/Illuminant.java | package mara.mybox.color;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import mara.mybox.data.StringTable;
import mara.mybox.tools.DoubleMatrixTools;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2019-5-21 12:09:26
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*
* Reference: * http://brucelindbloom.com/index.html?Eqn_ChromAdapt.html
* http://brucelindbloom.com/index.html?ColorCalculator.html
* https://ww2.mathworks.cn/help/images/ref/whitepoint.html
* http://www.thefullwiki.org/Standard_illuminant
* http://www.wikizero.biz/index.php?q=aHR0cHM6Ly9lbi53aWtpcGVkaWEub3JnL3dpa2kvU3RhbmRhcmRfaWxsdW1pbmFudA
*/
public class Illuminant extends CIEData {
public IlluminantType type;
public Observer observer;
public String name, comments, whitePointValues;
public int temperature;
public Illuminant(IlluminantType illuminant) {
this.type = illuminant;
init1931(illuminant);
}
public Illuminant(IlluminantType illuminant, Observer observer) {
this.type = illuminant;
if (observer == null || observer == Observer.CIE1931) {
init1931(illuminant);
} else if (observer == Observer.CIE1964) {
init1964(illuminant);
}
}
public final void init1931(IlluminantType illuminant) {
this.type = illuminant;
switch (illuminant) {
case A:
init("A", Observer.CIE1931, Illuminant1931A, Illuminant1931A_Temperature, Illuminant1931A_Comments);
break;
case B:
init("B", Observer.CIE1931, Illuminant1931B, Illuminant1931B_Temperature, Illuminant1931B_Comments);
break;
case C:
init("C", Observer.CIE1931, Illuminant1931C, Illuminant1931C_Temperature, Illuminant1931C_Comments);
break;
case D50:
init("D50", Observer.CIE1931, Illuminant1931D50, Illuminant1931D50_Temperature, Illuminant1931D50_Comments);
break;
case D55:
init("D55", Observer.CIE1931, Illuminant1931D55, Illuminant1931D55_Temperature, Illuminant1931D55_Comments);
break;
case D65:
init("D65", Observer.CIE1931, Illuminant1931D65, Illuminant1931D65_Temperature, Illuminant1931D65_Comments);
break;
case D75:
init("D75", Observer.CIE1931, Illuminant1931D75, Illuminant1931D75_Temperature, Illuminant1931D75_Comments);
break;
case E:
init("E", Observer.CIE1931, Illuminant1931E, Illuminant1931E_Temperature, Illuminant1931E_Comments);
break;
case F1:
init("F1", Observer.CIE1931, Illuminant1931F1, Illuminant1931F1_Temperature, Illuminant1931F1_Comments);
break;
case F2:
init("F2", Observer.CIE1931, Illuminant1931F2, Illuminant1931F2_Temperature, Illuminant1931F2_Comments);
break;
case F3:
init("F3", Observer.CIE1931, Illuminant1931F3, Illuminant1931F3_Temperature, Illuminant1931F3_Comments);
break;
case F4:
init("F4:", Observer.CIE1931, Illuminant1931F4, Illuminant1931F4_Temperature, Illuminant1931F4_Comments);
break;
case F5:
init("F5", Observer.CIE1931, Illuminant1931F5, Illuminant1931F5_Temperature, Illuminant1931F5_Comments);
break;
case F6:
init("F6", Observer.CIE1931, Illuminant1931F6, Illuminant1931F6_Temperature, Illuminant1931F6_Comments);
break;
case F7:
init("F7", Observer.CIE1931, Illuminant1931F7, Illuminant1931F7_Temperature, Illuminant1931F7_Comments);
break;
case F8:
init("F8", Observer.CIE1931, Illuminant1931F8, Illuminant1931F8_Temperature, Illuminant1931F8_Comments);
break;
case F9:
init("F9", Observer.CIE1931, Illuminant1931F9, Illuminant1931F9_Temperature, Illuminant1931F9_Comments);
break;
case F10:
init("F10", Observer.CIE1931, Illuminant1931F10, Illuminant1931F10_Temperature, Illuminant1931F10_Comments);
break;
case F11:
init("F11", Observer.CIE1931, Illuminant1931F11, Illuminant1931F11_Temperature, Illuminant1931F11_Comments);
break;
case F12:
init("F12", Observer.CIE1931, Illuminant1931F12, Illuminant1931F12_Temperature, Illuminant1931F12_Comments);
break;
case ICC:
init("ICC", Observer.CIE1931, IlluminantICC, IlluminantICC_Temperature, IlluminantICC_Comments);
break;
}
}
public final void init1964(IlluminantType illuminant) {
this.type = illuminant;
switch (illuminant) {
case A:
init("A", Observer.CIE1964, Illuminant1964A, Illuminant1964A_Temperature, Illuminant1964A_Comments);
break;
case B:
init("B", Observer.CIE1964, Illuminant1964B, Illuminant1964B_Temperature, Illuminant1964B_Comments);
break;
case C:
init("C", Observer.CIE1964, Illuminant1964C, Illuminant1964C_Temperature, Illuminant1964C_Comments);
break;
case D50:
init("D50", Observer.CIE1964, Illuminant1964D50, Illuminant1964D50_Temperature, Illuminant1964D50_Comments);
break;
case D55:
init("D55", Observer.CIE1964, Illuminant1964D55, Illuminant1964D55_Temperature, Illuminant1964D55_Comments);
break;
case D65:
init("D65", Observer.CIE1964, Illuminant1964D65, Illuminant1964D65_Temperature, Illuminant1964D65_Comments);
break;
case D75:
init("D75", Observer.CIE1964, Illuminant1964D75, Illuminant1964D75_Temperature, Illuminant1964D75_Comments);
break;
case E:
init("E", Observer.CIE1964, Illuminant1964E, Illuminant1964E_Temperature, Illuminant1964E_Comments);
break;
case F1:
init("F1", Observer.CIE1964, Illuminant1964F1, Illuminant1964F1_Temperature, Illuminant1964F1_Comments);
break;
case F2:
init("F2", Observer.CIE1964, Illuminant1964F2, Illuminant1964F2_Temperature, Illuminant1964F2_Comments);
break;
case F3:
init("F3", Observer.CIE1964, Illuminant1964F3, Illuminant1964F3_Temperature, Illuminant1964F3_Comments);
break;
case F4:
init("F4:", Observer.CIE1964, Illuminant1964F4, Illuminant1964F4_Temperature, Illuminant1964F4_Comments);
break;
case F5:
init("F5", Observer.CIE1964, Illuminant1964F5, Illuminant1964F5_Temperature, Illuminant1964F5_Comments);
break;
case F6:
init("F6", Observer.CIE1964, Illuminant1964F6, Illuminant1964F6_Temperature, Illuminant1964F6_Comments);
break;
case F7:
init("F7", Observer.CIE1964, Illuminant1964F7, Illuminant1964F7_Temperature, Illuminant1964F7_Comments);
break;
case F8:
init("F8", Observer.CIE1964, Illuminant1964F8, Illuminant1964F8_Temperature, Illuminant1964F8_Comments);
break;
case F9:
init("F9", Observer.CIE1964, Illuminant1964F9, Illuminant1964F9_Temperature, Illuminant1964F9_Comments);
break;
case F10:
init("F10", Observer.CIE1964, Illuminant1964F10, Illuminant1964F10_Temperature, Illuminant1964F10_Comments);
break;
case F11:
init("F11", Observer.CIE1964, Illuminant1964F11, Illuminant1964F11_Temperature, Illuminant1964F11_Comments);
break;
case F12:
init("F12", Observer.CIE1964, Illuminant1964F12, Illuminant1964F12_Temperature, Illuminant1964F12_Comments);
break;
case ICC:
init("ICC", Observer.CIE1964, Illuminant1964D50, IlluminantICC_Temperature, IlluminantICC_Comments);
break;
}
}
public final void init(String name, Observer observer,
double[] xy, int temperature, String comments) {
this.name = name;
this.observer = observer;
this.temperature = temperature;
if (comments != null) {
this.comments = Languages.message(comments);
}
setNormalziedXY(xy);
}
public double[][] whitePoint() {
return DoubleMatrixTools.columnVector(relativeX, relativeY, relativeZ);
}
/*
Static methods
*/
public static List<Illuminant> all() {
List<Illuminant> data = new ArrayList<>();
for (IlluminantType type : IlluminantType.values()) {
data.add(new Illuminant(type, Observer.CIE1931));
data.add(new Illuminant(type, Observer.CIE1964));
}
return data;
}
public static List<Illuminant> all(int scale) {
List<Illuminant> data = all();
for (Illuminant d : data) {
d.scaleValues(scale);
}
return data;
}
public static List<String> names() {
List<String> data = new ArrayList<>();
for (IlluminantType type : IlluminantType.values()) {
data.add(type + " - " + Observer.CIE1931);
data.add(type + " - " + Observer.CIE1964);
}
return data;
}
public static StringTable table(int scale) {
List<String> names = new ArrayList<>();
names.addAll(Arrays.asList(Languages.message("Illuminant"), Languages.message("Observer"),
Languages.message("NormalizedX"), Languages.message("NormalizedY"), Languages.message("NormalizedZ"),
Languages.message("RelativeX"), Languages.message("RelativeY"), Languages.message("RelativeZ"),
Languages.message("ColorTemperature"), Languages.message("Comments")
));
StringTable table = new StringTable(names, Languages.message("Illuminants"));
for (Illuminant d : all(8)) {
List<String> row = new ArrayList<>();
row.addAll(Arrays.asList(d.name, d.observer.name(),
d.getNormalizedX() + "", d.getNormalizedY() + "", d.getNormalizedZ() + "",
d.getRelativeX() + "", d.getRelativeY() + "", d.getRelativeZ() + "",
d.temperature + "", d.comments
));
table.add(row);
}
return table;
}
public static String string() {
StringBuilder s = new StringBuilder();
String sp = "\t";
s.append(Languages.message("Illuminant")).append(sp).append(Languages.message("Observer")).append(sp).
append(Languages.message("NormalizedX")).append(sp).append(Languages.message("NormalizedY")).append(sp).append(Languages.message("NormalizedZ")).append(sp).
append(Languages.message("RelativeX")).append(sp).append(Languages.message("RelativeY")).append(sp).append(Languages.message("RelativeZ")).append(sp).
append(Languages.message("ColorTemperature")).append(sp).append(Languages.message("Comments")).append("\n");
List<Illuminant> data = all(8);
for (Illuminant d : data) {
s.append(d.name).append(sp).append(d.observer).append(sp).
append(d.getNormalizedX()).append(sp).
append(d.getNormalizedY()).append(sp).
append(d.getNormalizedZ()).append(sp).
append(d.getRelativeX()).append(sp).
append(d.getRelativeY()).append(sp).
append(d.getRelativeZ()).append(sp).
append(d.temperature).append("K").append(sp).
append(d.comments).append(sp).append("\n");
}
return s.toString();
}
public static IlluminantType type(String name) {
switch (name) {
case "A":
return IlluminantType.A;
case "B":
return IlluminantType.B;
case "C":
return IlluminantType.C;
case "D50":
return IlluminantType.D50;
case "D55":
return IlluminantType.D55;
case "D65":
return IlluminantType.D65;
case "D75":
return IlluminantType.D75;
case "E":
return IlluminantType.E;
case "F1":
return IlluminantType.F1;
case "F2":
return IlluminantType.F2;
case "F3":
return IlluminantType.F3;
case "F4":
return IlluminantType.F4;
case "F5":
return IlluminantType.F5;
case "F6":
return IlluminantType.F6;
case "F7":
return IlluminantType.F7;
case "F8":
return IlluminantType.F8;
case "F9":
return IlluminantType.F9;
case "F10":
return IlluminantType.F10;
case "F11":
return IlluminantType.F11;
case "F12":
return IlluminantType.F12;
case "ICC":
return IlluminantType.ICC;
}
return null;
}
public static double[] whitePoint1931(IlluminantType illuminant) {
switch (illuminant) {
case A:
return Illuminant1931A;
case B:
return Illuminant1931B;
case C:
return Illuminant1931C;
case D50:
return Illuminant1931D50;
case D55:
return Illuminant1931D55;
case D65:
return Illuminant1931D65;
case D75:
return Illuminant1931D65;
case E:
return Illuminant1931E;
case F1:
return Illuminant1931F1;
case F2:
return Illuminant1931F2;
case F3:
return Illuminant1931F3;
case F4:
return Illuminant1931F4;
case F5:
return Illuminant1931F5;
case F6:
return Illuminant1931F6;
case F7:
return Illuminant1931F7;
case F8:
return Illuminant1931F8;
case F9:
return Illuminant1931F9;
case F10:
return Illuminant1931F10;
case F11:
return Illuminant1931F11;
case F12:
return Illuminant1931F12;
case ICC:
return IlluminantICC;
}
return null;
}
public static double[] whitePoint1964(IlluminantType illuminant) {
switch (illuminant) {
case A:
return Illuminant1964A;
case B:
return Illuminant1964B;
case C:
return Illuminant1964C;
case D50:
return Illuminant1964D50;
case D55:
return Illuminant1964D55;
case D65:
return Illuminant1964D65;
case D75:
return Illuminant1964D65;
case E:
return Illuminant1964E;
case F1:
return Illuminant1964F1;
case F2:
return Illuminant1964F2;
case F3:
return Illuminant1964F3;
case F4:
return Illuminant1964F4;
case F5:
return Illuminant1964F5;
case F6:
return Illuminant1964F6;
case F7:
return Illuminant1964F7;
case F8:
return Illuminant1964F8;
case F9:
return Illuminant1964F9;
case F10:
return Illuminant1964F10;
case F11:
return Illuminant1964F11;
case F12:
return Illuminant1964F12;
case ICC:
return Illuminant1964D50;
}
return null;
}
/*
Data
*/
public static enum IlluminantType {
A, B, C, D50, D55, D65, D75, E, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, ICC
}
public static enum Observer {
CIE1931, CIE1964
}
// x, y
public static String Illuminant1931A_Comments = "IlluminantAComments";
public static int Illuminant1931A_Temperature = 2856;
public static double[] Illuminant1931A = {
0.44757, 0.40745
};
public static String Illuminant1931B_Comments = "IlluminantBComments";
public static int Illuminant1931B_Temperature = 4874;
public static double[] Illuminant1931B = {
0.34842, 0.35161
};
public static String Illuminant1931C_Comments = "IlluminantCComments";
public static int Illuminant1931C_Temperature = 6774;
public static double[] Illuminant1931C = {
0.31006, 0.31616
};
public static String Illuminant1931D50_Comments = "IlluminantD50Comments";
public static int Illuminant1931D50_Temperature = 5003;
public static double[] Illuminant1931D50 = {
0.34567, 0.35850
};
public static String Illuminant1931D55_Comments = "IlluminantD55Comments";
public static int Illuminant1931D55_Temperature = 5503;
public static double[] Illuminant1931D55 = {
0.33242, 0.34743
};
public static String Illuminant1931D65_Comments = "IlluminantD65Comments";
public static int Illuminant1931D65_Temperature = 6504;
public static double[] Illuminant1931D65 = {
0.31271, 0.32902
};
public static String Illuminant1931D75_Comments = "IlluminantD75Comments";
public static int Illuminant1931D75_Temperature = 7504;
public static double[] Illuminant1931D75 = {
0.29902, 0.31485
};
public static String Illuminant1931E_Comments = "IlluminantEComments";
public static int Illuminant1931E_Temperature = 5454;
public static double[] Illuminant1931E = {
0.33333, 0.33333
};
public static String Illuminant1931F1_Comments = "IlluminantF1Comments";
public static int Illuminant1931F1_Temperature = 6430;
public static double[] Illuminant1931F1 = {
0.31310, 0.33727
};
public static String Illuminant1931F2_Comments = "IlluminantF2Comments";
public static int Illuminant1931F2_Temperature = 4230;
public static double[] Illuminant1931F2 = {
0.37208, 0.37529
};
public static String Illuminant1931F3_Comments = "IlluminantF3Comments";
public static int Illuminant1931F3_Temperature = 3450;
public static double[] Illuminant1931F3 = {
0.40910, 0.39430
};
public static String Illuminant1931F4_Comments = "IlluminantF4Comments";
public static int Illuminant1931F4_Temperature = 2940;
public static double[] Illuminant1931F4 = {
0.44018, 0.40329
};
public static String Illuminant1931F5_Comments = "IlluminantF5Comments";
public static int Illuminant1931F5_Temperature = 6350;
public static double[] Illuminant1931F5 = {
0.31379, 0.34531
};
public static String Illuminant1931F6_Comments = "IlluminantF6Comments";
public static int Illuminant1931F6_Temperature = 4150;
public static double[] Illuminant1931F6 = {
0.37790, 0.38835
};
public static String Illuminant1931F7_Comments = "IlluminantF7Comments";
public static int Illuminant1931F7_Temperature = 6500;
public static double[] Illuminant1931F7 = {
0.31292, 0.32933
};
public static String Illuminant1931F8_Comments = "IlluminantF8Comments";
public static int Illuminant1931F8_Temperature = 5000;
public static double[] Illuminant1931F8 = {
0.34588, 0.35875
};
public static String Illuminant1931F9_Comments = "IlluminantF9Comments";
public static int Illuminant1931F9_Temperature = 4150;
public static double[] Illuminant1931F9 = {
0.37417, 0.37281
};
public static String Illuminant1931F10_Comments = "IlluminantF10Comments";
public static int Illuminant1931F10_Temperature = 5000;
public static double[] Illuminant1931F10 = {
0.34609, 0.35986
};
public static String Illuminant1931F11_Comments = "IlluminantF11Comments";
public static int Illuminant1931F11_Temperature = 4000;
public static double[] Illuminant1931F11 = {
0.38052, 0.37713
};
public static String Illuminant1931F12_Comments = "IlluminantF12Comments";
public static int Illuminant1931F12_Temperature = 3000;
public static double[] Illuminant1931F12 = {
0.43695, 0.40441
};
public static String IlluminantICC_Comments = "IlluminantICCComments";
public static int IlluminantICC_Temperature = 5003;
public static double[] IlluminantICC = {
0.34570, 0.35854
};
public static String Illuminant1964A_Comments = "IlluminantAComments";
public static int Illuminant1964A_Temperature = 2856;
public static double[] Illuminant1964A = {
0.45117, 0.40594
};
public static String Illuminant1964B_Comments = "IlluminantBComments";
public static int Illuminant1964B_Temperature = 4874;
public static double[] Illuminant1964B = {
0.3498, 0.3527
};
public static String Illuminant1964C_Comments = "IlluminantCComments";
public static int Illuminant1964C_Temperature = 6774;
public static double[] Illuminant1964C = {
0.31039, 0.31905
};
public static String Illuminant1964D50_Comments = "IlluminantD50Comments";
public static int Illuminant1964D50_Temperature = 5003;
public static double[] Illuminant1964D50 = {
0.34773, 0.35952
};
public static String Illuminant1964D55_Comments = "IlluminantD55Comments";
public static int Illuminant1964D55_Temperature = 5503;
public static double[] Illuminant1964D55 = {
0.33411, 0.34877
};
public static String Illuminant1964D65_Comments = "IlluminantD65Comments";
public static int Illuminant1964D65_Temperature = 6504;
public static double[] Illuminant1964D65 = {
0.31382, 0.33100
};
public static String Illuminant1964D75_Comments = "IlluminantD75Comments";
public static int Illuminant1964D75_Temperature = 7504;
public static double[] Illuminant1964D75 = {
0.29968, 0.31740
};
public static String Illuminant1964E_Comments = "IlluminantEComments";
public static int Illuminant1964E_Temperature = 5454;
public static double[] Illuminant1964E = {
0.33333, 0.33333
};
public static String Illuminant1964F1_Comments = "IlluminantF1Comments";
public static int Illuminant1964F1_Temperature = 6430;
public static double[] Illuminant1964F1 = {
0.31811, 0.33559
};
public static String Illuminant1964F2_Comments = "IlluminantF2Comments";
public static int Illuminant1964F2_Temperature = 4230;
public static double[] Illuminant1964F2 = {
0.37925, 0.36733
};
public static String Illuminant1964F3_Comments = "IlluminantF3Comments";
public static int Illuminant1964F3_Temperature = 3450;
public static double[] Illuminant1964F3 = {
0.41761, 0.38324
};
public static String Illuminant1964F4_Comments = "IlluminantF4Comments";
public static int Illuminant1964F4_Temperature = 2940;
public static double[] Illuminant1964F4 = {
0.44920, 0.39074
};
public static String Illuminant1964F5_Comments = "IlluminantF5Comments";
public static int Illuminant1964F5_Temperature = 6350;
public static double[] Illuminant1964F5 = {
0.31975, 0.34246
};
public static String Illuminant1964F6_Comments = "IlluminantF6Comments";
public static int Illuminant1964F6_Temperature = 4150;
public static double[] Illuminant1964F6 = {
0.38660, 0.37847
};
public static String Illuminant1964F7_Comments = "IlluminantF7Comments";
public static int Illuminant1964F7_Temperature = 6500;
public static double[] Illuminant1964F7 = {
0.31569, 0.32960
};
public static String Illuminant1964F8_Comments = "IlluminantF8Comments";
public static int Illuminant1964F8_Temperature = 5000;
public static double[] Illuminant1964F8 = {
0.34902, 0.35939
};
public static String Illuminant1964F9_Comments = "IlluminantF9Comments";
public static int Illuminant1964F9_Temperature = 4150;
public static double[] Illuminant1964F9 = {
0.37829, 0.37045
};
public static String Illuminant1964F10_Comments = "IlluminantF10Comments";
public static int Illuminant1964F10_Temperature = 5000;
public static double[] Illuminant1964F10 = {
0.35090, 0.35444
};
public static String Illuminant1964F11_Comments = "IlluminantF11Comments";
public static int Illuminant1964F11_Temperature = 4000;
public static double[] Illuminant1964F11 = {
0.38541, 0.37123
};
public static String Illuminant1964F12_Comments = "IlluminantF12Comments";
public static int Illuminant1964F12_Temperature = 3000;
public static double[] Illuminant1964F12 = {
0.44256, 0.39717
};
/*
get/set
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public int getTemperature() {
return temperature;
}
public void setTemperature(int temperature) {
this.temperature = temperature;
}
public IlluminantType getType() {
return type;
}
public void setType(IlluminantType type) {
this.type = type;
}
public Observer getObserver() {
return observer;
}
public void setObserver(Observer observer) {
this.observer = observer;
}
public String getWhitePointValues() {
return whitePointValues;
}
public void setWhitePointValues(String whitePointValues) {
this.whitePointValues = whitePointValues;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/CIEData.java | released/MyBox/src/main/java/mara/mybox/color/CIEData.java | package mara.mybox.color;
import java.awt.Color;
import java.awt.color.ColorSpace;
import static mara.mybox.tools.DoubleTools.scale;
/**
* @Author Mara
* @CreateDate 2019-5-20 18:51:37
* @License Apache License Version 2.0
*/
public class CIEData {
public int waveLength; // nm
public double X, Y, Z; // tristimulus values in 0~1.
public double normalizedX, normalizedY, normalizedZ; // x + y + z = 1
public double relativeX, relativeY, relativeZ; // y = 1;
public double red = -1, green = -1, blue = -1; // sRGB
public int redi = -1, greeni = -1, bluei = -1; // sRGB integer
public ColorSpace colorSpace;
public double[] channels;
public int scale = 8;
public CIEData() {
}
public CIEData(int waveLength, double X, double Y, double Z) {
this.waveLength = waveLength;
setTristimulusValues(X, Y, Z);
}
public CIEData(int waveLength, double X, double Y, double Z, ColorSpace cs) {
this.waveLength = waveLength;
setTristimulusValues(X, Y, Z);
convert(cs);
}
public CIEData(double x, double y) {
setxy(x, y);
}
public CIEData(Color color) {
double[] xyz = SRGB.SRGBtoXYZd50(color);
setTristimulusValues(xyz[0], xyz[1], xyz[2]);
}
public CIEData(javafx.scene.paint.Color color) {
double[] xyz = SRGB.SRGBtoXYZd50(new Color((float) color.getRed(), (float) color.getGreen(), (float) color.getBlue()));
setTristimulusValues(xyz[0], xyz[1], xyz[2]);
}
public final void setTristimulusValues(double X, double Y, double Z) {
this.X = X;
this.Y = Y;
this.Z = Z;
double[] xyz = CIEDataTools.normalize(X, Y, Z);
this.normalizedX = xyz[0];
this.normalizedY = xyz[1];
this.normalizedZ = xyz[2];
xyz = CIEDataTools.relative(X, Y, Z);
this.relativeX = xyz[0];
this.relativeY = xyz[1];
this.relativeZ = xyz[2];
}
public final void setxy(double x, double y) {
setxyY(x, y, 1.0);
}
public final void setxyY(double[] xyY) {
setxyY(xyY[0], xyY[1], xyY[2]);
}
public final void setxyY(double x, double y, double Y) {
this.normalizedX = x;
this.normalizedY = y;
this.normalizedZ = 1 - x - y;
this.X = x * Y / y;
this.Y = Y;
this.Z = (1 - x - y) * Y / y;
this.relativeX = x / y;
this.relativeY = 1.0;
this.relativeZ = (1 - x - y) / y;
}
public final void setRelativeXYZ(double[] XYZ) {
setRelativeXYZ(XYZ[0], XYZ[1], XYZ[2]);
}
public final void setRelativeXYZ(double X, double Y, double Z) {
this.relativeX = X;
this.relativeY = Y;
this.relativeZ = Z;
double[] xyz = CIEDataTools.normalize(X, Y, Z);
this.normalizedX = xyz[0];
this.normalizedY = xyz[1];
this.normalizedZ = xyz[2];
this.X = relativeX * 100;
this.Y = relativeY * 100;
this.Z = relativeZ * 100;
}
public final void setNormalziedXY(double[] xy) {
setNormalziedXY(xy[0], xy[1]);
}
public final void setNormalziedXY(double x, double y) {
this.normalizedX = x;
this.normalizedY = y;
this.normalizedZ = 1 - x - y;
this.relativeX = x / y;
this.relativeY = 1;
this.relativeZ = (1 - x - y) / y;
this.X = relativeX * 100;
this.Y = relativeY * 100;
this.Z = relativeZ * 100;
}
public final double[] convert(ColorSpace cs) {
if (cs == null) {
channels = CIEDataTools.CIERGB(this);
} else {
colorSpace = cs;
if (cs.isCS_sRGB()) {
channels = CIEDataTools.sRGB65(this);
} else {
channels = CIEDataTools.convert(cs, this);
}
}
return channels;
}
public void scaleValues() {
scaleValues(this.scale);
}
public void scaleValues(int scale) {
this.scale = scale;
X = scale(X, scale);
Y = scale(Y, scale);
Z = scale(Z, scale);
normalizedX = scale(normalizedX, scale);
normalizedY = scale(normalizedY, scale);
normalizedZ = scale(normalizedZ, scale);
relativeX = scale(relativeX, scale);
relativeY = scale(relativeY, scale);
relativeZ = scale(relativeZ, scale);
if (channels != null) {
for (int i = 0; i < channels.length; ++i) {
channels[i] = scale(channels[i], scale);
}
}
}
/*
get/set
*/
public double getX() {
return X;
}
public void setX(double X) {
this.X = X;
}
public double getY() {
return Y;
}
public void setY(double Y) {
this.Y = Y;
}
public double getZ() {
return Z;
}
public void setZ(double Z) {
this.Z = Z;
}
public int getScale() {
return scale;
}
public void setScale(int scale) {
this.scale = scale;
}
public int getWaveLength() {
return waveLength;
}
public void setWaveLength(int waveLength) {
this.waveLength = waveLength;
}
public double getNormalizedX() {
return normalizedX;
}
public void setNormalizedX(double normalizedX) {
this.normalizedX = normalizedX;
}
public double getNormalizedY() {
return normalizedY;
}
public void setNormalizedY(double normalizedY) {
this.normalizedY = normalizedY;
}
public double getNormalizedZ() {
return normalizedZ;
}
public void setNormalizedZ(double normalizedZ) {
this.normalizedZ = normalizedZ;
}
public double getRed() {
if (red == -1) {
red = channels[0];
}
return red;
}
public void setRed(double red) {
this.red = red;
}
public double getGreen() {
if (green == -1) {
green = channels[1];
}
return green;
}
public void setGreen(double green) {
this.green = green;
}
public double getBlue() {
if (blue == -1) {
blue = channels[2];
}
return blue;
}
public void setBlue(double blue) {
this.blue = blue;
}
public int getRedi() {
if (redi == -1) {
redi = (int) Math.round(255 * channels[0]);
}
return redi;
}
public void setRedi(int redi) {
this.redi = redi;
}
public int getGreeni() {
if (greeni == -1) {
greeni = (int) Math.round(255 * channels[1]);
}
return greeni;
}
public void setGreeni(int greeni) {
this.greeni = greeni;
}
public int getBluei() {
if (bluei == -1) {
bluei = (int) Math.round(255 * channels[2]);
}
return bluei;
}
public void setBluei(int bluei) {
this.bluei = bluei;
}
public double getRelativeX() {
return relativeX;
}
public void setRelativeX(double relativeX) {
this.relativeX = relativeX;
}
public double getRelativeY() {
return relativeY;
}
public void setRelativeY(double relativeY) {
this.relativeY = relativeY;
}
public double getRelativeZ() {
return relativeZ;
}
public void setRelativeZ(double relativeZ) {
this.relativeZ = relativeZ;
}
public ColorSpace getColorSpace() {
return colorSpace;
}
public void setColorSpace(ColorSpace colorSpace) {
this.colorSpace = colorSpace;
}
public double[] getChannels() {
return channels;
}
public void setChannels(double[] channels) {
this.channels = channels;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/IccTagType.java | released/MyBox/src/main/java/mara/mybox/color/IccTagType.java | package mara.mybox.color;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static mara.mybox.color.IccProfile.toBytes;
import mara.mybox.tools.ByteTools;
import static mara.mybox.tools.ByteTools.bytesToInt;
import static mara.mybox.tools.ByteTools.bytesToUshort;
import static mara.mybox.tools.ByteTools.intToBytes;
import static mara.mybox.tools.ByteTools.shortToBytes;
import static mara.mybox.tools.ByteTools.subBytes;
import mara.mybox.tools.StringTools;
import mara.mybox.value.AppVariables;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.value.AppValues;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.Languages;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2019-5-7 20:41:49
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class IccTagType {
// All in Big-Endian
public static String[][] IlluminantTypes = {
{"0", "Unknown"},
{"1", "D50"},
{"2", "D65"},
{"3", "D93"},
{"4", "F2"},
{"5", "D55"},
{"6", "A"},
{"7", "Equi-Power (E)"},
{"8 ", "F8"}
};
public static String[][] ObserverTypes = {
{"0", "Unknown"},
{"1", "CIE 1931 2 Degree Observer"},
{"2", "CIE 1964 10 Degree Observer"},};
public static String[][] GeometryTypes = {
{"0", "Unknown"},
{"1", "0°:45° or 45°:0°"},
{"2", "0°:d or d:0°"},};
/*
Decode values of Base Types
*/
public static int bytes4ToInt(byte[] b) {
return b[3] & 0xFF
| (b[2] & 0xFF) << 8
| (b[1] & 0xFF) << 16
| (b[0] & 0xFF) << 24;
}
public static int uInt8Number(byte b) {
return b & 0xFF;
}
public static double u8Fixed8Number(byte[] b) {
int integer = b[0] & 0xFF;
double fractional = (b[1] & 0xFF) / 256d;
return integer + fractional;
}
public static double s15Fixed16Number(byte[] b) {
int integer = b[1] & 0xFF | b[0] << 8;
double fractional = (b[3] & 0xFF | (b[2] & 0xFF) << 8) / 65536d;
return integer + fractional;
}
public static double u16Fixed16Number(byte[] b) {
int integer = b[1] & 0xFF | (b[0] & 0xFF) << 8;
double fractional = (b[3] & 0xFF | (b[2] & 0xFF) << 8) / 65536d;
return integer + fractional;
}
public static int uInt16Number(byte[] b) {
int integer = b[1] & 0xFF | (b[0] & 0xFF) << 8;
return integer;
}
public static long uInt32Number(byte[] b) {
long v = b[3] & 0xFF
| (b[2] & 0xFF) << 8
| (b[1] & 0xFF) << 16
| (b[0] & 0xFF) << 24;
return v;
}
public static String dateTimeString(byte[] v) {
if (v == null || v.length != 12) {
return "";
}
String d = bytesToUshort(subBytes(v, 0, 2)) + "-"
+ StringTools.fillLeftZero(uInt16Number(subBytes(v, 2, 2)), 2) + "-"
+ StringTools.fillLeftZero(uInt16Number(subBytes(v, 4, 2)), 2) + " "
+ StringTools.fillLeftZero(uInt16Number(subBytes(v, 6, 2)), 2) + ":"
+ StringTools.fillLeftZero(uInt16Number(subBytes(v, 8, 2)), 2) + ":"
+ StringTools.fillLeftZero(uInt16Number(subBytes(v, 10, 2)), 2);
return d;
}
public static double[] XYZNumber(byte[] v) {
if (v == null || v.length != 12) {
return null;
}
double[] xyz = new double[3];
xyz[0] = IccTagType.s15Fixed16Number(subBytes(v, 0, 4));
xyz[1] = IccTagType.s15Fixed16Number(subBytes(v, 4, 4));
xyz[2] = IccTagType.s15Fixed16Number(subBytes(v, 8, 4));
return xyz;
}
public static List<String> illuminantTypes() {
List<String> types = new ArrayList<>();
for (String[] item : IlluminantTypes) {
types.add(item[1]);
}
return types;
}
public static String illuminantType(byte[] bytes) {
if (bytes == null || bytes.length != 4) {
return "Unknown";
}
String type = bytesToInt(bytes) + "";
for (String[] item : IlluminantTypes) {
if (item[0].equals(type)) {
return item[1];
}
}
return "Unknown";
}
public static List<String> observerTypes() {
List<String> types = new ArrayList<>();
for (String[] item : ObserverTypes) {
types.add(item[1]);
}
return types;
}
public static String observerType(byte[] bytes) {
if (bytes == null || bytes.length != 4) {
return "Unknown";
}
String type = bytesToInt(bytes) + "";
for (String[] item : ObserverTypes) {
if (item[0].equals(type)) {
return item[1];
}
}
return "Unknown";
}
public static List<String> geometryTypes() {
List<String> types = new ArrayList<>();
for (String[] item : GeometryTypes) {
types.add(item[1]);
}
return types;
}
public static String geometryType(byte[] bytes) {
if (bytes == null || bytes.length != 4) {
return "Unknown";
}
String type = bytesToInt(bytes) + "";
for (String[] item : GeometryTypes) {
if (item[0].equals(type)) {
return item[1];
}
}
return "Unknown";
}
/*
Decode value of Tag Type
*/
public static double[][] XYZ(byte[] bytes) {
if (bytes == null || bytes.length < 12
|| !"XYZ ".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
int size = (bytes.length - 8) / 12;
double[][] xyzArray = new double[size][3];
for (int i = 0; i < size; ++i) {
double[] xyz = XYZNumber(subBytes(bytes, 8 + i * 12, 12));
xyzArray[i] = xyz;
}
return xyzArray;
}
public static String dateTime(byte[] bytes) {
if (bytes == null || bytes.length < 20
|| !"dtim".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
return dateTimeString(subBytes(bytes, 8, 12));
}
public static String signature(byte[] bytes) {
if (bytes == null || !"sig ".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
String value = new String(subBytes(bytes, 8, 4));
return value;
}
public static String text(byte[] bytes) {
if (bytes == null || !"text".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
String value = new String(subBytes(bytes, 8, bytes.length - 8));
return value;
}
public static Map<String, Object> multiLocalizedUnicode(byte[] bytes) {
if (bytes == null || !"desc".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
String signature = new String(subBytes(bytes, 0, 4));
switch (signature) {
case "desc":
return textDescription(bytes);
case "mluc":
return multiLocalizedUnicodes(bytes);
default:
return null;
}
}
// REVISION of ICC.1:1998-09
public static Map<String, Object> textDescription(byte[] bytes) {
if (bytes == null || !"desc".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
Map<String, Object> values = new HashMap<>();
int AsciiLength = (int) uInt32Number(subBytes(bytes, 8, 4));
values.put("AsciiLength", AsciiLength);
String value = new String(subBytes(bytes, 12, AsciiLength));
values.put("Ascii", value);
try {
values.put("UnicodeCode", bytesToInt(subBytes(bytes, 12 + AsciiLength, 4)));
int UnicodeLength = (int) uInt32Number(subBytes(bytes, 16 + AsciiLength, 4));
values.put("UnicodeLength", UnicodeLength);
if (UnicodeLength == 0) {
values.put("Unicode", "");
} else {
values.put("Unicode", new String(subBytes(bytes, 20 + AsciiLength, UnicodeLength * 2), "UTF-16"));
}
values.put("ScriptCodeCode", uInt16Number(subBytes(bytes, 20 + AsciiLength + UnicodeLength * 2, 2)));
int ScriptCodeLength = uInt8Number(bytes[22 + AsciiLength + UnicodeLength * 2]);
values.put("ScriptCodeLength", ScriptCodeLength);
if (ScriptCodeLength == 0) {
values.put("ScriptCode", "");
} else {
byte[] scriptCode = subBytes(bytes, 23 + AsciiLength + UnicodeLength * 2, ScriptCodeLength);
values.put("ScriptCode", new String(scriptCode));
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
return values;
}
// REVISION of ICC.1:2004-10
public static Map<String, Object> multiLocalizedUnicodes(byte[] bytes) {
MyBoxLog.debug(new String(subBytes(bytes, 0, 4)));
if (bytes == null || !"mluc".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
Map<String, Object> values = new HashMap<>();
int num = (int) uInt32Number(subBytes(bytes, 8, 4));
int size = (int) uInt32Number(subBytes(bytes, 12, 4));
values.put("number", num);
values.put("size", size);
MyBoxLog.debug(num + " " + size);
int offset = 16;
for (int i = 0; i < num; ++i) {
int languageCode = uInt16Number(subBytes(bytes, offset + i * 12, 2));
values.put("languageCode" + i, languageCode);
int countryCode = uInt16Number(subBytes(bytes, offset + i * 12 + 2, 2));
values.put("countryCode" + i, countryCode);
int length = (int) uInt32Number(subBytes(bytes, offset + i * 12 + 4, 4));
values.put("length" + i, length);
int ioffset = (int) uInt32Number(subBytes(bytes, offset + i * 12 + 8, 4));
values.put("offset" + i, ioffset);
MyBoxLog.debug(languageCode + " " + countryCode + " " + length + " " + ioffset);
}
// try {
// values.put("UnicodeCode", bytesToInt(subBytes(bytes, 12 + AsciiLength, 4)));
// int UnicodeLength = (int) uInt32Number(subBytes(bytes, 16 + AsciiLength, 4));
// MyBoxLog.debug(UnicodeLength);
// values.put("UnicodeLength", UnicodeLength);
// if (UnicodeLength == 0) {
// values.put("Unicode", "");
// } else {
// values.put("Unicode", new String(subBytes(bytes, 20 + AsciiLength, UnicodeLength)));
// }
//
// values.put("ScriptCodeCode", uInt16Number(subBytes(bytes, 20 + AsciiLength + UnicodeLength, 2)));
// int ScriptCodeLength = uInt8Number(bytes[22 + AsciiLength + UnicodeLength]);
// MyBoxLog.debug(ScriptCodeLength);
// values.put("ScriptCodeLength", ScriptCodeLength);
// if (ScriptCodeLength == 0) {
// values.put("ScriptCode", "");
// } else {
// byte[] scriptCode = subBytes(bytes, 23 + AsciiLength + UnicodeLength, ScriptCodeLength);
// values.put("ScriptCode", new String(scriptCode));
// }
// } catch (Exception e) {
// MyBoxLog.debug(e);
// }
return values;
}
public static double[] curve(byte[] bytes) {
if (bytes == null || !"curv".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
int count = bytesToInt(subBytes(bytes, 8, 4));
double[] values;
switch (count) {
case 0:
values = new double[1];
values[0] = 1.0d;
break;
case 1:
values = new double[1];
values[0] = u8Fixed8Number(subBytes(bytes, 12, 2));
break;
default:
values = new double[count];
for (int i = 0; i < count; ++i) {
values[i] = uInt16Number(subBytes(bytes, 12 + i * 2, 2)) / 65535d;
}
break;
}
return values;
}
public static Map<String, Object> viewingConditions(byte[] bytes) {
if (bytes == null || !"view".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
Map<String, Object> values = new HashMap<>();
values.put("illuminant", XYZNumber(subBytes(bytes, 8, 12)));
values.put("surround", XYZNumber(subBytes(bytes, 20, 12)));
values.put("illuminantType", illuminantType(subBytes(bytes, 32, 4)));
return values;
}
public static Map<String, Object> measurement(byte[] bytes) {
if (bytes == null || !"meas".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
Map<String, Object> values = new HashMap<>();
values.put("observer", observerType(subBytes(bytes, 8, 4)));
values.put("tristimulus", XYZNumber(subBytes(bytes, 12, 12)));
values.put("geometry", geometryType(subBytes(bytes, 24, 4)));
values.put("flare", u16Fixed16Number(subBytes(bytes, 28, 4)));
values.put("illuminantType", illuminantType(subBytes(bytes, 32, 4)));
return values;
}
public static double[] s15Fixed16Array(byte[] bytes) {
if (bytes == null || bytes.length < 4
|| !"sf32".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
int size = (bytes.length - 8) / 4;
double[] array = new double[size];
for (int i = 0; i < size; ++i) {
double v = IccTagType.s15Fixed16Number(subBytes(bytes, 8 + i * 4, 4));
array[i] = v;
}
return array;
}
public static Map<String, Object> lut(byte[] bytes, boolean normalizedLut) {
if (bytes == null) {
return null;
}
String type = new String(subBytes(bytes, 0, 4));
switch (type) {
case "mft1":
return lut8(bytes, normalizedLut);
case "mft2":
return lut16(bytes, normalizedLut);
case "mAB ":
return lutAToB(bytes, normalizedLut);
default:
return null;
}
}
public static Map<String, Object> lut8(byte[] bytes, boolean normalizedLut) {
try {
if (bytes == null || !"mft1".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
Map<String, Object> values = new HashMap<>();
values.put("type", "lut8");
int InputChannelsNumber = uInt8Number(bytes[8]);
values.put("InputChannelsNumber", InputChannelsNumber);
int OutputChannelsNumber = uInt8Number(bytes[9]);
values.put("OutputChannelsNumber", OutputChannelsNumber);
int GridPointsNumber = uInt8Number(bytes[10]);
values.put("GridPointsNumber", GridPointsNumber);
double e1 = IccTagType.s15Fixed16Number(subBytes(bytes, 12, 4));
values.put("e1", e1);
double e2 = IccTagType.s15Fixed16Number(subBytes(bytes, 16, 4));
values.put("e2", e2);
double e3 = IccTagType.s15Fixed16Number(subBytes(bytes, 20, 4));
values.put("e3", e3);
double e4 = IccTagType.s15Fixed16Number(subBytes(bytes, 24, 4));
values.put("e4", e4);
double e5 = IccTagType.s15Fixed16Number(subBytes(bytes, 28, 4));
values.put("e5", e5);
double e6 = IccTagType.s15Fixed16Number(subBytes(bytes, 32, 4));
values.put("e6", e6);
double e7 = IccTagType.s15Fixed16Number(subBytes(bytes, 36, 4));
values.put("e7", e7);
double e8 = IccTagType.s15Fixed16Number(subBytes(bytes, 40, 4));
values.put("e8", e8);
double e9 = IccTagType.s15Fixed16Number(subBytes(bytes, 44, 4));
values.put("e9", e9);
int offset = 48;
int maxItems = UserConfig.getInt("ICCMaxDecodeNumber", 500);
List<List<Double>> InputTables = new ArrayList<>();
for (int n = 0; n < 256; n++) {
List<Double> InputTable = new ArrayList<>();
for (int i = 0; i < InputChannelsNumber; ++i) {
double v = uInt8Number(bytes[offset++]);
if (normalizedLut) {
InputTable.add(v / 255);
} else {
InputTable.add(v);
}
}
InputTables.add(InputTable);
if (InputTables.size() >= maxItems) {
values.put("InputTablesTruncated", true);
break;
}
}
values.put("InputTables", InputTables);
List<List<Double>> CLUTTables = new ArrayList<>();
double dimensionSize = Math.pow(GridPointsNumber, InputChannelsNumber);
for (int i = 0; i < dimensionSize; ++i) {
List<Double> GridPoint = new ArrayList<>();
for (int o = 0; o < OutputChannelsNumber; o++) {
double v = uInt8Number(bytes[offset++]);
if (normalizedLut) {
GridPoint.add(v / 255);
} else {
GridPoint.add(v);
}
}
CLUTTables.add(GridPoint);
if (CLUTTables.size() >= maxItems) {
values.put("CLUTTablesTruncated", true);
break;
}
}
values.put("CLUTTables", CLUTTables);
List<List<Double>> OutputTables = new ArrayList<>();
for (int m = 0; m < 256; m++) {
List<Double> OutputTable = new ArrayList<>();
for (int i = 0; i < OutputChannelsNumber; ++i) {
double v = uInt8Number(bytes[offset++]);
if (normalizedLut) {
OutputTable.add(v / 255);
} else {
OutputTable.add(v);
}
}
OutputTables.add(OutputTable);
if (OutputTables.size() >= maxItems) {
values.put("OutputTablesTruncated", true);
break;
}
}
values.put("OutputTables", OutputTables);
return values;
} catch (Exception e) {
return null;
}
}
public static Map<String, Object> lut16(byte[] bytes, boolean normalizedLut) {
try {
if (bytes == null || !"mft2".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
Map<String, Object> values = new HashMap<>();
values.put("type", "lut16");
int InputChannelsNumber = uInt8Number(bytes[8]);
values.put("InputChannelsNumber", InputChannelsNumber);
int OutputChannelsNumber = uInt8Number(bytes[9]);
values.put("OutputChannelsNumber", OutputChannelsNumber);
int GridPointsNumber = uInt8Number(bytes[10]);
values.put("GridPointsNumber", GridPointsNumber);
double e1 = IccTagType.s15Fixed16Number(subBytes(bytes, 12, 4));
values.put("e1", e1);
double e2 = IccTagType.s15Fixed16Number(subBytes(bytes, 16, 4));
values.put("e2", e2);
double e3 = IccTagType.s15Fixed16Number(subBytes(bytes, 20, 4));
values.put("e3", e3);
double e4 = IccTagType.s15Fixed16Number(subBytes(bytes, 24, 4));
values.put("e4", e4);
double e5 = IccTagType.s15Fixed16Number(subBytes(bytes, 28, 4));
values.put("e5", e5);
double e6 = IccTagType.s15Fixed16Number(subBytes(bytes, 32, 4));
values.put("e6", e6);
double e7 = IccTagType.s15Fixed16Number(subBytes(bytes, 36, 4));
values.put("e7", e7);
double e8 = IccTagType.s15Fixed16Number(subBytes(bytes, 40, 4));
values.put("e8", e8);
double e9 = IccTagType.s15Fixed16Number(subBytes(bytes, 44, 4));
values.put("e9", e9);
int InputTablesNumber = uInt16Number(subBytes(bytes, 48, 2));
values.put("InputTablesNumber", InputTablesNumber);
int OutputTablesNumber = uInt16Number(subBytes(bytes, 50, 2));
values.put("OutputTablesNumber", OutputTablesNumber);
int offset = 52;
int maxItems = UserConfig.getInt("ICCMaxDecodeNumber", 500);
List<List<Double>> InputTables = new ArrayList<>();
for (int n = 0; n < InputTablesNumber; n++) {
List<Double> InputTable = new ArrayList<>();
for (int i = 0; i < InputChannelsNumber; ++i) {
double v = uInt16Number(subBytes(bytes, offset, 2));
if (normalizedLut) {
InputTable.add(v / 65535);
} else {
InputTable.add(v);
}
offset += 2;
}
InputTables.add(InputTable);
if (InputTables.size() >= maxItems) {
values.put("InputTablesTruncated", true);
break;
}
}
values.put("InputTables", InputTables);
List<List<Double>> CLUTTables = new ArrayList<>();
double dimensionSize = Math.pow(GridPointsNumber, InputChannelsNumber);
for (int i = 0; i < dimensionSize; ++i) {
List<Double> GridPoint = new ArrayList<>();
for (int o = 0; o < OutputChannelsNumber; o++) {
double v = uInt16Number(subBytes(bytes, offset, 2));
if (normalizedLut) {
GridPoint.add(v / 65535);
} else {
GridPoint.add(v);
}
offset += 2;
}
CLUTTables.add(GridPoint);
if (CLUTTables.size() >= maxItems) {
values.put("CLUTTablesTruncated", true);
break;
}
}
values.put("CLUTTables", CLUTTables);
List<List<Double>> OutputTables = new ArrayList<>();
for (int m = 0; m < OutputTablesNumber; m++) {
List<Double> OutputTable = new ArrayList<>();
for (int i = 0; i < OutputChannelsNumber; ++i) {
double v = uInt16Number(subBytes(bytes, offset, 2));
if (normalizedLut) {
OutputTable.add(v / 65535);
} else {
OutputTable.add(v);
}
offset += 2;
}
OutputTables.add(OutputTable);
if (OutputTables.size() >= maxItems) {
values.put("OutputTablesTruncated", true);
break;
}
}
values.put("OutputTables", OutputTables);
return values;
} catch (Exception e) {
return null;
}
}
public static Map<String, Object> lutAToB(byte[] bytes, boolean normalizedLut) {
try {
if (bytes == null || !"mAB ".equals(new String(subBytes(bytes, 0, 4)))) {
return null;
}
Map<String, Object> values = new HashMap<>();
values.put("lutAToB", "lutAToB");
int InputChannelsNumber = uInt8Number(bytes[8]);
values.put("InputChannelsNumber", InputChannelsNumber);
int OutputChannelsNumber = uInt8Number(bytes[9]);
values.put("OutputChannelsNumber", OutputChannelsNumber);
long OffsetBCurve = uInt32Number(subBytes(bytes, 12, 4));
values.put("OffsetBCurve", OffsetBCurve);
long OffsetMatrix = uInt32Number(subBytes(bytes, 16, 4));
values.put("OffsetMatrix", OffsetMatrix);
long OffsetMCurve = uInt32Number(subBytes(bytes, 20, 4));
values.put("OffsetMCurve", OffsetMCurve);
long OffsetCLUT = uInt32Number(subBytes(bytes, 24, 4));
values.put("OffsetCLUT", OffsetCLUT);
long OffsetACurve = uInt32Number(subBytes(bytes, 28, 4));
values.put("OffsetACurve", OffsetACurve);
return values;
} catch (Exception e) {
return null;
}
}
/*
Encode value of Base Type
*/
public static byte[] u8Fixed8Number(double d) {
byte[] bytes = new byte[2];
int integer = (int) d;
bytes[0] = (byte) (integer & 0xFF);
int fractional = (int) Math.round((d - integer) * 256);
bytes[1] = (byte) (fractional & 0xFF);
return bytes;
}
public static byte[] uInt16Number(int d) {
return ByteTools.uShortToBytes(d);
}
public static byte[] s15Fixed16Number(double d) {
byte[] bytes = new byte[4];
short s = (short) d;
byte[] shortBytes = shortToBytes(s);
System.arraycopy(shortBytes, 0, bytes, 0, 2);
int fractional = (int) Math.round((d - s) * 65536);
byte[] fractionalBytes = intToBytes(fractional);
System.arraycopy(fractionalBytes, 2, bytes, 2, 2);
return bytes;
}
public static byte[] u16Fixed16Number(double d) {
byte[] bytes = new byte[4];
int integer = (int) d;
byte[] integerBytes = intToBytes(integer);
System.arraycopy(integerBytes, 2, bytes, 0, 2);
int fractional = (int) Math.round((d - integer) * 65536);
byte[] fractionalBytes = intToBytes(fractional);
System.arraycopy(fractionalBytes, 2, bytes, 2, 2);
return bytes;
}
public static byte[] uInt32Number(long a) {
return new byte[]{
(byte) ((a >> 24) & 0xFF),
(byte) ((a >> 16) & 0xFF),
(byte) ((a >> 8) & 0xFF),
(byte) (a & 0xFF)
};
}
public static byte[] dateTimeBytes(String v) {
try {
String d = v.trim();
if (d.length() == 17) {
d = "19" + d;
}
if (d.length() != 19
|| d.indexOf('-') != 4 || d.indexOf('-', 5) != 7
|| d.indexOf(' ') != 10
|| d.indexOf(':') != 13 || d.indexOf(':', 14) != 16) {
return null;
}
byte[] bytes = new byte[12];
int i = Integer.parseInt(d.substring(0, 4));
byte[] vBytes = ByteTools.intToBytes(i);
System.arraycopy(vBytes, 2, bytes, 0, 2);
i = Integer.parseInt(d.substring(5, 7));
vBytes = ByteTools.intToBytes(i);
System.arraycopy(vBytes, 2, bytes, 2, 2);
i = Integer.parseInt(d.substring(8, 10));
vBytes = ByteTools.intToBytes(i);
System.arraycopy(vBytes, 2, bytes, 4, 2);
i = Integer.parseInt(d.substring(11, 13));
vBytes = ByteTools.intToBytes(i);
System.arraycopy(vBytes, 2, bytes, 6, 2);
i = Integer.parseInt(d.substring(14, 16));
vBytes = ByteTools.intToBytes(i);
System.arraycopy(vBytes, 2, bytes, 8, 2);
i = Integer.parseInt(d.substring(17, 19));
vBytes = ByteTools.intToBytes(i);
System.arraycopy(vBytes, 2, bytes, 10, 2);
return bytes;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static double[] XYZNumberDoubles(String values) {
try {
String[] strings = StringTools.splitBySpace(values.replace("\n", " "));
if (strings.length < 3) {
return null;
}
double[] doubles = new double[3];
for (int i = 0; i < doubles.length; ++i) {
doubles[i] = Double.parseDouble(strings[i]);
}
return doubles;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static byte[] XYZNumber(String values) {
return XYZNumber(XYZNumberDoubles(values));
}
public static byte[] XYZNumber(double[] xyz) {
byte[] bytes = new byte[12];
byte[] xBytes = s15Fixed16Number(xyz[0]);
System.arraycopy(xBytes, 0, bytes, 0, 4);
byte[] yBytes = s15Fixed16Number(xyz[1]);
System.arraycopy(yBytes, 0, bytes, 0, 4);
byte[] zBytes = s15Fixed16Number(xyz[2]);
System.arraycopy(zBytes, 0, bytes, 8, 4);
return bytes;
}
public static byte[] illuminantType(String value) {
for (String[] item : IlluminantTypes) {
if (item[1].equals(value)) {
return uInt32Number(Integer.parseInt(item[0]));
}
}
return uInt32Number(0);
}
public static byte[] observerType(String value) {
for (String[] item : ObserverTypes) {
if (item[1].equals(value)) {
return uInt32Number(Integer.parseInt(item[0]));
}
}
return uInt32Number(0);
}
public static byte[] geometryType(String value) {
for (String[] item : GeometryTypes) {
if (item[1].equals(value)) {
return uInt32Number(Integer.parseInt(item[0]));
}
}
return uInt32Number(0);
}
/*
Encode value of Tag Type
*/
public static byte[] text(String value) {
try {
byte[] sigBytes = toBytes("text");
byte[] valueBytes = toBytes(value);
byte[] tagBytes = new byte[valueBytes.length + 8];
System.arraycopy(sigBytes, 0, tagBytes, 0, 4);
System.arraycopy(valueBytes, 0, tagBytes, 8, valueBytes.length);
return tagBytes;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static byte[] signature(String value) {
try {
byte[] sigBytes = toBytes("sig ");
byte[] valueBytes = toBytes(value);
byte[] tagBytes = new byte[12];
System.arraycopy(sigBytes, 0, tagBytes, 0, 4);
System.arraycopy(valueBytes, 0, tagBytes, 8, Math.min(4, valueBytes.length));
return tagBytes;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static byte[] dateTime(String value) {
try {
byte[] sigBytes = toBytes("dtim");
byte[] valueBytes = dateTimeBytes(value);
byte[] tagBytes = new byte[20];
System.arraycopy(sigBytes, 0, tagBytes, 0, 4);
System.arraycopy(valueBytes, 0, tagBytes, 8, 12);
return tagBytes;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static double[][] XYZDoubles(String values) {
try {
String[] strings = StringTools.splitBySpace(values.replace("\n", " "));
if (strings.length % 3 != 0) {
return null;
}
double[][] doubles = new double[strings.length / 3][3];
for (int i = 0; i < doubles.length; ++i) {
doubles[i][0] = Double.parseDouble(strings[i * 3]);
doubles[i][1] = Double.parseDouble(strings[i * 3 + 1]);
doubles[i][2] = Double.parseDouble(strings[i * 3 + 2]);
}
return doubles;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static byte[] XYZ(String values) {
return XYZ(XYZDoubles(values));
}
public static byte[] XYZ(double[][] values) {
try {
byte[] sigBytes = toBytes("XYZ ");
byte[] tagBytes = new byte[12 * values.length + 8];
System.arraycopy(sigBytes, 0, tagBytes, 0, 4);
for (int i = 0; i < values.length; ++i) {
double[] xyz = values[i];
byte[] xyzBytes = XYZNumber(xyz);
System.arraycopy(xyzBytes, 0, tagBytes, 8 + 12 * i, 12);
}
return tagBytes;
} catch (Exception e) {
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | true |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/AdobeRGB.java | released/MyBox/src/main/java/mara/mybox/color/AdobeRGB.java | package mara.mybox.color;
import static mara.mybox.color.RGBColorSpace.gamma22;
import static mara.mybox.color.RGBColorSpace.linear22;
/**
* @Author Mara
* @CreateDate 2019-5-21 12:14:18
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class AdobeRGB {
public static double linearAdobeRGB(double v) {
return linear22(v);
}
public static double gammaAdobeRGB(double v) {
return gamma22(v);
}
public static double[] gammaAdobeRGB(double[] linearRGB) {
double[] rgb = new double[3];
rgb[0] = gamma22(linearRGB[0]);
rgb[1] = gamma22(linearRGB[1]);
rgb[2] = gamma22(linearRGB[2]);
return rgb;
}
public static double[] AdobeRGBtoXYZ(double[] adobergb) {
double linearRed = linearAdobeRGB(adobergb[0]);
double linearGreen = linearAdobeRGB(adobergb[1]);
double linearBlue = linearAdobeRGB(adobergb[2]);
double[] xyz = new double[3];
xyz[0] = 0.5767309 * linearRed + 0.1855540 * linearGreen + 0.1881852 * linearBlue;
xyz[1] = 0.2973769 * linearRed + 0.6273491 * linearGreen + 0.0752741 * linearBlue;
xyz[2] = 0.0270343 * linearRed + 0.0706872 * linearGreen + 0.9911085 * linearBlue;
return xyz;
}
public static double[] AdobeRGBtoSRGB(double[] adobergb) {
double[] xyz = AdobeRGBtoXYZ(adobergb);
return CIEColorSpace.XYZd65toSRGBd65(xyz);
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/ColorBase.java | released/MyBox/src/main/java/mara/mybox/color/ColorBase.java | package mara.mybox.color;
import java.awt.Color;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
/**
* @Author Mara
* @CreateDate 2018-6-4 16:07:27
* @Description
* @License Apache License Version 2.0
*
* Reference http://brucelindbloom.com/index.html?Eqn_RGB_to_XYZ.html //
* http://www.easyrgb.com/en/math.php //
* http://www.color.org/registry/index.xalter //
* https://www.w3.org/Graphics/Color/sRGB.html //
* https://ninedegreesbelow.com/photography/xyz-rgb.html //
* https://stackoverflow.com/questions/40017741/mathematical-conversion-srgb-and-adobergb
* https://supportdownloads.adobe.com/detail.jsp?ftpID=3680 //
*/
public class ColorBase {
public static int colorSpaceType(String colorSpaceType) {
int csType = -1;
if (colorSpaceType != null) {
switch (colorSpaceType) {
case "sRGB":
csType = ICC_ColorSpace.CS_sRGB;
break;
case "XYZ":
csType = ICC_ColorSpace.CS_CIEXYZ;
break;
case "PYCC":
csType = ICC_ColorSpace.CS_PYCC;
break;
case "GRAY":
csType = ICC_ColorSpace.CS_GRAY;
break;
case "LINEAR_RGB":
csType = ICC_ColorSpace.CS_LINEAR_RGB;
break;
}
}
return csType;
}
/*
Methods based on JDK
*/
public static String colorSpaceType(int colorType) {
switch (colorType) {
case ColorSpace.TYPE_XYZ:
return "XYZ";
case ColorSpace.TYPE_Lab:
return "Lab";
case ColorSpace.TYPE_Luv:
return "Luv";
case ColorSpace.TYPE_YCbCr:
return "YCbCr";
case ColorSpace.TYPE_Yxy:
return "Yxy";
case ColorSpace.TYPE_RGB:
return "RGB";
case ColorSpace.TYPE_GRAY:
return "GRAY";
case ColorSpace.TYPE_HSV:
return "HSV";
case ColorSpace.TYPE_HLS:
return "HLS";
case ColorSpace.TYPE_CMYK:
return "CMYK";
case ColorSpace.TYPE_CMY:
return "CMY";
case ColorSpace.TYPE_2CLR:
return "2CLR";
case ColorSpace.TYPE_3CLR:
return "3CLR";
case ColorSpace.TYPE_4CLR:
return "4CLR";
case ColorSpace.TYPE_5CLR:
return "5CLR";
case ColorSpace.TYPE_6CLR:
return "6CLR";
case ColorSpace.TYPE_7CLR:
return "CMY";
case ColorSpace.TYPE_8CLR:
return "8CLR";
case ColorSpace.TYPE_9CLR:
return "9CLR";
case ColorSpace.TYPE_ACLR:
return "ACLR";
case ColorSpace.TYPE_BCLR:
return "BCLR";
case ColorSpace.TYPE_CCLR:
return "CCLR";
case ColorSpace.TYPE_DCLR:
return "DCLR";
case ColorSpace.TYPE_ECLR:
return "ECLR";
case ColorSpace.TYPE_FCLR:
return "FCLR";
case ColorSpace.CS_sRGB:
return "sRGB";
case ColorSpace.CS_LINEAR_RGB:
return "LINEAR_RGB";
case ColorSpace.CS_CIEXYZ:
return "CIEXYZ";
case ColorSpace.CS_PYCC:
return "PYCC";
case ColorSpace.CS_GRAY:
return "GRAY";
default:
return "Unknown";
}
}
public static String profileClass(int value) {
switch (value) {
case ICC_Profile.CLASS_INPUT:
return "InputDeviceProfile";
case ICC_Profile.CLASS_DISPLAY:
return "DisplayDeviceProfile";
case ICC_Profile.CLASS_OUTPUT:
return "OutputDeviceProfile";
case ICC_Profile.CLASS_DEVICELINK:
return "DeviceLinkProfile";
case ICC_Profile.CLASS_ABSTRACT:
return "AbstractProfile";
case ICC_Profile.CLASS_COLORSPACECONVERSION:
return "ColorSpaceConversionProfile";
case ICC_Profile.CLASS_NAMEDCOLOR:
return "NamedColorProfile";
default:
return "Unknown";
}
}
public static String profileClassSignature(int value) {
switch (value) {
case ICC_Profile.icSigInputClass:
return "InputDeviceProfile";
case ICC_Profile.icSigDisplayClass:
return "DisplayDeviceProfile";
case ICC_Profile.icSigOutputClass:
return "OutputDeviceProfile";
case ICC_Profile.icSigLinkClass:
return "DeviceLinkProfile";
case ICC_Profile.icSigAbstractClass:
return "AbstractProfile";
case ICC_Profile.icSigColorSpaceClass:
return "ColorSpaceConversionProfile";
case ICC_Profile.icSigNamedColorClass:
return "NamedColorProfile";
default:
return "Unknown";
}
}
public static double[] clipRGB(double[] rgb) {
double[] outputs = new double[rgb.length];
System.arraycopy(rgb, 0, outputs, 0, rgb.length);
// for (int i = 0; i < outputs.length; ++i) {
// if (outputs[i] < 0) {
// for (int j = 0; j < outputs.length; ++j) {
// outputs[j] = outputs[j] - outputs[i];
// }
// }
// }
for (int i = 0; i < outputs.length; ++i) {
if (outputs[i] < 0) {
outputs[i] = 0;
}
if (outputs[i] > 1) {
outputs[i] = 1;
}
}
return outputs;
}
public static double[] array(Color color) {
double[] rgb = new double[3];
rgb[0] = color.getRed() / 255d;
rgb[1] = color.getGreen() / 255d;
rgb[2] = color.getBlue() / 255d;
return rgb;
}
public static float[] array(float r, float g, float b) {
float[] rgb = new float[3];
rgb[0] = r;
rgb[1] = g;
rgb[2] = b;
return rgb;
}
public static double[] array(double r, double g, double b) {
double[] rgb = new double[3];
rgb[0] = r;
rgb[1] = g;
rgb[2] = b;
return rgb;
}
public static float[] arrayFloat(Color color) {
float[] rgb = new float[3];
rgb[0] = color.getRed() / 255f;
rgb[1] = color.getGreen() / 255f;
rgb[2] = color.getBlue() / 255f;
return rgb;
}
public static float[] arrayFloat(double r, double g, double b) {
float[] rgb = new float[3];
rgb[0] = (float) r;
rgb[1] = (float) g;
rgb[2] = (float) b;
return rgb;
}
public static float[] arrayFloat(double[] d) {
float[] rgb = new float[3];
rgb[0] = (float) d[0];
rgb[1] = (float) d[1];
rgb[2] = (float) d[2];
return rgb;
}
public static double[] arrayDouble(float r, float g, float b) {
double[] rgb = new double[3];
rgb[0] = r;
rgb[1] = g;
rgb[2] = b;
return rgb;
}
public static double[] arrayDouble(float[] frgb) {
double[] rgb = new double[3];
rgb[0] = frgb[0];
rgb[1] = frgb[1];
rgb[2] = frgb[2];
return rgb;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/CIEDataTools.java | released/MyBox/src/main/java/mara/mybox/color/CIEDataTools.java | package mara.mybox.color;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static mara.mybox.color.ColorBase.array;
import static mara.mybox.color.ColorBase.arrayDouble;
import static mara.mybox.color.ColorBase.clipRGB;
import mara.mybox.data.StringTable;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxFileTools;
import mara.mybox.tools.FileTools;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2019-5-20 18:51:37
* @License Apache License Version 2.0
*/
public class CIEDataTools {
public static double[] CIERGB(CIEData d) {
double[] xyz = ColorBase.array(d.getRelativeX(), d.getRelativeY(), d.getRelativeZ());
double[] outputs = CIEColorSpace.XYZd50toCIERGB(xyz);
return outputs;
}
public static double[][] normalize(double[][] rgb) {
double[][] n = new double[3][3];
n[0] = normalize(rgb[0]);
n[1] = normalize(rgb[1]);
n[2] = normalize(rgb[2]);
return n;
}
public static double[] normalize(double[] XYZ) {
return normalize(XYZ[0], XYZ[1], XYZ[2]);
}
public static double[] normalize(double X, double Y, double Z) {
double[] xyz = new double[3];
double sum = X + Y + Z;
if (sum == 0) {
return array(X, Y, Z);
}
xyz[0] = X / sum;
xyz[1] = Y / sum;
xyz[2] = Z / sum;
return xyz;
}
public static double[][] relative(double[][] rgb) {
double[][] r = new double[3][3];
r[0] = relative(rgb[0]);
r[1] = relative(rgb[1]);
r[2] = relative(rgb[2]);
return r;
}
public static double[] relative(double[] xyz) {
return relative(xyz[0], xyz[1], xyz[2]);
}
public static double[] relative(double x, double y, double z) {
if (y == 0) {
return array(x, y, z);
}
double[] xyz = new double[3];
xyz[0] = x / y;
xyz[1] = 1.0;
xyz[2] = z / y;
return xyz;
}
public static List<CIEData> cie1931Observer2Degree1nmData() {
return read(cie1931Observer2Degree1nmFile());
}
public static List<CIEData> cie1931Observer2Degree1nmData(ColorSpace cs) {
try {
List<CIEData> data = cie1931Observer2Degree1nmData();
for (CIEData d : data) {
d.convert(cs);
d.scaleValues();
}
return data;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static List<CIEData> cie1931Observer2Degree5nmData() {
return read(cie1931Observer2Degree5nmFile());
}
public static List<CIEData> cie1931Observer2Degree5nmData(ColorSpace cs) {
try {
List<CIEData> data = cie1931Observer2Degree5nmData();
for (CIEData d : data) {
d.convert(cs);
d.scaleValues();
}
return data;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static List<CIEData> read(String texts) {
try {
String[] lines = texts.split("\n");
List<CIEData> data = new ArrayList<>();
for (String line : lines) {
CIEData d = readLine(line);
if (d != null) {
data.add(d);
}
}
return data;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static List<CIEData> read(File file) {
try {
List<CIEData> data = new ArrayList<>();
File validFile = FileTools.removeBOM(null, file);
try (final BufferedReader reader = new BufferedReader(new FileReader(validFile))) {
String line;
while ((line = reader.readLine()) != null) {
CIEData d = readLine(line);
if (d != null) {
data.add(d);
}
}
}
return data;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static List<CIEData> read(File file, ColorSpace cs) {
try {
List<CIEData> data = read(file);
for (CIEData d : data) {
d.convert(cs);
}
return data;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static StringTable cieTable(List<CIEData> data, ColorSpace cs, String title) {
try {
if (data == null || data.isEmpty()) {
return null;
}
List<String> names = new ArrayList<>();
names.addAll(Arrays.asList(Languages.message("WaveLength"), Languages.message("TristimulusX"), Languages.message("TristimulusY"), Languages.message("TristimulusZ"),
Languages.message("NormalizedX"), Languages.message("NormalizedY"), Languages.message("NormalizedZ"), Languages.message("RelativeX"), Languages.message("RelativeY"), Languages.message("RelativeZ")));
int num = 0;
if (cs != null) {
num = cs.getNumComponents();
for (int i = 0; i < num; ++i) {
names.add(Languages.message(cs.getName(i)));
}
if (cs.getType() == ColorSpace.TYPE_RGB) {
for (int i = 0; i < num; ++i) {
names.add(Languages.message(cs.getName(i)) + "-" + Languages.message("Integer"));
}
}
}
StringTable table = new StringTable(names, title);
double[] channels;
for (int i = 0; i < data.size(); ++i) {
CIEData d = data.get(i);
List<String> row = new ArrayList<>();
row.addAll(Arrays.asList(d.getWaveLength() + "", d.X + "", d.Y + "", d.Z + "", d.getNormalizedX() + "", d.getNormalizedX() + "", d.getNormalizedX() + "", d.getRelativeX() + "", d.getRelativeY() + "", d.getRelativeZ() + ""));
if (cs != null) {
channels = d.getChannels();
for (int j = 0; j < num; ++j) {
row.add(channels[j] + "");
}
if (cs.getType() == ColorSpace.TYPE_RGB) {
for (int j = 0; j < num; ++j) {
row.add(Math.round(channels[j] * 255) + "");
}
}
}
table.add(row);
}
return table;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static File cie1964Observer10Degree1nmFile() {
File f = FxFileTools.getInternalFile("/data/CIE/CIE1964-10-degree-1nm.txt", "CIE", "CIE1964-10-degree-1nm.txt", false);
return f;
}
public static File cie1931Observer2Degree5nmFile() {
File f = FxFileTools.getInternalFile("/data/CIE/CIE1931-2-degree-5nm.txt", "CIE", "CIE1931-2-degree-5nm.txt", false);
return f;
}
/*
Source data: CIE standard Observer functions and CIE D50 Reference Illuminant
*/
public static File cie1931Observer2Degree1nmFile() {
File f = FxFileTools.getInternalFile("/data/CIE/CIE1931-2-degree-1nm.txt", "CIE", "CIE1931-2-degree-1nm.txt", false);
return f;
}
public static CIEData readLine(String line) {
try {
String DataIgnoreChars = "\t|,|\uff0c|\\||\\{|\\}|\\[|\\]|\\\"|\\'";
line = line.replaceAll(DataIgnoreChars, " ");
String[] values = line.split("\\s+");
List<Double> dList = new ArrayList<>();
for (String v : values) {
try {
double d = Double.parseDouble(v);
dList.add(d);
if (dList.size() >= 4) {
CIEData data = new CIEData((int) Math.round(dList.get(0)), dList.get(1), dList.get(2), dList.get(3));
data.scaleValues();
return data;
}
} catch (Exception e) {
break;
}
}
return null;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static File cie1964Observer10Degree5nmFile() {
File f = FxFileTools.getInternalFile("/data/CIE/CIE1964-10-degree-5nm.txt", "CIE", "CIE1964-10-degree-5nm.txt", false);
return f;
}
public static List<CIEData> cie1964Observer10Degree1nmData() {
return read(cie1964Observer10Degree1nmFile());
}
public static List<CIEData> cie1964Observer10Degree1nmData(ColorSpace cs) {
try {
List<CIEData> data = cie1964Observer10Degree1nmData();
for (CIEData d : data) {
d.convert(cs);
d.scaleValues();
}
return data;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static String cieString(String texts) {
return cieString(read(texts), null, null);
}
public static String cieString(List<CIEData> data, ColorSpace cs, String title) {
try {
if (data == null || data.isEmpty()) {
return null;
}
String sp = "\t";
StringBuilder s = new StringBuilder();
if (title != null) {
s.append(title).append("\n\n");
}
s.append(Languages.message("WaveLength")).append(sp).append(Languages.message("TristimulusX")).append(sp).append(Languages.message("TristimulusY")).append(sp).append(Languages.message("TristimulusZ")).append(sp).append(Languages.message("NormalizedX")).append(sp).append(Languages.message("NormalizedY")).append(sp).append(Languages.message("NormalizedZ")).append(sp).append(Languages.message("RelativeX")).append(sp).append(Languages.message("RelativeY")).append(sp).append(Languages.message("RelativeZ")).append(sp);
int num = 0;
if (cs != null) {
num = cs.getNumComponents();
for (int i = 0; i < num; ++i) {
s.append(Languages.message(cs.getName(i))).append(sp);
}
if (cs.getType() == ColorSpace.TYPE_RGB) {
for (int i = 0; i < num; ++i) {
s.append(Languages.message(cs.getName(i))).append("-").append(Languages.message("Integer")).append(sp);
}
}
}
s.append("\n");
double[] channels;
for (int i = 0; i < data.size(); ++i) {
CIEData d = data.get(i);
s.append(d.getWaveLength()).append(sp).append(d.X).append(sp).append(d.Y).append(sp).append(d.Z).append(sp).append(d.getNormalizedX()).append(sp).append(d.getNormalizedY()).append(sp).append(d.getNormalizedZ()).append(sp).append(d.getRelativeX()).append(sp).append(d.getRelativeY()).append(sp).append(d.getRelativeZ()).append(sp);
if (cs != null) {
channels = d.getChannels();
for (int j = 0; j < num; ++j) {
s.append(channels[j]).append(sp);
}
if (cs.getType() == ColorSpace.TYPE_RGB) {
for (int j = 0; j < num; ++j) {
s.append(Math.round(channels[j] * 255)).append(sp);
}
}
}
s.append("\n");
}
return s.toString();
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static List<CIEData> cie1964Observer10Degree5nmData() {
return read(cie1964Observer10Degree5nmFile());
}
public static List<CIEData> cie1964Observer10Degree5nmData(ColorSpace cs) {
try {
List<CIEData> data = cie1964Observer10Degree5nmData();
for (CIEData d : data) {
d.convert(cs);
d.scaleValues();
}
return data;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static float[] convert(CIEData d, String iccProfile) {
try {
ICC_ColorSpace cs = new ICC_ColorSpace(ICC_Profile.getInstance(iccProfile));
return convert(d, cs);
} catch (Exception e) {
return null;
}
}
public static float[] convert(CIEData d, ICC_Profile iccProfile) {
try {
ICC_ColorSpace cs = new ICC_ColorSpace(iccProfile);
return convert(d, cs);
} catch (Exception e) {
return null;
}
}
public static float[] convert(CIEData d, ICC_ColorSpace cs) {
float[] fxyz = new float[3];
float[] outputs;
fxyz[0] = (float) d.getRelativeX();
fxyz[1] = (float) d.getRelativeY();
fxyz[2] = (float) d.getRelativeZ();
outputs = cs.fromCIEXYZ(fxyz);
return outputs;
}
// https://www.w3.org/TR/css-color-4/#lab-to-rgb
// http://brucelindbloom.com/index.html?Eqn_ChromAdapt.html
// http://brucelindbloom.com/index.html?Eqn_ChromAdapt.html
/*
Source data: CIE standard Observer functions and CIE D50 Reference Illuminant
*/
public static double[] convert(ColorSpace cs, CIEData d) {
double[] xyz = ColorBase.array(d.getRelativeX(), d.getRelativeY(), d.getRelativeZ());
float[] fxyz = cs.fromCIEXYZ(ColorBase.arrayFloat(xyz));
double[] outputs = clipRGB(arrayDouble(fxyz));
return outputs;
}
public static double[] sRGB65(CIEData d) {
double[] xyz = ColorBase.array(d.getRelativeX(), d.getRelativeY(), d.getRelativeZ());
return CIEColorSpace.XYZd50toSRGBd65(xyz);
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/SRGB.java | released/MyBox/src/main/java/mara/mybox/color/SRGB.java | package mara.mybox.color;
import java.awt.Color;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import static mara.mybox.color.AppleRGB.XYZtoAppleRGB;
import static mara.mybox.color.RGBColorSpace.linearSRGB;
import mara.mybox.fxml.image.FxColorTools;
import mara.mybox.image.data.ImageColorSpace;
import mara.mybox.image.tools.ColorConvertTools;
import mara.mybox.tools.DoubleMatrixTools;
/**
* @Author Mara
* @CreateDate 2019-5-21 12:07:33
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class SRGB {
/*
static methods
*/
public static double[] gammaSRGB(double[] linearRGB) {
double[] srgb = new double[3];
srgb[0] = RGBColorSpace.gammaSRGB(linearRGB[0]);
srgb[1] = RGBColorSpace.gammaSRGB(linearRGB[1]);
srgb[2] = RGBColorSpace.gammaSRGB(linearRGB[2]);
return srgb;
}
public static double[] SRGBtoLinearSRGB(double[] sRGB) {
double[] linearRGB = new double[3];
linearRGB[0] = linearSRGB(sRGB[0]);
linearRGB[1] = linearSRGB(sRGB[1]);
linearRGB[2] = linearSRGB(sRGB[2]);
return linearRGB;
}
public static double[] SRGBd50toXYZd50(double[] srgb) {
double[] linearRGB = SRGBtoLinearSRGB(srgb);
double[][] matrix = {
{0.436065673828125, 0.3851470947265625, 0.14306640625},
{0.2224884033203125, 0.7168731689453125, 0.06060791015625},
{0.013916015625, 0.097076416015625, 0.7140960693359375}
};
double[] xyz = DoubleMatrixTools.multiply(matrix, linearRGB);
return xyz;
}
public static double[] SRGBtoXYZd65(Color color) {
return SRGBd65toXYZd65(ColorBase.array(color));
}
public static double[] SRGBd65toXYZd65(double[] srgb) {
double[] linearRGB = SRGBtoLinearSRGB(srgb);
double[][] matrix = {
{0.4124564, 0.3575761, 0.1804375},
{0.2126729, 0.7151522, 0.0721750},
{0.0193339, 0.1191920, 0.9503041}
};
double[] xyz = DoubleMatrixTools.multiply(matrix, linearRGB);
return xyz;
}
public static double[] SRGBtoXYZd50(Color color) {
return SRGBd65toXYZd50(color);
}
// public static double[] SRGBd65toXYZd50(Color color) {
// ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
// float[] xyzD50 = cs.toCIEXYZ(ColorBase.arrayFloat(color));
// return ColorBase.arrayDouble(xyzD50);
// }
//
public static double[] SRGBd65toXYZd50(Color color) {
return SRGBd65toXYZd50(ColorBase.array(color));
}
public static double[] SRGBd65toXYZd50(double[] srgb) {
double[] xyzD65 = SRGBd65toXYZd65(srgb);
return ChromaticAdaptation.D65toD50(xyzD65);
}
public static double[] SRGBtoAdobeRGB(double[] srgb) {
double[] xyz = SRGBd65toXYZd65(srgb);
return CIEColorSpace.XYZd65toAdobeRGBd65(xyz);
}
public static double[] SRGBtoAppleRGB(double[] srgb) {
double[] xyz = SRGBd65toXYZd65(srgb);
return XYZtoAppleRGB(xyz);
}
public static double[] SRGBtoCIELab(Color color) {
double[] xyzD50 = SRGBd65toXYZd50(color);
return CIEColorSpace.XYZd50toCIELab(xyzD50[0], xyzD50[1], xyzD50[2]);
}
public static float[] srgb2profile(ICC_Profile profile, Color color) {
return srgb2profile(profile, ColorConvertTools.color2srgb(color));
}
public static float[] srgb2profile(ICC_Profile profile, javafx.scene.paint.Color color) {
return srgb2profile(profile, FxColorTools.color2srgb(color));
}
public static float[] srgb2profile(ICC_Profile profile, float[] srgb) {
if (profile == null) {
profile = ImageColorSpace.eciCmykProfile();
}
ICC_ColorSpace colorSpace = new ICC_ColorSpace(profile);
return colorSpace.fromRGB(srgb);
}
// http://www.easyrgb.com/en/math.php
public static double[] rgb2cmy(javafx.scene.paint.Color color) {
double[] cmy = new double[3];
cmy[0] = 1 - color.getRed();
cmy[1] = 1 - color.getGreen();
cmy[2] = 1 - color.getBlue();
return cmy;
}
public static double[] rgb2cmy(Color color) {
double[] cmy = new double[3];
cmy[0] = 1 - color.getRed() / 255d;
cmy[1] = 1 - color.getGreen() / 255d;
cmy[2] = 1 - color.getBlue() / 255d;
return cmy;
}
public static double[] rgb2cmyk(javafx.scene.paint.Color color) {
return CMYKColorSpace.cmy2cmky(rgb2cmy(color));
}
public static double[] rgb2cmyk(Color color) {
return CMYKColorSpace.cmy2cmky(rgb2cmy(color));
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/CMYKColorSpace.java | released/MyBox/src/main/java/mara/mybox/color/CMYKColorSpace.java | package mara.mybox.color;
import java.util.ArrayList;
import java.util.List;
/**
* @Author Mara
* @CreateDate 2019-6-7 9:38:03
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class CMYKColorSpace {
public static enum ColorSpaceType {
CMY, CMYK
}
public static List<String> names() {
List<String> names = new ArrayList<>();
for (ColorSpaceType cs : ColorSpaceType.values()) {
names.add(cs + "");
}
return names;
}
public static double[] cmy2cmky(double[] cmy) {
double[] cmyk = new double[4];
cmyk[0] = cmy[0];
cmyk[1] = cmy[1];
cmyk[2] = cmy[2];
cmyk[3] = 1;
if (cmyk[0] < cmyk[3]) {
cmyk[3] = cmyk[0];
}
if (cmyk[1] < cmyk[3]) {
cmyk[3] = cmyk[1];
}
if (cmyk[2] < cmyk[3]) {
cmyk[3] = cmyk[2];
}
if (cmyk[3] == 1) {
cmyk[0] = 0;
cmyk[1] = 0;
cmyk[2] = 0;
} else {
cmyk[0] = (cmyk[0] - cmyk[3]) / (1 - cmyk[3]);
cmyk[1] = (cmyk[1] - cmyk[3]) / (1 - cmyk[3]);
cmyk[2] = (cmyk[2] - cmyk[3]) / (1 - cmyk[3]);
}
return cmyk;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/ColorMatch.java | released/MyBox/src/main/java/mara/mybox/color/ColorMatch.java | package mara.mybox.color;
import java.awt.Color;
import java.util.List;
import static mara.mybox.color.SRGB.SRGBtoCIELab;
import mara.mybox.image.tools.ColorConvertTools;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2025-2-7
* @License Apache License Version 2.0
*/
public class ColorMatch {
private double threshold, realThreshold;
protected double brightnessWeight, saturationWeight, hueWeight;
private boolean accurateMatch;
protected MatchAlgorithm algorithm;
public final static MatchAlgorithm DefaultAlgorithm = MatchAlgorithm.RGBRoughWeightedEuclidean;
public static enum MatchAlgorithm {
CIEDE2000, CIE94, CIE76,
HSBEuclidean, Hue, Saturation, Brightness,
RGBEuclidean, RGBRoughWeightedEuclidean, RGBWeightedEuclidean,
RGBManhattan,
Red, Green, Blue,
CMC
}
public ColorMatch() {
init();
}
public final void init() {
algorithm = DefaultAlgorithm;
setThreshold(suggestedThreshold(algorithm));
brightnessWeight = 1d;
saturationWeight = 1d;
hueWeight = 1d;
}
public ColorMatch copyTo(ColorMatch match) {
if (match == null) {
return match;
}
match.setAlgorithm(algorithm);
match.setThreshold(threshold);
match.setHueWeight(hueWeight);
match.setBrightnessWeight(brightnessWeight);
match.setSaturationWeight(saturationWeight);
return match;
}
public String info() {
return "Algorithm :" + algorithm + "\n"
+ "threshold :" + threshold + "\n"
+ "hueWeight :" + hueWeight + "\n"
+ "brightnessWeight :" + brightnessWeight + "\n"
+ "saturationWeight :" + saturationWeight;
}
/*
parameters
*/
public final ColorMatch setThreshold(double value) {
threshold = value;
accurateMatch = threshold < 1e-10;
switch (algorithm) {
case RGBRoughWeightedEuclidean:
case RGBWeightedEuclidean:
case RGBEuclidean:
case HSBEuclidean:
case CIEDE2000:
case CIE94:
case CIE76:
case CMC:
realThreshold = accurateMatch ? 1e-10 : threshold * threshold;
break;
case Red:
case Green:
case Blue:
case Hue:
case Saturation:
case Brightness:
case RGBManhattan:
realThreshold = threshold;
break;
}
return this;
}
public static double suggestedThreshold(MatchAlgorithm a) {
switch (a) {
case RGBRoughWeightedEuclidean:
return 20d;
case RGBWeightedEuclidean:
return 20d;
case RGBEuclidean:
return 20d;
case CIEDE2000:
return 5d;
case CIE94:
return 5d;
case CIE76:
return 5d;
case CMC:
return 5d;
case HSBEuclidean:
return 20d;
case Red:
case Green:
case Blue:
return 20d;
case Hue:
return 20d;
case Saturation:
return 20d;
case Brightness:
return 20d;
case RGBManhattan:
return 20d;
}
return 20d;
}
public static boolean supportWeights(MatchAlgorithm a) {
switch (a) {
case RGBRoughWeightedEuclidean:
case RGBWeightedEuclidean:
case RGBEuclidean:
case Red:
case Green:
case Blue:
case Hue:
case Saturation:
case Brightness:
case RGBManhattan:
case CIE76:
return false;
case CIEDE2000:
case CIE94:
case HSBEuclidean:
case CMC:
return true;
}
return false;
}
public static MatchAlgorithm algorithm(String as) {
try {
for (MatchAlgorithm a : MatchAlgorithm.values()) {
if (Languages.matchIgnoreCase(a.name(), as)) {
return a;
}
}
} catch (Exception e) {
}
return DefaultAlgorithm;
}
public boolean setColorWeights(String weights) {
try {
String[] values = weights.split(":");
hueWeight = Double.parseDouble(values[0]);
saturationWeight = Double.parseDouble(values[1]);
brightnessWeight = Double.parseDouble(values[2]);
return true;
} catch (Exception e) {
return false;
}
}
public String getColorWeights() {
return hueWeight + ":" + saturationWeight + ":" + brightnessWeight;
}
/*
match
*/
public boolean isMatch(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return false;
}
if (color1.getRGB() == color2.getRGB()) {
return true;
} else if (accurateMatch || color1.getRGB() == 0 || color2.getRGB() == 0) {
return false;
}
return distance(color1, color2) <= realThreshold;
}
public boolean isMatchColors(List<Color> colors, Color color, boolean excluded) {
if (colors == null || colors.isEmpty()) {
return true;
}
if (excluded) {
for (Color oColor : colors) {
if (isMatch(color, oColor)) {
return false;
}
}
return true;
} else {
for (Color oColor : colors) {
if (isMatch(color, oColor)) {
return true;
}
}
return false;
}
}
/*
distance
*/
public double distance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Integer.MAX_VALUE;
}
switch (algorithm) {
case RGBRoughWeightedEuclidean:
return rgbRoughWeightedEuclideanDistance(color1, color2);
case RGBWeightedEuclidean:
return rgbWeightEuclideanDistance(color1, color2);
case RGBEuclidean:
return rgbEuclideanDistance(color1, color2);
case Red:
return redDistance(color1, color2);
case Green:
return greenDistance(color1, color2);
case Blue:
return blueDistance(color1, color2);
case RGBManhattan:
return manhattanDistance(color1, color2);
case CIEDE2000:
return ciede2000Distance(color1, color2);
case CIE94:
return cie94Distance(color1, color2);
case CIE76:
return cie76Distance(color1, color2);
case CMC:
return cmcDistance(color1, color2);
case HSBEuclidean:
return hsbEuclideanDistance(color1, color2);
case Hue:
return hueDistance(color1, color2);
case Saturation:
return saturationDistance(color1, color2);
case Brightness:
return brightnessDistance(color1, color2);
}
return Integer.MAX_VALUE;
}
public static double rgbEuclideanDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
int redDistance = color1.getRed() - color2.getRed();
int greenDistance = color1.getGreen() - color2.getGreen();
int blueDistance = color1.getBlue() - color2.getBlue();
return redDistance * redDistance
+ greenDistance * greenDistance
+ blueDistance * blueDistance;
}
// https://www.compuphase.com/cmetric.htm
public static double rgbWeightEuclideanDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
int redDistance = color1.getRed() - color2.getRed();
int greenDistance = color1.getGreen() - color2.getGreen();
int blueDistance = color1.getBlue() - color2.getBlue();
int redAvg = (color1.getRed() + color2.getRed()) / 2;
return Math.round(((512 + redAvg) * redDistance * redDistance) >> 8
+ 4 * greenDistance * greenDistance
+ ((767 - redAvg) * blueDistance * blueDistance) >> 8);
}
// https://en.wikipedia.org/wiki/Color_difference
public static double rgbRoughWeightedEuclideanDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
int redDistance = color1.getRed() - color2.getRed();
int greenDistance = color1.getGreen() - color2.getGreen();
int blueDistance = color1.getBlue() - color2.getBlue();
return 2 * redDistance * redDistance
+ 4 * greenDistance * greenDistance
+ 3 * blueDistance * blueDistance;
}
public static double manhattanDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
return Math.abs(color1.getRed() - color2.getRed())
+ Math.abs(color1.getGreen() - color2.getGreen())
+ Math.abs(color1.getBlue() - color2.getBlue());
}
public static double redDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
return Math.abs(color1.getRed() - color2.getRed());
}
public static double greenDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
return Math.abs(color1.getGreen() - color2.getGreen());
}
public static double blueDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
return Math.abs(color1.getBlue() - color2.getBlue());
}
public double hsbEuclideanDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
float[] hsb1 = ColorConvertTools.color2hsb(color1);
float[] hsb2 = ColorConvertTools.color2hsb(color2);
double hueDistance = Math.abs(hsb1[0] * 360 - hsb2[0] * 360);
hueDistance = Math.min(hueDistance, 360 - hueDistance) / 1.8;
double saturationDistance = Math.ceil(Math.abs(hsb1[1] - hsb2[1]) * 100);
double brightnessDistance = Math.ceil(Math.abs(hsb1[2] - hsb2[2]) * 100);
return hueWeight * hueDistance * hueDistance
+ saturationWeight * saturationDistance * saturationDistance
+ brightnessWeight * brightnessDistance * brightnessDistance;
}
public static double hueDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
return Math.abs(ColorConvertTools.getHue(color1) - ColorConvertTools.getHue(color2)) * 360;
}
public static double saturationDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
return Math.abs(ColorConvertTools.getSaturation(color1) - ColorConvertTools.getSaturation(color2)) * 100;
}
public static double brightnessDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
return Math.abs(ColorConvertTools.getBrightness(color1) - ColorConvertTools.getBrightness(color2)) * 100;
}
public static double cie76Distance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
double[] lab1 = SRGBtoCIELab(color1);
double[] lab2 = SRGBtoCIELab(color2);
double lDistance = lab1[0] - lab2[0];
double aDistance = lab1[1] - lab2[1];
double bDistance = lab1[2] - lab2[2];
return lDistance * lDistance + aDistance * aDistance + bDistance * bDistance;
}
public double cie94Distance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
double[] lab1 = SRGBtoCIELab(color1);
double[] lab2 = SRGBtoCIELab(color2);
double L1 = lab1[0];
double a1 = lab1[1];
double b1 = lab1[2];
double L2 = lab2[0];
double a2 = lab2[1];
double b2 = lab2[2];
// Following lines are generated by DeepSeek
// 计算亮度差
double deltaL = L1 - L2;
// 计算色度C
double C1 = Math.sqrt(a1 * a1 + b1 * b1);
double C2 = Math.sqrt(a2 * a2 + b2 * b2);
double deltaC = C1 - C2;
// 计算色调差ΔH
double deltaH = Math.sqrt(Math.pow(a1 - a2, 2) + Math.pow(b1 - b2, 2) - Math.pow(deltaC, 2));
// 计算权重因子
double SL = 1.0; // 亮度权重因子
double SC = 1.0 + 0.045 * (C1 + C2) / 2.0; // 色度权重因子
double SH = 1.0 + 0.015 * (C1 + C2) / 2.0; // 色调权重因子
// 计算CIE94色差
double term1 = deltaL / (brightnessWeight * SL);
double term2 = deltaC / (saturationWeight * SC);
double term3 = deltaH / (hueWeight * SH);
// Avoid "sqrt"
return term1 * term1 + term2 * term2 + term3 * term3;
}
public double ciede2000Distance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
double[] lab1 = SRGBtoCIELab(color1);
double[] lab2 = SRGBtoCIELab(color2);
double L1 = lab1[0];
double a1 = lab1[1];
double b1 = lab1[2];
double L2 = lab2[0];
double a2 = lab2[1];
double b2 = lab2[2];
// Following lines are generated by DeepSeek
// 步骤1: 计算色度C和色调角h
double C1 = Math.sqrt(a1 * a1 + b1 * b1);
double C2 = Math.sqrt(a2 * a2 + b2 * b2);
double C_avg = (C1 + C2) / 2.0;
// 步骤2: 计算G因子(色度非线性补偿)
double G = 0.5 * (1 - Math.sqrt(Math.pow(C_avg, 7) / (Math.pow(C_avg, 7) + Math.pow(25, 7))));
double a1_prime = a1 * (1 + G);
double a2_prime = a2 * (1 + G);
// 更新色度C'
C1 = Math.sqrt(a1_prime * a1_prime + b1 * b1);
C2 = Math.sqrt(a2_prime * a2_prime + b2 * b2);
// 步骤3: 计算色调角差Δh'
double h1 = Math.toDegrees(Math.atan2(b1, a1_prime));
if (h1 < 0) {
h1 += 360;
}
double h2 = Math.toDegrees(Math.atan2(b2, a2_prime));
if (h2 < 0) {
h2 += 360;
}
double delta_h_prime;
if (Math.abs(h2 - h1) <= 180) {
delta_h_prime = h2 - h1;
} else {
delta_h_prime = (h2 - h1 > 180) ? (h2 - h1 - 360) : (h2 - h1 + 360);
}
// 步骤4: 计算色调平均H'
double H_prime_avg = (Math.abs(h1 - h2) > 180) ? ((h1 + h2 + 360) / 2.0) : ((h1 + h2) / 2.0);
// 步骤5: 补偿因子计算
double T = 1 - 0.17 * Math.cos(Math.toRadians(H_prime_avg - 30))
+ 0.24 * Math.cos(Math.toRadians(2 * H_prime_avg))
+ 0.32 * Math.cos(Math.toRadians(3 * H_prime_avg + 6))
- 0.20 * Math.cos(Math.toRadians(4 * H_prime_avg - 63));
double delta_L_prime = L2 - L1;
double delta_C_prime = C2 - C1;
double delta_H_prime = 2 * Math.sqrt(C1 * C2) * Math.sin(Math.toRadians(delta_h_prime / 2.0));
// 步骤6: 权重因子
double SL = 1 + (0.015 * Math.pow((L1 + L2) / 2.0 - 50, 2)) / Math.sqrt(20 + Math.pow((L1 + L2) / 2.0 - 50, 2));
double SC = 1 + 0.045 * ((C1 + C2) / 2.0);
double SH = 1 + 0.015 * ((C1 + C2) / 2.0) * T;
// 步骤7: 旋转因子RT
double delta_theta = 30 * Math.exp(-Math.pow((H_prime_avg - 275) / 25, 2));
double RT = -2 * Math.sqrt(Math.pow(C_avg, 7) / (Math.pow(C_avg, 7) + Math.pow(25, 7))) * Math.sin(Math.toRadians(2 * delta_theta));
// 最终计算ΔE00
double term1 = delta_L_prime / (brightnessWeight * SL);
double term2 = delta_C_prime / (saturationWeight * SC);
double term3 = delta_H_prime / (hueWeight * SH);
// Avoid "sqrt"
return term1 * term1 + term2 * term2 + term3 * term3 + RT * term2 * term3;
}
public double cmcDistance(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Double.MAX_VALUE;
}
double[] lab1 = SRGBtoCIELab(color1);
double[] lab2 = SRGBtoCIELab(color2);
double L1 = lab1[0];
double a1 = lab1[1];
double b1 = lab1[2];
double L2 = lab2[0];
double a2 = lab2[1];
double b2 = lab2[2];
// Following lines are generated by DeepSeek
// 计算 C1 和 C2
double C1 = Math.sqrt(a1 * a1 + b1 * b1);
double C2 = Math.sqrt(a2 * a2 + b2 * b2);
// 计算 ΔL, ΔC, ΔH
double deltaL = L2 - L1;
double deltaC = C2 - C1;
double deltaH = Math.sqrt(Math.pow(a2 - a1, 2) + Math.pow(b2 - b1, 2) - Math.pow(deltaC, 2));
// 计算 h1(色相)
double h1 = Math.toDegrees(Math.atan2(b1, a1));
if (h1 < 0) {
h1 += 360; // 确保色相在 [0, 360] 范围内
}
// 计算 S_L, S_C
double S_L = L1 < 16 ? 0.511 : (0.040975 * L1) / (1 + 0.01765 * L1);
double S_C = (0.0638 * C1) / (1 + 0.0131 * C1) + 0.638;
// 计算 T
double F = Math.sqrt(Math.pow(C1, 4) / (Math.pow(C1, 4) + 1900));
double T = F == 0 ? 1 : (0.56 + Math.abs(0.2 * Math.cos(Math.toRadians(h1 + 168))));
// 计算 ΔE*cmc
double termL = deltaL / (brightnessWeight * S_L);
double termC = deltaC / (saturationWeight * S_C);
double termH = deltaH / (S_C * T);
// Avoid "sqrt"
return termL * termL + termC * termC + termH * termH;
}
/*
get/set
*/
public double getThreshold() {
return threshold;
}
public double getRealThreshold() {
return realThreshold;
}
public MatchAlgorithm getAlgorithm() {
if (algorithm == null) {
algorithm = DefaultAlgorithm;
}
return algorithm;
}
public ColorMatch setAlgorithm(MatchAlgorithm algorithm) {
if (algorithm != null) {
this.algorithm = algorithm;
}
return this;
}
public double getBrightnessWeight() {
return brightnessWeight;
}
public ColorMatch setBrightnessWeight(double brightnessWeight) {
this.brightnessWeight = brightnessWeight;
return this;
}
public double getSaturationWeight() {
return saturationWeight;
}
public ColorMatch setSaturationWeight(double saturationWeight) {
this.saturationWeight = saturationWeight;
return this;
}
public double getHueWeight() {
return hueWeight;
}
public ColorMatch setHueWeight(double hueWeight) {
this.hueWeight = hueWeight;
return this;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/ColorConversion.java | released/MyBox/src/main/java/mara/mybox/color/ColorConversion.java | package mara.mybox.color;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2019-5-21 12:26:36
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class ColorConversion {
public enum SpaceType {
RGB, CIE, CMYK, Others
}
public enum RangeType {
Normalized, RGB, Hundred
}
public static BufferedImage sRGB(BufferedImage source, int colorSpace) {
ICC_ColorSpace iccColorSpace = new ICC_ColorSpace(ICC_Profile.getInstance(ColorSpace.CS_sRGB));
ColorConvertOp converter = new ColorConvertOp(iccColorSpace, null);
BufferedImage target = converter.filter(source, null);
return target;
}
public static BufferedImage convertColorSpace(BufferedImage source, int colorSpace) {
ICC_Profile profile = ICC_Profile.getInstance(colorSpace);
ICC_ColorSpace iccColorSpace = new ICC_ColorSpace(profile);
ColorConvertOp converter = new ColorConvertOp(iccColorSpace, null);
BufferedImage target = converter.filter(source, null);
return target;
}
public static BufferedImage convertColorSpace(BufferedImage source, String iccFile) {
try {
ICC_Profile profile = ICC_Profile.getInstance(iccFile);
ICC_ColorSpace iccColorSpace = new ICC_ColorSpace(profile);
ColorConvertOp converter = new ColorConvertOp(iccColorSpace, null);
BufferedImage target = converter.filter(source, null);
return target;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static float[] fromSRGB(int colorSpace, float[] srgb) {
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
float[] xyz = cs.toCIEXYZ(srgb);
cs = ColorSpace.getInstance(colorSpace);
float[] rgb = cs.fromCIEXYZ(xyz);
return rgb;
}
public static float[] toSRGB(int colorSpace, float[] rgb) {
ColorSpace cs = ColorSpace.getInstance(colorSpace);
float[] xyz = cs.toCIEXYZ(rgb);
cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
float[] srgb = cs.fromCIEXYZ(xyz);
return srgb;
}
public static float[] SRGBtoXYZ(float[] srgb) {
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
float[] xyz = cs.toCIEXYZ(srgb);
return xyz;
}
public static float[] XYZtoSRGB(float[] xyz) {
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
float[] srgb = cs.fromCIEXYZ(xyz);
return srgb;
}
// http://what-when-how.com/introduction-to-video-and-image-processing/conversion-between-rgb-and-yuvycbcr-introduction-to-video-and-image-processing
/*
YUV
Y: 0~255 U: -111~111 V: -157~157
*/
public static float[] RGBtoYUV(float[] rgb) {
float[] yuv = new float[3];
yuv[0] = 0.299f * rgb[0] + 0.587f * rgb[1] + 0.114f * rgb[2];
yuv[1] = 0.492f * (rgb[2] - yuv[0]);
yuv[2] = 0.877f * (rgb[0] - yuv[0]);
return yuv;
}
public static float[] YUVtoRGB(float[] yuv) {
float[] rgb = new float[3];
rgb[0] = yuv[0] + 1.140f * yuv[2];
rgb[1] = yuv[0] - 0.395f * yuv[1] - 0.581f * yuv[2];
rgb[2] = yuv[0] + 2.032f * yuv[1];
return rgb;
}
public static double[] RGBtoYUV(double[] rgb) {
double[] yuv = new double[3];
yuv[0] = 0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2];
yuv[1] = 0.492 * (rgb[2] - yuv[0]);
yuv[2] = 0.877 * (rgb[0] - yuv[0]);
return yuv;
}
public static double[] YUVtoRGB(double[] yuv) {
double[] rgb = new double[3];
rgb[0] = yuv[0] + 1.140 * yuv[2];
rgb[1] = yuv[0] - 0.395 * yuv[1] - 0.581 * yuv[2];
rgb[2] = yuv[0] + 2.032 * yuv[1];
return rgb;
}
// https://wolfcrow.com/whats-the-difference-between-yuv-yiq-ypbpr-and-ycbcr/
/*
YCbCr
Y: 0~255 Cb: 0~255 Cr: 0~255
*/
public static float[] RGBtoYCrCb(float[] rgb) {
float[] YCbCr = new float[3];
float offset = 128f / 255;
YCbCr[0] = 0.299f * rgb[0] + 0.578f * rgb[1] + 0.114f * rgb[2];
YCbCr[1] = -0.1687f * rgb[0] - 0.3313f * rgb[1] + 0.500f * rgb[2] + offset;
YCbCr[2] = 0.500f * rgb[0] - 0.4187f * rgb[1] - 0.0813f * rgb[2] + offset;
return YCbCr;
}
public static float[] YCrCbtoRGB(float[] YCbCr) {
float[] rgb = new float[3];
float offset = 128f / 255;
rgb[0] = YCbCr[0] + 1.4020f * (YCbCr[2] - offset);
rgb[1] = YCbCr[0] - 0.3441f * (YCbCr[1] - offset) - 0.7141f * (YCbCr[2] - offset);
rgb[2] = YCbCr[0] + 1.7720f * (YCbCr[1] - offset);
return rgb;
}
public static double[] RGBtoYCrCb(double[] rgb) {
double[] YCbCr = new double[3];
double offset = 128d / 255;
YCbCr[0] = 0.299 * rgb[0] + 0.578 * rgb[1] + 0.114 * rgb[2];
YCbCr[1] = -0.1687 * rgb[0] - 0.3313 * rgb[1] + 0.500 * rgb[2] + offset;
YCbCr[2] = 0.500 * rgb[0] - 0.4187 * rgb[1] - 0.0813 * rgb[2] + offset;
return YCbCr;
}
public static double[] YCrCbtoRGB(double[] YCbCr) {
double[] rgb = new double[3];
double offset = 128d / 255;
rgb[0] = YCbCr[0] + 1.4020 * (YCbCr[2] - offset);
rgb[1] = YCbCr[0] - 0.3441 * (YCbCr[1] - offset) - 0.7141 * (YCbCr[2] - offset);
rgb[2] = YCbCr[0] + 1.7720 * (YCbCr[1] - offset);
return rgb;
}
/*
Yxy
*/
public static float[] XYZtoYXY(float[] xyz) {
float x = xyz[0];
float y = xyz[1];
float z = xyz[2];
float[] Yxy = new float[3];
Yxy[0] = y;
Yxy[1] = x / (x + y + z);
Yxy[2] = y / (x + y + z);
return Yxy;
}
public static float[] YXYtoXYZ(float[] Yxy) {
float Y = Yxy[0];
float x = Yxy[1];
float y = Yxy[2];
float[] xyz = new float[3];
xyz[0] = x * (Y / y);
xyz[1] = Y;
xyz[2] = (1 - x - y) * (Y / y);
return xyz;
}
public static double[] XYZtoYXY(double[] xyz) {
double x = xyz[0];
double y = xyz[1];
double z = xyz[2];
double[] Yxy = new double[3];
Yxy[0] = y;
Yxy[1] = x / (x + y + z);
Yxy[2] = y / (x + y + z);
return Yxy;
}
public static double[] YXYtoXYZ(double[] Yxy) {
double Y = Yxy[0];
double x = Yxy[1];
double y = Yxy[2];
double[] xyz = new double[3];
xyz[0] = x * (Y / y);
xyz[1] = Y;
xyz[2] = (1 - x - y) * (Y / y);
return xyz;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/IccTag.java | released/MyBox/src/main/java/mara/mybox/color/IccTag.java | package mara.mybox.color;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static mara.mybox.color.IccTagType.XYZ;
import static mara.mybox.color.IccTagType.XYZDoubles;
import static mara.mybox.color.IccTagType.XYZNumber;
import static mara.mybox.color.IccTagType.XYZNumberDoubles;
import static mara.mybox.color.IccTagType.curve;
import static mara.mybox.color.IccTagType.curveDoubles;
import static mara.mybox.color.IccTagType.dateTime;
import static mara.mybox.color.IccTagType.geometryType;
import static mara.mybox.color.IccTagType.illuminantType;
import static mara.mybox.color.IccTagType.lut;
import static mara.mybox.color.IccTagType.measurement;
import static mara.mybox.color.IccTagType.multiLocalizedUnicode;
import static mara.mybox.color.IccTagType.observerType;
import static mara.mybox.color.IccTagType.s15Fixed16Array;
import static mara.mybox.color.IccTagType.s15Fixed16ArrayDoubles;
import static mara.mybox.color.IccTagType.signature;
import static mara.mybox.color.IccTagType.text;
import static mara.mybox.color.IccTagType.u16Fixed16Number;
import static mara.mybox.color.IccTagType.viewingConditions;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.value.AppValues;
/**
* @Author Mara
* @CreateDate 2019-5-7 16:11:08
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class IccTag {
private String tag, name, description;
private int offset, size;
private Object value;
private byte[] bytes;
private TagType type;
private List<String> valueSelection, arrayNames;
private boolean isHeaderField, editable, selectionEditable, changed, first4ascii, normalizeLut;
public static enum TagType {
Text, MultiLocalizedUnicode, Int, Double, XYZ, Curve, ViewingConditions,
Measurement, Signature, S15Fixed16Array, DateTime, LUT, Boolean, Bytes, BooleanArray
}
public IccTag(String tag, int offset, byte[] bytes, boolean normalizeLut) {
this.tag = tag;
this.offset = offset;
this.bytes = bytes;
this.normalizeLut = normalizeLut;
name = tagName(tag);
description = tagDescription(name);
type = tagType(tag);
value = tagValue(this.type, bytes, normalizeLut);
valueSelection = tagSelection(tag);
changed = false;
isHeaderField = false;
selectionEditable = false;
editable = false;
}
public IccTag(String tag, int offset, byte[] bytes,
TagType type, Object value) {
this.tag = tag;
this.offset = offset;
this.bytes = bytes;
this.name = tag;
this.description = tag;
this.type = type;
this.value = value;
this.valueSelection = null;
this.selectionEditable = false;
this.isHeaderField = true;
this.editable = true;
changed = false;
}
public IccTag(String tag, int offset, byte[] bytes,
TagType type, Object value,
List<String> valueSelection, boolean selectionEditable) {
this.tag = tag;
this.offset = offset;
this.bytes = bytes;
this.name = tag;
this.description = tag;
this.type = type;
this.value = value;
this.valueSelection = valueSelection;
this.selectionEditable = selectionEditable;
this.isHeaderField = true;
this.editable = true;
changed = false;
}
public String display() {
try {
if (valueSelection != null) {
String v = (String) value;
for (String s : valueSelection) {
if (s.startsWith(v)) {
return s;
}
}
}
return tagDisplay(type, value);
} catch (Exception e) {
return null;
}
}
public boolean update(String newValue) {
return update(this, newValue);
}
public boolean update(String key, String newValue) {
if (key == null) {
return update(newValue);
}
switch (type) {
case ViewingConditions:
switch (key.toLowerCase()) {
case "illuminant":
return updateViewingConditionsIlluminant(this, newValue);
case "surround":
return updateViewingConditionsSurround(this, newValue);
case "illuminanttype":
return updateViewingConditionsType(this, newValue);
}
case Measurement:
switch (key.toLowerCase()) {
case "observer":
return updateMeasurementObserver(this, newValue);
case "tristimulus":
return updateMeasurementTristimulus(this, newValue);
case "geometry":
return updateMeasurementGeometry(this, newValue);
case "flare":
return updateMeasurementFlare(this, newValue);
case "illuminanttype":
return updateMeasurementType(this, newValue);
}
}
return update(this, newValue);
}
/*
Decode tag
*/
public static String tagName(String tag) {
for (String[] item : tagNames) {
if (item[0].equals(tag)) {
return item[1];
}
}
return tag;
}
public static String tagDescription(String tagName) {
for (String[] item : tagDescriptions) {
if (item[0].equals(tagName)) {
return item[1];
}
}
return "";
}
public static TagType tagType(String tag) {
if (tag == null) {
return null;
}
switch (tag) {
case "desc":
case "dmnd":
case "dmdd":
case "vued":
return TagType.MultiLocalizedUnicode;
case "cprt":
return TagType.Text;
case "wtpt":
case "bkpt":
case "rXYZ":
case "gXYZ":
case "bXYZ":
case "lumi":
return TagType.XYZ;
case "rTRC":
case "gTRC":
case "bTRC":
case "kTRC":
return TagType.Curve;
case "view":
return TagType.ViewingConditions;
case "meas":
return TagType.Measurement;
case "tech":
return TagType.Signature;
case "chad":
return TagType.S15Fixed16Array;
case "calt":
return TagType.DateTime;
case "A2B0":
case "A2B1":
case "A2B2":
case "B2A0":
case "B2A1":
case "B2A2":
case "gamt":
return TagType.LUT;
}
return null;
}
public static Object tagValue(TagType type, byte[] bytes, boolean normalizeLut) {
if (type == null || bytes == null) {
return null;
}
switch (type) {
case MultiLocalizedUnicode:
return multiLocalizedUnicode(bytes);
case Text:
return text(bytes);
case XYZ:
return XYZ(bytes);
case Curve:
return curve(bytes);
case ViewingConditions:
return viewingConditions(bytes);
case Measurement:
return measurement(bytes);
case Signature:
return signature(bytes);
case S15Fixed16Array:
return s15Fixed16Array(bytes);
case DateTime:
return dateTime(bytes);
case LUT:
return lut(bytes, normalizeLut);
}
return null;
}
public static List<String> tagSelection(String tag) {
switch (tag) {
case "tech":
return technologyTypes();
}
return null;
}
public static String tagDisplay(TagType type, Object value) {
if (type == null || value == null) {
return "";
}
String display;
try {
switch (type) {
case Text:
case Signature:
case DateTime:
display = value + "";
break;
case MultiLocalizedUnicode:
display = IccTagType.textDescriptionDisplay((Map<String, Object>) value);
break;
case XYZ:
display = IccTagType.XYZNumberDisplay((double[][]) value);
break;
case Curve:
display = IccTagType.curveDisplay((double[]) value);
break;
case ViewingConditions:
display = IccTagType.viewingConditionsDisplay((Map<String, Object>) value);
break;
case Measurement:
display = IccTagType.measurementDisplay((Map<String, Object>) value);
break;
case S15Fixed16Array:
display = IccTagType.s15Fixed16ArrayDisplay((double[]) value);
break;
case LUT:
display = IccTagType.lutDisplay((Map<String, Object>) value);
break;
default:
display = value + "";
}
} catch (Exception e) {
display = value + "";
}
return display;
}
/*
Encode tag
*/
public static boolean update(IccTag tag, String newValue) {
try {
byte[] bytes = null;
Object value = null;
switch (tag.getType()) {
case Text: {
value = newValue;
bytes = text(newValue);
break;
}
case MultiLocalizedUnicode:
bytes = multiLocalizedUnicode(tag, newValue);
value = multiLocalizedUnicode(bytes);
break;
case Signature:
bytes = signature(newValue);
value = signature(bytes);
break;
case DateTime:
bytes = dateTime(newValue);
value = dateTime(bytes);
break;
case XYZ: {
double[][] doubles = XYZDoubles(newValue);
bytes = XYZ(doubles);
value = doubles;
break;
}
case Curve: {
double[] doubles = curveDoubles(newValue);
bytes = curve(doubles);
value = doubles;
break;
}
case S15Fixed16Array: {
double[] doubles = s15Fixed16ArrayDoubles(newValue);
bytes = s15Fixed16Array(doubles);
value = doubles;
break;
}
}
if (value == null || bytes == null) {
return false;
}
tag.setValue(value);
tag.setBytes(bytes);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public static boolean updateViewingConditionsIlluminant(IccTag tag, String newValue) {
try {
if (tag.getType() != TagType.ViewingConditions) {
return false;
}
double[] doubles = XYZNumberDoubles(newValue);
Map<String, Object> values = (Map<String, Object>) tag.getValue();
values.put("illuminant", doubles);
tag.setValue(values);
byte[] tagBytes = tag.getBytes();
byte[] illuminantBytes = XYZNumber(doubles);
System.arraycopy(illuminantBytes, 0, tagBytes, 8, 12);
tag.setBytes(tagBytes);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public static boolean updateViewingConditionsSurround(IccTag tag, String newValue) {
try {
if (tag.getType() != TagType.ViewingConditions) {
return false;
}
double[] doubles = XYZNumberDoubles(newValue);
Map<String, Object> values = (Map<String, Object>) tag.getValue();
values.put("surround", doubles);
tag.setValue(values);
byte[] tagBytes = tag.getBytes();
byte[] surroundBytes = XYZNumber(doubles);
System.arraycopy(surroundBytes, 0, tagBytes, 20, 12);
tag.setBytes(tagBytes);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public static boolean updateViewingConditionsType(IccTag tag, String newValue) {
try {
if (tag.getType() != TagType.ViewingConditions) {
return false;
}
Map<String, Object> values = (Map<String, Object>) tag.getValue();
values.put("illuminantType", newValue);
tag.setValue(values);
byte[] tagBytes = tag.getBytes();
byte[] typeBytes = illuminantType(newValue);
System.arraycopy(typeBytes, 0, tagBytes, 32, 4);
tag.setBytes(tagBytes);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public static boolean updateMeasurementObserver(IccTag tag, String newValue) {
try {
if (tag.getType() != TagType.Measurement) {
return false;
}
Map<String, Object> values = (Map<String, Object>) tag.getValue();
values.put("observer", newValue);
tag.setValue(values);
byte[] tagBytes = tag.getBytes();
byte[] observerBytes = observerType(newValue);
System.arraycopy(observerBytes, 0, tagBytes, 8, 4);
tag.setBytes(tagBytes);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public static boolean updateMeasurementTristimulus(IccTag tag, String newValue) {
try {
if (tag.getType() != TagType.Measurement) {
return false;
}
double[] doubles = XYZNumberDoubles(newValue);
Map<String, Object> values = (Map<String, Object>) tag.getValue();
values.put("tristimulus", doubles);
tag.setValue(values);
byte[] tagBytes = tag.getBytes();
byte[] tristimulusBytes = XYZNumber(doubles);
System.arraycopy(tristimulusBytes, 0, tagBytes, 12, 12);
tag.setBytes(tagBytes);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public static boolean updateMeasurementGeometry(IccTag tag, String newValue) {
try {
if (tag.getType() != TagType.Measurement) {
return false;
}
Map<String, Object> values = (Map<String, Object>) tag.getValue();
values.put("geometry", newValue);
tag.setValue(values);
byte[] tagBytes = tag.getBytes();
byte[] geometryBytes = geometryType(newValue);
System.arraycopy(geometryBytes, 0, tagBytes, 24, 4);
tag.setBytes(tagBytes);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public static boolean updateMeasurementFlare(IccTag tag, String newValue) {
try {
if (tag.getType() != TagType.Measurement) {
return false;
}
double flare = Double.parseDouble(newValue);
Map<String, Object> values = (Map<String, Object>) tag.getValue();
values.put("flare", flare);
tag.setValue(values);
byte[] tagBytes = tag.getBytes();
byte[] flareBytes = u16Fixed16Number(flare);
System.arraycopy(flareBytes, 0, tagBytes, 28, 4);
tag.setBytes(tagBytes);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public static boolean updateMeasurementType(IccTag tag, String newValue) {
try {
if (tag.getType() != TagType.Measurement) {
return false;
}
Map<String, Object> values = (Map<String, Object>) tag.getValue();
values.put("illuminantType", newValue);
tag.setValue(values);
byte[] tagBytes = tag.getBytes();
byte[] typeBytes = illuminantType(newValue);
System.arraycopy(typeBytes, 0, tagBytes, 32, 4);
tag.setBytes(tagBytes);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
/*
Values
*/
// https://sno.phy.queensu.ca/~phil/exiftool/TagNames/ICC_Profile.html
public static String[][] tagNames = {
{"A2B0", "AToB0"},
{"A2B1", "AToB1"},
{"A2B2", "AToB2"},
{"B2A0", "BToA0"},
{"B2A1", "BToA1"},
{"B2A2", "BToA2"},
{"B2D0", "BToD0"},
{"B2D1", "BToD1"},
{"B2D2", "BToD2"},
{"B2D3", "BToD3"},
{"D2B0", "DToB0"},
{"D2B1", "DToB1"},
{"D2B2", "DToB2"},
{"D2B3", "DToB3"},
{"Header", "ProfileHeader"},
{"MS00", "WCSProfiles"},
{"bTRC", "BlueTRC"},
{"bXYZ", "BlueMatrixColumn"},
{"bfd", "UCRBG"},
{"bkpt", "MediaBlackPoint"},
{"calt", "CalibrationDateTime"},
{"chad", "ChromaticAdaptation"},
{"chrm", "Chromaticity"},
{"ciis", "ColorimetricIntentImageState"},
{"clot", "ColorantTableOut"},
{"clro", "ColorantOrder"},
{"clrt", "ColorantTable"},
{"cprt", "ProfileCopyright"},
{"crdi", "CRDInfo"},
{"desc", "ProfileDescription"},
{"devs", "DeviceSettings"},
{"dmdd", "DeviceModelDesc"},
{"dmnd", "DeviceMfgDesc"},
{"dscm", "ProfileDescriptionML"},
{"fpce", "FocalPlaneColorimetryEstimates"},
{"gTRC", "GreenTRC"},
{"gXYZ", "GreenMatrixColumn"},
{"gamt", "Gamut"},
{"kTRC", "GrayTRC"},
{"lumi", "Luminance"},
{"meas", "Measurement"},
{"meta", "Metadata"},
{"mmod", "MakeAndModel"},
{"ncl2", "NamedColor2"},
{"ncol", "NamedColor"},
{"ndin", "NativeDisplayInfo"},
{"pre0", "Preview0"},
{"pre1", "Preview1"},
{"pre2", "Preview2"},
{"ps2i", "PS2RenderingIntent"},
{"ps2s", "PostScript2CSA"},
{"psd0", "PostScript2CRD0"},
{"psd1", "PostScript2CRD1"},
{"psd2", "PostScript2CRD2"},
{"psd3", "PostScript2CRD3"},
{"pseq", "ProfileSequenceDesc"},
{"psid", "ProfileSequenceIdentifier"},
{"psvm", "PS2CRDVMSize"},
{"rTRC", "RedTRC"},
{"rXYZ", "RedMatrixColumn"},
{"resp", "OutputResponse"},
{"rhoc", "ReflectionHardcopyOrigColorimetry"},
{"rig0", "PerceptualRenderingIntentGamut"},
{"rig2", "SaturationRenderingIntentGamut"},
{"rpoc", "ReflectionPrintOutputColorimetry"},
{"sape", "SceneAppearanceEstimates"},
{"scoe", "SceneColorimetryEstimates"},
{"scrd", "ScreeningDesc"},
{"scrn", "Screening"},
{"targ", "CharTarget"},
{"tech", "Technology"},
{"vcgt", "VideoCardGamma"},
{"view", "ViewingConditions"},
{"vued", "ViewingCondDesc"},
{"wtpt", "MediaWhitePoint"}
};
public static String[][] tagDescriptions = {
{"AToB0", "Multi-dimensional transformation structure"},
{"AToB1", "Multi-dimensional transformation structure"},
{"AToB2", "Multi-dimensional transformation structure"},
{"BlueMatrixColumn", "The third column in the matrix used in matrix/TRC transforms. (This column is combined with the linear blue channel during the matrix multiplication)."},
{"BlueTRC", "Blue channel tone reproduction curve"},
{"BToA0", "Multi-dimensional transformation structure"},
{"BToA1", "Multi-dimensional transformation structure"},
{"BToA2", "Multi-dimensional transformation structure"},
{"BToD0", "Multi-dimensional transformation structure"},
{"BToD1", "Multi-dimensional transformation structure"},
{"BToD2", "Multi-dimensional transformation structure"},
{"BToD3", "Multi-dimensional transformation structure"},
{"CalibrationDateTime", "Profile calibration date and time"},
{"CharTarget", "Characterization target such as IT8/7.2"},
{"ChromaticAdaptation", "Converts an nCIEXYZ colour relative to the actual adopted white to the nCIEXYZ colour relative to the PCS adopted white. Required only if the chromaticity of the actual adopted white is different from that of the PCS adopted white."},
{"Chromaticity", "Set of phosphor/colorant chromaticity"},
{"ColorantOrder", "Identifies the laydown order of colorants"},
{"ColorantTable", "Identifies the colorants used in the profile. Required for N-component based Output profiles and DeviceLink profiles only if the data colour space field is xCLR (e.g. 3CLR)"},
{"ColorantTableOut", "Identifies the output colorants used in the profile, required only if the PCS Field is xCLR (e.g. 3CLR)"},
{"ColorimetricIntentImageState", "Indicates the image state of PCS colorimetry produced using the colorimetric intent transforms"},
{"ProfileCopyright", "Profile copyright information"},
{"DeviceMfgDesc", "Displayable description of device manufacturer"},
{"DeviceModelDesc", "Displayable description of device model"},
{"DToB0", "Multi-dimensional transformation structure"},
{"DToB1", "Multi-dimensional transformation structure"},
{"DToB2", "Multi-dimensional transformation structure"},
{"DToB3", "Multi-dimensional transformation structure"},
{"Gamut", "Out of gamut: 8-bit or 16-bit data"},
{"GrayTRC", "Grey tone reproduction curve"},
{"GreenMatrixColumn", "The second column in the matrix used in matrix/TRC transforms (This column is combined with the linear green channel during the matrix multiplication)."},
{"GreenTRC", "Green channel tone reproduction curve"},
{"Luminance", "Absolute luminance for emissive device"},
{"Measurement", "Alternative measurement specification information"},
{"MediaBlackPoint", "nCIEXYZ of Media black point"},
{"MediaWhitePoint", "nCIEXYZ of media white point"},
{"NamedColor2", "PCS and optional device representation for named colours"},
{"OutputResponse", "Description of the desired device response"},
{"PerceptualRenderingIntentGamut", "When present, the specified gamut is defined to be the reference medium gamut for the PCS side of both the A2B0 and B2A0 tags"},
{"Preview0", "Preview transformation: 8-bit or 16-bit data"},
{"Preview1", "Preview transformation: 8-bit or 16-bit data"},
{"Preview2", "Preview transformation: 8-bit or 16-bit data"},
{"ProfileDescription", "Structure containing invariant and localizable versions of the profile name for displays"},
{"ProfileSequenceDesc", "An array of descriptions of the profile sequence"},
{"RedMatrixColumn", "The first column in the matrix used in matrix/TRC transforms. (This column is combined with the linear red channel during the matrix multiplication)."},
{"RedTRC", "Red channel tone reproduction curve"},
{"SaturationRenderingIntentGamut", "When present, the specified gamut is defined to be the reference medium gamut for the PCS side of both the A2B2 and B2A2 tags"},
{"Technology", "Device technology information such as LCD, CRT, Dye Sublimation, etc."},
{"ViewingCondDesc", "Viewing condition description"},
{"ViewingConditions", "Viewing condition parameters"}
};
public static String[][] Technology = {
{"fscn", "Film scanner"},
{"dcam", "Digital camera"},
{"rscn", "Reflective scanner"},
{"ijet", "Ink jet printer"},
{"twax", "Thermal wax printer"},
{"epho", "Electrophotographic printer"},
{"esta", "Electrostatic printer"},
{"dsub", "Dye sublimation printer"},
{"rpho", "Photographic paper printer"},
{"fprn", "Film writer"},
{"vidm", "Video monitor"},
{"vidc", "Video camera"},
{"pjtv", "Projection television"},
{"CRT ", "Cathode ray tube display"},
{"PMD ", "Passive matrix display"},
{"AMD ", "Active matrix display"},
{"KPCD", "Photo CD"},
{"imgs", "Photographic image setter"},
{"grav", "Gravure"},
{"offs", "Offset lithography"},
{"silk", "Silkscreen"},
{"flex", "Flexography"},
{"mpfs", "Motion picture film scanner"},
{"mpfr", "Motion picture film recorder"},
{"dmpc", "Digital motion picture camera"},
{"dcpj", "Digital cinema projector"}
};
public static String technology(String value) {
for (String[] item : Technology) {
if (item[0].equals(value)) {
return item[0] + AppValues.Indent + item[1];
}
}
return value;
}
public static List<String> technologyTypes() {
List<String> types = new ArrayList<>();
for (String[] item : Technology) {
types.add(item[0] + AppValues.Indent + item[1]);
}
return types;
}
/*
Set/Get
*/
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte[] getBytes() {
return bytes;
}
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
@SuppressWarnings("unchecked")
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public TagType getType() {
return type;
}
public void setType(TagType type) {
this.type = type;
}
public List<String> getValueSelection() {
return valueSelection;
}
public void setValueSelection(List<String> valueSelection) {
this.valueSelection = valueSelection;
}
public boolean isChanged() {
return changed;
}
public void setChanged(boolean changed) {
this.changed = changed;
}
public boolean isIsHeaderField() {
return isHeaderField;
}
public void setIsHeaderField(boolean isHeaderField) {
this.isHeaderField = isHeaderField;
}
public boolean isEditable() {
return editable;
}
public void setEditable(boolean editable) {
this.editable = editable;
}
public boolean isSelectionEditable() {
return selectionEditable;
}
public void setSelectionEditable(boolean selectionEditable) {
this.selectionEditable = selectionEditable;
}
public List<String> getArrayNames() {
return arrayNames;
}
public void setArrayNames(List<String> arrayNames) {
this.arrayNames = arrayNames;
}
public int getSize() {
size = bytes.length;
return size;
}
public void setSize(int size) {
this.size = size;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/IccHeader.java | released/MyBox/src/main/java/mara/mybox/color/IccHeader.java | package mara.mybox.color;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import mara.mybox.color.IccTag.TagType;
import static mara.mybox.color.IccXML.iccHeaderXml;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.ByteTools;
import static mara.mybox.tools.ByteTools.bytesToHex;
import static mara.mybox.tools.ByteTools.bytesToHexFormat;
import static mara.mybox.tools.ByteTools.bytesToInt;
import static mara.mybox.tools.ByteTools.intToBytes;
import static mara.mybox.tools.ByteTools.subBytes;
import mara.mybox.value.AppValues;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2019-5-12
* @Description
* @License Apache License Version 2.0
*/
public class IccHeader {
private byte[] header;
private LinkedHashMap<String, IccTag> fields;
private boolean isValid;
private String error;
public IccHeader(byte[] data) {
try {
this.header = ByteTools.subBytes(data, 0, 128);
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public LinkedHashMap<String, IccTag> readFields() {
if (header == null) {
return null;
}
if (fields == null) {
fields = iccHeaderFields(header);
}
return fields;
}
public IccTag field(String name) {
try {
return getFields().get(name);
} catch (Exception e) {
return null;
}
}
public Object value(String name) {
try {
IccTag tag = getFields().get(name);
return tag.getValue();
} catch (Exception e) {
return null;
}
}
public String hex(int offset, int size) {
try {
return bytesToHexFormat(subBytes(header, offset, size));
} catch (Exception e) {
return null;
}
}
public String xml() {
try {
return iccHeaderXml(getFields());
} catch (Exception e) {
return null;
}
}
public boolean update(byte[] newHeader) {
if (newHeader == null || newHeader.length != 128) {
return false;
}
LinkedHashMap<String, IccTag> newFields = iccHeaderFields(newHeader);
if (newFields == null) {
return false;
}
this.header = newHeader;
fields = newFields;
return true;
}
/*
Methods based on bytes
*/
public static LinkedHashMap<String, IccTag> iccHeaderFields(byte[] header) {
try {
LinkedHashMap<String, IccTag> fields = new LinkedHashMap<>();
fields.put("ProfileSize",
new IccTag("ProfileSize", 0, subBytes(header, 0, 4), TagType.Int,
bytesToInt(subBytes(header, 0, 4))));
fields.put("CMMType",
new IccTag("CMMType", 4, subBytes(header, 4, 4), TagType.Text,
deviceManufacturerDisplay(subBytes(header, 4, 4)), DeviceManufacturers(), true));
fields.put("ProfileVersion",
new IccTag("ProfileVersion", 8, subBytes(header, 8, 2), TagType.Text,
profileVersion(subBytes(header, 8, 2))));
fields.put("ProfileDeviceClass",
new IccTag("ProfileDeviceClass", 12, subBytes(header, 12, 4), TagType.Text,
profileDeviceClassDisplay(subBytes(header, 12, 4)), ProfileDeviceClasses(), false));
fields.put("ColorSpaceType",
new IccTag("ColorSpaceType", 16, subBytes(header, 16, 4), TagType.Text,
colorSpaceType(subBytes(header, 16, 4)), ColorSpaceTypes(), true));
fields.put("PCSType",
new IccTag("PCSType", 20, subBytes(header, 20, 4), TagType.Text,
new String(subBytes(header, 20, 4)), PCSTypes(), false));
fields.put("CreateTime",
new IccTag("CreateTime", 24, subBytes(header, 24, 12), TagType.Text,
IccTagType.dateTimeString(subBytes(header, 24, 12))));
fields.put("ProfileFile",
new IccTag("ProfileFile", 36, subBytes(header, 36, 4), TagType.Text,
new String(subBytes(header, 36, 4))));
fields.put("PrimaryPlatform",
new IccTag("PrimaryPlatform", 40, subBytes(header, 40, 4), TagType.Text,
primaryPlatformDisplay(subBytes(header, 40, 4)), PrimaryPlatforms(), false));
boolean[] profileFlags = IccHeader.profileFlags(header[47]);
byte[] bytes = subBytes(header, 44, 4);
fields.put("ProfileFlagEmbedded",
new IccTag("ProfileFlagEmbedded", 44, bytes, TagType.Boolean,
profileFlags[0]));
fields.put("ProfileFlagIndependently",
new IccTag("ProfileFlagIndependently", 44, bytes, TagType.Boolean,
!profileFlags[1]));
fields.put("ProfileFlagMCSSubset",
new IccTag("ProfileFlagMCSSubset", 44, bytes, TagType.Boolean,
profileFlags[2]));
fields.put("DeviceManufacturer",
new IccTag("DeviceManufacturer", 48, subBytes(header, 48, 4), TagType.Text,
deviceManufacturerDisplay(subBytes(header, 48, 4)), DeviceManufacturers(), true));
fields.put("DeviceModel",
new IccTag("DeviceModel", 52, subBytes(header, 52, 4), TagType.Text,
new String(subBytes(header, 52, 4))));
bytes = subBytes(header, 56, 8);
boolean[] deviceAttributes = IccHeader.deviceAttributes(header[63]);
fields.put("DeviceAttributeTransparency",
new IccTag("DeviceAttributeTransparency", 56, bytes, TagType.Boolean,
deviceAttributes[0]));
fields.put("DeviceAttributeMatte",
new IccTag("DeviceAttributeMatte", 56, bytes, TagType.Boolean,
deviceAttributes[1]));
fields.put("DeviceAttributeNegative",
new IccTag("DeviceAttributeNegative", 56, bytes, TagType.Boolean,
deviceAttributes[2]));
fields.put("DeviceAttributeBlackOrWhite",
new IccTag("DeviceAttributeBlackOrWhite", 56, bytes, TagType.Boolean,
deviceAttributes[3]));
fields.put("DeviceAttributePaperBased",
new IccTag("DeviceAttributePaperBased", 56, bytes, TagType.Boolean,
!deviceAttributes[4]));
fields.put("DeviceAttributeTextured",
new IccTag("DeviceAttributeTextured", 56, bytes, TagType.Boolean,
deviceAttributes[5]));
fields.put("DeviceAttributeIsotropic",
new IccTag("DeviceAttributeIsotropic", 56, bytes, TagType.Boolean,
!deviceAttributes[6]));
fields.put("DeviceAttributeSelfLuminous",
new IccTag("DeviceAttributeSelfLuminous", 56, bytes, TagType.Boolean,
deviceAttributes[7]));
fields.put("RenderingIntent",
new IccTag("RenderingIntent", 64, subBytes(header, 64, 4), TagType.Text,
renderingIntentDisplay(subBytes(header, 64, 4)), RenderingIntents(), true));
double[] xyz = IccTagType.XYZNumber(subBytes(header, 68, 12));
fields.put("PCCIlluminantX",
new IccTag("PCCIlluminantX", 68, subBytes(header, 68, 4), TagType.Double,
xyz[0]));
fields.put("PCCIlluminantY",
new IccTag("PCCIlluminantY", 72, subBytes(header, 72, 4), TagType.Double,
xyz[1]));
fields.put("PCCIlluminantZ",
new IccTag("PCCIlluminantZ", 76, subBytes(header, 76, 4), TagType.Double,
xyz[2]));
fields.put("Creator",
new IccTag("Creator", 80, subBytes(header, 80, 4), TagType.Text,
deviceManufacturerDisplay(subBytes(header, 80, 4)), DeviceManufacturers(), true));
fields.put("ProfileID",
new IccTag("ProfileID", 84, subBytes(header, 84, 16), TagType.Bytes,
bytesToHexFormat(subBytes(header, 84, 16))));
fields.put("SpectralPCS",
new IccTag("SpectralPCS", 100, subBytes(header, 100, 4), TagType.Text,
new String(subBytes(header, 100, 4))));
fields.put("SpectralPCSWaveLengthRange",
new IccTag("SpectralPCSWaveLengthRange", 104, subBytes(header, 104, 6), TagType.Bytes,
bytesToHexFormat(subBytes(header, 104, 6))));
fields.put("BispectralPCSWaveLengthRange",
new IccTag("BispectralPCSWaveLengthRange", 110, subBytes(header, 110, 6), TagType.Bytes,
bytesToHexFormat(subBytes(header, 110, 6))));
fields.put("MCS",
new IccTag("MCS", 116, subBytes(header, 116, 4), TagType.Bytes,
bytesToHexFormat(subBytes(header, 116, 4))));
fields.put("ProfileDeviceSubclass",
new IccTag("ProfileDeviceSubclass", 120, subBytes(header, 120, 4), TagType.Text,
new String(subBytes(header, 120, 4))));
fields.put("ProfileSubclassVersion",
new IccTag("ProfileSubclassVersion", 104, subBytes(header, 104, 6), TagType.Double,
Float.parseFloat((int) (header[10]) + "." + (int) (header[11]))));
return fields;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
/*
Decode values of Header Fields
*/
public static String profileVersion(byte[] value) {
int major = (int) value[0];
int minor = (value[1] & 0xff) >>> 4;
int bug = value[1] & 0x0f;
return major + "." + minor + "." + bug + ".0";
}
public static boolean[] profileFlags(byte value) {
boolean[] values = new boolean[3];
values[0] = (value & 0x01) == 0x01;
values[1] = (value & 0x02) == 0x02;
values[2] = (value & 0x04) == 0x04;
return values;
}
public static boolean[] deviceAttributes(byte value) {
boolean[] values = new boolean[8];
values[0] = (value & 0x01) == 0x01;
values[1] = (value & 0x02) == 0x02;
values[2] = (value & 0x04) == 0x04;
values[3] = (value & 0x08) == 0x08;
values[4] = (value & 0x10) == 0x10;
values[5] = (value & 0x20) == 0x20;
values[6] = (value & 0x40) == 0x40;
values[7] = (value & 0x80) == 0x80;
return values;
}
public static String colorSpaceType(byte[] value) {
String cs = new String(value);
if (cs.startsWith("nc")) {
cs = "nc" + bytesToHex(subBytes(value, 2, 2)).toUpperCase();
}
return cs;
}
public static String renderingIntent(byte[] value) {
int intv = bytesToInt(value);
switch (intv) {
case 0:
return "Perceptual";
case 1:
return "MediaRelativeColorimetric";
case 2:
return "Saturation";
case 3:
return "ICCAbsoluteColorimetric";
default:
return bytesToHex(value);
}
}
/*
Display of Header Fields
*/
public static String deviceManufacturerDisplay(byte[] value) {
return deviceManufacturerDisplay(new String(value));
}
public static String deviceManufacturerDisplay(String value) {
for (String[] item : DeviceManufacturers) {
if (item[0].equals(value)) {
return item[0] + AppValues.Indent + item[1];
}
}
return value;
}
public static String profileDeviceClassDisplay(byte[] value) {
return profileDeviceClassDisplay(new String(value));
}
public static String profileDeviceClassDisplay(String value) {
for (String[] item : ProfileDeviceClasses) {
if (item[0].equals(value)) {
return item[0] + AppValues.Indent + Languages.message(item[1]);
}
}
return value;
}
public static String primaryPlatformDisplay(byte[] value) {
return primaryPlatformDisplay(new String(value));
}
public static String primaryPlatformDisplay(String value) {
for (String[] item : PrimaryPlatforms) {
if (item[0].equals(value)) {
return item[0] + AppValues.Indent + item[1];
}
}
return value;
}
public static String renderingIntentDisplay(byte[] value) {
int intv = bytesToInt(value);
switch (intv) {
case 0:
return Languages.message("Perceptual");
case 1:
return Languages.message("MediaRelativeColorimetric");
case 2:
return Languages.message("Saturation");
case 3:
return Languages.message("ICCAbsoluteColorimetric");
default:
return bytesToHex(value);
}
}
/*
Encode values of Header Fields
*/
public static byte[] profileVersion(String value) {
byte[] bytes = new byte[4];
try {
String[] values = value.split(".");
if (values.length > 0) {
bytes[0] = ByteTools.intSmallByte(Integer.parseInt(values[0]));
if (values.length > 1) {
Byte b = ByteTools.intSmallByte(Integer.parseInt(values[1]));
bytes[1] = (byte) (b << 4);
if (values.length > 2) {
b = ByteTools.intSmallByte(Integer.parseInt(values[2]));
bytes[1] = (byte) (bytes[1] & b);
}
}
}
} catch (Exception e) {
}
return bytes;
}
public static byte[] colorSpaceType(String value) {
if (!value.startsWith("nc")) {
return IccProfile.first4ASCII(value);
}
byte[] bytes = new byte[4];
try {
if (value.length() < 6) {
return bytes;
}
byte[] vBytes = IccProfile.toBytes("nc");
System.arraycopy(vBytes, 0, bytes, 0, 2);
vBytes = ByteTools.hexToBytes(value.substring(2, 6));
System.arraycopy(vBytes, 0, bytes, 2, 2);
} catch (Exception e) {
}
return bytes;
}
public static byte[] profileFlags(boolean Embedded,
boolean Independently, boolean MCSSubset) {
int v = Embedded ? 0x01 : 0;
v = v | (Independently ? 0 : 0x02);
v = v | (MCSSubset ? 0x04 : 0);
return intToBytes(v);
}
public static byte[] deviceAttributes(
boolean Transparency, boolean Matte, boolean Negative, boolean BlackOrWhite,
boolean PaperBased, boolean Textured, boolean Isotropic, boolean SelfLuminous) {
int v = Transparency ? 0x01 : 0;
v = v | (Matte ? 0x02 : 0);
v = v | (Negative ? 0x04 : 0);
v = v | (BlackOrWhite ? 0x08 : 0);
v = v | (PaperBased ? 0 : 0x10);
v = v | (Textured ? 0x20 : 0);
v = v | (Isotropic ? 0 : 0x40);
v = v | (SelfLuminous ? 0x80 : 0);
byte[] bytes = intToBytes(v);
byte[] bytes8 = new byte[8];
System.arraycopy(bytes, 0, bytes8, 4, 4);
return bytes8;
}
public static byte[] RenderingIntent(String value) {
byte[] bytes = new byte[4];
if ("Perceptual".equals(value)
|| Languages.message("Perceptual").equals(value)) {
bytes[3] = 0;
} else if ("MediaRelativeColorimetric".equals(value)
|| Languages.message("MediaRelativeColorimetric").equals(value)) {
bytes[3] = 1;
} else if ("Saturation".equals(value)
|| Languages.message("Saturation").equals(value)) {
bytes[3] = 2;
} else if ("ICCAbsoluteColorimetric".equals(value)
|| Languages.message("ICCAbsoluteColorimetric").equals(value)) {
bytes[3] = 3;
}
return bytes;
}
/*
Data
*/
public static List<String> ProfileDeviceClasses() {
List<String> types = new ArrayList<>();
for (String[] item : ProfileDeviceClasses) {
types.add(item[0] + AppValues.Indent + Languages.message(item[1]));
}
return types;
}
public static String[][] ProfileDeviceClasses = {
{"scnr", "InputDeviceProfile"},
{"mntr", "DisplayDeviceProfile"},
{"prtr", "OutputDeviceProfile"},
{"link", "DeviceLinkProfile"},
{"abst", "AbstractProfile"},
{"spac", "ColorSpaceConversionProfile"},
{"nmcl", "NamedColorProfile"},
{"cenc", "ColorEncodingSpaceProfile"},
{"mid ", "MultiplexIdentificationProfile"},
{"mlnk", "MultiplexLinkProfile"},
{"mvis", "MultiplexVisualizationProfile"}
};
public static List<String> PrimaryPlatforms() {
List<String> types = new ArrayList<>();
for (String[] item : PrimaryPlatforms) {
types.add(item[0] + AppValues.Indent + item[1]);
}
return types;
}
public static String[][] PrimaryPlatforms = {
{"APPL", "Apple Computer Inc."},
{"MSFT", "Microsoft Corporation"},
{"SGI ", "Silicon Graphics Inc."},
{"SUNW", "Sun Microsystems Inc."},
{"TGNT", "Taligent Inc."}
};
public static List<String> ColorSpaceTypes() {
return Arrays.asList(ColorSpaceTypes);
}
public static String[] ColorSpaceTypes = {
"XYZ ", "Lab ", "Luv ", "YCbr", "Yxy ", "LMS ", "RGB ", "GRAY", "HSV ", "HLS ", "CMYK", "CMY ",
"2CLR", "3CLR", "4CLR", "5CLR", "6CLR", "7CLR", "8CLR", "9CLR",
"ACLR", "BCLR", "CCLR", "DCLR", "ECLR", "FCLR"
};
public static List<String> PCSTypes() {
return Arrays.asList(PCSTypes);
}
public static String[] PCSTypes = {
"XYZ ", "Lab ", " "
};
public static List<String> RenderingIntents() {
return Arrays.asList(RenderingIntents);
}
public static String[] RenderingIntents = {
"Perceptual", "MediaRelativeColorimetric", "Saturation", "ICCAbsoluteColorimetric"
};
public static List<String> DeviceManufacturers() {
List<String> types = new ArrayList<>();
for (String[] item : DeviceManufacturers) {
types.add(item[0] + AppValues.Indent + item[1]);
}
return types;
}
public static String[][] DeviceManufacturers = {
{"4d2p", "Erdt Systems GmbH & Co KG"},
{"AAMA", "Aamazing Technologies, Inc."},
{"ACER", "Acer Peripherals"},
{"ACLT", "Acolyte Color Research"},
{"ACTI", "Actix Sytems, Inc."},
{"ADAR", "Adara Technology, Inc."},
{"ADBE", "Adobe Systems Inc."},
{"ADI ", "ADI Systems, Inc."},
{"AGFA", "Agfa Graphics N.V."},
{"ALMD", "Alps Electric USA, Inc."},
{"ALPS", "Alps Electric USA, Inc."},
{"ALWN", "Alwan Color Expertise"},
{"AMTI", "Amiable Technologies, Inc."},
{"AOC ", "AOC International (U.S.A), Ltd."},
{"APAG", "Apago"},
{"APPL", "Apple Computer Inc."},
{"AST ", "AST"},
{"AT&T", "AT&T Computer Systems"},
{"BAEL", "BARBIERI electronic"},
{"BRCO", "Barco NV"},
{"BRKP", "Breakpoint Pty Limited"},
{"BROT", "Brother Industries, LTD"},
{"BULL", "Bull"},
{"BUS ", "Bus Computer Systems"},
{"C-IT", "C-Itoh"},
{"CAMR", "Intel Corporation"},
{"CANO", "Canon, Inc. (Canon Development Americas, Inc.)"},
{"CARR", "Carroll Touch"},
{"CASI", "Casio Computer Co., Ltd."},
{"CBUS", "Colorbus PL"},
{"CEL ", "Crossfield"},
{"CELx", "Crossfield"},
{"CGS ", "CGS Publishing Technologies International GmbH"},
{"CHM ", "Rochester Robotics"},
{"CIGL", "Colour Imaging Group, London"},
{"CITI", "Citizen"},
{"CL00", "Candela, Ltd."},
{"CLIQ", "Color IQ"},
{"CMCO", "Chromaco, Inc."},
{"CMiX", "CHROMiX"},
{"COLO", "Colorgraphic Communications Corporation"},
{"COMP", "COMPAQ Computer Corporation"},
{"COMp", "Compeq USA/Focus Technology"},
{"CONR", "Conrac Display Products"},
{"CORD", "Cordata Technologies, Inc."},
{"CPQ ", "Compaq Computer Corporation"},
{"CPRO", "ColorPro"},
{"CRN ", "Cornerstone"},
{"CTX ", "CTX International, Inc."},
{"CVIS", "ColorVision"},
{"CWC ", "Fujitsu Laboratories, Ltd."},
{"DARI", "Darius Technology, Ltd."},
{"DATA", "Dataproducts"},
{"DCP ", "Dry Creek Photo"},
{"DCRC", "Digital Contents Resource Center, Chung-Ang University"},
{"DELL", "Dell Computer Corporation"},
{"DIC ", "Dainippon Ink and Chemicals"},
{"DICO", "Diconix"},
{"DIGI", "Digital"},
{"DL&C", "Digital Light & Color"},
{"DPLG", "Doppelganger, LLC"},
{"DS ", "Dainippon Screen"},
{"DSOL", "DOOSOL"},
{"DUPN", "DuPont"},
{"EPSO", "Epson"},
{"ESKO", "Esko-Graphics"},
{"ETRI", "Electronics and Telecommunications Research Institute"},
{"EVER", "Everex Systems, Inc."},
{"EXAC", "ExactCODE GmbH"},
{"Eizo", "EIZO NANAO CORPORATION"},
{"FALC", "Falco Data Products, Inc."},
{"FF ", "Fuji Photo Film Co.,LTD"},
{"FFEI", "FujiFilm Electronic Imaging, Ltd."},
{"FNRD", "fnord software"},
{"FORA", "Fora, Inc."},
{"FORE", "Forefront Technology Corporation"},
{"FP ", "Fujitsu"},
{"FPA ", "WayTech Development, Inc."},
{"FUJI", "Fujitsu"},
{"FX ", "Fuji Xerox Co., Ltd."},
{"GCC ", "GCC Technologies, Inc."},
{"GGSL", "Global Graphics Software Limited"},
{"GMB ", "Gretagmacbeth"},
{"GMG ", "GMG GmbH & Co. KG"},
{"GOLD", "GoldStar Technology, Inc."},
{"GOOG", "Google"},
{"GPRT", "Giantprint Pty Ltd"},
{"GTMB", "Gretagmacbeth"},
{"GVC ", "WayTech Development, Inc."},
{"GW2K", "Sony Corporation"},
{"HCI ", "HCI"},
{"HDM ", "Heidelberger Druckmaschinen AG"},
{"HERM", "Hermes"},
{"HITA", "Hitachi America, Ltd."},
{"HP ", "Hewlett-Packard"},
{"HTC ", "Hitachi, Ltd."},
{"HiTi", "HiTi Digital, Inc."},
{"IBM ", "IBM Corporation"},
{"IDNT", "Scitex Corporation, Ltd."},
{"IEC ", "Hewlett-Packard"},
{"IIYA", "Iiyama North America, Inc."},
{"IKEG", "Ikegami Electronics, Inc."},
{"IMAG", "Image Systems Corporation"},
{"IMI ", "Ingram Micro, Inc."},
{"INTC", "Intel Corporation"},
{"INTL", "N/A (INTL)"},
{"INTR", "Intra Electronics USA, Inc."},
{"IOCO", "Iocomm International Technology Corporation"},
{"IPS ", "InfoPrint Solutions Company"},
{"IRIS", "Scitex Corporation, Ltd."},
{"ISL ", "Ichikawa Soft Laboratory"},
{"ITNL", "N/A (ITNL)"},
{"IVM ", "IVM"},
{"IWAT", "Iwatsu Electric Co., Ltd."},
{"Idnt", "Scitex Corporation, Ltd."},
{"Inca", "Inca Digital Printers Ltd."},
{"Iris", "Scitex Corporation, Ltd."},
{"JPEG", "Joint Photographic Experts Group"},
{"JSFT", "Jetsoft Development"},
{"JVC ", "JVC Information Products Co."},
{"KART", "Scitex Corporation, Ltd."},
{"KFC ", "KFC Computek Components Corporation"},
{"KLH ", "KLH Computers"},
{"KMHD", "Konica Minolta Holdings, Inc."},
{"KNCA", "Konica Corporation"},
{"KODA", "Kodak"},
{"KYOC", "Kyocera"},
{"Kart", "Scitex Corporation, Ltd."},
{"LCAG", "Leica Camera AG"},
{"LCCD", "Leeds Colour"},
{"LDAK", "Left Dakota"},
{"LEAD", "Leading Technology, Inc."},
{"LEXM", "Lexmark International, Inc."},
{"LINK", "Link Computer, Inc."},
{"LINO", "Linotronic"},
{"LITE", "Lite-On, Inc."},
{"Leaf", "Leaf"},
{"Lino", "Linotronic"},
{"MAGC", "Mag Computronic (USA) Inc."},
{"MAGI", "MAG Innovision, Inc."},
{"MANN", "Mannesmann"},
{"MICN", "Micron Technology, Inc."},
{"MICR", "Microtek"},
{"MICV", "Microvitec, Inc."},
{"MINO", "Minolta"},
{"MITS", "Mitsubishi Electronics America, Inc."},
{"MITs", "Mitsuba Corporation"},
{"MNLT", "Minolta"},
{"MODG", "Modgraph, Inc."},
{"MONI", "Monitronix, Inc."},
{"MONS", "Monaco Systems Inc."},
{"MORS", "Morse Technology, Inc."},
{"MOTI", "Motive Systems"},
{"MSFT", "Microsoft Corporation"},
{"MUTO", "MUTOH INDUSTRIES LTD."},
{"Mits", "Mitsubishi Electric Corporation Kyoto Works"},
{"NANA", "NANAO USA Corporation"},
{"NEC ", "NEC Corporation"},
{"NEXP", "NexPress Solutions LLC"},
{"NISS", "Nissei Sangyo America, Ltd."},
{"NKON", "Nikon Corporation"},
{"NONE", "none"},
{"OCE ", "Oce Technologies B.V."},
{"OCEC", "OceColor"},
{"OKI ", "Oki"},
{"OKID", "Okidata"},
{"OKIP", "Okidata"},
{"OLIV", "Olivetti"},
{"OLYM", "OLYMPUS OPTICAL CO., LTD"},
{"ONYX", "Onyx Graphics"},
{"OPTI", "Optiquest"},
{"PACK", "Packard Bell"},
{"PANA", "Matsushita Electric Industrial Co., Ltd."},
{"PANT", "Pantone, Inc."},
{"PBN ", "Packard Bell"},
{"PFU ", "PFU Limited"},
{"PHIL", "Philips Consumer Electronics Co."},
{"PNTX", "HOYA Corporation PENTAX Imaging Systems Division"},
{"POne", "Phase One A/S"},
{"PREM", "Premier Computer Innovations"},
{"PRIN", "Princeton Graphic Systems"},
{"PRIP", "Princeton Publishing Labs"},
{"QLUX", "Hong Kong"},
{"QMS ", "QMS, Inc."},
{"QPCD", "QPcard AB"},
{"QUAD", "QuadLaser"},
{"QUME", "Qume Corporation"},
{"RADI", "Radius, Inc."},
{"RDDx", "Integrated Color Solutions, Inc."},
{"RDG ", "Roland DG Corporation"},
{"REDM", "REDMS Group, Inc."},
{"RELI", "Relisys"},
{"RGMS", "Rolf Gierling Multitools"},
{"RICO", "Ricoh Corporation"},
{"RNLD", "Edmund Ronald"},
{"ROYA", "Royal"},
{"RPC ", "Ricoh Printing Systems,Ltd."},
{"RTL ", "Royal Information Electronics Co., Ltd."},
{"SAMP", "Sampo Corporation of America"},
{"SAMS", "Samsung, Inc."},
{"SANT", "Jaime Santana Pomares"},
{"SCIT", "Scitex Corporation, Ltd."},
{"SCRN", "Dainippon Screen"},
{"SDP ", "Scitex Corporation, Ltd."},
{"SEC ", "SAMSUNG ELECTRONICS CO.,LTD"},
{"SEIK", "Seiko Instruments U.S.A., Inc."},
{"SEIk", "Seikosha"},
{"SGUY", "ScanGuy.com"},
{"SHAR", "Sharp Laboratories"},
{"SICC", "International Color Consortium"},
{"SONY", "SONY Corporation"},
{"SPCL", "SpectraCal"},
{"STAR", "Star"},
{"STC ", "Sampo Technology Corporation"},
{"Scit", "Scitex Corporation, Ltd."},
{"Sdp ", "Scitex Corporation, Ltd."},
{"Sony", "Sony Corporation"},
{"TALO", "Talon Technology Corporation"},
{"TAND", "Tandy"},
{"TATU", "Tatung Co. of America, Inc."},
{"TAXA", "TAXAN America, Inc."},
{"TDS ", "Tokyo Denshi Sekei K.K."},
{"TECO", "TECO Information Systems, Inc."},
{"TEGR", "Tegra"},
{"TEKT", "Tektronix, Inc."},
{"TI ", "Texas Instruments"},
{"TMKR", "TypeMaker Ltd."},
{"TOSB", "TOSHIBA corp."},
{"TOSH", "Toshiba, Inc."},
{"TOTK", "TOTOKU ELECTRIC Co., LTD"},
{"TRIU", "Triumph"},
{"TSBT", "TOSHIBA TEC CORPORATION"},
{"TTX ", "TTX Computer Products, Inc."},
{"TVM ", "TVM Professional Monitor Corporation"},
{"TW ", "TW Casper Corporation"},
{"ULSX", "Ulead Systems"},
{"UNIS", "Unisys"},
{"UTZF", "Utz Fehlau & Sohn"},
{"VARI", "Varityper"},
{"VIEW", "Viewsonic"},
{"VISL", "Visual communication"},
{"VIVO", "Vivo Mobile Communication Co., Ltd"},
{"WANG", "Wang"},
{"WLBR", "Wilbur Imaging"},
{"WTG2", "Ware To Go"},
{"WYSE", "WYSE Technology"},
{"XERX", "Xerox Corporation"},
{"XRIT", "X-Rite"},
{"Z123", "Lavanya's test Company"},
{"ZRAN", "Zoran Corporation"},
{"Zebr", "Zebra Technologies Inc"},
{"appl", "Apple Computer Inc."},
{"bICC", "basICColor GmbH"},
{"berg", "bergdesign incorporated"},
{"ceyd", "Integrated Color Solutions, Inc."},
{"clsp", "MacDermid ColorSpan, Inc."},
{"ds ", "Dainippon Screen"},
{"dupn", "DuPont"},
{"ffei", "FujiFilm Electronic Imaging, Ltd."},
{"flux", "FluxData Corporation"},
{"iris", "Scitex Corporation, Ltd."},
{"kart", "Scitex Corporation, Ltd."},
{"lcms", "Little CMS"},
{"lino", "Linotronic"},
{"none", "none"},
{"ob4d", "Erdt Systems GmbH & Co KG"},
{"obic", "Medigraph GmbH"},
{"quby", "Qubyx Sarl"},
{"scit", "Scitex Corporation, Ltd."},
{"scrn", "Dainippon Screen"},
{"sdp ", "Scitex Corporation, Ltd."},
{"siwi", "SIWI GRAFIKA CORPORATION"},
{"yxym", "YxyMaster GmbH"}
};
/*
Get/Set
*/
public byte[] getHeader() {
return header;
}
public void setHeader(byte[] header) {
this.header = header;
}
public LinkedHashMap<String, IccTag> getFields() {
if (fields == null) {
readFields();
}
return fields;
}
public void setFields(LinkedHashMap<String, IccTag> fields) {
this.fields = fields;
}
public boolean isIsValid() {
return isValid;
}
public void setIsValid(boolean isValid) {
this.isValid = isValid;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/ChromaticAdaptation.java | released/MyBox/src/main/java/mara/mybox/color/ChromaticAdaptation.java | package mara.mybox.color;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mara.mybox.color.Illuminant.IlluminantType;
import mara.mybox.color.Illuminant.Observer;
import mara.mybox.data.StringTable;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.DoubleMatrixTools;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2019-5-21 12:09:26
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
// http://brucelindbloom.com/index.html?Eqn_ChromAdapt.html
// http://brucelindbloom.com/index.html?ColorCalculator.html
// https://ww2.mathworks.cn/help/images/ref/whitepoint.html
// http://www.thefullwiki.org/Standard_illuminant
public class ChromaticAdaptation {
public String source, target;
public String BradfordMethod, XYZScalingMethod, VonKriesMethod;
public ChromaticAdaptation() {
}
public ChromaticAdaptation(String source, String target,
String BradfordMethod, String XYZScalingMethod, String VonKriesMethod) {
this.source = source;
this.target = target;
this.BradfordMethod = BradfordMethod;
this.XYZScalingMethod = XYZScalingMethod;
this.VonKriesMethod = VonKriesMethod;
}
/*
Generation of Chromatic Adaptation matrices
*/
public static List<ChromaticAdaptation> all(int scale) {
List<ChromaticAdaptation> data = new ArrayList<>();
for (IlluminantType sourceIlluminant : IlluminantType.values()) {
for (IlluminantType targetIlluminant : IlluminantType.values()) {
for (Observer sourceObserver : Observer.values()) {
for (Observer targetObserver : Observer.values()) {
if (sourceIlluminant == targetIlluminant
&& sourceObserver == targetObserver) {
continue;
}
double[][] m1 = matrix(sourceIlluminant, sourceObserver,
targetIlluminant, targetObserver, ChromaticAdaptationAlgorithm.Bradford, -1);
double[][] m2 = matrix(sourceIlluminant, sourceObserver,
targetIlluminant, targetObserver, ChromaticAdaptationAlgorithm.XYZScaling, -1);
double[][] m3 = matrix(sourceIlluminant, sourceObserver,
targetIlluminant, targetObserver, ChromaticAdaptationAlgorithm.VonKries, -1);
ChromaticAdaptation ca = new ChromaticAdaptation();
ca.setSource(sourceIlluminant + " - " + sourceObserver);
ca.setTarget(targetIlluminant + " - " + targetObserver);
ca.setBradfordMethod(DoubleMatrixTools.print(m1, 0, scale));
ca.setXYZScalingMethod(DoubleMatrixTools.print(m2, 0, scale));
ca.setVonKriesMethod(DoubleMatrixTools.print(m3, 0, scale));
data.add(ca);
}
}
}
}
return data;
}
public static StringTable table(int scale) {
List<String> names = new ArrayList<>();
names.addAll(Arrays.asList(Languages.message("Source"), Languages.message("Target"),
"Bradford", "XYZ", "Von Kries"
));
StringTable table = new StringTable(names, Languages.message("ChromaticAdaptationMatrix"));
for (IlluminantType sourceIlluminant : IlluminantType.values()) {
for (IlluminantType targetIlluminant : IlluminantType.values()) {
for (Observer sourceObserver : Observer.values()) {
for (Observer targetObserver : Observer.values()) {
if (sourceIlluminant == targetIlluminant
&& sourceObserver == targetObserver) {
continue;
}
double[][] m1 = matrix(sourceIlluminant, sourceObserver,
targetIlluminant, targetObserver, ChromaticAdaptationAlgorithm.Bradford, -1);
double[][] m2 = matrix(sourceIlluminant, sourceObserver,
targetIlluminant, targetObserver, ChromaticAdaptationAlgorithm.XYZScaling, -1);
double[][] m3 = matrix(sourceIlluminant, sourceObserver,
targetIlluminant, targetObserver, ChromaticAdaptationAlgorithm.VonKries, -1);
List<String> row = new ArrayList<>();
row.addAll(Arrays.asList(sourceIlluminant.name() + " - " + sourceObserver.name(),
targetIlluminant.name() + " - " + targetObserver.name(),
DoubleMatrixTools.html(m1, scale),
DoubleMatrixTools.html(m2, scale),
DoubleMatrixTools.html(m3, scale)
));
table.add(row);
}
}
}
}
return table;
}
public static String allTexts(int scale) {
StringBuilder s = new StringBuilder();
for (IlluminantType sourceIlluminant : IlluminantType.values()) {
for (IlluminantType targetIlluminant : IlluminantType.values()) {
for (Observer sourceObserver : Observer.values()) {
for (Observer targetObserver : Observer.values()) {
if (sourceIlluminant == targetIlluminant
&& sourceObserver == targetObserver) {
continue;
}
for (ChromaticAdaptationAlgorithm a : ChromaticAdaptationAlgorithm.values()) {
double[][] m = matrix(sourceIlluminant, sourceObserver,
targetIlluminant, targetObserver, a, -1);
s.append(Languages.message("Source")).append(": ").append(sourceIlluminant).append(" - ").
append(sourceObserver).append("\n");
s.append(Languages.message("Target")).append(": ").append(targetIlluminant).append(" - ").
append(targetObserver).append("\n");
s.append(Languages.message("Algorithm")).append(": ").append(a).append("\n");
s.append(Languages.message("ChromaticAdaptationMatrix")).append(": ").append("\n");
s.append(DoubleMatrixTools.print(m, 20, scale)).append("\n\n");
}
}
}
}
}
return s.toString();
}
public static double[] adapt(double[] xyz,
IlluminantType fromType, Observer fromObserver,
IlluminantType toType, Observer toObserver,
ChromaticAdaptationAlgorithm algorithm) {
return adapt(xyz[0], xyz[1], xyz[2], fromType, fromObserver, toType, toObserver, algorithm);
}
public static double[] adapt(double x, double y, double z,
IlluminantType fromType, Observer fromObserver,
IlluminantType toType, Observer toObserver,
ChromaticAdaptationAlgorithm algorithm) {
Illuminant from = new Illuminant(fromType, fromObserver);
double[][] sourceWhitePoint = from.whitePoint();
Illuminant to = new Illuminant(toType, toObserver);
double[][] targetWhitePoint = to.whitePoint();
return (double[]) adapt(x, y, z, sourceWhitePoint, targetWhitePoint, algorithm, -1, false);
}
public static double[] adapt(double[] xyz,
IlluminantType fromType, IlluminantType toType,
ChromaticAdaptationAlgorithm algorithm) {
return adapt(xyz[0], xyz[1], xyz[2], fromType, toType, algorithm);
}
public static double[] adapt(double x, double y, double z,
IlluminantType fromType, IlluminantType toType,
ChromaticAdaptationAlgorithm algorithm) {
Illuminant from = new Illuminant(fromType);
double[][] sourceWhitePoint = from.whitePoint();
Illuminant to = new Illuminant(toType);
double[][] targetWhitePoint = to.whitePoint();
return (double[]) adapt(x, y, z, sourceWhitePoint, targetWhitePoint, algorithm, -1, false);
}
public static Object adapt(double x, double y, double z,
double sourceWhitePointX, double sourceWhitePointY, double sourceWhitePointZ,
double targetWhitePointX, double targetWhitePointY, double targetWhitePointZ,
ChromaticAdaptationAlgorithm algorithm, int scale, boolean isDemo) {
double[][] sourceWhitePoint
= DoubleMatrixTools.columnVector(sourceWhitePointX, sourceWhitePointY, sourceWhitePointZ);
double[][] targetWhitePoint
= DoubleMatrixTools.columnVector(targetWhitePointX, targetWhitePointY, targetWhitePointZ);
return adapt(x, y, z, sourceWhitePoint, targetWhitePoint, algorithm, scale, isDemo);
}
public static double[] adapt(double[] xyz,
double[][] sourceWhitePoint, double[][] targetWhitePoint,
ChromaticAdaptationAlgorithm algorithm) {
return adapt(xyz[0], xyz[1], xyz[2], sourceWhitePoint, targetWhitePoint, algorithm);
}
public static double[] adapt(double x, double y, double z,
double[][] sourceWhitePoint, double[][] targetWhitePoint,
ChromaticAdaptationAlgorithm algorithm) {
return (double[]) adapt(x, y, z, sourceWhitePoint, targetWhitePoint, algorithm, -1, false);
}
public static Object adapt(double[] xyz,
double[][] sourceWhitePoint, double[][] targetWhitePoint,
ChromaticAdaptationAlgorithm algorithm, int scale, boolean isDemo) {
return adapt(xyz[0], xyz[1], xyz[2], sourceWhitePoint, targetWhitePoint, algorithm, scale, isDemo);
}
public static Object adapt(double x, double y, double z,
double[][] sourceWhitePoint, double[][] targetWhitePoint,
ChromaticAdaptationAlgorithm algorithm, int scale, boolean isDemo) {
try {
if (DoubleMatrixTools.same(sourceWhitePoint, targetWhitePoint, scale)) {
double[] result = {x, y, z};
if (isDemo) {
Map<String, Object> ret = new HashMap<>();
ret.put("procedure", Languages.message("NeedNotAdaptChromatic"));
ret.put("matrix", DoubleMatrixTools.identityDouble(3));
ret.put("adaptedColor", result);
return ret;
} else {
return result;
}
}
double[][] adaptMatrix;
String adaptString = null;
Object adaptObject = matrix(sourceWhitePoint, targetWhitePoint, algorithm, scale, isDemo);
if (isDemo) {
Map<String, Object> adapt = (Map<String, Object>) adaptObject;
adaptMatrix = (double[][]) adapt.get("adpatMatrix");
adaptString = (String) adapt.get("procedure");
} else {
adaptMatrix = (double[][]) adaptObject;
}
double[][] sourceColor = DoubleMatrixTools.columnVector(x, y, z);
double[][] adaptedColor = DoubleMatrixTools.multiply(adaptMatrix, sourceColor);
double[] result = DoubleMatrixTools.columnValues(adaptedColor, 0);
if (isDemo) {
String s = "";
s += "\naaaaaaaaaaaaa " + Languages.message("Step") + " - " + Languages.message("ChromaticAdaptationMatrix") + " aaaaaaaaaaaaa\n\n";
s += adaptString + "\n";
s += "\naaaaaaaaaaaaa " + Languages.message("Step") + " - " + Languages.message("ChromaticAdaptation") + " aaaaaaaaaaaaa\n\n";
s += "SourceColor = \n";
s += DoubleMatrixTools.print(sourceColor, 20, scale);
s += "\nAdaptedColor = M * SourceColor = \n";
s += DoubleMatrixTools.print(adaptedColor, 20, scale);
Map<String, Object> ret = new HashMap<>();
ret.put("matrix", adaptMatrix);
ret.put("procedure", s);
ret.put("adaptedColor", result);
return ret;
} else {
return result;
}
} catch (Exception e) {
return null;
}
}
public static double[][] matrix(
IlluminantType fromType, IlluminantType toType,
ChromaticAdaptationAlgorithm algorithm, int scale) {
Illuminant from = new Illuminant(fromType);
double[][] sourceWhitePoint = from.whitePoint();
Illuminant to = new Illuminant(toType);
double[][] targetWhitePoint = to.whitePoint();
return matrix(sourceWhitePoint, targetWhitePoint, algorithm, scale);
}
public static double[][] matrix(
IlluminantType fromType, Observer fromObserver,
IlluminantType toType, Observer toObserver,
ChromaticAdaptationAlgorithm algorithm, int scale) {
Illuminant from = new Illuminant(fromType, fromObserver);
double[][] sourceWhitePoint = from.whitePoint();
Illuminant to = new Illuminant(toType, toObserver);
double[][] targetWhitePoint = to.whitePoint();
return matrix(sourceWhitePoint, targetWhitePoint, algorithm, scale);
}
public static double[][] matrix(
double[][] sourceWhitePoint, double[][] targetWhitePoint,
ChromaticAdaptationAlgorithm algorithm, int scale) {
return (double[][]) matrix(sourceWhitePoint, targetWhitePoint, algorithm, scale, false);
}
public static Map<String, Object> matrixDemo(
double sourceWhitePointX, double sourceWhitePointY, double sourceWhitePointZ,
double targetWhitePointX, double targetWhitePointY, double targetWhitePointZ,
ChromaticAdaptationAlgorithm algorithm, int scale) {
double[][] sourceWhitePoint = DoubleMatrixTools.columnVector(sourceWhitePointX, sourceWhitePointY, sourceWhitePointZ);
double[][] targetWhitePoint = DoubleMatrixTools.columnVector(targetWhitePointX, targetWhitePointY, targetWhitePointZ);
return ChromaticAdaptation.matrixDemo(sourceWhitePoint, targetWhitePoint, algorithm, scale);
}
public static Map<String, Object> matrixDemo(
double[][] sourceWhitePoint, double[][] targetWhitePoint,
ChromaticAdaptationAlgorithm algorithm, int scale) {
return (Map<String, Object>) matrix(sourceWhitePoint, targetWhitePoint, algorithm, scale, true);
}
public static Object matrix(
double[][] sourceWhitePoint, double[][] targetWhitePoint,
ChromaticAdaptationAlgorithm algorithm, int scale, boolean isDemo) {
try {
if (targetWhitePoint == null || DoubleMatrixTools.same(sourceWhitePoint, targetWhitePoint, scale)) {
if (isDemo) {
Map<String, Object> ret = new HashMap<>();
ret.put("procedure", Languages.message("NeedNotAdaptChromatic"));
ret.put("adpatMatrix", DoubleMatrixTools.identityDouble(3));
return ret;
} else {
return DoubleMatrixTools.identityDouble(3);
}
}
double[][] MA, MAI;
if (algorithm == null) {
algorithm = ChromaticAdaptationAlgorithm.Bradford;
}
switch (algorithm) {
case Bradford:
MA = Bradford;
MAI = BradfordInversed;
break;
case XYZScaling:
MA = XYZScaling;
MAI = XYZScalingInversed;
break;
case VonKries:
MA = VonKries;
MAI = VonKriesInversed;
break;
default:
return null;
}
double[][] sourceCone = DoubleMatrixTools.multiply(MA, sourceWhitePoint);
double[][] targetCone = DoubleMatrixTools.multiply(MA, targetWhitePoint);
double[][] ratioMatrix = new double[3][3];
ratioMatrix[0][0] = targetCone[0][0] / sourceCone[0][0];
ratioMatrix[1][1] = targetCone[1][0] / sourceCone[1][0];
ratioMatrix[2][2] = targetCone[2][0] / sourceCone[2][0];
double[][] M = DoubleMatrixTools.multiply(MAI, ratioMatrix);
M = DoubleMatrixTools.multiply(M, MA);
if (scale >= 0) {
M = DoubleMatrixTools.scale(M, scale);
} else {
scale = 8;
}
if (isDemo) {
String s = "";
s += "SourceWhitePoint = \n";
s += DoubleMatrixTools.print(sourceWhitePoint, 20, scale);
s += "TargetWhitePoint = \n";
s += DoubleMatrixTools.print(targetWhitePoint, 20, scale);
s += "\n" + Languages.message("Algorithm") + ": " + algorithm + "\n";
s += "MA = \n";
s += DoubleMatrixTools.print(MA, 20, scale);
s += "MA_Inversed =\n";
s += DoubleMatrixTools.print(MAI, 20, scale);
s += "\n" + "SourceCone = MA * SourceWhitePoint =\n";
s += DoubleMatrixTools.print(sourceCone, 20, scale);
s += "\n" + "TargetCone = MA * TargetWhitePoint =\n";
s += DoubleMatrixTools.print(targetCone, 20, scale);
s += "\n" + "RatioMatrix = TargetCone / SourceCone =\n";
s += DoubleMatrixTools.print(ratioMatrix, 20, scale);
s += "\n" + "Adaptation_Matrix = MA_Inversed * RatioMatrix * MA =\n";
s += DoubleMatrixTools.print(M, 20, scale);
Map<String, Object> ret = new HashMap<>();
ret.put("procedure", s);
ret.put("adpatMatrix", M);
return ret;
} else {
return M;
}
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
/*
Chromatic Adaptation matrix
Algorithm: Bradford
*/
public static double[] AtoD50(double[] a) {
double[][] matrix = {
{0.8779529, -0.0915288, 0.2566181},
{-0.1117372, 1.0924325, 0.0851788},
{0.0502012, -0.0837636, 2.3994031}
};
double[] d50 = DoubleMatrixTools.multiply(matrix, a);
return d50;
}
public static double[] BtoD50(double[] b) {
double[][] matrix = {
{0.9850292, -0.0093910, -0.0026720},
{-0.0147751, 1.0146711, -0.0000389},
{-0.0017035, 0.0035957, 0.9660561}
};
double[] d50 = DoubleMatrixTools.multiply(matrix, b);
return d50;
}
public static double[] CtoD50(double[] c) {
double[][] matrix = {
{1.0376976, 0.0153932, -0.0582624},
{0.0170675, 1.0056038, -0.0188973},
{-0.0120126, 0.0204361, 0.6906380}
};
double[] d50 = DoubleMatrixTools.multiply(matrix, c);
return d50;
}
public static double[] EtoD65(double[] e) {
double[][] matrix = {
{0.9531874, -0.0265906, 0.0238731},
{-0.0382467, 1.0288406, 0.0094060},
{0.0026068, -0.0030332, 1.0892565}
};
double[] d65 = DoubleMatrixTools.multiply(matrix, e);
return d65;
}
public static double[] EtoD50(double[] e) {
double[][] matrix = {
{0.9977545, -0.0041632, -0.0293713},
{-0.0097677, 1.0183168, -0.0085490},
{-0.0074169, 0.0134416, 0.8191853}
};
double[] d65 = DoubleMatrixTools.multiply(matrix, e);
return d65;
}
public static double[] D50toE(double[] d50) {
double[][] matrix = {
{1.0025535, 0.0036238, 0.0359837},
{0.0096914, 0.9819125, 0.0105947},
{0.0089181, -0.0160789, 1.2208770}
};
double[] e = DoubleMatrixTools.multiply(matrix, d50);
return e;
}
public static double[] D50toD65(double[] d50) {
double[][] matrix = {
{0.9555766, -0.0230393, 0.0631636},
{-0.0282895, 1.0099416, 0.0210077},
{0.0122982, -0.0204830, 1.3299098}
};
double[] d65 = DoubleMatrixTools.multiply(matrix, d50);
return d65;
}
public static double[] D55toD50(double[] d55) {
double[][] matrix = {
{1.0184567, 0.0093864, -0.0213199},
{0.0120291, 0.9951460, -0.0072228},
{-0.0039673, 0.0064899, 0.8925936}
};
double[] d50 = DoubleMatrixTools.multiply(matrix, d55);
return d50;
}
public static double[] D65toE(double[] d65) {
double[][] matrix = {
{1.0502616, 0.0270757, -0.0232523},
{0.0390650, 0.9729502, -0.0092579},
{-0.0024047, 0.0026446, 0.9180873}
};
double[] e = DoubleMatrixTools.multiply(matrix, d65);
return e;
}
public static double[] D65toD50(double[] d65) {
double[][] matrix = {
{1.0478112, 0.0228866, -0.0501270},
{0.0295424, 0.9904844, -0.0170491},
{-0.0092345, 0.0150436, 0.7521316}
};
double[] d50 = DoubleMatrixTools.multiply(matrix, d65);
return d50;
}
/*
Data
*/
public static enum ChromaticAdaptationAlgorithm {
Bradford, XYZScaling, VonKries
}
public static List<String> names() {
List<String> names = new ArrayList<>();
for (ChromaticAdaptationAlgorithm c : ChromaticAdaptationAlgorithm.values()) {
names.add(c + "");
}
return names;
}
// Chromatic Adaptation Algorithms
public static double[][] XYZScaling = {
{1.0000000, 0.0000000, 0.0000000},
{0.0000000, 1.0000000, 0.0000000},
{0.0000000, 0.0000000, 1.0000000}
};
public static double[][] XYZScalingInversed = {
{1.0000000, 0.0000000, 0.0000000},
{0.0000000, 1.0000000, 0.0000000},
{0.0000000, 0.0000000, 1.0000000}
};
public static double[][] Bradford = {
{0.8951000, 0.2664000, -0.1614000},
{-0.7502000, 1.7135000, 0.0367000},
{0.0389000, -0.0685000, 1.0296000}
};
public static double[][] BradfordInversed = {
{0.9869929, -0.1470543, 0.1599627},
{0.4323053, 0.5183603, 0.0492912},
{-0.0085287, 0.0400428, 0.9684867}
};
public static double[][] VonKries = {
{0.4002400, 0.7076000, -0.0808100},
{-0.2263000, 1.1653200, 0.0457000},
{0.0000000, 0.0000000, 0.9182200}
};
public static double[][] VonKriesInversed = {
{1.8599364, -1.1293816, 0.2198974},
{0.3611914, 0.6388125, -0.0000064},
{0.0000000, 0.0000000, 1.0890636}
};
/*
get/set
*/
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public String getBradfordMethod() {
return BradfordMethod;
}
public void setBradfordMethod(String BradfordMethod) {
this.BradfordMethod = BradfordMethod;
}
public String getXYZScalingMethod() {
return XYZScalingMethod;
}
public void setXYZScalingMethod(String XYZScalingMethod) {
this.XYZScalingMethod = XYZScalingMethod;
}
public String getVonKriesMethod() {
return VonKriesMethod;
}
public void setVonKriesMethod(String VonKriesMethod) {
this.VonKriesMethod = VonKriesMethod;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/ColorValue.java | released/MyBox/src/main/java/mara/mybox/color/ColorValue.java | package mara.mybox.color;
import mara.mybox.tools.DoubleTools;
/**
* @Author Mara
* @CreateDate 2019-5-24 7:59:40
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class ColorValue {
public static enum ColorType {
CIEXYZ, CIExyY, CIELab, CIELCH, CIELuv,
sRGB, AdobeRGB, AppleRGB, CIERGB, PALRGB, NTSCRGB, ColorMatchRGB, ProPhotoRGB, SMPTECRGB,
HSB, CMYK
}
private ColorType type;
private double d1, d2, d3, d4;
private int i1 = -1, i2 = -1, i3 = -1, i4 = -1;
private String colorSpace, conditions, values,
gamma, illuminant, v1, v2, v3, v4;
public ColorValue(String colorSpace, String conditions, double[] values) {
this.colorSpace = colorSpace;
d1 = DoubleTools.scale(values[0], 2);
d2 = DoubleTools.scale(values[1], 2);
d3 = DoubleTools.scale(values[2], 2);
this.values = d1 + " " + d2 + " " + d3;
if (values.length == 4) {
d4 = DoubleTools.scale(values[3], 2);
this.values += " " + d4;
}
this.conditions = conditions;
}
public ColorValue(String colorSpace, String conditions, double[] values, int scale) {
this.colorSpace = colorSpace;
d1 = Math.round(values[0] * scale);
d2 = Math.round(values[1] * scale);
d3 = Math.round(values[2] * scale);
this.values = (int) d1 + " " + (int) d2 + " " + (int) d3;
if (values.length == 4) {
d4 = Math.round(values[3] * scale);
this.values += " " + (int) d4;
}
this.conditions = conditions;
}
public ColorValue(String colorSpace, String gamma, String illuminant, double[] values) {
this.colorSpace = colorSpace;
d1 = DoubleTools.scale(values[0], 8);
d2 = DoubleTools.scale(values[1], 8);
d3 = DoubleTools.scale(values[2], 8);
this.gamma = gamma;
this.illuminant = illuminant;
}
public ColorValue(String colorSpace, String gamma, String illuminant, double[] values, int scale) {
this.colorSpace = colorSpace;
d1 = Math.round(values[0] * scale);
d2 = Math.round(values[1] * scale);
d3 = Math.round(values[2] * scale);
this.gamma = gamma;
this.illuminant = illuminant;
}
public ColorValue(String colorSpace, String gamma, String illuminant, double v1, double v2, double v3) {
this.colorSpace = colorSpace;
d1 = v1;
d2 = v2;
d3 = v3;
this.gamma = gamma;
this.illuminant = illuminant;
}
public ColorValue(String colorSpace, String gamma, String illuminant, double v1, double v2, double v3, double v4) {
this.colorSpace = colorSpace;
d1 = v1;
d2 = v2;
d3 = v3;
d4 = v4;
this.gamma = gamma;
this.illuminant = illuminant;
}
public final void scale() {
if (type == null) {
return;
}
int ratio = 0;
switch (type) {
case CIEXYZ:
case CMYK:
ratio = 100;
break;
case sRGB:
case AdobeRGB:
case AppleRGB:
case CIERGB:
case PALRGB:
case NTSCRGB:
case ColorMatchRGB:
case ProPhotoRGB:
case SMPTECRGB:
ratio = 255;
break;
default:
return;
}
i1 = (int) Math.round(ratio * d1);
i2 = (int) Math.round(ratio * d2);
i3 = (int) Math.round(ratio * d3);
i4 = (int) Math.round(ratio * d4);
}
/*
get/set
*/
public ColorType getType() {
return type;
}
public void setType(ColorType type) {
this.type = type;
}
public double getD1() {
return d1;
}
public void setD1(double d1) {
this.d1 = d1;
}
public double getD2() {
return d2;
}
public void setD2(double d2) {
this.d2 = d2;
}
public double getD3() {
return d3;
}
public void setD3(double d3) {
this.d3 = d3;
}
public double getD4() {
return d4;
}
public void setD4(double d4) {
this.d4 = d4;
}
public int getI1() {
return i1;
}
public void setI1(int i1) {
this.i1 = i1;
}
public int getI2() {
return i2;
}
public void setI2(int i2) {
this.i2 = i2;
}
public int getI3() {
return i3;
}
public void setI3(int i3) {
this.i3 = i3;
}
public int getI4() {
return i4;
}
public void setI4(int i4) {
this.i4 = i4;
}
public String getGamma() {
return gamma;
}
public void setGamma(String gamma) {
this.gamma = gamma;
}
public String getIlluminant() {
return illuminant;
}
public void setIlluminant(String illuminant) {
this.illuminant = illuminant;
}
public String getColorSpace() {
return colorSpace;
}
public void setColorSpace(String colorSpace) {
this.colorSpace = colorSpace;
}
public String getConditions() {
return conditions;
}
public void setConditions(String conditions) {
this.conditions = conditions;
}
public String getValues() {
return values;
}
public void setValues(String values) {
this.values = values;
}
public String getV1() {
return v1;
}
public void setV1(String v1) {
this.v1 = v1;
}
public String getV2() {
return v2;
}
public void setV2(String v2) {
this.v2 = v2;
}
public String getV3() {
return v3;
}
public void setV3(String v3) {
this.v3 = v3;
}
public String getV4() {
return v4;
}
public void setV4(String v4) {
this.v4 = v4;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/AppleRGB.java | released/MyBox/src/main/java/mara/mybox/color/AppleRGB.java | package mara.mybox.color;
import static mara.mybox.color.RGBColorSpace.gamma18;
import static mara.mybox.color.RGBColorSpace.linear18;
/**
* @Author Mara
* @CreateDate 2019-5-21 12:17:46
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class AppleRGB {
public static double linearAppleRGB(double v) {
return linear18(v);
}
public static double gammaAppleRGB(double v) {
return gamma18(v);
}
public static double[] gammaAppleRGB(double[] linearRGB) {
double[] rgb = new double[3];
rgb[0] = gamma18(linearRGB[0]);
rgb[1] = gamma18(linearRGB[1]);
rgb[2] = gamma18(linearRGB[2]);
return rgb;
}
public static double[] AppleRGBtoXYZ(double[] applergb) {
double linearRed = linearAppleRGB(applergb[0]);
double linearGreen = linearAppleRGB(applergb[1]);
double linearBlue = linearAppleRGB(applergb[2]);
double[] xyz = new double[3];
xyz[0] = 0.4497288 * linearRed + 0.3162486 * linearGreen + 0.1844926 * linearBlue;
xyz[1] = 0.2446525 * linearRed + 0.6720283 * linearGreen + 0.0833192 * linearBlue;
xyz[2] = 0.0251848 * linearRed + 0.1411824 * linearGreen + 0.9224628 * linearBlue;
return xyz;
}
public static double[] XYZtoAppleRGB(double[] xyz) {
double linearRed = 2.9515373 * xyz[0] - 1.2894116 * xyz[1] - 0.4738445 * xyz[2];
double linearGreen = -1.0851093 * xyz[0] + 1.9908566 * xyz[1] + 0.0372026 * xyz[2];
double linearBlue = 0.0854934 * xyz[0] - 0.2694964 * xyz[1] + 1.0912975 * xyz[2];
double[] applergb = new double[3];
applergb[0] = gammaAppleRGB(linearRed);
applergb[1] = gammaAppleRGB(linearGreen);
applergb[2] = gammaAppleRGB(linearBlue);
return applergb;
}
public static double[] AppleRGBtoSRGB(double[] applergb) {
double[] xyz = AppleRGBtoXYZ(applergb);
return CIEColorSpace.XYZd65toSRGBd65(xyz);
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/IccTags.java | released/MyBox/src/main/java/mara/mybox/color/IccTags.java | package mara.mybox.color;
import java.awt.color.ICC_Profile;
import java.util.ArrayList;
import java.util.List;
import static mara.mybox.color.IccProfile.toBytes;
import static mara.mybox.color.IccXML.iccTagsXml;
import static mara.mybox.tools.ByteTools.bytesToInt;
import static mara.mybox.tools.ByteTools.intToBytes;
import static mara.mybox.tools.ByteTools.subBytes;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2019-5-6
* @Description
* @License Apache License Version 2.0
*/
public class IccTags {
private byte[] data; // all bytes in the profile, including 128 bytes of header
private List<IccTag> tags;
private String xml;
private boolean isValid, normalizeLut;
private String error;
public IccTags(byte[] data, boolean normalizeLut) {
try {
this.data = data;
this.normalizeLut = normalizeLut;
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public List<IccTag> readTags() {
if (data == null) {
return null;
}
if (tags == null) {
tags = iccTagsValues(data, normalizeLut);
}
return tags;
}
public IccTag getTag(String tag) {
if (tags == null) {
tags = iccTagsValues(data, normalizeLut);
}
return getTag(tags, tag);
}
public byte[] update() {
data = encodeTags(tags);
return data;
}
/*
Static methods
*/
public static List<IccTag> iccTagsValues(ICC_Profile profile, boolean normalizedLut) {
if (profile == null) {
return null;
}
byte[] data = profile.getData();
return IccTags.iccTagsValues(data, normalizedLut);
}
public static List<IccTag> iccTagsValues(byte[] data, boolean normalizedLut) {
List<IccTag> tags = new ArrayList<>();
try {
if (data == null || data.length < 132) {
return tags;
}
int number = bytesToInt(subBytes(data, 128, 4));
for (int i = 0; i < number; ++i) {
int offset = bytesToInt(subBytes(data, 136 + i * 12, 4));
int size = bytesToInt(subBytes(data, 140 + i * 12, 4));
IccTag tag = new IccTag(new String(subBytes(data, 132 + i * 12, 4)),
offset, subBytes(data, offset, size), normalizedLut);
tags.add(tag);
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
return tags;
}
public static IccTag getTag(List<IccTag> tags, String tag) {
if (tags == null || tag == null || tag.trim().isEmpty()) {
return null;
}
for (IccTag iccTag : tags) {
if (iccTag.getTag().equals(tag)) {
return iccTag;
}
}
return null;
}
/*
Encode data
*/
public static byte[] encodeTags(List<IccTag> tags) {
try {
if (tags == null) {
return null;
}
int number = tags.size();
int size = 132 + 12 * number;
for (IccTag tag : tags) {
size += tag.getBytes().length;
int m = size % 4;
if (m > 0) {
size += 4 - m;
}
}
byte[] data = new byte[size];
System.arraycopy(intToBytes(size), 0, data, 0, 4);
System.arraycopy(intToBytes(number), 0, data, 128, 4);
int offset = 132 + 12 * number;
for (int i = 0; i < number; ++i) {
IccTag tag = tags.get(i);
size = tag.getBytes().length;
// Item in Tags Table
byte[] tagBytes = toBytes(tag.getTag());
System.arraycopy(tagBytes, 0, data, 132 + i * 12, 4);
byte[] offsetBytes = intToBytes(offset);
System.arraycopy(offsetBytes, 0, data, 136 + i * 12, 4);
byte[] sizeBytes = intToBytes(size);
System.arraycopy(sizeBytes, 0, data, 140 + i * 12, 4);
// Tag data
System.arraycopy(tag.getBytes(), 0, data, offset, size);
offset += size;
int m = offset % 4;
if (m > 0) {
offset += 4 - m;
}
}
return data;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
/*
Get/Set
*/
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public String getXml() {
if (xml == null) {
xml = iccTagsXml(getTags());
}
return xml;
}
public void setXml(String xml) {
this.xml = xml;
}
public List<IccTag> getTags() {
if (tags == null) {
readTags();
}
return tags;
}
public void setTags(List<IccTag> tags) {
this.tags = tags;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public boolean isIsValid() {
return isValid;
}
public void setIsValid(boolean isValid) {
this.isValid = isValid;
}
public boolean isNormalizeLut() {
return normalizeLut;
}
public void setNormalizeLut(boolean normalizeLut) {
this.normalizeLut = normalizeLut;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/RGB2RGBConversionMatrix.java | released/MyBox/src/main/java/mara/mybox/color/RGB2RGBConversionMatrix.java | package mara.mybox.color;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mara.mybox.color.ChromaticAdaptation.ChromaticAdaptationAlgorithm;
import mara.mybox.color.RGBColorSpace.ColorSpaceType;
import static mara.mybox.color.RGBColorSpace.primariesTristimulus;
import static mara.mybox.color.RGBColorSpace.whitePointMatrix;
import mara.mybox.data.StringTable;
import mara.mybox.tools.DoubleMatrixTools;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2019-5-21 12:09:26
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
// http://brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
// http://brucelindbloom.com/index.html?WorkingSpaceInfo.html
// http://brucelindbloom.com/index.html?ColorCalculator.html
public class RGB2RGBConversionMatrix {
public String source, sourceWhite, target, targetWhite;
public String algorithm, source2target;
public RGB2RGBConversionMatrix() {
}
/*
Generation of Conversion matrices
*/
public static List<RGB2RGBConversionMatrix> all(int scale) {
List<RGB2RGBConversionMatrix> data = new ArrayList<>();
for (ColorSpaceType source : ColorSpaceType.values()) {
Illuminant.IlluminantType sourceWhite = RGBColorSpace.illuminantType(source);
for (ColorSpaceType target : ColorSpaceType.values()) {
if (source == target) {
continue;
}
for (ChromaticAdaptationAlgorithm algorithm : ChromaticAdaptationAlgorithm.values()) {
double[][] source2target = rgb2rgb(source, target, algorithm);
RGB2RGBConversionMatrix c = new RGB2RGBConversionMatrix();
c.setSource(RGBColorSpace.name(source));
c.setSourceWhite(sourceWhite + "");
c.setTarget(RGBColorSpace.name(target));
c.setTargetWhite(RGBColorSpace.illuminantType(target) + "");
c.setAlgorithm(algorithm + "");
c.setSource2target(DoubleMatrixTools.print(source2target, 0, scale));
data.add(c);
}
}
}
return data;
}
public static StringTable allTable(int scale) {
List<String> names = new ArrayList<>();
names.addAll(Arrays.asList(Languages.message("SourceColorSpace"),
Languages.message("SourceReferenceWhite"), Languages.message("TargetColorSpace"), Languages.message("TargetReferenceWhite"),
"Bradford", "XYZ", "Von Kries"
));
StringTable table = new StringTable(names, Languages.message("LinearRGB2RGBMatrix"));
for (ColorSpaceType source : ColorSpaceType.values()) {
Illuminant.IlluminantType sourceWhite = RGBColorSpace.illuminantType(source);
for (ColorSpaceType target : ColorSpaceType.values()) {
if (source == target) {
continue;
}
double[][] m1 = rgb2rgb(source, target, ChromaticAdaptationAlgorithm.Bradford);
double[][] m2 = rgb2rgb(source, target, ChromaticAdaptationAlgorithm.XYZScaling);
double[][] m3 = rgb2rgb(source, target, ChromaticAdaptationAlgorithm.VonKries);
List<String> row = new ArrayList<>();
row.addAll(Arrays.asList(
RGBColorSpace.name(source), sourceWhite.name(), RGBColorSpace.name(target),
RGBColorSpace.illuminantType(target).name(),
DoubleMatrixTools.html(m1, scale),
DoubleMatrixTools.html(m2, scale),
DoubleMatrixTools.html(m3, scale)
));
table.add(row);
}
}
return table;
}
public static String allTexts(int scale) {
StringBuilder s = new StringBuilder();
for (ColorSpaceType source : ColorSpaceType.values()) {
Illuminant.IlluminantType sourceWhite = RGBColorSpace.illuminantType(source);
for (ColorSpaceType target : ColorSpaceType.values()) {
if (source == target) {
continue;
}
for (ChromaticAdaptationAlgorithm algorithm : ChromaticAdaptationAlgorithm.values()) {
double[][] source2target = rgb2rgb(source, target, algorithm);
s.append(Languages.message("SourceColorSpace")).append(": ").
append(RGBColorSpace.name(source)).append("\n");
s.append(Languages.message("SourceReferenceWhite")).append(": ").
append(sourceWhite).append("\n");
s.append(Languages.message("TargetColorSpace")).append(": ").
append(RGBColorSpace.name(target)).append("\n");
s.append(Languages.message("TargetReferenceWhite")).append(": ").
append(RGBColorSpace.illuminantType(target)).append("\n");
s.append(Languages.message("AdaptationAlgorithm")).append(": ").
append(algorithm).append("\n");
s.append(Languages.message("LinearRGB2RGBMatrix")).append(": \n");
s.append(DoubleMatrixTools.print(source2target, 20, scale)).append("\n");
}
}
}
return s.toString();
}
public static double[][] rgb2rgb(ColorSpaceType source, ColorSpaceType target) {
return rgb2rgb(source, target, ChromaticAdaptationAlgorithm.Bradford);
}
public static double[][] rgb2rgb(ColorSpaceType source, ColorSpaceType target,
ChromaticAdaptationAlgorithm algorithm) {
return rgb2rgb(primariesTristimulus(source), whitePointMatrix(source),
primariesTristimulus(target), whitePointMatrix(target),
algorithm, -1);
}
public static double[][] rgb2rgb(
double[][] sourcePrimaries, double[][] sourceWhitePoint,
double[][] targetPrimaries, double[][] targetWhitePoint,
ChromaticAdaptation.ChromaticAdaptationAlgorithm algorithm, int scale) {
return (double[][]) rgb2rgb(sourcePrimaries, sourceWhitePoint, targetPrimaries, targetWhitePoint,
algorithm, scale, false);
}
public static Object rgb2rgb(
double[][] sourcePrimaries, double[][] sourceWhitePoint,
double[][] targetPrimaries, double[][] targetWhitePoint,
ChromaticAdaptation.ChromaticAdaptationAlgorithm algorithm, int scale, boolean isDemo) {
try {
Map<String, Object> map;
Object rgb2xyzObject = RGB2XYZConversionMatrix.rgb2xyz(sourcePrimaries, sourceWhitePoint,
targetWhitePoint, algorithm, scale, isDemo);
double[][] rgb2xyzMatrix;
String rgb2xyzString = null;
if (isDemo) {
map = (Map<String, Object>) rgb2xyzObject;
rgb2xyzMatrix = (double[][]) map.get("conversionMatrix");
rgb2xyzString = (String) map.get("procedure");
} else {
rgb2xyzMatrix = (double[][]) rgb2xyzObject;
}
Object xyz2rgbObject = RGB2XYZConversionMatrix.xyz2rgb(targetPrimaries, targetWhitePoint, targetWhitePoint,
algorithm, scale, isDemo);
double[][] xyz2rgbMatrix;
String xyz2rgbString = null;
if (isDemo) {
map = (Map<String, Object>) xyz2rgbObject;
xyz2rgbMatrix = (double[][]) map.get("conversionMatrix");
xyz2rgbString = (String) map.get("procedure");
} else {
xyz2rgbMatrix = (double[][]) xyz2rgbObject;
}
double[][] conversionMatrix = DoubleMatrixTools.multiply(xyz2rgbMatrix, rgb2xyzMatrix);
Object ret;
if (isDemo) {
String s = "ccccccccccccc " + Languages.message("Step") + " - Source Linear RGB -> XYZ ccccccccccccc\n";
s += rgb2xyzString + "\n";
s += "\nccccccccccccc " + Languages.message("Step") + " - XYZ -> target Linear RGB ccccccccccccc\n";
s += xyz2rgbString + "\n";
s += "\nccccccccccccc " + Languages.message("Step") + " - Source Linear RGB -> target Linear RGB ccccccccccccc\n";
s += "\nRGB_to_RGB_Matrix = XYZ_to_RGB_Matrix * RGB_to_XYZ_Matrix =\n";
s += DoubleMatrixTools.print(conversionMatrix, 20, scale);
map = new HashMap<>();
map.put("procedure", s);
map.put("conversionMatrix", conversionMatrix);
ret = map;
} else {
ret = conversionMatrix;
}
return ret;
} catch (Exception e) {
return null;
}
}
/*
get/set
*/
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getSourceWhite() {
return sourceWhite;
}
public void setSourceWhite(String sourceWhite) {
this.sourceWhite = sourceWhite;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public String getTargetWhite() {
return targetWhite;
}
public void setTargetWhite(String targetWhite) {
this.targetWhite = targetWhite;
}
public String getAlgorithm() {
return algorithm;
}
public void setAlgorithm(String algorithm) {
this.algorithm = algorithm;
}
public String getSource2target() {
return source2target;
}
public void setSource2target(String source2target) {
this.source2target = source2target;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/IccXML.java | released/MyBox/src/main/java/mara/mybox/color/IccXML.java | package mara.mybox.color;
import java.awt.color.ICC_Profile;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static mara.mybox.color.IccHeader.renderingIntent;
import static mara.mybox.tools.ByteTools.subBytes;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.value.AppValues;
/**
* @Author Mara
* @CreateDate 2019-5-14 10:21:53
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class IccXML {
public static String iccXML(IccHeader header, IccTags tags) {
try {
StringBuilder s = new StringBuilder();
s.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
s.append("<IccProfile>\n");
String headerXml = iccHeaderXml(header.getFields());
if (headerXml == null) {
return null;
}
s.append(headerXml);
s.append("\n");
String tagesXml = iccTagsXml(tags.getTags());
if (tagesXml == null) {
return null;
}
s.append(tagesXml);
s.append("</IccProfile>\n");
return s.toString();
} catch (Exception e) {
return null;
}
}
public static String iccHeaderXml(ICC_Profile profile) {
if (profile == null) {
return null;
}
return iccHeaderXml(subBytes(profile.getData(), 0, 128));
}
public static String iccHeaderXml(byte[] header) {
return iccHeaderXml(IccHeader.iccHeaderFields(header));
}
public static String iccHeaderXml(LinkedHashMap<String, IccTag> fields) {
if (fields == null) {
return null;
}
try {
StringBuilder s = new StringBuilder();
s.append(AppValues.Indent).append("<Header>\n");
for (String key : fields.keySet()) {
IccTag field = fields.get(key);
switch (key) {
case "ProfileFlagIndependently":
case "ProfileFlagMCSSubset":
case "DeviceAttributeMatte":
case "DeviceAttributeNegative":
case "DeviceAttributeBlackOrWhite":
case "DeviceAttributePaperBased":
case "DeviceAttributeTextured":
case "DeviceAttributeIsotropic":
case "DeviceAttributeSelfLuminous":
case "PCCIlluminantY":
case "PCCIlluminantZ":
continue;
case "CMMType":
case "ProfileDeviceClass":
case "PrimaryPlatform":
case "DeviceManufacturer":
case "Creator":
String v = (String) field.getValue();
s.append(AppValues.Indent).append(AppValues.Indent).append("<").append(key).append(">")
.append(v.substring(0, 4)).append("</").append(key).append(">\n");
break;
case "RenderingIntent":
s.append(AppValues.Indent).append(AppValues.Indent).append("<").append(key).append(">")
.append(renderingIntent(field.getBytes())).append("</").append(key).append(">\n");
break;
case "ProfileFlagEmbedded":
s.append(AppValues.Indent).append(AppValues.Indent).append("<ProfileFlags>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<Embedded>")
.append(field.getValue()).append("</Embedded>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<Independently>")
.append(fields.get("ProfileFlagIndependently").getValue()).append("</Independently>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<MCSSubset>")
.append(fields.get("ProfileFlagMCSSubset").getValue()).append("</MCSSubset>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append("</ProfileFlags>\n");
break;
case "DeviceAttributeTransparency":
s.append(AppValues.Indent).append(AppValues.Indent).append("<DeviceAttributes>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<Transparency>")
.append(field.getValue()).append("</Transparency>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<Matte>")
.append(fields.get("DeviceAttributeMatte").getValue()).append("</Matte>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<Negative>")
.append(fields.get("DeviceAttributeNegative").getValue()).append("</Negative>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<BlackOrWhite>")
.append(fields.get("DeviceAttributeBlackOrWhite").getValue()).append("</BlackOrWhite>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<PaperBased>")
.append(fields.get("DeviceAttributePaperBased").getValue()).append("</PaperBased>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<Textured>")
.append(fields.get("DeviceAttributeTextured").getValue()).append("</Textured>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<Isotropic>")
.append(fields.get("DeviceAttributeIsotropic").getValue()).append("</Isotropic>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<SelfLuminous>")
.append(fields.get("DeviceAttributeSelfLuminous").getValue()).append("</SelfLuminous>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append("</DeviceAttributes>\n");
break;
case "PCCIlluminantX":
s.append(AppValues.Indent).append(AppValues.Indent).append("<ConnectionSpaceIlluminant>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<X>")
.append(field.getValue()).append("</X>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<Y>")
.append(fields.get("PCCIlluminantY").getValue()).append("</Y>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<Z>")
.append(fields.get("PCCIlluminantZ").getValue()).append("</Z>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append("</ConnectionSpaceIlluminant>\n");
break;
default:
s.append(AppValues.Indent).append(AppValues.Indent).append("<").append(key).append(">")
.append(field.getValue()).append("</").append(key).append(">\n");
break;
}
}
s.append(AppValues.Indent).append("</Header>\n");
return s.toString();
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static String iccTagsXml(List<IccTag> tags) {
if (tags == null || tags.isEmpty()) {
return null;
}
try {
StringBuilder s = new StringBuilder();
s.append(AppValues.Indent).append("<Tags>\n");
for (IccTag tag : tags) {
s.append(AppValues.Indent).append(AppValues.Indent).append("<").append(tag.getName())
.append(" tag=\"").append(tag.getTag()).append("\" offset=\"")
.append(tag.getOffset()).append("\" size=\"").append(tag.getBytes().length);
if (tag.getType() != null) {
s.append("\" type=\"").append(tag.getType()).append("\">\n");
if (tag.getValue() != null) {
switch (tag.getType()) {
case Text:
case Signature: {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<value>").append(tag.getValue()).append("</value>\n");
break;
}
case MultiLocalizedUnicode: {
Map<String, Object> values = (Map<String, Object>) tag.getValue();
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<ASCII length=\"").append(values.get("AsciiLength")).append("\">\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<![CDATA[").append(values.get("Ascii")).append("]]>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("</ASCII>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<Unicode code=\"").append(values.get("UnicodeCode")).
append("\" length=\"").append(values.get("UnicodeLength")).append("\">\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<![CDATA[").append(values.get("Unicode")).append("]]>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("</Unicode>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<ScriptCode code=\"").append(values.get("ScriptCodeCode")).
append("\" length=\"").append(values.get("ScriptCodeLength")).append("\">\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<![CDATA[").append(values.get("ScriptCode")).append("]]>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("</ScriptCode>\n");
break;
}
case XYZ: {
double[][] values = (double[][]) tag.getValue();
for (double[] xyz : values) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<XYZ x=\"").append(xyz[0]).append("\" y=\"").
append(xyz[1]).append("\" z=\"").append(xyz[2]).append("\"/>\n");
}
break;
}
case Curve: {
double[] values = (double[]) tag.getValue();
int count = 1;
for (double value : values) {
if (count % 6 == 1) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent);
}
s.append(value).append(" ");
if (count % 6 == 0 && count < values.length) {
s.append("\n");
}
count++;
}
s.append("\n");
break;
}
case Measurement: {
Map<String, Object> values = (Map<String, Object>) tag.getValue();
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<observer>").append(values.get("observer")).append("</observer>\n");
double[] tristimulus = (double[]) values.get("tristimulus");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<tristimulus x=\"").append(tristimulus[0]).append("\" y=\"").
append(tristimulus[1]).append("\" z=\"").append(tristimulus[2]).append("\"/>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<geometry>").append(values.get("geometry")).append("</geometry>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<flare>").append((double) values.get("flare")).append("</flare>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<type>").append(values.get("illuminantType")).append("</type>\n");
break;
}
case ViewingConditions: {
Map<String, Object> values = (Map<String, Object>) tag.getValue();
double[] illuminant = (double[]) values.get("illuminant");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<illuminant x=\"").append(illuminant[0]).append("\" y=\"").
append(illuminant[1]).append("\" z=\"").append(illuminant[2]).append("\"/>\n");
double[] surround = (double[]) values.get("surround");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<surround x=\"").append(surround[0]).append("\" y=\"").
append(surround[1]).append("\" z=\"").append(surround[2]).append("\"/>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<type>").append(values.get("illuminantType")).append("</type>\n");
break;
}
case S15Fixed16Array: {
double[] values = (double[]) tag.getValue();
for (int i = 0; i < values.length; ++i) {
if (i % 3 == 0) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent);
if (i > 0 && i < values.length - 1) {
s.append("\n");
}
}
s.append(values[i]).append(" ");
}
s.append("\n");
break;
}
case DateTime: {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append(tag.getValue()).append("\n");
break;
}
case LUT: {
try {
Map<String, Object> values = (Map<String, Object>) tag.getValue();
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<InputChannelsNumber>").append(values.get("InputChannelsNumber")).
append("</InputChannelsNumber>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<OutputChannelsNumber>").append(values.get("OutputChannelsNumber")).
append("</OutputChannelsNumber>\n");
if (values.get("type") != null) {
String type = (String) values.get("type");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<type>").append(type).append("</type>\n");
if (type.equals("lut8") || type.equals("lut16")) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<GridPointsNumber>").append(values.get("GridPointsNumber")).
append("</GridPointsNumber>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<Matrix>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append(values.get("e1")).append(AppValues.Indent).
append(values.get("e2")).append(AppValues.Indent).
append(values.get("e3")).append(AppValues.Indent).append("\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append(values.get("e4")).append(AppValues.Indent).
append(values.get("e5")).append(AppValues.Indent).
append(values.get("e6")).append(AppValues.Indent).append("\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append(values.get("e7")).append(AppValues.Indent).
append(values.get("e8")).append(AppValues.Indent).
append(values.get("e9")).append(AppValues.Indent).append("\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("</Matrix>\n");
if (type.equals("lut16")) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<InputTablesNumber>").append(values.get("InputTablesNumber")).
append("</InputTablesNumber>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<OutputTablesNumber>").append(values.get("OutputTablesNumber")).
append("</OutputTablesNumber>\n");
}
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<InputTables>\n");
List<List<Double>> InputTables = (List<List<Double>>) values.get("InputTables");
for (List<Double> input : InputTables) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent);
for (Double i : input) {
s.append(i).append(AppValues.Indent);
}
s.append("\n");
}
if (values.get("InputTablesTruncated") != null) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append(" <!-- Truncated -->\n");
}
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("</InputTables>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<CLUTTables>\n");
List<List<Double>> CLUTTables = (List<List<Double>>) values.get("CLUTTables");
for (List<Double> GridPoint : CLUTTables) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent);
for (Double p : GridPoint) {
s.append(p).append(AppValues.Indent);
}
s.append("\n");
}
if (values.get("CLUTTablesTruncated") != null) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append(" <!-- Truncated -->\n");
}
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("</CLUTTables>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("<OutputTables>\n");
List<List<Double>> OutputTables = (List<List<Double>>) values.get("OutputTables");
for (List<Double> output : OutputTables) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent);
for (Double o : output) {
s.append(o).append(AppValues.Indent);
}
s.append("\n");
}
if (values.get("OutputTablesTruncated") != null) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append(" <!-- Truncated -->\n");
}
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).append("</OutputTables>\n");
} else {
MyBoxLog.debug("OffsetBCurve:" + values.get("OffsetBCurve"));
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<OffsetBCurve>").append(values.get("OffsetBCurve")).append("</OffsetBCurve>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<OffsetMatrix>").append(values.get("OffsetMatrix")).append("</OffsetMatrix>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<OffsetMCurve>").append(values.get("OffsetMCurve")).append("</OffsetMCurve>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<OffsetCLUT>").append(values.get("OffsetCLUT")).append("</OffsetCLUT>\n");
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append("<OffsetACurve>").append(values.get("OffsetACurve")).append("</OffsetACurve>\n");
}
} else {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append(" <!-- Not Decoded -->\n");
}
} catch (Exception e) {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append(" <!-- Not Decoded -->\n");
}
break;
}
}
} else {
s.append(AppValues.Indent).append(AppValues.Indent).append(AppValues.Indent).
append(" <!-- Not Decoded -->\n");
}
} else {
s.append("\" type=\"Not Decoded\">\n");
}
s.append(AppValues.Indent).append(AppValues.Indent).append("</").append(tag.getName()).append(">\n");
}
s.append(AppValues.Indent).append("</Tags>\n");
return s.toString();
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/IccProfile.java | released/MyBox/src/main/java/mara/mybox/color/IccProfile.java | package mara.mybox.color;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import java.io.File;
import java.nio.charset.StandardCharsets;
import static mara.mybox.color.IccXML.iccXML;
import mara.mybox.tools.StringTools;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.ByteFileTools;
import mara.mybox.tools.MessageDigestTools;
/**
* @Author Mara
* @CreateDate 2019-5-6
* @Description
* @License Apache License Version 2.0
*/
public class IccProfile {
private ICC_Profile profile;
private File file;
private ColorSpace colorSpace;
private int predefinedColorSpaceType;
private byte[] data;
private IccHeader header;
private IccTags tags;
private boolean isValid, normalizeLut;
private String error;
public IccProfile(int colorSpaceType) {
try {
profile = ICC_Profile.getInstance(colorSpaceType);
init();
isValid = true;
} catch (Exception e) {
MyBoxLog.error(e);
error = e.toString();
isValid = false;
}
}
public IccProfile(String colorSpaceType) {
try {
predefinedColorSpaceType = ColorBase.colorSpaceType(colorSpaceType);
if (predefinedColorSpaceType < 0) {
return;
}
profile = ICC_Profile.getInstance(predefinedColorSpaceType);
init();
isValid = true;
} catch (Exception e) {
MyBoxLog.error(e);
error = e.toString();
isValid = false;
}
}
public IccProfile(File profileFile) {
try {
if (profileFile == null || !profileFile.exists()) {
return;
}
this.file = profileFile;
predefinedColorSpaceType = -1;
profile = ICC_Profile.getInstance(profileFile.getAbsolutePath());
init();
isValid = true;
} catch (Exception e) {
MyBoxLog.error(e);
error = e.toString();
isValid = false;
}
}
public IccProfile(byte[] data) {
try {
if (data == null) {
return;
}
this.data = data;
predefinedColorSpaceType = -1;
isValid = true;
} catch (Exception e) {
MyBoxLog.error(e);
error = e.toString();
isValid = false;
}
}
private void init() {
try {
if (profile == null) {
return;
}
if (predefinedColorSpaceType < 0) {
colorSpace = new ICC_ColorSpace(profile);
} else {
colorSpace = ColorSpace.getInstance(predefinedColorSpaceType);
}
isValid = colorSpace != null;
} catch (Exception e) {
MyBoxLog.error(e);
error = e.toString();
isValid = false;
}
}
public byte[] readData() {
if (data == null) {
if (file != null) {
data = ByteFileTools.readBytes(file);
} else if (profile != null) {
data = profile.getData();
}
}
return data;
}
public String readXML() {
return iccXML(getHeader(), getTags());
}
public boolean update(byte[] newHeader) {
if (newHeader == null || newHeader.length != 128) {
return false;
}
header.update(newHeader);
data = tags.update();
System.arraycopy(newHeader, 4, data, 4, 124);
return setProfileID();
}
public boolean setProfileID() {
try {
byte[] bytes44 = new byte[4];
System.arraycopy(data, 44, bytes44, 0, 4);
byte[] bytes64 = new byte[4];
System.arraycopy(data, 64, bytes64, 0, 4);
byte[] bytes84 = new byte[16];
System.arraycopy(data, 84, bytes84, 0, 16);
byte[] blank = new byte[4];
System.arraycopy(blank, 0, data, 44, 4);
System.arraycopy(blank, 0, data, 64, 4);
blank = new byte[16];
System.arraycopy(blank, 0, data, 84, 16);
byte[] digest = MessageDigestTools.MD5(data);
System.arraycopy(bytes44, 0, data, 44, 4);
System.arraycopy(bytes64, 0, data, 64, 4);
System.arraycopy(digest, 0, data, 84, 16);
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
// public boolean write(File file) {
// return FileTools.writeFile(file, data);
// }
public boolean write(File file, byte[] newHeader) {
if (!update(newHeader)) {
return false;
}
return ByteFileTools.writeFile(file, data) != null;
}
public float[] calculateXYZ(float[] color) {
if (profile == null) {
return null;
}
if (colorSpace == null) {
colorSpace = new ICC_ColorSpace(profile);
}
if (colorSpace == null) {
return null;
}
return colorSpace.toCIEXYZ(color);
}
public float[] calculateCoordinate(float[] xyz) {
if (xyz == null) {
return null;
}
float x = xyz[0];
float y = xyz[1];
float z = xyz[2];
float sum = x + y + z;
float[] xy = new float[2];
xy[0] = x / sum;
xy[1] = y / sum;
return xy;
}
/*
Encode
*/
public static byte[] toBytes(String value) {
try {
return value.getBytes(StandardCharsets.US_ASCII);
} catch (Exception e) {
return null;
}
}
public static byte[] first4ASCII(String value) {
byte[] bytes = new byte[4];
try {
String vString = value;
if (value.length() > 4) {
vString = value.substring(0, 4);
} else if (value.length() < 4) {
vString = StringTools.fillRightBlank(value, 4);
}
byte[] vBytes = toBytes(vString);
System.arraycopy(vBytes, 0, bytes, 0, 4);
} catch (Exception e) {
}
return bytes;
}
/*
Get/Set
*/
public ICC_Profile getProfile() {
return profile;
}
public void setProfile(ICC_Profile profile) {
this.profile = profile;
}
public byte[] getData() {
if (data == null) {
readData();
}
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public boolean isIsValid() {
return isValid;
}
public void setIsValid(boolean isValid) {
this.isValid = isValid;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public ColorSpace getColorSpace() {
if (profile == null) {
return null;
}
if (colorSpace == null) {
if (predefinedColorSpaceType < 0) {
colorSpace = new ICC_ColorSpace(profile);
} else {
colorSpace = ColorSpace.getInstance(predefinedColorSpaceType);
}
}
return colorSpace;
}
public void setColorSpace(ColorSpace iccColorSpace) {
this.colorSpace = iccColorSpace;
}
public IccHeader getHeader() {
if (header == null) {
header = new IccHeader(getData());
}
return header;
}
public void setHeader(IccHeader header) {
this.header = header;
}
public IccTags getTags() {
if (tags == null) {
tags = new IccTags(getData(), normalizeLut);
}
return tags;
}
public void setTags(IccTags tags) {
this.tags = tags;
}
public boolean isNormalizeLut() {
return normalizeLut;
}
public void setNormalizeLut(boolean normalizeLut) {
this.normalizeLut = normalizeLut;
}
public int getPredefinedColorSpaceType() {
return predefinedColorSpaceType;
}
public void setPredefinedColorSpaceType(int predefinedColorSpaceType) {
this.predefinedColorSpaceType = predefinedColorSpaceType;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/RGB2XYZConversionMatrix.java | released/MyBox/src/main/java/mara/mybox/color/RGB2XYZConversionMatrix.java | package mara.mybox.color;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mara.mybox.color.ChromaticAdaptation.ChromaticAdaptationAlgorithm;
import static mara.mybox.color.ChromaticAdaptation.matrix;
import mara.mybox.color.Illuminant.IlluminantType;
import mara.mybox.color.Illuminant.Observer;
import mara.mybox.color.RGBColorSpace.ColorSpaceType;
import static mara.mybox.color.RGBColorSpace.primariesTristimulus;
import static mara.mybox.color.RGBColorSpace.whitePointMatrix;
import mara.mybox.data.StringTable;
import mara.mybox.tools.DoubleMatrixTools;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2019-5-21 12:09:26
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
// http://brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
// http://brucelindbloom.com/index.html?WorkingSpaceInfo.html
// http://brucelindbloom.com/index.html?ColorCalculator.html
public class RGB2XYZConversionMatrix {
public String rgb, rgbWhite, xyzWhite, algorithm;
public String rgb2xyz, xyz2rgb;
public RGB2XYZConversionMatrix() {
}
/*
Generation of Conversion matrices
*/
public static List<RGB2XYZConversionMatrix> all(int scale) {
List<RGB2XYZConversionMatrix> data = new ArrayList<>();
for (ColorSpaceType colorSpace : ColorSpaceType.values()) {
IlluminantType csWhite = RGBColorSpace.illuminantType(colorSpace);
double[][] rgb2xyz = rgb2xyz(colorSpace);
for (IlluminantType targetIlluminant : IlluminantType.values()) {
for (Observer sourceObserver : Observer.values()) {
for (Observer targetObserver : Observer.values()) {
if (csWhite != targetIlluminant
|| sourceObserver == targetObserver) {
for (ChromaticAdaptationAlgorithm algorithm : ChromaticAdaptationAlgorithm.values()) {
double[][] adpatM = matrix(csWhite, Observer.CIE1931,
targetIlluminant, targetObserver, algorithm, -1);
double[][] adpatedC = DoubleMatrixTools.multiply(adpatM, rgb2xyz);
RGB2XYZConversionMatrix c = new RGB2XYZConversionMatrix();
c.setRgb(RGBColorSpace.name(colorSpace));
c.setRgbWhite(csWhite + " - " + Observer.CIE1931);
c.setXyzWhite(targetIlluminant + " - " + targetObserver);
c.setAlgorithm(algorithm + "");
c.setRgb2xyz(DoubleMatrixTools.print(adpatedC, 0, scale));
double[][] xyz2rgb = DoubleMatrixTools.inverse(adpatedC);
c.setXyz2rgb(DoubleMatrixTools.print(xyz2rgb, 0, scale));
data.add(c);
}
} else {
RGB2XYZConversionMatrix c = new RGB2XYZConversionMatrix();
c.setRgb(RGBColorSpace.name(colorSpace));
c.setRgbWhite(csWhite + " - " + Observer.CIE1931);
c.setXyzWhite(targetIlluminant + " - " + targetObserver);
c.setAlgorithm("");
c.setRgb2xyz(DoubleMatrixTools.print(rgb2xyz, 0, scale));
double[][] xyz2rgb = DoubleMatrixTools.inverse(rgb2xyz);
c.setXyz2rgb(DoubleMatrixTools.print(xyz2rgb, 0, scale));
data.add(c);
}
}
}
}
}
return data;
}
public static StringTable allTable(int scale) {
List<String> names = new ArrayList<>();
names.addAll(Arrays.asList(Languages.message("RGBColorSpace"),
Languages.message("RGBReferenceWhite"), Languages.message("XYZReferenceWhite"), Languages.message("Algorithm"),
"Linear RGB -> XYZ", "XYZ -> Linear RGB"
));
StringTable table = new StringTable(names, Languages.message("LinearRGB2XYZMatrix"));
for (ColorSpaceType colorSpace : ColorSpaceType.values()) {
IlluminantType csWhite = RGBColorSpace.illuminantType(colorSpace);
double[][] rgb2xyz = rgb2xyz(colorSpace);
for (IlluminantType targetIlluminant : IlluminantType.values()) {
for (Observer sourceObserver : Observer.values()) {
for (Observer targetObserver : Observer.values()) {
if (csWhite != targetIlluminant
|| sourceObserver == targetObserver) {
for (ChromaticAdaptationAlgorithm algorithm : ChromaticAdaptationAlgorithm.values()) {
double[][] adpatM = matrix(csWhite, Observer.CIE1931,
targetIlluminant, targetObserver, algorithm, -1);
double[][] adpatedC = DoubleMatrixTools.multiply(adpatM, rgb2xyz);
double[][] xyz2rgb = DoubleMatrixTools.inverse(adpatedC);
List<String> row = new ArrayList<>();
row.addAll(Arrays.asList(
RGBColorSpace.name(colorSpace),
csWhite + " - " + Observer.CIE1931,
targetIlluminant + " - " + targetObserver,
algorithm.name(),
DoubleMatrixTools.html(adpatedC, scale),
DoubleMatrixTools.html(xyz2rgb, scale)
));
table.add(row);
}
} else {
double[][] xyz2rgb = DoubleMatrixTools.inverse(rgb2xyz);
List<String> row = new ArrayList<>();
row.addAll(Arrays.asList(
RGBColorSpace.name(colorSpace),
csWhite + " - " + Observer.CIE1931,
targetIlluminant + " - " + targetObserver,
"",
DoubleMatrixTools.html(rgb2xyz, scale),
DoubleMatrixTools.html(xyz2rgb, scale)
));
table.add(row);
}
}
}
}
}
return table;
}
public static String allTexts(int scale) {
StringBuilder s = new StringBuilder();
for (ColorSpaceType colorSpace : ColorSpaceType.values()) {
IlluminantType csWhite = RGBColorSpace.illuminantType(colorSpace);
double[][] rgb2xyz = rgb2xyz(colorSpace);
for (IlluminantType targetIlluminant : IlluminantType.values()) {
for (Observer sourceObserver : Observer.values()) {
for (Observer targetObserver : Observer.values()) {
if (csWhite != targetIlluminant
|| sourceObserver == targetObserver) {
for (ChromaticAdaptationAlgorithm algorithm : ChromaticAdaptationAlgorithm.values()) {
double[][] adpatM = matrix(csWhite, Observer.CIE1931,
targetIlluminant, targetObserver, algorithm, -1);
double[][] adpatedC = DoubleMatrixTools.multiply(adpatM, rgb2xyz);
double[][] xyz2rgb = DoubleMatrixTools.inverse(adpatedC);
s.append(Languages.message("RGBColorSpace")).append(": ").
append(RGBColorSpace.name(colorSpace)).append("\n");
s.append(Languages.message("RGBReferenceWhite")).append(": ").
append(csWhite).append(" - ").append(Observer.CIE1931).append("\n");
s.append(Languages.message("XYZReferenceWhite")).append(": ").
append(targetIlluminant).append(" - ").append(targetObserver).append("\n");
s.append(Languages.message("AdaptationAlgorithm")).append(": ").
append(algorithm).append("\n");
s.append("Linear RGB -> XYZ: ").append("\n");
s.append(DoubleMatrixTools.print(adpatedC, 20, scale));
s.append("XYZ -> Linear RGB: ").append("\n");
s.append(DoubleMatrixTools.print(xyz2rgb, 20, scale)).append("\n");
}
} else {
double[][] xyz2rgb = DoubleMatrixTools.inverse(rgb2xyz);
s.append(Languages.message("RGBColorSpace")).append(": ").
append(RGBColorSpace.name(colorSpace)).append("\n");
s.append(Languages.message("RGBReferenceWhite")).append(": ").
append(csWhite).append(" - ").append(Observer.CIE1931).append("\n");
s.append(Languages.message("XYZReferenceWhite")).append(": ").
append(targetIlluminant).append(" - ").append(targetObserver).append("\n");
s.append("Linear RGB -> XYZ: ").append("\n");
s.append(DoubleMatrixTools.print(rgb2xyz, 20, scale));
s.append("XYZ -> Linear RGB: ").append("\n");
s.append(DoubleMatrixTools.print(xyz2rgb, 20, scale)).append("\n");
}
}
}
}
}
return s.toString();
}
public static double[][] rgb2xyz(ColorSpaceType colorSpace) {
return rgb2xyz(primariesTristimulus(colorSpace), whitePointMatrix(colorSpace));
}
public static double[][] rgb2xyz(double[][] primaries, double[][] sourceWhitePoint) {
return (double[][]) rgb2xyz(primaries, sourceWhitePoint, null, null, -1, false);
}
public static double[][] xyz2rgb(ColorSpaceType colorSpace) {
return DoubleMatrixTools.inverse(rgb2xyz(colorSpace));
}
public static double[][] xyz2rgb(double[][] primaries, double[][] sourceWhitePoint) {
return DoubleMatrixTools.inverse(rgb2xyz(primaries, sourceWhitePoint));
}
public static Object rgb2xyz(double[][] primaries,
double[][] sourceWhitePoint, double[][] targetWhitePoint,
ChromaticAdaptationAlgorithm algorithm, int scale, boolean isDemo) {
try {
double[][] t = DoubleMatrixTools.transpose(primaries);
double[][] i = DoubleMatrixTools.inverse(t);
double[][] s = DoubleMatrixTools.multiply(i, sourceWhitePoint);
double[][] conversionMatrix = new double[3][3];
conversionMatrix[0][0] = s[0][0] * t[0][0];
conversionMatrix[1][0] = s[0][0] * t[1][0];
conversionMatrix[2][0] = s[0][0] * t[2][0];
conversionMatrix[0][1] = s[1][0] * t[0][1];
conversionMatrix[1][1] = s[1][0] * t[1][1];
conversionMatrix[2][1] = s[1][0] * t[2][1];
conversionMatrix[0][2] = s[2][0] * t[0][2];
conversionMatrix[1][2] = s[2][0] * t[1][2];
conversionMatrix[2][2] = s[2][0] * t[2][2];
Object ret;
String d = "";
Map<String, Object> map;
if (isDemo) {
d += "WhitePoint =\n";
d += DoubleMatrixTools.print(sourceWhitePoint, 20, scale);
d += "\nRGB Primaires = (Each primary color is one row)\n";
d += DoubleMatrixTools.print(primaries, 20, scale);
d += "\nRGB_Transposed_Primaires = (Each primary color is one column)\n";
d += DoubleMatrixTools.print(t, 20, scale);
d += "\nInversed = inverse(RGB_Transposed_Primaires) = \n";
d += DoubleMatrixTools.print(i, 20, scale);
d += "\nSrgb = Inversed * RGB_WhitePoint = \n";
d += DoubleMatrixTools.print(s, 20, scale);
d += "\nRGB_to_XYZ_Matrix = (Column in Srgb) * (columns in RGB_Transposed_Primaires) =\n";
d += DoubleMatrixTools.print(conversionMatrix, 20, scale);
d += Languages.message("XYZSameWhiteRGB") + "\n";
}
if (targetWhitePoint == null || DoubleMatrixTools.same(sourceWhitePoint, targetWhitePoint, scale)) {
if (isDemo) {
d = "ccccccccccccc " + Languages.message("Step") + " - Linear RGB -> XYZ ccccccccccccc\n\n" + d;
map = new HashMap<>();
map.put("procedure", d);
map.put("conversionMatrix", conversionMatrix);
ret = map;
} else {
ret = conversionMatrix;
}
return ret;
}
double[][] adaptMatrix;
String adaptString = null;
Object adaptObject = matrix(sourceWhitePoint, targetWhitePoint, algorithm, scale, isDemo);
if (isDemo) {
map = (Map<String, Object>) adaptObject;
adaptMatrix = (double[][]) map.get("adpatMatrix");
adaptString = (String) map.get("procedure");
} else {
adaptMatrix = (double[][]) adaptObject;
}
double[][] adaptedConversionMatrix = DoubleMatrixTools.multiply(adaptMatrix, conversionMatrix);
if (scale >= 0) {
adaptedConversionMatrix = DoubleMatrixTools.scale(adaptedConversionMatrix, scale);
} else {
scale = 8;
}
if (isDemo) {
d = "ccccccccccccc " + Languages.message("Step") + " - Linear RGB -> XYZ , "
+ Languages.message("RGBXYZsameWhite") + " ccccccccccccc\n\n" + d;
d += "\naaaaaaaaaaaaa " + Languages.message("Step") + " - " + Languages.message("ChromaticAdaptation") + " aaaaaaaaaaaaa\n\n";
d += adaptString + "\n";
d += "\nccccccccccccc " + Languages.message("Step") + " - Linear RGB -> XYZ , "
+ Languages.message("RGBXYZdifferentWhite") + " ccccccccccccc\n";
d += "\nRGB Primaires = (Each primary color is one row)\n";
d += DoubleMatrixTools.print(primaries, 20, scale);
d += "\nRGB_WhitePoint =\n";
d += DoubleMatrixTools.print(sourceWhitePoint, 20, scale);
d += "\nXYZ_WhitePoint =\n";
d += DoubleMatrixTools.print(targetWhitePoint, 20, scale);
d += "\nRGB_to_XYZ_Matrix_different_WhitePoint = Adaptation_Matrix * RGB_to_XYZ_Matrix_same_WhitePoint\n";
d += DoubleMatrixTools.print(adaptedConversionMatrix, 20, scale);
map = new HashMap<>();
map.put("procedure", d);
map.put("conversionMatrix", adaptedConversionMatrix);
ret = map;
} else {
ret = adaptedConversionMatrix;
}
return ret;
} catch (Exception e) {
return null;
}
}
public static Object xyz2rgb(double[][] primaries,
double[][] sourceWhitePoint, double[][] targetWhitePoint,
ChromaticAdaptationAlgorithm algorithm, int scale, boolean isDemo) {
Object rgb2xyz = rgb2xyz(primaries, sourceWhitePoint, targetWhitePoint,
algorithm, scale, isDemo);
double[][] conversionMatrix;
Object rgb2xyzObject = rgb2xyz(primaries, sourceWhitePoint, targetWhitePoint, algorithm, scale, isDemo);
if (isDemo) {
Map<String, Object> map = (Map<String, Object>) rgb2xyzObject;
conversionMatrix = (double[][]) map.get("conversionMatrix");
conversionMatrix = DoubleMatrixTools.inverse(conversionMatrix);
map.put("conversionMatrix", conversionMatrix);
String s = (String) map.get("procedure");
s += "\nccccccccccccc " + Languages.message("Step") + " - XYZ -> Linear RGB ccccccccccccc\n\n";
s += "\nXYZ_to_RGB_Matrix = inverse( RGB_to_XYZ_Matrix ) = \n";
s += DoubleMatrixTools.print(conversionMatrix, 20, scale);
map.put("procedure", s);
return map;
} else {
conversionMatrix = (double[][]) rgb2xyzObject;
conversionMatrix = DoubleMatrixTools.inverse(conversionMatrix);
return conversionMatrix;
}
}
/*
get/set
*/
public String getAlgorithm() {
return algorithm;
}
public void setAlgorithm(String algorithm) {
this.algorithm = algorithm;
}
public String getXyzWhite() {
return xyzWhite;
}
public void setXyzWhite(String xyzWhite) {
this.xyzWhite = xyzWhite;
}
public String getRgb() {
return rgb;
}
public void setRgb(String rgb) {
this.rgb = rgb;
}
public String getRgbWhite() {
return rgbWhite;
}
public void setRgbWhite(String rgbWhite) {
this.rgbWhite = rgbWhite;
}
public String getRgb2xyz() {
return rgb2xyz;
}
public void setRgb2xyz(String rgb2xyz) {
this.rgb2xyz = rgb2xyz;
}
public String getXyz2rgb() {
return xyz2rgb;
}
public void setXyz2rgb(String xyz2rgb) {
this.xyz2rgb = xyz2rgb;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/CIEColorSpace.java | released/MyBox/src/main/java/mara/mybox/color/CIEColorSpace.java | package mara.mybox.color;
import java.util.ArrayList;
import java.util.List;
import static mara.mybox.color.AdobeRGB.gammaAdobeRGB;
import static mara.mybox.color.AppleRGB.gammaAppleRGB;
import static mara.mybox.color.ColorBase.clipRGB;
import static mara.mybox.color.SRGB.gammaSRGB;
import mara.mybox.tools.DoubleMatrixTools;
/**
* @Author Mara
* @CreateDate 2019-5-24 8:44:35
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class CIEColorSpace {
public static enum ColorSpaceType {
CIEXYZ, CIExyY, CIELuv, CIELab, LCHab, LCHuv
}
public static List<String> names() {
List<String> names = new ArrayList<>();
for (ColorSpaceType cs : ColorSpaceType.values()) {
names.add(cs + "");
}
return names;
}
public static double[] XYZd50toCIERGB(double[] xyz) {
double[][] matrix = {
{2.3706743, -0.9000405, -0.4706338},
{-0.5138850, 1.4253036, 0.0885814},
{0.0052982, -0.0146949, 1.0093968}
};
double[] cieRGB = DoubleMatrixTools.multiply(matrix, xyz);
return cieRGB;
}
public static double[] XYZd50toCIELab(double X, double Y, double Z) {
return XYZtoCIELab(0.96422, 1, 0.82521, X, Y, Z);
}
// http://brucelindbloom.com/index.html?Eqn_XYZ_to_Lab.html
public static double[] XYZtoCIELab(
double rX, double rY, double rZ,
double X, double Y, double Z) {
double xr = X / rX;
double yr = Y / rY;
double zr = Z / rZ;
double threshold = 0.008856;
double d3 = 0.333333;
double p1 = 7.787069;
double p2 = 0.137931;
if (xr > threshold) {
xr = Math.pow(xr, d3);
} else {
xr = p1 * xr + p2;
}
if (yr > threshold) {
yr = Math.pow(yr, d3);
} else {
yr = p1 * yr + p2;
}
if (zr > threshold) {
zr = Math.pow(zr, d3);
} else {
zr = p1 * zr + p2;
}
double[] CIELab = new double[3];
CIELab[0] = 116 * yr - 16;
CIELab[1] = 500 * (xr - yr);
CIELab[2] = 200 * (yr - zr);
return CIELab;
}
public static double[] XYZd50toCIELuv(double X, double Y, double Z) {
return XYZtoCIELuv(0.96422, 1, 0.82521, X, Y, Z);
}
// http://brucelindbloom.com/index.html?Eqn_XYZ_to_Luv.html
public static double[] XYZtoCIELuv(
double rX, double rY, double rZ,
double X, double Y, double Z) {
if (X == 0 && Y == 0 && Z == 0) {
return new double[3];
}
double yr = Y / rY;
double u = (4 * X) / (X + 15 * Y + 3 * Z);
double v = (9 * Y) / (X + 15 * Y + 3 * Z);
double ru = (4 * rX) / (rX + 15 * rY + 3 * rZ);
double rv = (9 * rY) / (rX + 15 * rY + 3 * rZ);
double[] CIELuv = new double[3];
if (yr > 0.008856) {
CIELuv[0] = 116 * Math.pow(yr, 1d / 3) - 16;
} else {
CIELuv[0] = 903.3 * yr;
}
CIELuv[1] = 13 * CIELuv[0] * (u - ru);
CIELuv[2] = 13 * CIELuv[0] * (v - rv);
return CIELuv;
}
public static double[] LabtoLCHab(double[] Lab) {
return LabtoLCHab(Lab[0], Lab[1], Lab[2]);
}
public static double[] LabtoLCHab(double L, double a, double b) {
double[] LCH = new double[3];
LCH[0] = L;
LCH[1] = Math.sqrt(a * a + b * b);
double d = Math.atan2(b, a) * 180 / Math.PI;
if (d >= 0) {
LCH[2] = d;
} else {
LCH[2] = d + 360;
}
return LCH;
}
public static double[] LuvtoLCHuv(double[] Luv) {
return LuvtoLCHuv(Luv[0], Luv[1], Luv[2]);
}
public static double[] LuvtoLCHuv(double L, double u, double v) {
double[] LCH = new double[3];
LCH[0] = L;
LCH[1] = Math.sqrt(u * u + v * v);
double d = Math.atan2(v, u) * 180 / Math.PI;
if (d >= 0) {
LCH[2] = d;
} else {
LCH[2] = d + 360;
}
return LCH;
}
/*
sRGB
*/
public static double[] XYZd50toSRGBd65(double X, double Y, double Z) {
return XYZd50toSRGBd65(ColorBase.array(X, Y, Z));
}
public static double[] XYZd50toSRGBd65(double[] xyzD50) {
double[] xyzD65 = ChromaticAdaptation.D50toD65(xyzD50);
return XYZd65toSRGBd65(xyzD65);
}
public static double[] XYZd50toSRGBd65Linear(double X, double Y, double Z) {
return XYZd50toSRGBd65Linear(ColorBase.array(X, Y, Z));
}
public static double[] XYZd50toSRGBd65Linear(double[] xyzD50) {
double[] xyzD65 = ChromaticAdaptation.D50toD65(xyzD50);
return XYZd65toSRGBd65Linear(xyzD65);
}
public static double[] XYZd50toSRGBd50(double[] xyz) {
double[][] matrix = {
{3.1338561, -1.6168667, -0.4906146},
{-0.9787684, 1.9161415, 0.0334540},
{0.0719453, -0.2289914, 1.4052427}
};
double[] linearRGB = DoubleMatrixTools.multiply(matrix, xyz);
linearRGB = clipRGB(linearRGB);
double[] srgb = gammaSRGB(linearRGB);
return srgb;
}
public static double[] XYZd65toSRGBd65(double[] xyzd65) {
double[] linearRGB = XYZd65toSRGBd65Linear(xyzd65);
double[] srgb = gammaSRGB(linearRGB);
return srgb;
}
public static double[] XYZd65toSRGBd65Linear(double[] xyzd65) {
double[][] matrix = {
{3.2409699419045235, -1.5373831775700944, -0.49861076029300355},
{-0.9692436362808797, 1.8759675015077204, 0.0415550574071756},
{0.05563007969699365, -0.20397695888897652, 1.0569715142428786}
};
double[] linearRGB = DoubleMatrixTools.multiply(matrix, xyzd65);
linearRGB = clipRGB(linearRGB);
return linearRGB;
}
/*
Adobe RGB
*/
public static double[] XYZd50toAdobeRGBd65(double X, double Y, double Z) {
return XYZd50toAdobeRGBd65(ColorBase.array(X, Y, Z));
}
public static double[] XYZd50toAdobeRGBd65(double[] xyzD50) {
double[] xyzD65 = ChromaticAdaptation.D50toD65(xyzD50);
return XYZd65toAdobeRGBd65(xyzD65);
}
public static double[] XYZd50toAdobeRGBd65Linear(double X, double Y, double Z) {
return XYZd50toAdobeRGBd65Linear(ColorBase.array(X, Y, Z));
}
public static double[] XYZd50toAdobeRGBd65Linear(double[] xyzD50) {
double[] xyzD65 = ChromaticAdaptation.D50toD65(xyzD50);
return XYZd65toAdobeRGBd65Linear(xyzD65);
}
public static double[] XYZd65toAdobeRGBd65(double[] xyzd65) {
double[] linearRGB = XYZd65toAdobeRGBd65Linear(xyzd65);
double[] rgb = gammaAdobeRGB(linearRGB);
return rgb;
}
public static double[] XYZd65toAdobeRGBd65Linear(double[] xyzd65) {
double[][] matrix = {
{2.0413690, -0.5649464, -0.3446944},
{-0.9692660, 1.8760108, 0.0415560},
{0.0134474, -0.1183897, 1.0154096}
};
double[] linearRGB = DoubleMatrixTools.multiply(matrix, xyzd65);
linearRGB = clipRGB(linearRGB);
return linearRGB;
}
public static double[] XYZd50toAdobeRGBd50(double[] xyzD50) {
double[][] matrix = {
{1.9624274, -0.6105343, -0.3413404},
{-0.9787684, 1.9161415, 0.0334540},
{0.0286869, -0.1406752, 1.3487655}
};
double[] linearRGB = DoubleMatrixTools.multiply(matrix, xyzD50);
linearRGB = clipRGB(linearRGB);
double[] rgb = gammaAdobeRGB(linearRGB);
return rgb;
}
/*
Apple RGB
*/
public static double[] XYZd50toAppleRGBd65(double X, double Y, double Z) {
return XYZd50toAppleRGBd65(ColorBase.array(X, Y, Z));
}
public static double[] XYZd50toAppleRGBd65(double[] xyzD50) {
double[] xyzD65 = ChromaticAdaptation.D50toD65(xyzD50);
return XYZd65toAppleRGBd65(xyzD65);
}
public static double[] XYZd50toAppleRGBd65Linear(double X, double Y, double Z) {
return XYZd50toAppleRGBd65Linear(ColorBase.array(X, Y, Z));
}
public static double[] XYZd50toAppleRGBd65Linear(double[] xyzD50) {
double[] xyzD65 = ChromaticAdaptation.D50toD65(xyzD50);
return XYZd65toAppleRGBd65Linear(xyzD65);
}
public static double[] XYZd65toAppleRGBd65(double[] xyzd65) {
double[] linearRGB = XYZd65toAppleRGBd65Linear(xyzd65);
double[] rgb = gammaAppleRGB(linearRGB);
return rgb;
}
public static double[] XYZd65toAppleRGBd65Linear(double[] xyzd65) {
double[][] matrix = {
{2.9515373, -1.2894116, -0.4738445},
{-1.0851093, 1.9908566, 0.0372026},
{0.0854934, -0.2694964, 1.09129756}
};
double[] linearRGB = DoubleMatrixTools.multiply(matrix, xyzd65);
linearRGB = clipRGB(linearRGB);
return linearRGB;
}
public static double[] XYZd50toAppleRGBd50(double[] xyzD50) {
double[][] matrix = {
{2.8510695, -1.3605261, -0.4708281},
{-1.0927680, 2.0348871, 0.0227598},
{0.1027403, -0.2964984, 1.4510659}
};
double[] linearRGB = DoubleMatrixTools.multiply(matrix, xyzD50);
linearRGB = clipRGB(linearRGB);
double[] rgb = gammaAppleRGB(linearRGB);
return rgb;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Mararsh/MyBox | https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/color/ColorStatistic.java | released/MyBox/src/main/java/mara/mybox/color/ColorStatistic.java | package mara.mybox.color;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javafx.scene.paint.Color;
import mara.mybox.tools.FloatTools;
/**
* @Author Mara
* @CreateDate 2019-2-11 12:53:19
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class ColorStatistic {
private String type;
private Color color;
private int number;
private float percentage;
public ColorStatistic() {
}
public ColorStatistic(String type, Color color, int number, float percentage) {
this.type = type;
this.color = color;
this.number = number;
this.percentage = percentage;
}
public static List<ColorStatistic> newSort(List<ColorStatistic> values) {
if (values == null) {
return null;
}
List<ColorStatistic> sorted = new ArrayList<>();
sorted.addAll(values);
Collections.sort(sorted, new Comparator<ColorStatistic>() {
@Override
public int compare(ColorStatistic p1, ColorStatistic p2) {
return p1.getNumber() - p2.getNumber();
}
});
return sorted;
}
public static void sort(List<ColorStatistic> values) {
if (values == null) {
return;
}
Collections.sort(values, new Comparator<ColorStatistic>() {
@Override
public int compare(ColorStatistic p1, ColorStatistic p2) {
return p1.getNumber() - p2.getNumber();
}
});
}
public static Map<String, Object> statistic(List<ColorStatistic> values) {
Map<String, Object> statistic = new HashMap<>();
if (values == null) {
return statistic;
}
statistic.put("data", values);
int sum = 0;
for (ColorStatistic s : values) {
sum += s.getNumber();
}
statistic.put("sum", new ColorStatistic("Sum", null, sum, 100.0f));
statistic.put("average", new ColorStatistic("Average", null, sum / values.size(),
FloatTools.roundFloat5(100.0f / values.size())));
List<ColorStatistic> newList = ColorStatistic.newSort(values);
ColorStatistic s = newList.get(0);
statistic.put("minimum", new ColorStatistic("Minimum", s.getColor(), s.getNumber(), s.getPercentage()));
s = newList.get(newList.size() - 1);
statistic.put("maximum", new ColorStatistic("Maximum", s.getColor(), s.getNumber(), s.getPercentage()));
ColorStatistic median = new ColorStatistic();
median.setType("Median");
if (newList.size() % 2 == 0) {
ColorStatistic m1 = newList.get(newList.size() / 2);
ColorStatistic m2 = newList.get(newList.size() / 2 + 1);
median.setColor(m1.getColor());
median.setNumber((m1.getNumber() + m2.getNumber()) / 2);
} else {
ColorStatistic m = newList.get(newList.size() / 2);
median.setColor(m.getColor());
median.setNumber(m.getNumber());
}
median.setPercentage(FloatTools.roundFloat5(median.getNumber() * 100.0f / sum));
statistic.put("median", median);
return statistic;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public float getPercentage() {
return percentage;
}
public void setPercentage(float percentage) {
this.percentage = percentage;
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
quux00/merkle-tree | https://github.com/quux00/merkle-tree/blob/34ebaf73fd520aaa886b44e53c00a324b875c053/src/test/java/net/quux00/MerkleTreeTest.java | src/test/java/net/quux00/MerkleTreeTest.java | package net.quux00;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.zip.Adler32;
import org.junit.Test;
public class MerkleTreeTest {
@Test
public void testConstructTree_4LeafEntries() {
MerkleTree m4tree = construct4LeafTree();
MerkleTree.Node root = m4tree.getRoot();
ByteBuffer buf = ByteBuffer.allocate(8);
buf.put(root.sig);
buf.rewind();
// pop off the leading 0 or 1 byte
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, root.type);
long rootSig = buf.getLong();
assertTrue(rootSig > 1);
assertEquals(2, m4tree.getHeight());
assertEquals(7, m4tree.getNumNodes());
MerkleTree.Node lev1Node0 = root.left;
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev1Node0.type);
MerkleTree.Node lev1Node1 = root.right;
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev1Node1.type);
MerkleTree.Node lev2Node0 = lev1Node0.left;
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev2Node0.type);
assertEquals("52e422506d8238ef3196b41db4c41ee0afd659b6", new String(lev2Node0.sig, UTF_8));
MerkleTree.Node lev2Node1 = lev1Node0.right;
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev2Node1.type);
assertEquals("6d0b51991ac3806192f3cb524a5a5d73ebdaacf8", new String(lev2Node1.sig, UTF_8));
MerkleTree.Node lev2Node2 = lev1Node1.left;
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev2Node2.type);
assertEquals("461848c8b70e5a57bd94008b2622796ec26db657", new String(lev2Node2.sig, UTF_8));
MerkleTree.Node lev2Node3 = lev1Node1.right;
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev2Node3.type);
assertEquals("c938037dc70d107b3386a86df7fef17a9983cf53", new String(lev2Node3.sig, UTF_8));
// check that internal Node signatures are correct
Adler32 adler = new Adler32();
adler.update(lev2Node0.sig);
adler.update(lev2Node1.sig);
buf.clear();
buf.put(lev1Node0.sig);
buf.rewind();
assertEquals(buf.getLong(), adler.getValue());
adler.reset();
adler.update(lev2Node2.sig);
adler.update(lev2Node3.sig);
buf.clear();
buf.put(lev1Node1.sig);
buf.rewind();
assertEquals(buf.getLong(), adler.getValue());
adler.reset();
adler.update(lev1Node0.sig);
adler.update(lev1Node1.sig);
buf.clear();
buf.put(root.sig);
buf.rewind();
assertEquals(buf.getLong(), adler.getValue());
}
@Test
public void test4and8LeafTreesHaveDifferentRootSigs() {
MerkleTree m4tree = construct4LeafTree();
MerkleTree m8tree = construct8LeafTree();
assertTrue(m4tree.getRoot().sig != m8tree.getRoot().sig);
}
@Test
public void testConstructTree_8LeafEntries() {
MerkleTree m8tree = construct8LeafTree();
MerkleTree.Node root = m8tree.getRoot();
ByteBuffer buf = ByteBuffer.allocate(8);
buf.put(root.sig);
buf.rewind();
// pop off the leading 0 or 1 byte
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, root.type);
long rootSig = buf.getLong();
assertTrue(rootSig > 1);
assertEquals(3, m8tree.getHeight());
assertEquals(15, m8tree.getNumNodes());
MerkleTree.Node lev1Node0 = root.left;
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev1Node0.type);
MerkleTree.Node lev1Node1 = root.right;
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev1Node1.type);
MerkleTree.Node lev2Node0 = lev1Node0.left;
MerkleTree.Node lev2Node1 = lev1Node0.right;
MerkleTree.Node lev2Node2 = lev1Node1.left;
MerkleTree.Node lev2Node3 = lev1Node1.right;
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev2Node0.type);
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev2Node1.type);
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev2Node2.type);
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev2Node3.type);
MerkleTree.Node lev3Node0 = lev2Node0.left;
MerkleTree.Node lev3Node1 = lev2Node0.right;
MerkleTree.Node lev3Node2 = lev2Node1.left;
MerkleTree.Node lev3Node3 = lev2Node1.right;
MerkleTree.Node lev3Node4 = lev2Node2.left;
MerkleTree.Node lev3Node5 = lev2Node2.right;
MerkleTree.Node lev3Node6 = lev2Node3.left;
MerkleTree.Node lev3Node7 = lev2Node3.right;
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev3Node0.type);
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev3Node1.type);
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev3Node2.type);
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev3Node3.type);
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev3Node4.type);
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev3Node5.type);
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev3Node6.type);
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev3Node7.type);
assertNull(lev3Node0.left);
assertNull(lev3Node0.right);
assertNull(lev3Node2.left);
assertNull(lev3Node6.right);
assertEquals("461848c8b70e5a57bd94008b2622796ec26db657", new String(lev3Node2.sig, UTF_8));
assertEquals("994d89c38e5b9384235696a0efea5b6b93efb270", new String(lev3Node7.sig, UTF_8));
// check some of the internal parent node signatures
Adler32 adler = new Adler32();
adler.update(lev3Node4.sig);
adler.update(lev3Node5.sig);
buf.clear();
buf.put(lev2Node2.sig);
buf.rewind();
assertEquals(buf.getLong(), adler.getValue());
adler.reset();
adler.update(lev2Node2.sig);
adler.update(lev2Node3.sig);
buf.clear();
buf.put(lev1Node1.sig);
buf.rewind();
assertEquals(buf.getLong(), adler.getValue());
adler.reset();
adler.update(lev1Node0.sig);
adler.update(lev1Node1.sig);
buf.clear();
buf.put(root.sig);
buf.rewind();
assertEquals(buf.getLong(), adler.getValue());
}
@Test
public void testConstructTree_9LeafEntries() {
MerkleTree m9tree = construct9LeafTree();
MerkleTree.Node root = m9tree.getRoot();
ByteBuffer buf = ByteBuffer.allocate(8);
buf.put(root.sig);
buf.rewind();
// pop off the leading 0 or 1 byte
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, root.type);
long rootSig = buf.getLong();
assertTrue(rootSig > 1);
assertEquals(4, m9tree.getHeight());
assertEquals(20, m9tree.getNumNodes());
MerkleTree.Node lev1Node0 = root.left;
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev1Node0.type);
MerkleTree.Node lev1Node1 = root.right;
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev1Node1.type);
// right hand tree should just be a linked list of promoted node sigs
assertNull(lev1Node1.right);
MerkleTree.Node lev2Node2 = lev1Node1.left;
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev2Node2.type);
assertArrayEquals(lev1Node1.sig, lev2Node2.sig);
assertNull(lev2Node2.right);
MerkleTree.Node lev3Node4 = lev2Node2.left;
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev3Node4.type);
assertArrayEquals(lev2Node2.sig, lev3Node4.sig);
assertNull(lev3Node4.right);
MerkleTree.Node lev4Node8 = lev3Node4.left;
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev4Node8.type);
assertArrayEquals(lev3Node4.sig, lev4Node8.sig);
// check some of the left hand trees to ensure correctness
MerkleTree.Node lev2Node0 = lev1Node0.left;
MerkleTree.Node lev3Node1 = lev2Node0.right;
MerkleTree.Node lev4Node3 = lev3Node1.right;
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev2Node0.type);
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev3Node1.type);
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev4Node3.type);
assertNull(lev4Node3.left);
assertNull(lev4Node3.right);
// check some of the internal parent node signatures
Adler32 adler = new Adler32();
adler.update(lev3Node1.left.sig);
adler.update(lev3Node1.right.sig);
buf.clear();
buf.put(lev3Node1.sig);
buf.rewind();
assertEquals(buf.getLong(), adler.getValue());
adler.reset();
adler.update(lev2Node0.left.sig);
adler.update(lev2Node0.right.sig);
buf.clear();
buf.put(lev2Node0.sig);
buf.rewind();
assertEquals(buf.getLong(), adler.getValue());
}
@Test
public void testConstructTree_10LeafEntries() {
MerkleTree m9tree = construct10LeafTree();
MerkleTree.Node root = m9tree.getRoot();
ByteBuffer buf = ByteBuffer.allocate(8);
buf.put(root.sig);
buf.rewind();
// pop off the leading 0 or 1 byte
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, root.type);
long rootSig = buf.getLong();
assertTrue(rootSig > 1);
assertEquals(4, m9tree.getHeight());
assertEquals(21, m9tree.getNumNodes());
MerkleTree.Node lev1Node0 = root.left;
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev1Node0.type);
MerkleTree.Node lev1Node1 = root.right;
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev1Node1.type);
// right hand tree should just be a linked list of promoted node sigs
assertNull(lev1Node1.right);
MerkleTree.Node lev2Node2 = lev1Node1.left;
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev2Node2.type);
assertArrayEquals(lev1Node1.sig, lev2Node2.sig);
assertNull(lev2Node2.right);
MerkleTree.Node lev3Node4 = lev2Node2.left;
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev3Node4.type);
assertArrayEquals(lev2Node2.sig, lev3Node4.sig);
// the bottom level has two nodes - only the first parent node was promoted
MerkleTree.Node lev4Node8 = lev3Node4.left;
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev4Node8.type);
assertFalse(new String(lev3Node4.sig, UTF_8).equals(new String(lev4Node8.sig, UTF_8)));
MerkleTree.Node lev4Node9 = lev3Node4.left;
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev4Node9.type);
assertFalse(new String(lev3Node4.sig, UTF_8).equals(new String(lev4Node9.sig, UTF_8)));
Adler32 adler = new Adler32();
adler.update(lev3Node4.left.sig);
adler.update(lev3Node4.right.sig);
buf.clear();
buf.put(lev3Node4.sig);
buf.rewind();
assertEquals(buf.getLong(), adler.getValue());
}
@Test
public void testMerkleCanDetectOutOfOrderMessages() {
MerkleTree order1m = construct4LeafTree();
MerkleTree order2m = construct4LeafTreeOrder2();
MerkleTree order3m = construct4LeafTreeOrder3();
MerkleTree order3mb = construct4LeafTreeOrder3();
assertArrayEquals(order3m.getRoot().sig, order3mb.getRoot().sig);
long order1RootSig = convertSigToLong(order1m.getRoot().sig);
long order2RootSig = convertSigToLong(order2m.getRoot().sig);
long order3RootSig = convertSigToLong(order3m.getRoot().sig);
assertNotEquals(order1RootSig, order2RootSig);
assertNotEquals(order1RootSig, order3RootSig);
assertNotEquals(order2RootSig, order3RootSig);
}
/* ---[ ser / deserialization tests ]--- */
@Test
public void testSerializationDeserialization4LeafTree() {
MerkleTree m4tree = construct4LeafTree();
byte[] serializedTree = m4tree.serialize();
ByteBuffer buf = ByteBuffer.wrap(serializedTree);
assertEquals(MerkleTree.MAGIC_HDR, buf.getInt());
assertEquals(m4tree.getNumNodes(), buf.getInt());
// root node
MerkleTree.Node root = new MerkleTree.Node();
root.type = buf.get();
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, root.type);
int len = buf.getInt();
assertEquals(MerkleTree.LONG_BYTES, len);
root.sig = new byte[len];
buf.get(root.sig);
long rootSig = convertSigToLong(root.sig);
long expectedRootSig = convertSigToLong(m4tree.getRoot().sig);
assertEquals(expectedRootSig, rootSig);
MerkleTree dtree = MerkleDeserializer.deserialize(serializedTree);
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, dtree.getRoot().type);
assertArrayEquals(root.sig, dtree.getRoot().sig);
root = dtree.getRoot();
assertEquals(2, dtree.getHeight());
assertEquals(7, dtree.getNumNodes());
MerkleTree.Node lev1Node0 = root.left;
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev1Node0.type);
MerkleTree.Node lev1Node1 = root.right;
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev1Node1.type);
MerkleTree.Node lev2Node0 = lev1Node0.left;
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev2Node0.type);
assertEquals("52e422506d8238ef3196b41db4c41ee0afd659b6", new String(lev2Node0.sig, UTF_8));
MerkleTree.Node lev2Node1 = lev1Node0.right;
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev2Node1.type);
assertEquals("6d0b51991ac3806192f3cb524a5a5d73ebdaacf8", new String(lev2Node1.sig, UTF_8));
MerkleTree.Node lev2Node2 = lev1Node1.left;
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev2Node2.type);
assertEquals("461848c8b70e5a57bd94008b2622796ec26db657", new String(lev2Node2.sig, UTF_8));
MerkleTree.Node lev2Node3 = lev1Node1.right;
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev2Node3.type);
assertEquals("c938037dc70d107b3386a86df7fef17a9983cf53", new String(lev2Node3.sig, UTF_8));
// check that internal Node signatures are correct
Adler32 adler = new Adler32();
adler.update(lev2Node0.sig);
adler.update(lev2Node1.sig);
buf.clear();
buf.put(lev1Node0.sig);
buf.rewind();
assertEquals(buf.getLong(), adler.getValue());
adler.reset();
adler.update(lev2Node2.sig);
adler.update(lev2Node3.sig);
buf.clear();
buf.put(lev1Node1.sig);
buf.rewind();
assertEquals(buf.getLong(), adler.getValue());
adler.reset();
adler.update(lev1Node0.sig);
adler.update(lev1Node1.sig);
buf.clear();
buf.put(root.sig);
buf.rewind();
assertEquals(buf.getLong(), adler.getValue());
}
@Test
public void testSerializationDeserialization9LeafTree() {
MerkleTree m9tree = construct9LeafTree();
byte[] serializedTree = m9tree.serialize();
ByteBuffer buf = ByteBuffer.wrap(serializedTree);
assertEquals(MerkleTree.MAGIC_HDR, buf.getInt());
assertEquals(m9tree.getNumNodes(), buf.getInt());
// root node
MerkleTree.Node root = new MerkleTree.Node();
root.type = buf.get();
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, root.type);
int len = buf.getInt();
assertEquals(MerkleTree.LONG_BYTES, len);
root.sig = new byte[len];
buf.get(root.sig);
long rootSig = convertSigToLong(root.sig);
long expectedRootSig = convertSigToLong(m9tree.getRoot().sig);
assertEquals(expectedRootSig, rootSig);
MerkleTree dtree = MerkleDeserializer.deserialize(serializedTree);
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, dtree.getRoot().type);
assertArrayEquals(root.sig, dtree.getRoot().sig);
assertEquals(4, dtree.getHeight());
assertEquals(20, dtree.getNumNodes());
root = dtree.getRoot();
MerkleTree.Node lev1Node0 = root.left;
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev1Node0.type);
MerkleTree.Node lev1Node1 = root.right;
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev1Node1.type);
// right hand tree should just be a linked list of promoted node sigs
assertNull(lev1Node1.right);
MerkleTree.Node lev2Node2 = lev1Node1.left;
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev2Node2.type);
assertArrayEquals(lev1Node1.sig, lev2Node2.sig);
assertNull(lev2Node2.right);
MerkleTree.Node lev3Node4 = lev2Node2.left;
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev3Node4.type);
assertArrayEquals(lev2Node2.sig, lev3Node4.sig);
assertNull(lev3Node4.right);
MerkleTree.Node lev4Node8 = lev3Node4.left;
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev4Node8.type);
assertArrayEquals(lev3Node4.sig, lev4Node8.sig);
// check some of the left hand trees to ensure correctness
MerkleTree.Node lev2Node0 = lev1Node0.left;
MerkleTree.Node lev3Node1 = lev2Node0.right;
MerkleTree.Node lev4Node3 = lev3Node1.right;
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev2Node0.type);
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, lev3Node1.type);
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev4Node3.type);
assertNull(lev4Node3.left);
assertNull(lev4Node3.right);
// check some of the internal parent node signatures
Adler32 adler = new Adler32();
adler.update(lev3Node1.left.sig);
adler.update(lev3Node1.right.sig);
buf.clear();
buf.put(lev3Node1.sig);
buf.rewind();
assertEquals(buf.getLong(), adler.getValue());
adler.reset();
adler.update(lev2Node0.left.sig);
adler.update(lev2Node0.right.sig);
buf.clear();
buf.put(lev2Node0.sig);
buf.rewind();
assertEquals(buf.getLong(), adler.getValue());
}
@Test
public void testSerializationDeserialization2LeafTree() {
MerkleTree m2tree = construct2LeafTree();
byte[] serializedTree = m2tree.serialize();
ByteBuffer buf = ByteBuffer.wrap(serializedTree);
assertEquals(MerkleTree.MAGIC_HDR, buf.getInt());
assertEquals(m2tree.getNumNodes(), buf.getInt());
// root node
MerkleTree.Node root = new MerkleTree.Node();
root.type = buf.get();
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, root.type);
int len = buf.getInt();
assertEquals(MerkleTree.LONG_BYTES, len);
root.sig = new byte[len];
buf.get(root.sig);
long rootSig = convertSigToLong(root.sig);
long expectedRootSig = convertSigToLong(m2tree.getRoot().sig);
assertEquals(expectedRootSig, rootSig);
// deserialize
MerkleTree dtree = MerkleDeserializer.deserialize(serializedTree);
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, dtree.getRoot().type);
assertArrayEquals(root.sig, dtree.getRoot().sig);
assertEquals(1, dtree.getHeight());
assertEquals(3, dtree.getNumNodes());
root = dtree.getRoot();
MerkleTree.Node lev1Node0 = root.left;
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev1Node0.type);
assertNull(lev1Node0.left);
assertNull(lev1Node0.right);
MerkleTree.Node lev1Node1 = root.right;
assertEquals(MerkleTree.LEAF_SIG_TYPE, lev1Node1.type);
assertEquals("26fe8e189fd5bb3fe56d4d3def6494802cb8cba3", new String(lev1Node1.sig, UTF_8));
assertNull(lev1Node1.left);
assertNull(lev1Node1.right);
}
@Test
public void testSerializationDeserialization1019LeafTree() {
MerkleTree m1019tree = construct1019LeafTree();
byte[] serializedTree = m1019tree.serialize();
ByteBuffer buf = ByteBuffer.wrap(serializedTree);
assertEquals(MerkleTree.MAGIC_HDR, buf.getInt());
assertEquals(m1019tree.getNumNodes(), buf.getInt());
assertTrue(m1019tree.getNumNodes() > 1019 * 2);
assertEquals(10, m1019tree.getHeight());
// root node
MerkleTree.Node root = new MerkleTree.Node();
root.type = buf.get();
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, root.type);
int len = buf.getInt();
assertEquals(MerkleTree.LONG_BYTES, len);
root.sig = new byte[len];
buf.get(root.sig);
long rootSig = convertSigToLong(root.sig);
long expectedRootSig = convertSigToLong(m1019tree.getRoot().sig);
assertEquals(expectedRootSig, rootSig);
// deserialize
MerkleTree dtree = MerkleDeserializer.deserialize(serializedTree);
assertEquals(MerkleTree.INTERNAL_SIG_TYPE, dtree.getRoot().type);
assertArrayEquals(root.sig, dtree.getRoot().sig);
assertEquals(10, dtree.getHeight());
assertEquals(m1019tree.getNumNodes(), dtree.getNumNodes());
}
// must have at least two entries to construct a MerkleTree
@SuppressWarnings("unused")
@Test(expected=IllegalArgumentException.class)
public void testConstruct1LeafTree() {
List<String> signatures = Arrays.asList("abc");
new MerkleTree(signatures);
}
/* ---[ helper methods ]--- */
private static long convertSigToLong(byte[] sig) {
ByteBuffer buf = ByteBuffer.wrap(sig);
return buf.getLong();
}
MerkleTree construct2LeafTree() {
List<String> signatures = Arrays.asList(
"52e422506d8238ef3196b41db4c41ee0afd659b6",
"26fe8e189fd5bb3fe56d4d3def6494802cb8cba3"
);
return new MerkleTree(signatures);
}
MerkleTree construct1019LeafTree() {
List<String> signatures = new ArrayList<>(1019);
for (int i = 0; i < 1019; i++) {
signatures.add(UUID.randomUUID().toString());
}
return new MerkleTree(signatures);
}
MerkleTree construct9LeafTree() {
List<String> signatures = Arrays.asList(
"52e422506d8238ef3196b41db4c41ee0afd659b6",
"6d0b51991ac3806192f3cb524a5a5d73ebdaacf8",
"461848c8b70e5a57bd94008b2622796ec26db657",
"c938037dc70d107b3386a86df7fef17a9983cf53",
"d9312928e5702168348fe67ee2a3e3a1b7bc7c93",
"506d93ebff5365d8f5dd9fedd4a063949be831a4",
"e45922755802b52f11599d4746035ecad18c0c46",
"994d89c38e5b9384235696a0efea5b6b93efb270",
"26fe8e189fd5bb3fe56d4d3def6494802cb8cba3"
);
return new MerkleTree(signatures);
}
MerkleTree construct10LeafTree() {
List<String> signatures = Arrays.asList(
"52e422506d8238ef3196b41db4c41ee0afd659b6",
"6d0b51991ac3806192f3cb524a5a5d73ebdaacf8",
"461848c8b70e5a57bd94008b2622796ec26db657",
"c938037dc70d107b3386a86df7fef17a9983cf53",
"d9312928e5702168348fe67ee2a3e3a1b7bc7c93",
"506d93ebff5365d8f5dd9fedd4a063949be831a4",
"e45922755802b52f11599d4746035ecad18c0c46",
"994d89c38e5b9384235696a0efea5b6b93efb270",
"26fe8e189fd5bb3fe56d4d3def6494802cb8cba3",
"3cf4172b27b7b182db0dd68276f08f7c27561c32"
);
return new MerkleTree(signatures);
}
MerkleTree construct8LeafTree() {
List<String> signatures = Arrays.asList(
"52e422506d8238ef3196b41db4c41ee0afd659b6",
"6d0b51991ac3806192f3cb524a5a5d73ebdaacf8",
"461848c8b70e5a57bd94008b2622796ec26db657",
"c938037dc70d107b3386a86df7fef17a9983cf53",
"d9312928e5702168348fe67ee2a3e3a1b7bc7c93",
"506d93ebff5365d8f5dd9fedd4a063949be831a4",
"e45922755802b52f11599d4746035ecad18c0c46",
"994d89c38e5b9384235696a0efea5b6b93efb270"
);
return new MerkleTree(signatures);
}
MerkleTree construct4LeafTree() {
List<String> signatures = Arrays.asList(
"52e422506d8238ef3196b41db4c41ee0afd659b6",
"6d0b51991ac3806192f3cb524a5a5d73ebdaacf8",
"461848c8b70e5a57bd94008b2622796ec26db657",
"c938037dc70d107b3386a86df7fef17a9983cf53");
return new MerkleTree(signatures);
}
MerkleTree construct4LeafTreeOrder2() {
// inverted [1] and [2] from the other order
List<String> signatures = Arrays.asList(
"52e422506d8238ef3196b41db4c41ee0afd659b6",
"461848c8b70e5a57bd94008b2622796ec26db657",
"6d0b51991ac3806192f3cb524a5a5d73ebdaacf8",
"c938037dc70d107b3386a86df7fef17a9983cf53");
return new MerkleTree(signatures);
}
MerkleTree construct4LeafTreeOrder3() {
// inverted [2] and [3] from the other order
List<String> signatures = Arrays.asList(
"52e422506d8238ef3196b41db4c41ee0afd659b6",
"6d0b51991ac3806192f3cb524a5a5d73ebdaacf8",
"c938037dc70d107b3386a86df7fef17a9983cf53",
"461848c8b70e5a57bd94008b2622796ec26db657");
return new MerkleTree(signatures);
}
}
| java | MIT | 34ebaf73fd520aaa886b44e53c00a324b875c053 | 2026-01-05T02:41:23.860799Z | false |
quux00/merkle-tree | https://github.com/quux00/merkle-tree/blob/34ebaf73fd520aaa886b44e53c00a324b875c053/src/main/java/net/quux00/MerkleTree.java | src/main/java/net/quux00/MerkleTree.java | package net.quux00;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.zip.Adler32;
/**
* MerkleTree is an implementation of a Merkle binary hash tree where the leaves
* are signatures (hashes, digests, CRCs, etc.) of some underlying data structure
* that is not explicitly part of the tree.
*
* The internal leaves of the tree are signatures of its two child nodes. If an
* internal node has only one child, the the signature of the child node is
* adopted ("promoted").
*
* MerkleTree knows how to serialize itself to a binary format, but does not
* implement the Java Serializer interface. The {@link #serialize()} method
* returns a byte array, which should be passed to
* {@link MerkleDeserializer#deserialize(byte[])} in order to hydrate into
* a MerkleTree in memory.
*
* This MerkleTree is intentionally ignorant of the hashing/checksum algorithm
* used to generate the leaf signatures. It uses Adler32 CRC to generate
* signatures for all internal node signatures (other than those "promoted"
* that have only one child).
*
* The Adler32 CRC is not cryptographically secure, so this implementation
* should NOT be used in scenarios where the data is being received from
* an untrusted source.
*/
public class MerkleTree {
public static final int MAGIC_HDR = 0xcdaace99;
public static final int INT_BYTES = 4;
public static final int LONG_BYTES = 8;
public static final byte LEAF_SIG_TYPE = 0x0;
public static final byte INTERNAL_SIG_TYPE = 0x01;
private final Adler32 crc = new Adler32();
private List<String> leafSigs;
private Node root;
private int depth;
private int nnodes;
/**
* Use this constructor to create a MerkleTree from a list of leaf signatures.
* The Merkle tree is built from the bottom up.
* @param leafSignatures
*/
public MerkleTree(List<String> leafSignatures) {
constructTree(leafSignatures);
}
/**
* Use this constructor when you have already constructed the tree of Nodes
* (from deserialization).
* @param treeRoot
* @param numNodes
* @param height
* @param leafSignatures
*/
public MerkleTree(Node treeRoot, int numNodes, int height, List<String> leafSignatures) {
root = treeRoot;
nnodes = numNodes;
depth = height;
leafSigs = leafSignatures;
}
/**
* Serialization format:
* (magicheader:int)(numnodes:int)[(nodetype:byte)(siglength:int)(signature:[]byte)]
* @return
*/
public byte[] serialize() {
int magicHeaderSz = INT_BYTES;
int nnodesSz = INT_BYTES;
int hdrSz = magicHeaderSz + nnodesSz;
int typeByteSz = 1;
int siglength = INT_BYTES;
int parentSigSz = LONG_BYTES;
int leafSigSz = leafSigs.get(0).getBytes(StandardCharsets.UTF_8).length;
// some of the internal nodes may use leaf signatures (when "promoted")
// so ensure that the ByteBuffer overestimates how much space is needed
// since ByteBuffer does not expand on demand
int maxSigSz = leafSigSz;
if (parentSigSz > maxSigSz) {
maxSigSz = parentSigSz;
}
int spaceForNodes = (typeByteSz + siglength + maxSigSz) * nnodes;
int cap = hdrSz + spaceForNodes;
ByteBuffer buf = ByteBuffer.allocate(cap);
buf.putInt(MAGIC_HDR).putInt(nnodes); // header
serializeBreadthFirst(buf);
// the ByteBuf allocated space is likely more than was needed
// so copy to a byte array of the exact size necesssary
byte[] serializedTree = new byte[buf.position()];
buf.rewind();
buf.get(serializedTree);
return serializedTree;
}
/**
* Serialization format after the header section:
* [(nodetype:byte)(siglength:int)(signature:[]byte)]
* @param buf
*/
void serializeBreadthFirst(ByteBuffer buf) {
Queue<Node> q = new ArrayDeque<Node>((nnodes / 2) + 1);
q.add(root);
while (!q.isEmpty()) {
Node nd = q.remove();
buf.put(nd.type).putInt(nd.sig.length).put(nd.sig);
if (nd.left != null) {
q.add(nd.left);
}
if (nd.right != null) {
q.add(nd.right);
}
}
}
/**
* Create a tree from the bottom up starting from the leaf signatures.
* @param signatures
*/
void constructTree(List<String> signatures) {
if (signatures.size() <= 1) {
throw new IllegalArgumentException("Must be at least two signatures to construct a Merkle tree");
}
leafSigs = signatures;
nnodes = signatures.size();
List<Node> parents = bottomLevel(signatures);
nnodes += parents.size();
depth = 1;
while (parents.size() > 1) {
parents = internalLevel(parents);
depth++;
nnodes += parents.size();
}
root = parents.get(0);
}
public int getNumNodes() {
return nnodes;
}
public Node getRoot() {
return root;
}
public int getHeight() {
return depth;
}
/**
* Constructs an internal level of the tree
*/
List<Node> internalLevel(List<Node> children) {
List<Node> parents = new ArrayList<Node>(children.size() / 2);
for (int i = 0; i < children.size() - 1; i += 2) {
Node child1 = children.get(i);
Node child2 = children.get(i+1);
Node parent = constructInternalNode(child1, child2);
parents.add(parent);
}
if (children.size() % 2 != 0) {
Node child = children.get(children.size()-1);
Node parent = constructInternalNode(child, null);
parents.add(parent);
}
return parents;
}
/**
* Constructs the bottom part of the tree - the leaf nodes and their
* immediate parents. Returns a list of the parent nodes.
*/
List<Node> bottomLevel(List<String> signatures) {
List<Node> parents = new ArrayList<Node>(signatures.size() / 2);
for (int i = 0; i < signatures.size() - 1; i += 2) {
Node leaf1 = constructLeafNode(signatures.get(i));
Node leaf2 = constructLeafNode(signatures.get(i+1));
Node parent = constructInternalNode(leaf1, leaf2);
parents.add(parent);
}
// if odd number of leafs, handle last entry
if (signatures.size() % 2 != 0) {
Node leaf = constructLeafNode(signatures.get(signatures.size() - 1));
Node parent = constructInternalNode(leaf, null);
parents.add(parent);
}
return parents;
}
private Node constructInternalNode(Node child1, Node child2) {
Node parent = new Node();
parent.type = INTERNAL_SIG_TYPE;
if (child2 == null) {
parent.sig = child1.sig;
} else {
parent.sig = internalHash(child1.sig, child2.sig);
}
parent.left = child1;
parent.right = child2;
return parent;
}
private static Node constructLeafNode(String signature) {
Node leaf = new Node();
leaf.type = LEAF_SIG_TYPE;
leaf.sig = signature.getBytes(StandardCharsets.UTF_8);
return leaf;
}
byte[] internalHash(byte[] leftChildSig, byte[] rightChildSig) {
crc.reset();
crc.update(leftChildSig);
crc.update(rightChildSig);
return longToByteArray(crc.getValue());
}
/* ---[ Node class ]--- */
/**
* The Node class should be treated as immutable, though immutable
* is not enforced in the current design.
*
* A Node knows whether it is an internal or leaf node and its signature.
*
* Internal Nodes will have at least one child (always on the left).
* Leaf Nodes will have no children (left = right = null).
*/
static class Node {
public byte type; // INTERNAL_SIG_TYPE or LEAF_SIG_TYPE
public byte[] sig; // signature of the node
public Node left;
public Node right;
@Override
public String toString() {
String leftType = "<null>";
String rightType = "<null>";
if (left != null) {
leftType = String.valueOf(left.type);
}
if (right != null) {
rightType = String.valueOf(right.type);
}
return String.format("MerkleTree.Node<type:%d, sig:%s, left (type): %s, right (type): %s>",
type, sigAsString(), leftType, rightType);
}
private String sigAsString() {
StringBuffer sb = new StringBuffer();
sb.append('[');
for (int i = 0; i < sig.length; i++) {
sb.append(sig[i]).append(' ');
}
sb.insert(sb.length()-1, ']');
return sb.toString();
}
}
/**
* Big-endian conversion
*/
public static byte[] longToByteArray(long value) {
return new byte[] {
(byte) (value >> 56),
(byte) (value >> 48),
(byte) (value >> 40),
(byte) (value >> 32),
(byte) (value >> 24),
(byte) (value >> 16),
(byte) (value >> 8),
(byte) value
};
}
}
| java | MIT | 34ebaf73fd520aaa886b44e53c00a324b875c053 | 2026-01-05T02:41:23.860799Z | false |
quux00/merkle-tree | https://github.com/quux00/merkle-tree/blob/34ebaf73fd520aaa886b44e53c00a324b875c053/src/main/java/net/quux00/MerkleDeserializer.java | src/main/java/net/quux00/MerkleDeserializer.java | package net.quux00;
import static net.quux00.MerkleTree.LEAF_SIG_TYPE;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import net.quux00.MerkleTree.Node;
/**
* The Deserialization code was separated from the MerkleTree class.
*/
public final class MerkleDeserializer {
private MerkleDeserializer() {}
/**
* Deserialize works from a byte array generated by {@link MerkleTree#serialize()}.
* Serialization format:
* (magicheader:int)(numnodes:int)[(nodetype:byte)(siglength:int)(signature:[]byte)]
* @param serializedTree
* @return
*/
public static MerkleTree deserialize(byte[] serializedTree) {
ByteBuffer buf = ByteBuffer.wrap(serializedTree);
/* ---[ read header ]--- */
if (buf.getInt() != MerkleTree.MAGIC_HDR) {
throw new IllegalArgumentException("serialized byte array does not start with appropriate Magic Header");
}
int totnodes = buf.getInt();
/* ---[ read data ]--- */
List<String> leafSigs = new ArrayList<>((totnodes / 2) + 1);
// read root
Node root = new Node();
root.type = buf.get();
if (root.type == LEAF_SIG_TYPE) {
throw new IllegalStateException("First serialized node is a leaf");
}
readNextSignature(buf, root);
Queue<Node> q = new ArrayDeque<>((totnodes / 2) + 1);
Node curr = root;
int height = 0;
int expNumNodes = 2;
int nodesThisLevel = 0;
for (int i = 1; i < totnodes; i++) {
Node child = new Node();
child.type = buf.get();
readNextSignature(buf, child);
q.add(child);
if (child.type == LEAF_SIG_TYPE) {
leafSigs.add(new String(child.sig, StandardCharsets.UTF_8));
}
// handles incomplete tree where a node has been "promoted"
if (signaturesEqual(child.sig,curr.sig)) {
curr.left = child;
curr = q.remove();
expNumNodes *= 2;
nodesThisLevel = 0;
height++;
continue;
}
nodesThisLevel++;
if (curr.left == null) {
curr.left = child;
} else {
curr.right = child;
curr = q.remove();
if (nodesThisLevel >= expNumNodes) {
expNumNodes *= 2;
nodesThisLevel = 0;
height++;
}
}
}
return new MerkleTree(root, totnodes, height, leafSigs);
}
/**
* Returns two if the two byte arrays passed in are exactly identical.
*/
static boolean signaturesEqual(byte[] sig, byte[] sig2) {
if (sig.length != sig2.length) {
return false;
}
for (int i = 0; i < sig.length; i++) {
if (sig[i] != sig2[i]) {
return false;
}
}
return true;
}
static void readNextSignature(ByteBuffer buf, Node nd) {
byte[] sigBytes = new byte[buf.getInt()];
buf.get(sigBytes);
nd.sig = sigBytes;
}
}
| java | MIT | 34ebaf73fd520aaa886b44e53c00a324b875c053 | 2026-01-05T02:41:23.860799Z | false |
hehonghui/simple_net_framework | https://github.com/hehonghui/simple_net_framework/blob/403b5b83ea2b42014ac5085b7bf1bb7a5e030e73/SimpleNet_Demo/src/com/example/simplenet_demo/MainActivity.java | SimpleNet_Demo/src/com/example/simplenet_demo/MainActivity.java |
package com.example.simplenet_demo;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Html;
import android.widget.TextView;
import org.simple.net.base.Request.HttpMethod;
import org.simple.net.base.Request.RequestListener;
import org.simple.net.core.RequestQueue;
import org.simple.net.core.SimpleNet;
import org.simple.net.entity.MultipartEntity;
import org.simple.net.requests.MultipartRequest;
import org.simple.net.requests.StringRequest;
import java.io.ByteArrayOutputStream;
import java.io.File;
/**
* SimpleNet简单示例
*
* @author mrsimple
*/
public class MainActivity extends Activity {
// 1、构建请求队列
RequestQueue mQueue = SimpleNet.newRequestQueue();
TextView mResultTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mResultTv = (TextView) findViewById(R.id.result_tv);
sendStringRequest();
}
/**
* 发送GET请求,返回的是String类型的数据, 同理还有{@see JsonRequest}、{@see MultipartRequest}
*/
private void sendStringRequest() {
StringRequest request = new StringRequest(HttpMethod.GET, "http://www.baidu.com",
new RequestListener<String>() {
@Override
public void onComplete(int stCode, String response, String errMsg) {
mResultTv.setText(Html.fromHtml(response));
}
});
mQueue.addRequest(request);
}
/**
* 发送MultipartRequest,可以传字符串参数、文件、Bitmap等参数,这种请求为POST类型
*/
protected void sendMultiRequest() {
// 2、创建请求
MultipartRequest multipartRequest = new MultipartRequest("你的url",
new RequestListener<String>() {
@Override
public void onComplete(int stCode, String response, String errMsg) {
// 该方法执行在UI线程
}
});
// 3、添加各种参数
// 添加header
multipartRequest.addHeader("header-name", "value");
// 通过MultipartEntity来设置参数
MultipartEntity multi = multipartRequest.getMultiPartEntity();
// 文本参数
multi.addStringPart("location", "模拟的地理位置");
multi.addStringPart("type", "0");
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
// 直接从上传Bitmap
multi.addBinaryPart("images", bitmapToBytes(bitmap));
// 上传文件
multi.addFilePart("imgfile", new File("storage/emulated/0/test.jpg"));
// 4、将请求添加到队列中
mQueue.addRequest(multipartRequest);
}
private byte[] bitmapToBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
return stream.toByteArray();
}
@Override
protected void onDestroy() {
mQueue.stop();
super.onDestroy();
}
}
| java | MIT | 403b5b83ea2b42014ac5085b7bf1bb7a5e030e73 | 2026-01-05T02:41:17.874060Z | false |
hehonghui/simple_net_framework | https://github.com/hehonghui/simple_net_framework/blob/403b5b83ea2b42014ac5085b7bf1bb7a5e030e73/src/org/simple/net/requests/JsonRequest.java | src/org/simple/net/requests/JsonRequest.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.simple.net.requests;
import org.json.JSONException;
import org.json.JSONObject;
import org.simple.net.base.Request;
import org.simple.net.base.Response;
/**
* 返回的数据类型为Json的请求, Json对应的对象类型为JSONObject
*
* @author mrsimple
*/
public class JsonRequest extends Request<JSONObject> {
public JsonRequest(HttpMethod method, String url, RequestListener<JSONObject> listener) {
super(method, url, listener);
}
/**
* 将Response的结果转换为JSONObject
*/
@Override
public JSONObject parseResponse(Response response) {
String jsonString = new String(response.getRawData());
try {
return new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
| java | MIT | 403b5b83ea2b42014ac5085b7bf1bb7a5e030e73 | 2026-01-05T02:41:17.874060Z | false |
hehonghui/simple_net_framework | https://github.com/hehonghui/simple_net_framework/blob/403b5b83ea2b42014ac5085b7bf1bb7a5e030e73/src/org/simple/net/requests/StringRequest.java | src/org/simple/net/requests/StringRequest.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.simple.net.requests;
import org.simple.net.base.Request;
import org.simple.net.base.Response;
public class StringRequest extends Request<String> {
public StringRequest(HttpMethod method, String url, RequestListener<String> listener) {
super(method, url, listener);
}
@Override
public String parseResponse(Response response) {
return new String(response.getRawData());
}
}
| java | MIT | 403b5b83ea2b42014ac5085b7bf1bb7a5e030e73 | 2026-01-05T02:41:17.874060Z | false |
hehonghui/simple_net_framework | https://github.com/hehonghui/simple_net_framework/blob/403b5b83ea2b42014ac5085b7bf1bb7a5e030e73/src/org/simple/net/requests/MultipartRequest.java | src/org/simple/net/requests/MultipartRequest.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.simple.net.requests;
import android.util.Log;
import org.simple.net.base.Request;
import org.simple.net.base.Response;
import org.simple.net.entity.MultipartEntity;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* Multipart请求 ( 只能为POST请求 ),该请求可以搭载多种类型参数,比如文本、文件等,但是文件仅限于小文件,否则会出现OOM异常.
*
* @author mrsimple
*/
public class MultipartRequest extends Request<String> {
MultipartEntity mMultiPartEntity = new MultipartEntity();
public MultipartRequest(String url, RequestListener<String> listener) {
super(HttpMethod.POST, url, listener);
}
/**
* @return
*/
public MultipartEntity getMultiPartEntity() {
return mMultiPartEntity;
}
@Override
public String getBodyContentType() {
return mMultiPartEntity.getContentType().getValue();
}
@Override
public byte[] getBody() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
// 将MultipartEntity中的参数写入到bos中
mMultiPartEntity.writeTo(bos);
} catch (IOException e) {
Log.e("", "IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
public String parseResponse(Response response) {
if (response != null && response.getRawData() != null) {
return new String(response.getRawData());
}
return "";
}
}
| java | MIT | 403b5b83ea2b42014ac5085b7bf1bb7a5e030e73 | 2026-01-05T02:41:17.874060Z | false |
hehonghui/simple_net_framework | https://github.com/hehonghui/simple_net_framework/blob/403b5b83ea2b42014ac5085b7bf1bb7a5e030e73/src/org/simple/net/base/Response.java | src/org/simple/net/base/Response.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.simple.net.base;
import org.apache.http.HttpEntity;
import org.apache.http.ProtocolVersion;
import org.apache.http.StatusLine;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
/**
* 请求结果类,继承自BasicHttpResponse,将结果存储在rawData中.
*
* @author mrsimple
*/
public class Response extends BasicHttpResponse {
public byte[] rawData = new byte[0];
public Response(StatusLine statusLine) {
super(statusLine);
}
public Response(ProtocolVersion ver, int code, String reason) {
super(ver, code, reason);
}
@Override
public void setEntity(HttpEntity entity) {
super.setEntity(entity);
rawData = entityToBytes(getEntity());
}
public byte[] getRawData() {
return rawData;
}
public int getStatusCode() {
return getStatusLine().getStatusCode();
}
public String getMessage() {
return getStatusLine().getReasonPhrase();
}
/** Reads the contents of HttpEntity into a byte[]. */
private byte[] entityToBytes(HttpEntity entity) {
try {
return EntityUtils.toByteArray(entity);
} catch (IOException e) {
e.printStackTrace();
}
return new byte[0];
}
}
| java | MIT | 403b5b83ea2b42014ac5085b7bf1bb7a5e030e73 | 2026-01-05T02:41:17.874060Z | false |
hehonghui/simple_net_framework | https://github.com/hehonghui/simple_net_framework/blob/403b5b83ea2b42014ac5085b7bf1bb7a5e030e73/src/org/simple/net/base/Request.java | src/org/simple/net/base/Request.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.simple.net.base;
import android.util.Log;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
/**
* 网络请求类. 注意GET和DELETE不能传递参数,因为其请求的性质所致,用户可以将参数构建到url后传递进来到Request中.
*
* @author mrsimple
* @param <T> T为请求返回的数据类型
*/
public abstract class Request<T> implements Comparable<Request<T>> {
/**
* http request method enum.
*
* @author mrsimple
*/
public static enum HttpMethod {
GET("GET"),
POST("POST"),
PUT("PUT"),
DELETE("DELETE");
/** http request type */
private String mHttpMethod = "";
private HttpMethod(String method) {
mHttpMethod = method;
}
@Override
public String toString() {
return mHttpMethod;
}
}
/**
* 优先级枚举
*
* @author mrsimple
*/
public static enum Priority {
LOW,
NORMAL,
HIGN,
IMMEDIATE
}
/**
* Default encoding for POST or PUT parameters. See
* {@link #getParamsEncoding()}.
*/
public static final String DEFAULT_PARAMS_ENCODING = "UTF-8";
/**
* Default Content-type
*/
public final static String HEADER_CONTENT_TYPE = "Content-Type";
/**
* 请求序列号
*/
protected int mSerialNum = 0;
/**
* 优先级默认设置为Normal
*/
protected Priority mPriority = Priority.NORMAL;
/**
* 是否取消该请求
*/
protected boolean isCancel = false;
/** 该请求是否应该缓存 */
private boolean mShouldCache = true;
/**
* 请求Listener
*/
protected RequestListener<T> mRequestListener;
/**
* 请求的url
*/
private String mUrl = "";
/**
* 请求的方法
*/
HttpMethod mHttpMethod = HttpMethod.GET;
/**
* 请求的header
*/
private Map<String, String> mHeaders = new HashMap<String, String>();
/**
* 请求参数
*/
private Map<String, String> mBodyParams = new HashMap<String, String>();
/**
* @param method
* @param url
* @param listener
*/
public Request(HttpMethod method, String url, RequestListener<T> listener) {
mHttpMethod = method;
mUrl = url;
mRequestListener = listener;
}
public void addHeader(String name, String value) {
mHeaders.put(name, value);
}
/**
* 从原生的网络请求中解析结果
*
* @param response
* @return
*/
public abstract T parseResponse(Response response);
/**
* 处理Response,该方法运行在UI线程.
*
* @param response
*/
public final void deliveryResponse(Response response) {
T result = parseResponse(response);
if (mRequestListener != null) {
int stCode = response != null ? response.getStatusCode() : -1;
String msg = response != null ? response.getMessage() : "unkown error";
Log.e("", "### 执行回调 : stCode = " + stCode + ", result : " + result + ", err : " + msg);
mRequestListener.onComplete(stCode, result, msg);
}
}
public String getUrl() {
return mUrl;
}
public RequestListener<T> getRequestListener() {
return mRequestListener;
}
public int getSerialNumber() {
return mSerialNum;
}
public void setSerialNumber(int mSerialNum) {
this.mSerialNum = mSerialNum;
}
public Priority getPriority() {
return mPriority;
}
public void setPriority(Priority mPriority) {
this.mPriority = mPriority;
}
protected String getParamsEncoding() {
return DEFAULT_PARAMS_ENCODING;
}
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=" + getParamsEncoding();
}
public HttpMethod getHttpMethod() {
return mHttpMethod;
}
public Map<String, String> getHeaders() {
return mHeaders;
}
public Map<String, String> getParams() {
return mBodyParams;
}
public boolean isHttps() {
return mUrl.startsWith("https");
}
/**
* 该请求是否应该缓存
*
* @param shouldCache
*/
public void setShouldCache(boolean shouldCache) {
this.mShouldCache = shouldCache;
}
public boolean shouldCache() {
return mShouldCache;
}
public void cancel() {
isCancel = true;
}
public boolean isCanceled() {
return isCancel;
}
/**
* Returns the raw POST or PUT body to be sent.
*
* @throws AuthFailureError in the event of auth failure
*/
public byte[] getBody() {
Map<String, String> params = getParams();
if (params != null && params.size() > 0) {
return encodeParameters(params, getParamsEncoding());
}
return null;
}
/**
* Converts <code>params</code> into an application/x-www-form-urlencoded
* encoded string.
*/
private byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {
StringBuilder encodedParams = new StringBuilder();
try {
for (Map.Entry<String, String> entry : params.entrySet()) {
encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
encodedParams.append('=');
encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
encodedParams.append('&');
}
return encodedParams.toString().getBytes(paramsEncoding);
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
}
}
@Override
public int compareTo(Request<T> another) {
Priority myPriority = this.getPriority();
Priority anotherPriority = another.getPriority();
// 如果优先级相等,那么按照添加到队列的序列号顺序来执行
return myPriority.equals(anotherPriority) ? this.getSerialNumber()
- another.getSerialNumber()
: myPriority.ordinal() - anotherPriority.ordinal();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((mHeaders == null) ? 0 : mHeaders.hashCode());
result = prime * result + ((mHttpMethod == null) ? 0 : mHttpMethod.hashCode());
result = prime * result + ((mBodyParams == null) ? 0 : mBodyParams.hashCode());
result = prime * result + ((mPriority == null) ? 0 : mPriority.hashCode());
result = prime * result + (mShouldCache ? 1231 : 1237);
result = prime * result + ((mUrl == null) ? 0 : mUrl.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Request<?> other = (Request<?>) obj;
if (mHeaders == null) {
if (other.mHeaders != null)
return false;
} else if (!mHeaders.equals(other.mHeaders))
return false;
if (mHttpMethod != other.mHttpMethod)
return false;
if (mBodyParams == null) {
if (other.mBodyParams != null)
return false;
} else if (!mBodyParams.equals(other.mBodyParams))
return false;
if (mPriority != other.mPriority)
return false;
if (mShouldCache != other.mShouldCache)
return false;
if (mUrl == null) {
if (other.mUrl != null)
return false;
} else if (!mUrl.equals(other.mUrl))
return false;
return true;
}
/**
* 网络请求Listener
*
* @author mrsimple
* @param <T> 请求的response类型
*/
public static interface RequestListener<T> {
/**
* 请求完成的回调
*
* @param response
*/
public void onComplete(int stCode, T response, String errMsg);
}
}
| java | MIT | 403b5b83ea2b42014ac5085b7bf1bb7a5e030e73 | 2026-01-05T02:41:17.874060Z | false |
hehonghui/simple_net_framework | https://github.com/hehonghui/simple_net_framework/blob/403b5b83ea2b42014ac5085b7bf1bb7a5e030e73/src/org/simple/net/cache/LruMemCache.java | src/org/simple/net/cache/LruMemCache.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.simple.net.cache;
import android.support.v4.util.LruCache;
import org.simple.net.base.Response;
/**
* 将请求结果缓存到内存中
*
* @author mrsimple
*/
public class LruMemCache implements Cache<String, Response> {
/**
* Reponse缓存
*/
private LruCache<String, Response> mResponseCache;
public LruMemCache() {
// 计算可使用的最大内存
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// 取八分之一的可用内存作为缓存
final int cacheSize = maxMemory / 8;
mResponseCache = new LruCache<String, Response>(cacheSize) {
@Override
protected int sizeOf(String key, Response response) {
return response.rawData.length / 1024;
}
};
}
@Override
public Response get(String key) {
return mResponseCache.get(key);
}
@Override
public void put(String key, Response response) {
mResponseCache.put(key, response);
}
@Override
public void remove(String key) {
mResponseCache.remove(key);
}
}
| java | MIT | 403b5b83ea2b42014ac5085b7bf1bb7a5e030e73 | 2026-01-05T02:41:17.874060Z | false |
hehonghui/simple_net_framework | https://github.com/hehonghui/simple_net_framework/blob/403b5b83ea2b42014ac5085b7bf1bb7a5e030e73/src/org/simple/net/cache/Cache.java | src/org/simple/net/cache/Cache.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.simple.net.cache;
/**
* 请求缓存接口
*
* @author mrsimple
* @param <K> key的类型
* @param <V> value类型
*/
public interface Cache<K, V> {
public V get(K key);
public void put(K key, V value);
public void remove(K key);
}
| java | MIT | 403b5b83ea2b42014ac5085b7bf1bb7a5e030e73 | 2026-01-05T02:41:17.874060Z | false |
hehonghui/simple_net_framework | https://github.com/hehonghui/simple_net_framework/blob/403b5b83ea2b42014ac5085b7bf1bb7a5e030e73/src/org/simple/net/httpstacks/HttpStack.java | src/org/simple/net/httpstacks/HttpStack.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.simple.net.httpstacks;
import org.simple.net.base.Request;
import org.simple.net.base.Response;
/**
* 执行网络请求的接口
*
* @author mrsimple
*/
public interface HttpStack {
/**
* 执行Http请求
*
* @param request 待执行的请求
* @return
*/
public Response performRequest(Request<?> request);
}
| java | MIT | 403b5b83ea2b42014ac5085b7bf1bb7a5e030e73 | 2026-01-05T02:41:17.874060Z | false |
hehonghui/simple_net_framework | https://github.com/hehonghui/simple_net_framework/blob/403b5b83ea2b42014ac5085b7bf1bb7a5e030e73/src/org/simple/net/httpstacks/HttpStackFactory.java | src/org/simple/net/httpstacks/HttpStackFactory.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.simple.net.httpstacks;
import android.os.Build;
/**
* 根据api版本选择HttpClient或者HttpURLConnection
*
* @author mrsimple
*/
public final class HttpStackFactory {
private static final int GINGERBREAD_SDK_NUM = 9;
/**
* 根据SDK版本号来创建不同的Http执行器,即SDK 9之前使用HttpClient,之后则使用HttlUrlConnection,
* 两者之间的差别请参考 :
* http://android-developers.blogspot.com/2011/09/androids-http-clients.html
*
* @return
*/
public static HttpStack createHttpStack() {
int runtimeSDKApi = Build.VERSION.SDK_INT;
if (runtimeSDKApi >= GINGERBREAD_SDK_NUM) {
return new HttpUrlConnStack();
}
return new HttpClientStack();
}
}
| java | MIT | 403b5b83ea2b42014ac5085b7bf1bb7a5e030e73 | 2026-01-05T02:41:17.874060Z | false |
hehonghui/simple_net_framework | https://github.com/hehonghui/simple_net_framework/blob/403b5b83ea2b42014ac5085b7bf1bb7a5e030e73/src/org/simple/net/httpstacks/HttpClientStack.java | src/org/simple/net/httpstacks/HttpClientStack.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.simple.net.httpstacks;
import android.net.http.AndroidHttpClient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.simple.net.base.Request;
import org.simple.net.base.Response;
import org.simple.net.config.HttpClientConfig;
import java.util.Map;
/**
* api 9以下使用HttpClient执行网络请求, https配置参考http://jackyrong.iteye.com/blog/1606444
*
* @author mrsimple
*/
public class HttpClientStack implements HttpStack {
/**
* 使用HttpClient执行网络请求时的Https配置
*/
HttpClientConfig mConfig = HttpClientConfig.getConfig();
/**
* HttpClient
*/
HttpClient mHttpClient = AndroidHttpClient.newInstance(mConfig.userAgent);
@Override
public Response performRequest(Request<?> request) {
try {
HttpUriRequest httpRequest = createHttpRequest(request);
// 添加连接参数
setConnectionParams(httpRequest);
// 添加header
addHeaders(httpRequest, request.getHeaders());
// https配置
configHttps(request);
// 执行请求
HttpResponse response = mHttpClient.execute(httpRequest);
// 构建Response
Response rawResponse = new Response(response.getStatusLine());
// 设置Entity
rawResponse.setEntity(response.getEntity());
return rawResponse;
} catch (Exception e) {
}
return null;
}
/**
* 如果是https请求,则使用用户配置的SSLSocketFactory进行配置.
*
* @param request
*/
private void configHttps(Request<?> request) {
SSLSocketFactory sslSocketFactory = mConfig.getSocketFactory();
if (request.isHttps() && sslSocketFactory != null) {
Scheme sch = new Scheme("https", sslSocketFactory, 443);
mHttpClient.getConnectionManager().getSchemeRegistry().register(sch);
}
}
/**
* 设置连接参数,这里比较简单啊.一些优化设置就没有写了.
*
* @param httpUriRequest
*/
private void setConnectionParams(HttpUriRequest httpUriRequest) {
HttpParams httpParams = httpUriRequest.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, mConfig.connTimeOut);
HttpConnectionParams.setSoTimeout(httpParams, mConfig.soTimeOut);
}
/**
* 根据请求类型创建不同的Http请求
*
* @param request
* @return
*/
static HttpUriRequest createHttpRequest(Request<?> request) {
HttpUriRequest httpUriRequest = null;
switch (request.getHttpMethod()) {
case GET:
httpUriRequest = new HttpGet(request.getUrl());
break;
case DELETE:
httpUriRequest = new HttpDelete(request.getUrl());
break;
case POST: {
httpUriRequest = new HttpPost(request.getUrl());
httpUriRequest.addHeader(Request.HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody((HttpPost) httpUriRequest, request);
}
break;
case PUT: {
httpUriRequest = new HttpPut(request.getUrl());
httpUriRequest.addHeader(Request.HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody((HttpPut) httpUriRequest, request);
}
break;
default:
throw new IllegalStateException("Unknown request method.");
}
return httpUriRequest;
}
private static void addHeaders(HttpUriRequest httpRequest, Map<String, String> headers) {
for (String key : headers.keySet()) {
httpRequest.setHeader(key, headers.get(key));
}
}
/**
* 将请求参数设置到HttpEntity中
*
* @param httpRequest
* @param request
*/
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest,
Request<?> request) {
byte[] body = request.getBody();
if (body != null) {
HttpEntity entity = new ByteArrayEntity(body);
httpRequest.setEntity(entity);
}
}
}
| java | MIT | 403b5b83ea2b42014ac5085b7bf1bb7a5e030e73 | 2026-01-05T02:41:17.874060Z | false |
hehonghui/simple_net_framework | https://github.com/hehonghui/simple_net_framework/blob/403b5b83ea2b42014ac5085b7bf1bb7a5e030e73/src/org/simple/net/httpstacks/HttpUrlConnStack.java | src/org/simple/net/httpstacks/HttpUrlConnStack.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.simple.net.httpstacks;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.ProtocolVersion;
import org.apache.http.StatusLine;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicStatusLine;
import org.simple.net.base.Request;
import org.simple.net.base.Request.HttpMethod;
import org.simple.net.base.Response;
import org.simple.net.config.HttpUrlConnConfig;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
/**
* 使用HttpURLConnection执行网络请求的HttpStack
*
* @author mrsimple
*/
public class HttpUrlConnStack implements HttpStack {
/**
* 配置Https
*/
HttpUrlConnConfig mConfig = HttpUrlConnConfig.getConfig();
@Override
public Response performRequest(Request<?> request) {
HttpURLConnection urlConnection = null;
try {
// 构建HttpURLConnection
urlConnection = createUrlConnection(request.getUrl());
// 设置headers
setRequestHeaders(urlConnection, request);
// 设置Body参数
setRequestParams(urlConnection, request);
// https 配置
configHttps(request);
return fetchResponse(urlConnection);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
private HttpURLConnection createUrlConnection(String url) throws IOException {
URL newURL = new URL(url);
URLConnection urlConnection = newURL.openConnection();
urlConnection.setConnectTimeout(mConfig.connTimeOut);
urlConnection.setReadTimeout(mConfig.soTimeOut);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
return (HttpURLConnection) urlConnection;
}
private void configHttps(Request<?> request) {
if (request.isHttps()) {
SSLSocketFactory sslFactory = mConfig.getSslSocketFactory();
// 配置https
if (sslFactory != null) {
HttpsURLConnection.setDefaultSSLSocketFactory(sslFactory);
HttpsURLConnection.setDefaultHostnameVerifier(mConfig.getHostnameVerifier());
}
}
}
private void setRequestHeaders(HttpURLConnection connection, Request<?> request) {
Set<String> headersKeys = request.getHeaders().keySet();
for (String headerName : headersKeys) {
connection.addRequestProperty(headerName, request.getHeaders().get(headerName));
}
}
protected void setRequestParams(HttpURLConnection connection, Request<?> request)
throws ProtocolException, IOException {
HttpMethod method = request.getHttpMethod();
connection.setRequestMethod(method.toString());
// add params
byte[] body = request.getBody();
if (body != null) {
// enable output
connection.setDoOutput(true);
// set content type
connection
.addRequestProperty(Request.HEADER_CONTENT_TYPE, request.getBodyContentType());
// write params data to connection
DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
dataOutputStream.write(body);
dataOutputStream.close();
}
}
private Response fetchResponse(HttpURLConnection connection) throws IOException {
// Initialize HttpResponse with data from the HttpURLConnection.
ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
int responseCode = connection.getResponseCode();
if (responseCode == -1) {
throw new IOException("Could not retrieve response code from HttpUrlConnection.");
}
// 状态行数据
StatusLine responseStatus = new BasicStatusLine(protocolVersion,
connection.getResponseCode(), connection.getResponseMessage());
// 构建response
Response response = new Response(responseStatus);
// 设置response数据
response.setEntity(entityFromURLConnwction(connection));
addHeadersToResponse(response, connection);
return response;
}
/**
* 执行HTTP请求之后获取到其数据流,即返回请求结果的流
*
* @param connection
* @return
*/
private HttpEntity entityFromURLConnwction(HttpURLConnection connection) {
BasicHttpEntity entity = new BasicHttpEntity();
InputStream inputStream = null;
try {
inputStream = connection.getInputStream();
} catch (IOException e) {
e.printStackTrace();
inputStream = connection.getErrorStream();
}
// TODO : GZIP
entity.setContent(inputStream);
entity.setContentLength(connection.getContentLength());
entity.setContentEncoding(connection.getContentEncoding());
entity.setContentType(connection.getContentType());
return entity;
}
private void addHeadersToResponse(BasicHttpResponse response, HttpURLConnection connection) {
for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
if (header.getKey() != null) {
Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
response.addHeader(h);
}
}
}
}
| java | MIT | 403b5b83ea2b42014ac5085b7bf1bb7a5e030e73 | 2026-01-05T02:41:17.874060Z | false |
hehonghui/simple_net_framework | https://github.com/hehonghui/simple_net_framework/blob/403b5b83ea2b42014ac5085b7bf1bb7a5e030e73/src/org/simple/net/entity/MultipartEntity.java | src/org/simple/net/entity/MultipartEntity.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.simple.net.entity;
import android.text.TextUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Random;
/**
* POST报文格式请参考博客 : http://blog.csdn.net/bboyfeiyu/article/details/41863951.
* <p>
* Android中的多参数类型的Entity实体类,用户可以使用该类来上传文件、文本参数、二进制参数,
* 不需要依赖于httpmime.jar来实现上传文件的功能.
* </p>
*
* @author mrsimple
*/
public class MultipartEntity implements HttpEntity {
private final static char[] MULTIPART_CHARS = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
.toCharArray();
/**
* 换行符
*/
private final String NEW_LINE_STR = "\r\n";
private final String CONTENT_TYPE = "Content-Type: ";
private final String CONTENT_DISPOSITION = "Content-Disposition: ";
/**
* 文本参数和字符集
*/
private final String TYPE_TEXT_CHARSET = "text/plain; charset=UTF-8";
/**
* 字节流参数
*/
private final String TYPE_OCTET_STREAM = "application/octet-stream";
/**
* 二进制参数
*/
private final byte[] BINARY_ENCODING = "Content-Transfer-Encoding: binary\r\n\r\n".getBytes();
/**
* 文本参数
*/
private final byte[] BIT_ENCODING = "Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes();
/**
* 分隔符
*/
private String mBoundary = null;
/**
* 输出流
*/
ByteArrayOutputStream mOutputStream = new ByteArrayOutputStream();
public MultipartEntity() {
this.mBoundary = generateBoundary();
}
/**
* 生成分隔符
*
* @return
*/
private final String generateBoundary() {
final StringBuffer buf = new StringBuffer();
final Random rand = new Random();
for (int i = 0; i < 30; i++) {
buf.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
}
return buf.toString();
}
/**
* 参数开头的分隔符
*
* @throws IOException
*/
private void writeFirstBoundary() throws IOException {
mOutputStream.write(("--" + mBoundary + "\r\n").getBytes());
}
/**
* 添加文本参数
*
* @param key
* @param value
*/
public void addStringPart(final String paramName, final String value) {
writeToOutputStream(paramName, value.getBytes(), TYPE_TEXT_CHARSET, BIT_ENCODING, "");
}
/**
* 将数据写入到输出流中
*
* @param key
* @param rawData
* @param type
* @param encodingBytes
* @param fileName
*/
private void writeToOutputStream(String paramName, byte[] rawData, String type,
byte[] encodingBytes,
String fileName) {
try {
writeFirstBoundary();
mOutputStream.write((CONTENT_TYPE + type + NEW_LINE_STR).getBytes());
mOutputStream
.write(getContentDispositionBytes(paramName, fileName));
mOutputStream.write(encodingBytes);
mOutputStream.write(rawData);
mOutputStream.write(NEW_LINE_STR.getBytes());
} catch (final IOException e) {
e.printStackTrace();
}
}
/**
* 添加二进制参数, 例如Bitmap的字节流参数
*
* @param key
* @param rawData
*/
public void addBinaryPart(String paramName, final byte[] rawData) {
writeToOutputStream(paramName, rawData, TYPE_OCTET_STREAM, BINARY_ENCODING, "no-file");
}
/**
* 添加文件参数,可以实现文件上传功能
*
* @param key
* @param file
*/
public void addFilePart(final String key, final File file) {
InputStream fin = null;
try {
fin = new FileInputStream(file);
writeFirstBoundary();
final String type = CONTENT_TYPE + TYPE_OCTET_STREAM + NEW_LINE_STR;
mOutputStream.write(getContentDispositionBytes(key, file.getName()));
mOutputStream.write(type.getBytes());
mOutputStream.write(BINARY_ENCODING);
final byte[] tmp = new byte[4096];
int len = 0;
while ((len = fin.read(tmp)) != -1) {
mOutputStream.write(tmp, 0, len);
}
mOutputStream.flush();
} catch (final IOException e) {
e.printStackTrace();
} finally {
closeSilently(fin);
}
}
private void closeSilently(Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (final IOException e) {
e.printStackTrace();
}
}
private byte[] getContentDispositionBytes(String paramName, String fileName) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(CONTENT_DISPOSITION + "form-data; name=\"" + paramName + "\"");
// 文本参数没有filename参数,设置为空即可
if (!TextUtils.isEmpty(fileName)) {
stringBuilder.append("; filename=\""
+ fileName + "\"");
}
return stringBuilder.append(NEW_LINE_STR).toString().getBytes();
}
@Override
public long getContentLength() {
return mOutputStream.toByteArray().length;
}
@Override
public Header getContentType() {
return new BasicHeader("Content-Type", "multipart/form-data; boundary=" + mBoundary);
}
@Override
public boolean isChunked() {
return false;
}
@Override
public boolean isRepeatable() {
return false;
}
@Override
public boolean isStreaming() {
return false;
}
@Override
public void writeTo(final OutputStream outstream) throws IOException {
// 参数最末尾的结束符
final String endString = "--" + mBoundary + "--\r\n";
// 写入结束符
mOutputStream.write(endString.getBytes());
//
outstream.write(mOutputStream.toByteArray());
}
@Override
public Header getContentEncoding() {
return null;
}
@Override
public void consumeContent() throws IOException,
UnsupportedOperationException {
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
@Override
public InputStream getContent() {
return new ByteArrayInputStream(mOutputStream.toByteArray());
}
}
| java | MIT | 403b5b83ea2b42014ac5085b7bf1bb7a5e030e73 | 2026-01-05T02:41:17.874060Z | false |
hehonghui/simple_net_framework | https://github.com/hehonghui/simple_net_framework/blob/403b5b83ea2b42014ac5085b7bf1bb7a5e030e73/src/org/simple/net/core/SimpleNet.java | src/org/simple/net/core/SimpleNet.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 bboyfeiyu@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.simple.net.core;
import org.simple.net.httpstacks.HttpStack;
/**
* SimpleNet入口
* @author mrsimple
*/
public final class SimpleNet {
/**
* 创建一个请求队列,NetworkExecutor数量为默认的数量
*
* @return
*/
public static RequestQueue newRequestQueue() {
return newRequestQueue(RequestQueue.DEFAULT_CORE_NUMS);
}
/**
* 创建一个请求队列,NetworkExecutor数量为coreNums
*
* @param coreNums
* @return
*/
public static RequestQueue newRequestQueue(int coreNums) {
return newRequestQueue(coreNums, null);
}
/**
* 创建一个请求队列,NetworkExecutor数量为coreNums
*
* @param coreNums 线程数量
* @param httpStack 网络执行者
* @return
*/
public static RequestQueue newRequestQueue(int coreNums, HttpStack httpStack) {
RequestQueue queue = new RequestQueue(Math.max(0, coreNums), httpStack);
queue.start();
return queue;
}
}
| java | MIT | 403b5b83ea2b42014ac5085b7bf1bb7a5e030e73 | 2026-01-05T02:41:17.874060Z | false |
hehonghui/simple_net_framework | https://github.com/hehonghui/simple_net_framework/blob/403b5b83ea2b42014ac5085b7bf1bb7a5e030e73/src/org/simple/net/core/ResponseDelivery.java | src/org/simple/net/core/ResponseDelivery.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.simple.net.core;
import android.os.Handler;
import android.os.Looper;
import org.simple.net.base.Request;
import org.simple.net.base.Response;
import java.util.concurrent.Executor;
/**
* 请求结果投递类,将请求结果投递给UI线程
*
* @author mrsimple
*/
class ResponseDelivery implements Executor {
/**
* 主线程的hander
*/
Handler mResponseHandler = new Handler(Looper.getMainLooper());
/**
* 处理请求结果,将其执行在UI线程
*
* @param request
* @param response
*/
public void deliveryResponse(final Request<?> request, final Response response) {
Runnable respRunnable = new Runnable() {
@Override
public void run() {
request.deliveryResponse(response);
}
};
execute(respRunnable);
}
@Override
public void execute(Runnable command) {
mResponseHandler.post(command);
}
}
| java | MIT | 403b5b83ea2b42014ac5085b7bf1bb7a5e030e73 | 2026-01-05T02:41:17.874060Z | false |
hehonghui/simple_net_framework | https://github.com/hehonghui/simple_net_framework/blob/403b5b83ea2b42014ac5085b7bf1bb7a5e030e73/src/org/simple/net/core/RequestQueue.java | src/org/simple/net/core/RequestQueue.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.simple.net.core;
import android.util.Log;
import org.simple.net.base.Request;
import org.simple.net.httpstacks.HttpStack;
import org.simple.net.httpstacks.HttpStackFactory;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 请求队列, 使用优先队列,使得请求可以按照优先级进行处理. [ Thread Safe ]
*
* @author mrsimple
*/
public final class RequestQueue {
/**
* 请求队列 [ Thread-safe ]
*/
private BlockingQueue<Request<?>> mRequestQueue = new PriorityBlockingQueue<Request<?>>();
/**
* 请求的序列化生成器
*/
private AtomicInteger mSerialNumGenerator = new AtomicInteger(0);
/**
* 默认的核心数
*/
public static int DEFAULT_CORE_NUMS = Runtime.getRuntime().availableProcessors() + 1;
/**
* CPU核心数 + 1个分发线程数
*/
private int mDispatcherNums = DEFAULT_CORE_NUMS;
/**
* NetworkExecutor,执行网络请求的线程
*/
private NetworkExecutor[] mDispatchers = null;
/**
* Http请求的真正执行者
*/
private HttpStack mHttpStack;
/**
* @param coreNums 线程核心数
* @param httpStack http执行器
*/
protected RequestQueue(int coreNums, HttpStack httpStack) {
mDispatcherNums = coreNums;
mHttpStack = httpStack != null ? httpStack : HttpStackFactory.createHttpStack();
}
/**
* 启动NetworkExecutor
*/
private final void startNetworkExecutors() {
mDispatchers = new NetworkExecutor[mDispatcherNums];
for (int i = 0; i < mDispatcherNums; i++) {
mDispatchers[i] = new NetworkExecutor(mRequestQueue, mHttpStack);
mDispatchers[i].start();
}
}
public void start() {
stop();
startNetworkExecutors();
}
/**
* 停止NetworkExecutor
*/
public void stop() {
if (mDispatchers != null && mDispatchers.length > 0) {
for (int i = 0; i < mDispatchers.length; i++) {
mDispatchers[i].quit();
}
}
}
/**
* 不能重复添加请求
*
* @param request
*/
public void addRequest(Request<?> request) {
if (!mRequestQueue.contains(request)) {
request.setSerialNumber(this.generateSerialNumber());
mRequestQueue.add(request);
} else {
Log.d("", "### 请求队列中已经含有");
}
}
public void clear() {
mRequestQueue.clear();
}
public BlockingQueue<Request<?>> getAllRequests() {
return mRequestQueue;
}
/**
* 为每个请求生成一个系列号
*
* @return 序列号
*/
private int generateSerialNumber() {
return mSerialNumGenerator.incrementAndGet();
}
}
| java | MIT | 403b5b83ea2b42014ac5085b7bf1bb7a5e030e73 | 2026-01-05T02:41:17.874060Z | false |
hehonghui/simple_net_framework | https://github.com/hehonghui/simple_net_framework/blob/403b5b83ea2b42014ac5085b7bf1bb7a5e030e73/src/org/simple/net/core/NetworkExecutor.java | src/org/simple/net/core/NetworkExecutor.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 bboyfeiyu@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.simple.net.core;
import android.util.Log;
import org.simple.net.base.Request;
import org.simple.net.base.Response;
import org.simple.net.cache.Cache;
import org.simple.net.cache.LruMemCache;
import org.simple.net.httpstacks.HttpStack;
import java.util.concurrent.BlockingQueue;
/**
* 网络请求Executor,继承自Thread,从网络请求队列中循环读取请求并且执行
*
* @author mrsimple
*/
final class NetworkExecutor extends Thread {
/**
* 网络请求队列
*/
private BlockingQueue<Request<?>> mRequestQueue;
/**
* 网络请求栈
*/
private HttpStack mHttpStack;
/**
* 结果分发器,将结果投递到主线程
*/
private static ResponseDelivery mResponseDelivery = new ResponseDelivery();
/**
* 请求缓存
*/
private static Cache<String, Response> mReqCache = new LruMemCache();
/**
* 是否停止
*/
private boolean isStop = false;
public NetworkExecutor(BlockingQueue<Request<?>> queue, HttpStack httpStack) {
mRequestQueue = queue;
mHttpStack = httpStack;
}
@Override
public void run() {
try {
while (!isStop) {
final Request<?> request = mRequestQueue.take();
if (request.isCanceled()) {
Log.d("### ", "### 取消执行了");
continue;
}
Response response = null;
if (isUseCache(request)) {
// 从缓存中取
response = mReqCache.get(request.getUrl());
} else {
// 从网络上获取数据
response = mHttpStack.performRequest(request);
// 如果该请求需要缓存,那么请求成功则缓存到mResponseCache中
if (request.shouldCache() && isSuccess(response)) {
mReqCache.put(request.getUrl(), response);
}
}
// 分发请求结果
mResponseDelivery.deliveryResponse(request, response);
}
} catch (InterruptedException e) {
Log.i("", "### 请求分发器退出");
}
}
private boolean isSuccess(Response response) {
return response != null && response.getStatusCode() == 200;
}
private boolean isUseCache(Request<?> request) {
return request.shouldCache() && mReqCache.get(request.getUrl()) != null;
}
public void quit() {
isStop = true;
interrupt();
}
}
| java | MIT | 403b5b83ea2b42014ac5085b7bf1bb7a5e030e73 | 2026-01-05T02:41:17.874060Z | false |
hehonghui/simple_net_framework | https://github.com/hehonghui/simple_net_framework/blob/403b5b83ea2b42014ac5085b7bf1bb7a5e030e73/src/org/simple/net/config/HttpConfig.java | src/org/simple/net/config/HttpConfig.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.simple.net.config;
/**
* http配置类
*
* @author mrsimple
*/
public abstract class HttpConfig {
public String userAgent = "default";
public int soTimeOut = 10000;
public int connTimeOut = 10000;
}
| java | MIT | 403b5b83ea2b42014ac5085b7bf1bb7a5e030e73 | 2026-01-05T02:41:17.874060Z | false |
hehonghui/simple_net_framework | https://github.com/hehonghui/simple_net_framework/blob/403b5b83ea2b42014ac5085b7bf1bb7a5e030e73/src/org/simple/net/config/HttpClientConfig.java | src/org/simple/net/config/HttpClientConfig.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.simple.net.config;
import org.apache.http.conn.ssl.SSLSocketFactory;
/**
* 这是针对于使用HttpClientStack执行请求时为https请求配置的SSLSocketFactory类
*
* @author mrsimple
*/
public class HttpClientConfig extends HttpConfig {
private static HttpClientConfig sConfig = new HttpClientConfig();
SSLSocketFactory mSslSocketFactory;
private HttpClientConfig() {
}
public static HttpClientConfig getConfig() {
return sConfig;
}
/**
* 配置https请求的SSLSocketFactory与HostnameVerifier
*
* @param sslSocketFactory
* @param hostnameVerifier
*/
public void setHttpsConfig(SSLSocketFactory sslSocketFactory) {
mSslSocketFactory = sslSocketFactory;
}
public SSLSocketFactory getSocketFactory() {
return mSslSocketFactory;
}
}
| java | MIT | 403b5b83ea2b42014ac5085b7bf1bb7a5e030e73 | 2026-01-05T02:41:17.874060Z | false |
hehonghui/simple_net_framework | https://github.com/hehonghui/simple_net_framework/blob/403b5b83ea2b42014ac5085b7bf1bb7a5e030e73/src/org/simple/net/config/HttpUrlConnConfig.java | src/org/simple/net/config/HttpUrlConnConfig.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 bboyfeiyu@gmail.com, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.simple.net.config;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSocketFactory;
/**
* 这是针对于使用HttpUrlStack执行请求时为https请求设置的SSLSocketFactory和HostnameVerifier的配置类,参考
* http://blog.csdn.net/xyz_lmn/article/details/8027334,http://www.cnblogs.com/
* vus520/archive/2012/09/07/2674725.html,
*
* @author mrsimple
*/
public class HttpUrlConnConfig extends HttpConfig {
private static HttpUrlConnConfig sConfig = new HttpUrlConnConfig();
private SSLSocketFactory mSslSocketFactory = null;
private HostnameVerifier mHostnameVerifier = null;
private HttpUrlConnConfig() {
}
public static HttpUrlConnConfig getConfig() {
return sConfig;
}
/**
* 配置https请求的SSLSocketFactory与HostnameVerifier
*
* @param sslSocketFactory
* @param hostnameVerifier
*/
public void setHttpsConfig(SSLSocketFactory sslSocketFactory,
HostnameVerifier hostnameVerifier) {
mSslSocketFactory = sslSocketFactory;
mHostnameVerifier = hostnameVerifier;
}
public HostnameVerifier getHostnameVerifier() {
return mHostnameVerifier;
}
public SSLSocketFactory getSslSocketFactory() {
return mSslSocketFactory;
}
}
| java | MIT | 403b5b83ea2b42014ac5085b7bf1bb7a5e030e73 | 2026-01-05T02:41:17.874060Z | false |
hehonghui/simple_net_framework | https://github.com/hehonghui/simple_net_framework/blob/403b5b83ea2b42014ac5085b7bf1bb7a5e030e73/simple_net_framework_test/src/com/umeng/network/test/RequestQueueTest.java | simple_net_framework_test/src/com/umeng/network/test/RequestQueueTest.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 Umeng, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.umeng.network.test;
import android.test.AndroidTestCase;
import org.simple.net.base.Request.HttpMethod;
import org.simple.net.base.Request.RequestListener;
import org.simple.net.core.RequestQueue;
import org.simple.net.core.SimpleNet;
import org.simple.net.requests.StringRequest;
public class RequestQueueTest extends AndroidTestCase {
RequestQueue mQueue = SimpleNet.newRequestQueue();
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
mQueue.clear();
}
public void testMultiRequests() {
for (int i = 0; i < 10; i++) {
StringRequest request = new StringRequest(HttpMethod.GET, "http://myhost.com", null);
mQueue.addRequest(request);
}
assertEquals(1, mQueue.getAllRequests().size());
}
public void testMultiRequestsWithListeners() {
// 添加lisener
for (int i = 0; i < 10; i++) {
StringRequest request = new StringRequest(HttpMethod.GET, "http://myhost.com",
new RequestListener<String>() {
@Override
public void onComplete(int stCode, String response, String errMsg) {
}
});
mQueue.addRequest(request);
}
assertEquals(1, mQueue.getAllRequests().size());
}
}
| java | MIT | 403b5b83ea2b42014ac5085b7bf1bb7a5e030e73 | 2026-01-05T02:41:17.874060Z | false |
hehonghui/simple_net_framework | https://github.com/hehonghui/simple_net_framework/blob/403b5b83ea2b42014ac5085b7bf1bb7a5e030e73/simple_net_framework_test/src/com/umeng/network/test/LURCacheTest.java | simple_net_framework_test/src/com/umeng/network/test/LURCacheTest.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 Umeng, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.umeng.network.test;
import android.support.v4.util.LruCache;
import android.test.AndroidTestCase;
import org.apache.http.ProtocolVersion;
import org.apache.http.StatusLine;
import org.simple.net.base.Request;
import org.simple.net.base.Response;
import org.simple.net.base.Request.HttpMethod;
import org.simple.net.requests.StringRequest;
public class LURCacheTest extends AndroidTestCase {
/**
* Reponse缓存
*/
private LruCache<Request<?>, Response> mResponseCache;
protected void setUp() throws Exception {
super.setUp();
initCache();
}
protected void tearDown() throws Exception {
super.tearDown();
}
private void initCache() {
mResponseCache = new LruCache<Request<?>, Response>(108 * 1024);
}
public void testMultiRequestCache() {
for (int i = 0; i < 20; i++) {
StringRequest request = new StringRequest(HttpMethod.GET, "http://url" + i, null);
request.getParams().put("key-" + i, "value-1");
request.getHeaders().put("header-" + i, "header-" + i);
Response response = new Response(mStatusLine);
mResponseCache.put(request, response);
}
assertEquals(20, mResponseCache.size());
}
public void testMultiRequestWithSame() {
for (int i = 0; i < 20; i++) {
StringRequest request = new StringRequest(HttpMethod.GET, "http://url", null);
request.getParams().put("key-1", "value-1");
request.getHeaders().put("header-1", "header-1");
Response response = new Response(mStatusLine);
mResponseCache.put(request, response);
}
assertEquals(1, mResponseCache.size());
}
StatusLine mStatusLine = new StatusLine() {
@Override
public int getStatusCode() {
return 0;
}
@Override
public String getReasonPhrase() {
return "msg";
}
@Override
public ProtocolVersion getProtocolVersion() {
return new ProtocolVersion("http", 1, 1);
}
};
}
| java | MIT | 403b5b83ea2b42014ac5085b7bf1bb7a5e030e73 | 2026-01-05T02:41:17.874060Z | false |
yannbriancon/spring-hibernate-query-utils | https://github.com/yannbriancon/spring-hibernate-query-utils/blob/c5eae0d811625d1a212b7c86e716b52c414d3e6f/.mvn/wrapper/MavenWrapperDownloader.java | .mvn/wrapper/MavenWrapperDownloader.java | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.5";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl type to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the type which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
| java | MIT | c5eae0d811625d1a212b7c86e716b52c414d3e6f | 2026-01-05T02:41:28.211339Z | false |
yannbriancon/spring-hibernate-query-utils | https://github.com/yannbriancon/spring-hibernate-query-utils/blob/c5eae0d811625d1a212b7c86e716b52c414d3e6f/src/test/java/com/yannbriancon/Application.java | src/test/java/com/yannbriancon/Application.java | package com.yannbriancon;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
| java | MIT | c5eae0d811625d1a212b7c86e716b52c414d3e6f | 2026-01-05T02:41:28.211339Z | false |
yannbriancon/spring-hibernate-query-utils | https://github.com/yannbriancon/spring-hibernate-query-utils/blob/c5eae0d811625d1a212b7c86e716b52c414d3e6f/src/test/java/com/yannbriancon/utils/repository/UserRepository.java | src/test/java/com/yannbriancon/utils/repository/UserRepository.java | package com.yannbriancon.utils.repository;
import com.yannbriancon.utils.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
| java | MIT | c5eae0d811625d1a212b7c86e716b52c414d3e6f | 2026-01-05T02:41:28.211339Z | false |
yannbriancon/spring-hibernate-query-utils | https://github.com/yannbriancon/spring-hibernate-query-utils/blob/c5eae0d811625d1a212b7c86e716b52c414d3e6f/src/test/java/com/yannbriancon/utils/repository/AvatarRepository.java | src/test/java/com/yannbriancon/utils/repository/AvatarRepository.java | package com.yannbriancon.utils.repository;
import com.yannbriancon.utils.entity.Avatar;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface AvatarRepository extends JpaRepository<Avatar, Long> {
}
| java | MIT | c5eae0d811625d1a212b7c86e716b52c414d3e6f | 2026-01-05T02:41:28.211339Z | false |
yannbriancon/spring-hibernate-query-utils | https://github.com/yannbriancon/spring-hibernate-query-utils/blob/c5eae0d811625d1a212b7c86e716b52c414d3e6f/src/test/java/com/yannbriancon/utils/repository/MessageRepository.java | src/test/java/com/yannbriancon/utils/repository/MessageRepository.java | package com.yannbriancon.utils.repository;
import com.yannbriancon.utils.entity.Message;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface MessageRepository extends JpaRepository<Message, Long> {
@EntityGraph(attributePaths = {"author"})
List<Message> getAllBy();
}
| java | MIT | c5eae0d811625d1a212b7c86e716b52c414d3e6f | 2026-01-05T02:41:28.211339Z | false |
yannbriancon/spring-hibernate-query-utils | https://github.com/yannbriancon/spring-hibernate-query-utils/blob/c5eae0d811625d1a212b7c86e716b52c414d3e6f/src/test/java/com/yannbriancon/utils/repository/PostRepository.java | src/test/java/com/yannbriancon/utils/repository/PostRepository.java | package com.yannbriancon.utils.repository;
import com.yannbriancon.utils.entity.Post;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PostRepository extends JpaRepository<Post, Long> {
}
| java | MIT | c5eae0d811625d1a212b7c86e716b52c414d3e6f | 2026-01-05T02:41:28.211339Z | false |
yannbriancon/spring-hibernate-query-utils | https://github.com/yannbriancon/spring-hibernate-query-utils/blob/c5eae0d811625d1a212b7c86e716b52c414d3e6f/src/test/java/com/yannbriancon/utils/entity/Avatar.java | src/test/java/com/yannbriancon/utils/entity/Avatar.java | package com.yannbriancon.utils.entity;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "avatars")
public class Avatar {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "pseudo", referencedColumnName = "pseudo")
private User user;
public Avatar() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
| java | MIT | c5eae0d811625d1a212b7c86e716b52c414d3e6f | 2026-01-05T02:41:28.211339Z | false |
yannbriancon/spring-hibernate-query-utils | https://github.com/yannbriancon/spring-hibernate-query-utils/blob/c5eae0d811625d1a212b7c86e716b52c414d3e6f/src/test/java/com/yannbriancon/utils/entity/Post.java | src/test/java/com/yannbriancon/utils/entity/Post.java | package com.yannbriancon.utils.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "posts")
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "message_id")
private Message message;
public Post() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
}
| java | MIT | c5eae0d811625d1a212b7c86e716b52c414d3e6f | 2026-01-05T02:41:28.211339Z | false |
yannbriancon/spring-hibernate-query-utils | https://github.com/yannbriancon/spring-hibernate-query-utils/blob/c5eae0d811625d1a212b7c86e716b52c414d3e6f/src/test/java/com/yannbriancon/utils/entity/Message.java | src/test/java/com/yannbriancon/utils/entity/Message.java | package com.yannbriancon.utils.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "messages")
public class Message {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "text")
private String text;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "author_id")
private User author;
public Message() {
}
public Message(String text, User author) {
this.text = text;
this.author = author;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
}
| java | MIT | c5eae0d811625d1a212b7c86e716b52c414d3e6f | 2026-01-05T02:41:28.211339Z | false |
yannbriancon/spring-hibernate-query-utils | https://github.com/yannbriancon/spring-hibernate-query-utils/blob/c5eae0d811625d1a212b7c86e716b52c414d3e6f/src/test/java/com/yannbriancon/utils/entity/User.java | src/test/java/com/yannbriancon/utils/entity/User.java | package com.yannbriancon.utils.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
@Entity
@Table(name = "users")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "pseudo", unique = true)
private String pseudo;
public User() {
}
public User(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| java | MIT | c5eae0d811625d1a212b7c86e716b52c414d3e6f | 2026-01-05T02:41:28.211339Z | false |
yannbriancon/spring-hibernate-query-utils | https://github.com/yannbriancon/spring-hibernate-query-utils/blob/c5eae0d811625d1a212b7c86e716b52c414d3e6f/src/test/java/com/yannbriancon/interceptor/NPlusOneQueriesLoggingTest.java | src/test/java/com/yannbriancon/interceptor/NPlusOneQueriesLoggingTest.java | package com.yannbriancon.interceptor;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.Appender;
import com.yannbriancon.utils.entity.Message;
import com.yannbriancon.utils.entity.Post;
import com.yannbriancon.utils.repository.MessageRepository;
import com.yannbriancon.utils.repository.PostRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
@SpringBootTest
@Transactional
class NPlusOneQueriesLoggingTest {
@Autowired
private MessageRepository messageRepository;
@Autowired
private PostRepository postRepository;
@Mock
private Appender mockedAppender;
@Captor
private ArgumentCaptor<LoggingEvent> loggingEventCaptor;
@BeforeEach
public void setup() {
Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
root.addAppender(mockedAppender);
}
@Test
void hibernateQueryInterceptor_isDetectingNPlusOneQueriesWhenMissingEagerFetchingOnQuery() {
// Fetch the 2 messages without the authors
List<Message> messages = messageRepository.findAll();
// The getters trigger N+1 queries
List<String> names = messages.stream()
.map(message -> message.getAuthor().getName())
.collect(Collectors.toList());
verify(mockedAppender, times(2)).doAppend(loggingEventCaptor.capture());
LoggingEvent loggingEvent = loggingEventCaptor.getAllValues().get(0);
assertThat(loggingEvent.getMessage())
.contains("N+1 queries detected on a getter of the entity com.yannbriancon.utils.entity.User\n" +
" at com.yannbriancon.interceptor.NPlusOneQueriesLoggingTest." +
"lambda$hibernateQueryInterceptor_isDetectingNPlusOneQueriesWhenMissingEagerFetchingOnQuery$0");
assertThat(Level.ERROR).isEqualTo(loggingEvent.getLevel());
}
@Test
void hibernateQueryInterceptor_isDetectingNPlusOneQueriesWhenMissingLazyFetchingOnEntityField() {
// The query triggers N+1 queries to eager fetch each post message
List<Post> posts = postRepository.findAll();
verify(mockedAppender, times(2)).doAppend(loggingEventCaptor.capture());
LoggingEvent loggingEvent = loggingEventCaptor.getAllValues().get(0);
assertThat(loggingEvent.getMessage())
.contains("N+1 queries detected with eager fetching on the entity com.yannbriancon.utils.entity.Message\n" +
" at com.yannbriancon.interceptor.NPlusOneQueriesLoggingTest." +
"hibernateQueryInterceptor_isDetectingNPlusOneQueriesWhenMissingLazyFetchingOnEntityField");
assertThat(Level.ERROR).isEqualTo(loggingEvent.getLevel());
}
@Test
void nPlusOneQueriesDetection_isNotLoggingWhenNoNPlusOneQueries() {
// Fetch the messages and does not trigger N+1 queries
messageRepository.findById(2L);
verify(mockedAppender, times(0)).doAppend(any());
}
}
| java | MIT | c5eae0d811625d1a212b7c86e716b52c414d3e6f | 2026-01-05T02:41:28.211339Z | false |
yannbriancon/spring-hibernate-query-utils | https://github.com/yannbriancon/spring-hibernate-query-utils/blob/c5eae0d811625d1a212b7c86e716b52c414d3e6f/src/test/java/com/yannbriancon/interceptor/NPlusOneQueriesExceptionTest.java | src/test/java/com/yannbriancon/interceptor/NPlusOneQueriesExceptionTest.java | package com.yannbriancon.interceptor;
import com.yannbriancon.exception.NPlusOneQueriesException;
import com.yannbriancon.utils.entity.Message;
import com.yannbriancon.utils.entity.User;
import com.yannbriancon.utils.repository.AvatarRepository;
import com.yannbriancon.utils.repository.MessageRepository;
import com.yannbriancon.utils.repository.UserRepository;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.util.List;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest("spring-hibernate-query-utils.n-plus-one-queries-detection.error-level=EXCEPTION")
@Transactional
class NPlusOneQueriesExceptionTest {
@Autowired
private AvatarRepository avatarRepository;
@Autowired
private EntityManager entityManager;
@Autowired
private MessageRepository messageRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private HibernateQueryInterceptor hibernateQueryInterceptor;
@Test
void nPlusOneQueriesDetection_throwsCallbackExceptionWhenNPlusOneQueries() {
// Fetch the 2 messages without the authors
List<Message> messages = messageRepository.findAll();
try {
// Trigger N+1 queries
List<String> names = messages.stream()
.map(message -> message.getAuthor().getName())
.collect(Collectors.toList());
assert false;
} catch (NPlusOneQueriesException exception) {
assertThat(exception.getMessage())
.contains("N+1 queries detected on a getter of the entity com.yannbriancon.utils.entity.User\n" +
" at com.yannbriancon.interceptor.NPlusOneQueriesExceptionTest." +
"lambda$nPlusOneQueriesDetection_throwsCallbackExceptionWhenNPlusOneQueries$0");
}
}
@Test
void nPlusOneQueriesDetection_isNotThrowingExceptionWhenNoNPlusOneQueries() {
// Fetch the 2 messages with the authors
List<Message> messages = messageRepository.getAllBy();
// Do not trigger N+1 queries
List<String> names = messages.stream()
.map(message -> message.getAuthor().getName())
.collect(Collectors.toList());
}
@Test
void nPlusOneQueriesDetection_isNotThrowingExceptionWhenLoopingOnSameMethod() {
for (Long id = 0L; id < 2; id++) {
messageRepository.findById(id);
}
}
@Test
void nPlusOneQueriesDetection_throwsExceptionWhenMissingEagerFetchingOnManyToOne() {
try {
// Test a method that should return a N+1 query
// The query triggers N+1 queries to eager fetch the user field
avatarRepository.findAll();
assert false;
} catch (NPlusOneQueriesException exception) {
assertThat(exception.getMessage())
.contains("N+1 queries detected with eager fetching on the entity com.yannbriancon.utils.entity.User\n" +
" at com.yannbriancon.interceptor.NPlusOneQueriesExceptionTest" +
".nPlusOneQueriesDetection_throwsExceptionWhenMissingEagerFetchingOnManyToOne");
}
}
@Test
void nPlusOneQueriesDetection_throwsExceptionWhenSessionIsCleared() {
User author = new User("author");
userRepository.saveAndFlush(author);
Message newMessage = new Message("text", author);
messageRepository.saveAndFlush(newMessage);
// Test a method that should return a N+1 query
// The method does not return an exception because we just created the message so it is loaded in the Session
getMessageAuthorNameWithNPlusOneQuery(newMessage.getId());
// Clear the session to be able to correctly detect the N+1 queries in the tests
hibernateQueryInterceptor.clearNPlusOneQuerySession(entityManager);
try {
// Test a method that should return a N+1 query
// This time the Session is empty and the N+1 query is detected
getMessageAuthorNameWithNPlusOneQuery(newMessage.getId());
assert false;
} catch (NPlusOneQueriesException exception) {
assertThat(exception.getMessage())
.contains("N+1 queries detected on a getter of the entity com.yannbriancon.utils.entity.User\n" +
" at com.yannbriancon.interceptor.NPlusOneQueriesExceptionTest" +
".getMessageAuthorNameWithNPlusOneQuery");
}
}
String getMessageAuthorNameWithNPlusOneQuery(Long messageId) {
Message message = messageRepository.findById(messageId).get();
// Should trigger N+1 query
return message.getAuthor().getName();
}
}
| java | MIT | c5eae0d811625d1a212b7c86e716b52c414d3e6f | 2026-01-05T02:41:28.211339Z | false |
yannbriancon/spring-hibernate-query-utils | https://github.com/yannbriancon/spring-hibernate-query-utils/blob/c5eae0d811625d1a212b7c86e716b52c414d3e6f/src/test/java/com/yannbriancon/interceptor/QueryCountTest.java | src/test/java/com/yannbriancon/interceptor/QueryCountTest.java | package com.yannbriancon.interceptor;
import com.yannbriancon.utils.entity.User;
import com.yannbriancon.utils.repository.MessageRepository;
import com.yannbriancon.utils.repository.UserRepository;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
class QueryCountTest {
@Autowired
private UserRepository userRepository;
@Autowired
private MessageRepository messageRepository;
@Autowired
private HibernateQueryInterceptor hibernateQueryInterceptor;
@Test
void queryCount_isOkWhenCallingRepository() {
hibernateQueryInterceptor.startQueryCount();
messageRepository.findAll();
assertThat(hibernateQueryInterceptor.getQueryCount()).isEqualTo(1);
}
@Test
void queryCount_isOkWhenSaveQueryIsExecutedBeforeStartingTheCount() {
userRepository.saveAndFlush(new User());
hibernateQueryInterceptor.startQueryCount();
messageRepository.findAll();
assertThat(hibernateQueryInterceptor.getQueryCount()).isEqualTo(1);
}
}
| java | MIT | c5eae0d811625d1a212b7c86e716b52c414d3e6f | 2026-01-05T02:41:28.211339Z | false |
yannbriancon/spring-hibernate-query-utils | https://github.com/yannbriancon/spring-hibernate-query-utils/blob/c5eae0d811625d1a212b7c86e716b52c414d3e6f/src/test/java/com/yannbriancon/interceptor/NPlusOneQueriesDisabledTest.java | src/test/java/com/yannbriancon/interceptor/NPlusOneQueriesDisabledTest.java | package com.yannbriancon.interceptor;
import com.yannbriancon.utils.entity.Message;
import com.yannbriancon.utils.repository.MessageRepository;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(properties = {
"spring-hibernate-query-utils.n-plus-one-queries-detection.error-level=EXCEPTION",
"spring-hibernate-query-utils.n-plus-one-queries-detection.enabled=false"
})
@Transactional
class NPlusOneQueriesDisabledTest {
@Autowired
private MessageRepository messageRepository;
@Autowired
private HibernateQueryInterceptor hibernateQueryInterceptor;
@Test
void nPlusOneQueriesDetection_whenDisabled_stillCountsQueries_doesNotThrowException() {
// Fetch the 2 messages without the authors
List<Message> messages = messageRepository.findAll();
hibernateQueryInterceptor.startQueryCount();
// Trigger N+1 queries, if this WAS enabled, it would throw an exception and fail the test.
messages.stream()
.map(message -> message.getAuthor().getName())
.collect(Collectors.toList());
//Assert that counting still runs when n+1 detection is disabled
assertThat(hibernateQueryInterceptor.getQueryCount()).isEqualTo(2);
}
}
| java | MIT | c5eae0d811625d1a212b7c86e716b52c414d3e6f | 2026-01-05T02:41:28.211339Z | false |
yannbriancon/spring-hibernate-query-utils | https://github.com/yannbriancon/spring-hibernate-query-utils/blob/c5eae0d811625d1a212b7c86e716b52c414d3e6f/src/main/java/com/yannbriancon/exception/NPlusOneQueriesException.java | src/main/java/com/yannbriancon/exception/NPlusOneQueriesException.java | package com.yannbriancon.exception;
/**
* Exception triggered when detecting N+1 queries
*/
public class NPlusOneQueriesException extends RuntimeException {
public NPlusOneQueriesException(String message) {
super(message);
}
}
| java | MIT | c5eae0d811625d1a212b7c86e716b52c414d3e6f | 2026-01-05T02:41:28.211339Z | false |
yannbriancon/spring-hibernate-query-utils | https://github.com/yannbriancon/spring-hibernate-query-utils/blob/c5eae0d811625d1a212b7c86e716b52c414d3e6f/src/main/java/com/yannbriancon/interceptor/HibernateQueryInterceptor.java | src/main/java/com/yannbriancon/interceptor/HibernateQueryInterceptor.java | package com.yannbriancon.interceptor;
import com.yannbriancon.config.NPlusOneQueriesDetectionProperties;
import com.yannbriancon.exception.NPlusOneQueriesException;
import org.hibernate.EmptyInterceptor;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import javax.persistence.EntityManager;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;
@Component
@EnableConfigurationProperties(NPlusOneQueriesDetectionProperties.class)
public class HibernateQueryInterceptor extends EmptyInterceptor {
private transient ThreadLocal<Long> threadQueryCount = new ThreadLocal<>();
private transient ThreadLocal<Set<String>> threadPreviouslyLoadedEntities =
ThreadLocal.withInitial(new EmptySetSupplier<>());
private transient ThreadLocal<Map<String, SelectQueriesInfo>> threadSelectQueriesInfoPerProxyMethod =
ThreadLocal.withInitial(new EmptyMapSupplier<>());
private static final Logger LOGGER = LoggerFactory.getLogger(HibernateQueryInterceptor.class);
private final NPlusOneQueriesDetectionProperties NPlusOneQueriesDetectionProperties;
private static final String HIBERNATE_PROXY_PREFIX = "org.hibernate.proxy";
private static final String PROXY_METHOD_PREFIX = "com.sun.proxy";
public HibernateQueryInterceptor(
NPlusOneQueriesDetectionProperties NPlusOneQueriesDetectionProperties
) {
this.NPlusOneQueriesDetectionProperties = NPlusOneQueriesDetectionProperties;
}
/**
* Reset the N+1 query detection state
*/
private void resetNPlusOneQueryDetectionState() {
threadPreviouslyLoadedEntities.set(new HashSet<>());
threadSelectQueriesInfoPerProxyMethod.set(new HashMap<>());
}
/**
* Clear the Hibernate Session and reset the N+1 query detection state
* <p>
* Clearing the Hibernate Session is necessary to detect N+1 queries in tests as they would be in production.
* Otherwise, every objects created in the setup of the tests would already be loaded in the Session and would
* hide potential N+1 queries.
*/
public void clearNPlusOneQuerySession(EntityManager entityManager) {
entityManager.clear();
this.resetNPlusOneQueryDetectionState();
}
/**
* Start or reset the query count to 0 for the considered thread
*/
public void startQueryCount() {
threadQueryCount.set(0L);
}
/**
* Get the query count for the considered thread
*/
public Long getQueryCount() {
return threadQueryCount.get();
}
/**
* Detect the N+1 queries by keeping the history of sql queries generated per proxy method.
* Increment the query count for the considered thread for each new statement if the count has been initialized.
*
* @param sql Query to be executed
* @return Query to be executed
*/
@Override
public String onPrepareStatement(String sql) {
if (NPlusOneQueriesDetectionProperties.isEnabled()) {
updateSelectQueriesInfoPerProxyMethod(sql);
}
Long count = threadQueryCount.get();
if (count != null) {
threadQueryCount.set(count + 1);
}
return super.onPrepareStatement(sql);
}
/**
* Reset previously loaded entities after the end of a transaction to avoid triggering
* N+1 queries exceptions because of loading same instance in two different transactions
*
* @param tx Transaction having been completed
*/
@Override
public void afterTransactionCompletion(Transaction tx) {
this.resetNPlusOneQueryDetectionState();
}
/**
* Detect the N+1 queries by keeping the history of the entities previously gotten.
*
* @param entityName Name of the entity to get
* @param id Id of the entity to get
*/
@Override
public Object getEntity(String entityName, Serializable id) {
if (NPlusOneQueriesDetectionProperties.isEnabled()) {
detectNPlusOneQueriesFromMissingEagerFetchingOnAQuery(entityName, id);
detectNPlusOneQueriesFromClassFieldEagerFetching(entityName);
}
return null;
}
/**
* Detect the N+1 queries caused by a missing eager fetching configuration on a query with a lazy loaded field
* <p>
* Detection checks:
* - The getEntity was called twice for the couple (entity, id)
* - There is an occurrence of hibernate proxy followed by entity class in the stackTraceElements
* Avoid detecting calls to queries like findById and queries with eager fetching on some entity fields
*
* @param entityName Name of the entity
* @param id Id of the entity objecy
*/
private void detectNPlusOneQueriesFromMissingEagerFetchingOnAQuery(String entityName, Serializable id) {
Set<String> previouslyLoadedEntities = threadPreviouslyLoadedEntities.get();
if (!previouslyLoadedEntities.contains(entityName + id)) {
previouslyLoadedEntities.add(entityName + id);
threadPreviouslyLoadedEntities.set(previouslyLoadedEntities);
return;
}
previouslyLoadedEntities.remove(entityName + id);
threadPreviouslyLoadedEntities.set(previouslyLoadedEntities);
// Detect N+1 queries by searching for newest occurrence of Hibernate proxy followed by entity class in stack
// elements
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
StackTraceElement originStackTraceElement = null;
for (int i = 0; i < stackTraceElements.length - 3; i++) {
if (
stackTraceElements[i].getClassName().indexOf(HIBERNATE_PROXY_PREFIX) == 0
&& stackTraceElements[i + 1].getClassName().indexOf(entityName) == 0
) {
originStackTraceElement = stackTraceElements[i + 2];
break;
}
}
if (originStackTraceElement == null) {
return;
}
String errorMessage = "N+1 queries detected on a getter of the entity " + entityName +
"\n at " + originStackTraceElement.toString() +
"\n Hint: Missing Eager fetching configuration on the query that fetched the object of " +
"type " + entityName + "\n";
logDetectedNPlusOneQueries(errorMessage);
}
/**
* Update the select queries info per proxy method to be able to detect potential N+1 queries
* due to Eager Fetching on a field of a class
* <p>
* Checks:
* - Detect queries that would not fit the N+1 queries problem, non select queries, and remove the entry
* - Detect multiple calls to same proxy method and reset the entry to avoid false positive
* - Detect select queries that could be potential N+1 queries and increment the count
*/
private void updateSelectQueriesInfoPerProxyMethod(String sql) {
Optional<String> optionalProxyMethodName = getProxyMethodName();
if (!optionalProxyMethodName.isPresent()) {
return;
}
String proxyMethodName = optionalProxyMethodName.get();
boolean isSelectQuery = sql.toLowerCase().startsWith("select");
Map<String, SelectQueriesInfo> selectQueriesInfoPerProxyMethod = threadSelectQueriesInfoPerProxyMethod.get();
// The N+1 queries problem is only related to select queries
// So we remove the entry when detecting non select query for the proxy method
if (!isSelectQuery) {
selectQueriesInfoPerProxyMethod.remove(proxyMethodName);
threadSelectQueriesInfoPerProxyMethod.set(selectQueriesInfoPerProxyMethod);
return;
}
SelectQueriesInfo selectQueriesInfo = selectQueriesInfoPerProxyMethod.get(proxyMethodName);
// Handle several calls to the same proxy method by resetting the SelectQueriesInfo
// when the initial select query is detected
if (selectQueriesInfo == null || selectQueriesInfo.getInitialSelectQuery().equals(sql)) {
selectQueriesInfoPerProxyMethod.put(proxyMethodName, new SelectQueriesInfo(sql));
threadSelectQueriesInfoPerProxyMethod.set(selectQueriesInfoPerProxyMethod);
return;
}
selectQueriesInfoPerProxyMethod.put(proxyMethodName, selectQueriesInfo.incrementSelectQueriesCount());
threadSelectQueriesInfoPerProxyMethod.set(selectQueriesInfoPerProxyMethod);
}
/**
* Detect the N+1 queries caused by a missing lazy fetching configuration on an entity field
* <p>
* Detection checks that several select queries were generated from the same proxy method
*/
private void detectNPlusOneQueriesFromClassFieldEagerFetching(String entityName) {
Optional<String> optionalProxyMethodName = getProxyMethodName();
if (!optionalProxyMethodName.isPresent()) {
return;
}
String proxyMethodName = optionalProxyMethodName.get();
Map<String, SelectQueriesInfo> selectQueriesInfoPerProxyMethod = threadSelectQueriesInfoPerProxyMethod.get();
SelectQueriesInfo selectQueriesInfo = selectQueriesInfoPerProxyMethod.get(proxyMethodName);
if (selectQueriesInfo == null || selectQueriesInfo.getSelectQueriesCount() < 2) {
return;
}
// Reset the count to 1 to log a message once per additional query
selectQueriesInfoPerProxyMethod.put(proxyMethodName, selectQueriesInfo.resetSelectQueriesCount());
threadSelectQueriesInfoPerProxyMethod.set(selectQueriesInfoPerProxyMethod);
String errorMessage = "N+1 queries detected with eager fetching on the entity " + entityName;
// Find origin of the N+1 queries in client package
// by getting oldest occurrence of proxy method in stack elements
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
for (int i = stackTraceElements.length - 1; i >= 1; i--) {
if (stackTraceElements[i - 1].getClassName().indexOf(PROXY_METHOD_PREFIX) == 0) {
errorMessage += "\n at " + stackTraceElements[i].toString();
break;
}
}
errorMessage += "\n Hint: Missing Lazy fetching configuration on a field of type " + entityName + " of " +
"one of the entities fetched in the query\n";
logDetectedNPlusOneQueries(errorMessage);
}
/**
* Get the Proxy method name that was called first to know which query triggered the interceptor
*
* @return Optional of method name if found
*/
private Optional<String> getProxyMethodName() {
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
for (int i = stackTraceElements.length - 1; i >= 0; i--) {
StackTraceElement stackTraceElement = stackTraceElements[i];
if (stackTraceElement.getClassName().indexOf(PROXY_METHOD_PREFIX) == 0) {
return Optional.of(stackTraceElement.getClassName() + stackTraceElement.getMethodName());
}
}
return Optional.empty();
}
/**
* Log the detected N+1 queries error message or throw an exception depending on the configured error level
*
* @param errorMessage Error message for the N+1 queries detected
*/
private void logDetectedNPlusOneQueries(String errorMessage) {
switch (NPlusOneQueriesDetectionProperties.getErrorLevel()) {
case INFO:
LOGGER.info(errorMessage);
break;
case WARN:
LOGGER.warn(errorMessage);
break;
case ERROR:
LOGGER.error(errorMessage);
break;
case EXCEPTION:
throw new NPlusOneQueriesException(errorMessage);
default:
break;
}
}
}
class EmptySetSupplier<T> implements Supplier<Set<T>> {
public Set<T> get() {
return new HashSet<>();
}
}
class EmptyMapSupplier<T> implements Supplier<Map<String, T>> {
public Map<String, T> get() {
return new HashMap<>();
}
}
| java | MIT | c5eae0d811625d1a212b7c86e716b52c414d3e6f | 2026-01-05T02:41:28.211339Z | false |
yannbriancon/spring-hibernate-query-utils | https://github.com/yannbriancon/spring-hibernate-query-utils/blob/c5eae0d811625d1a212b7c86e716b52c414d3e6f/src/main/java/com/yannbriancon/interceptor/SelectQueriesInfo.java | src/main/java/com/yannbriancon/interceptor/SelectQueriesInfo.java | package com.yannbriancon.interceptor;
class SelectQueriesInfo {
private final String initialSelectQuery;
private Integer selectQueriesCount = 1;
public SelectQueriesInfo(String initialSelectQuery) {
this.initialSelectQuery = initialSelectQuery;
}
public String getInitialSelectQuery() {
return initialSelectQuery;
}
public Integer getSelectQueriesCount() {
return selectQueriesCount;
}
public void setSelectQueriesCount(Integer selectQueriesCount) {
this.selectQueriesCount = selectQueriesCount;
}
SelectQueriesInfo incrementSelectQueriesCount() {
selectQueriesCount = selectQueriesCount + 1;
return this;
}
SelectQueriesInfo resetSelectQueriesCount() {
selectQueriesCount = 1;
return this;
}
}
| java | MIT | c5eae0d811625d1a212b7c86e716b52c414d3e6f | 2026-01-05T02:41:28.211339Z | false |
yannbriancon/spring-hibernate-query-utils | https://github.com/yannbriancon/spring-hibernate-query-utils/blob/c5eae0d811625d1a212b7c86e716b52c414d3e6f/src/main/java/com/yannbriancon/config/NPlusOneQueriesDetectionProperties.java | src/main/java/com/yannbriancon/config/NPlusOneQueriesDetectionProperties.java | package com.yannbriancon.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.io.Serializable;
@ConfigurationProperties("spring-hibernate-query-utils.n-plus-one-queries-detection")
public class NPlusOneQueriesDetectionProperties implements Serializable {
public enum ErrorLevel {
INFO,
WARN,
ERROR,
EXCEPTION
}
/**
* Error level for the N+1 queries detection
*/
private ErrorLevel errorLevel = ErrorLevel.valueOf("ERROR");
/**
* Boolean allowing to enable or disable the N+1 queries detection
*/
private boolean enabled = true;
public ErrorLevel getErrorLevel() {
return errorLevel;
}
public void setErrorLevel(ErrorLevel errorLevel) {
this.errorLevel = errorLevel;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
| java | MIT | c5eae0d811625d1a212b7c86e716b52c414d3e6f | 2026-01-05T02:41:28.211339Z | false |
yannbriancon/spring-hibernate-query-utils | https://github.com/yannbriancon/spring-hibernate-query-utils/blob/c5eae0d811625d1a212b7c86e716b52c414d3e6f/src/main/java/com/yannbriancon/config/HibernatePropertiesConfig.java | src/main/java/com/yannbriancon/config/HibernatePropertiesConfig.java | package com.yannbriancon.config;
import com.yannbriancon.interceptor.HibernateQueryInterceptor;
import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import java.util.Map;
@Configuration
@ComponentScan(basePackages = {"com.yannbriancon"})
class HibernatePropertiesConfig implements HibernatePropertiesCustomizer {
private HibernateQueryInterceptor hibernateQueryInterceptor;
public HibernatePropertiesConfig(HibernateQueryInterceptor hibernateQueryInterceptor) {
this.hibernateQueryInterceptor = hibernateQueryInterceptor;
}
@Override
public void customize(Map<String, Object> hibernateProperties) {
hibernateProperties.put("hibernate.session_factory.interceptor", hibernateQueryInterceptor);
}
}
| java | MIT | c5eae0d811625d1a212b7c86e716b52c414d3e6f | 2026-01-05T02:41:28.211339Z | false |
ZuInnoTe/hadoopcryptoledger | https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/hiveudf/src/test/java/org/zuinnote/hadoop/namecoin/hive/udf/NamecoinUDFTest.java | hiveudf/src/test/java/org/zuinnote/hadoop/namecoin/hive/udf/NamecoinUDFTest.java | /**
* Copyright 2017 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.zuinnote.hadoop.namecoin.hive.udf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.List;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.junit.jupiter.api.Test;
import org.zuinnote.hadoop.bitcoin.format.common.BitcoinUtil;
import org.zuinnote.hadoop.namecoin.format.common.NamecoinUtil;
/**
* @author jornfranke
*
*/
public class NamecoinUDFTest {
@Test
public void extractNamecoinFieldFirstUpdate() throws HiveException {
String firstUpdateScript ="520A642F666C6173687570641460C7B068EDEA60281DAF424C38D8DAB87C96CF993D7B226970223A223134352E3234392E3130362E323238222C226D6170223A7B222A223A7B226970223A223134352E3234392E3130362E323238227D7D7D6D6D76A91451B4FC93AAB8CBDBD0AC9BC8EAF824643FC1E29B88AC";
byte[] firstUpdateScriptBytes = BitcoinUtil.convertHexStringToByteArray(firstUpdateScript);
NamecoinExtractFieldUDF nefu = new NamecoinExtractFieldUDF();
ObjectInspector[] arguments = new ObjectInspector[1];
arguments[0] = PrimitiveObjectInspectorFactory.writableBinaryObjectInspector;;
nefu.initialize(arguments);
GenericUDF.DeferredObject[] doa = new GenericUDF.DeferredObject[1];
doa[0]=new GenericUDF.DeferredJavaObject(new BytesWritable(firstUpdateScriptBytes));
List<Text> resultList = (List<Text>) nefu.evaluate(doa);
Text[] result=resultList.toArray(new Text[resultList.size()]);
assertNotNull( result,"Valid result obtained");
// test for domain name
assertEquals("d/flashupd",result[0].toString(),"Domain name of first update detected correctly");
// test for domain value
assertEquals("{\"ip\":\"145.249.106.228\",\"map\":{\"*\":{\"ip\":\"145.249.106.228\"}}}",result[1].toString(),"Domain value of first update detected correctly");
}
@Test
public void extractNamecoinFieldUpdate() throws HiveException {
String updateScript = "5309642F70616E656C6B612D7B226970223A22382E382E382E38222C226D6170223A7B222A223A7B226970223A22382E382E382E38227D7D7D6D7576A9148D804B079AC79AD0CA108A4E5B679DB591FF069B88AC";
byte[] updateScriptBytes = BitcoinUtil.convertHexStringToByteArray(updateScript);
NamecoinExtractFieldUDF nefu = new NamecoinExtractFieldUDF();
ObjectInspector[] arguments = new ObjectInspector[1];
arguments[0] = PrimitiveObjectInspectorFactory.writableBinaryObjectInspector;;
nefu.initialize(arguments);
GenericUDF.DeferredObject[] doa = new GenericUDF.DeferredObject[1];
doa[0]=new GenericUDF.DeferredJavaObject(new BytesWritable(updateScriptBytes));
List<Text> resultList = (List<Text>) nefu.evaluate(doa);
Text[] result=resultList.toArray(new Text[resultList.size()]);
assertNotNull( result,"Valid result obtained");
// test for domain name
assertEquals("d/panelka",result[0].toString(),"Domain name of first update detected correctly");
// test for domain value
assertEquals("{\"ip\":\"8.8.8.8\",\"map\":{\"*\":{\"ip\":\"8.8.8.8\"}}}",result[1].toString(),"Domain value of first update detected correctly");
}
@Test
public void getNameOperationUDF() {
NamecoinGetNameOperationUDF ngno = new NamecoinGetNameOperationUDF();
// new
String newScript = "511459C39A7CC5E0B91801294A272AD558B1F67A4E6D6D76A914DD900A6C1223698FC262E28C8A1D8D73B40B375188AC";
byte[] newScriptByte = BitcoinUtil.convertHexStringToByteArray(newScript);
String resultOpNew = ngno.evaluate(new BytesWritable(newScriptByte)).toString();
assertEquals(NamecoinUtil.STR_OP_NAME_NEW,resultOpNew,"Script containing new op detected correctly");
// firstupdate
String firstUpdateScript ="520A642F666C6173687570641460C7B068EDEA60281DAF424C38D8DAB87C96CF993D7B226970223A223134352E3234392E3130362E323238222C226D6170223A7B222A223A7B226970223A223134352E3234392E3130362E323238227D7D7D6D6D76A91451B4FC93AAB8CBDBD0AC9BC8EAF824643FC1E29B88AC";
byte[] firstUpdateScriptByte = BitcoinUtil.convertHexStringToByteArray(firstUpdateScript);
String resultOpFirstUpdate=ngno.evaluate(new BytesWritable(firstUpdateScriptByte)).toString();
assertEquals(NamecoinUtil.STR_OP_NAME_FIRSTUPDATE,resultOpFirstUpdate,"Script containing firstupdate op detected correctly");
// update
String updateScript = "5309642F70616E656C6B612D7B226970223A22382E382E382E38222C226D6170223A7B222A223A7B226970223A22382E382E382E38227D7D7D6D7576A9148D804B079AC79AD0CA108A4E5B679DB591FF069B88AC";
byte[] updateScriptByte = BitcoinUtil.convertHexStringToByteArray(updateScript);
String resultOpUpdate=ngno.evaluate(new BytesWritable(updateScriptByte)).toString();
assertEquals(NamecoinUtil.STR_OP_NAME_UDPATE,resultOpUpdate,"Script containing updateScript op detected correctly");
}
}
| java | Apache-2.0 | b2df90b216a6024b3179c3afaa6f2bcfc975784c | 2026-01-05T02:40:55.994732Z | false |
ZuInnoTe/hadoopcryptoledger | https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/hiveudf/src/test/java/org/zuinnote/hadoop/bitcoin/hive/udf/TestBitcoinTransaction.java | hiveudf/src/test/java/org/zuinnote/hadoop/bitcoin/hive/udf/TestBitcoinTransaction.java | /**
* Copyright 2016 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.zuinnote.hadoop.bitcoin.hive.udf;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.hadoop.io.*;
import java.util.List;
import java.util.ArrayList;
/** This is simply for testing the UDF **/
public class TestBitcoinTransaction implements Writable {
private ByteWritable flag;
private ByteWritable marker;
private IntWritable version;
private BytesWritable inCounter;
private BytesWritable outCounter;
private List<TestBitcoinTransactionInput> listOfInputs;
private List<TestBitcoinTransactionOutput> listOfOutputs;
private List<TestBitcoinScriptWitnessItem> listOfScriptWitnessItem;
private IntWritable lockTime;
public TestBitcoinTransaction() {
this.marker=new ByteWritable((byte) 0x01);
this.flag=new ByteWritable((byte) 0x00);
this.version=new IntWritable(0);
this.inCounter=new BytesWritable(new byte[0]);
this.outCounter=new BytesWritable(new byte[0]);
this.listOfInputs=new ArrayList<TestBitcoinTransactionInput>();
this.listOfOutputs=new ArrayList<TestBitcoinTransactionOutput>();
this.listOfScriptWitnessItem=new ArrayList<TestBitcoinScriptWitnessItem>();
this.lockTime=new IntWritable(0);
}
public TestBitcoinTransaction(int version, byte[] inCounter, List<TestBitcoinTransactionInput> listOfInputs, byte[] outCounter, List<TestBitcoinTransactionOutput> listOfOutputs, int lockTime) {
this.marker=new ByteWritable((byte) 0x01);
this.flag=new ByteWritable((byte) 0x00);
this.version=new IntWritable(version);
this.inCounter=new BytesWritable(inCounter);
this.listOfInputs=listOfInputs;
this.outCounter=new BytesWritable(outCounter);
this.listOfOutputs=listOfOutputs;
this.listOfScriptWitnessItem=new ArrayList<TestBitcoinScriptWitnessItem>();
this.lockTime=new IntWritable(lockTime);
}
public TestBitcoinTransaction(byte marker, byte flag, int version, byte[] inCounter, List<TestBitcoinTransactionInput> listOfInputs, byte[] outCounter, List<TestBitcoinTransactionOutput> listOfOutputs, List<TestBitcoinScriptWitnessItem> listOfScriptWitnessItem,int lockTime) {
this.marker=new ByteWritable(marker);
this.flag=new ByteWritable(flag);
this.version=new IntWritable(version);
this.inCounter=new BytesWritable(inCounter);
this.listOfInputs=listOfInputs;
this.outCounter=new BytesWritable(outCounter);
this.listOfOutputs=listOfOutputs;
this.listOfScriptWitnessItem=listOfScriptWitnessItem;
this.lockTime=new IntWritable(lockTime);
}
public ByteWritable getMarker() {
return this.marker;
}
public ByteWritable getFlag() {
return this.flag;
}
public IntWritable getVersion() {
return this.version;
}
public BytesWritable getInCounter() {
return this.inCounter;
}
public List<TestBitcoinTransactionInput> getListOfInputs() {
return this.listOfInputs;
}
public BytesWritable getOutCounter() {
return this.outCounter;
}
public List<TestBitcoinTransactionOutput> getListOfOutputs() {
return this.listOfOutputs;
}
public List<TestBitcoinScriptWitnessItem> getListOfScriptWitnessItem() {
return this.listOfScriptWitnessItem;
}
public IntWritable getLockTime() {
return this.lockTime;
}
public void set(TestBitcoinTransaction newTransaction) {
this.marker=newTransaction.getMarker();
this.flag=newTransaction.getFlag();
this.version=newTransaction.getVersion();
this.inCounter=newTransaction.getInCounter();
this.listOfInputs=newTransaction.getListOfInputs();
this.outCounter=newTransaction.getOutCounter();
this.listOfOutputs=newTransaction.getListOfOutputs();
this.listOfScriptWitnessItem=newTransaction.getListOfScriptWitnessItem();
this.lockTime=newTransaction.getLockTime();
}
/** Writable **/
@Override
public void write(DataOutput dataOutput) throws IOException {
throw new UnsupportedOperationException("write unsupported");
}
@Override
public void readFields(DataInput dataInput) throws IOException {
throw new UnsupportedOperationException("readFields unsupported");
}
}
| java | Apache-2.0 | b2df90b216a6024b3179c3afaa6f2bcfc975784c | 2026-01-05T02:40:55.994732Z | false |
ZuInnoTe/hadoopcryptoledger | https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/hiveudf/src/test/java/org/zuinnote/hadoop/bitcoin/hive/udf/BitcoinUDFTest.java | hiveudf/src/test/java/org/zuinnote/hadoop/bitcoin/hive/udf/BitcoinUDFTest.java | /**
* Copyright 2016 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.zuinnote.hadoop.bitcoin.hive.udf;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.junit.jupiter.api.Test;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.StringObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.ql.udf.generic.*;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.common.type.HiveDecimal;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.zuinnote.hadoop.bitcoin.format.common.*;
import org.zuinnote.hadoop.bitcoin.hive.datatypes.HiveBitcoinTransaction;
import org.zuinnote.hadoop.bitcoin.hive.datatypes.HiveBitcoinTransactionOutput;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class BitcoinUDFTest {
@Test
public void BitcoinScriptPaymentPatternAnalyzerUDFNotNull() {
BitcoinScriptPaymentPatternAnalyzerUDF bsppaUDF = new BitcoinScriptPaymentPatternAnalyzerUDF();
byte[] txOutScriptGenesis= new byte[]{(byte)0x41,(byte)0x04,(byte)0x67,(byte)0x8A,(byte)0xFD,(byte)0xB0,(byte)0xFE,(byte)0x55,(byte)0x48,(byte)0x27,(byte)0x19,(byte)0x67,(byte)0xF1,(byte)0xA6,(byte)0x71,(byte)0x30,(byte)0xB7,(byte)0x10,(byte)0x5C,(byte)0xD6,(byte)0xA8,(byte)0x28,(byte)0xE0,(byte)0x39,(byte)0x09,(byte)0xA6,(byte)0x79,(byte)0x62,(byte)0xE0,(byte)0xEA,(byte)0x1F,(byte)0x61,(byte)0xDE,(byte)0xB6,(byte)0x49,(byte)0xF6,(byte)0xBC,(byte)0x3F,(byte)0x4C,(byte)0xEF,(byte)0x38,(byte)0xC4,(byte)0xF3,(byte)0x55,(byte)0x04,(byte)0xE5,(byte)0x1E,(byte)0xC1,(byte)0x12,(byte)0xDE,(byte)0x5C,(byte)0x38,(byte)0x4D,(byte)0xF7,(byte)0xBA,(byte)0x0B,(byte)0x8D,(byte)0x57,(byte)0x8A,(byte)0x4C,(byte)0x70,(byte)0x2B,(byte)0x6B,(byte)0xF1,(byte)0x1D,(byte)0x5F,(byte)0xAC};
BytesWritable evalObj = new BytesWritable(txOutScriptGenesis);
String result = bsppaUDF.evaluate(evalObj).toString();
String comparatorText = "bitcoinpubkey_4104678AFDB0FE5548271967F1A67130B7105CD6A828E03909A67962E0EA1F61DEB649F6BC3F4CEF38C4F35504E51EC112DE5C384DF7BA0B8D578A4C702B6BF11D5F";
assertEquals(comparatorText,result,"TxOutScript from Genesis should be payment to a pubkey address");
}
@Test
public void BitcoinScriptPaymentPatternAnalyzerUDFPaymentDestinationNull() {
BitcoinScriptPaymentPatternAnalyzerUDF bsppaUDF = new BitcoinScriptPaymentPatternAnalyzerUDF();
byte[] txOutScriptTestNull= new byte[]{(byte)0x00};
BytesWritable evalObj = new BytesWritable(txOutScriptTestNull);
Text result = bsppaUDF.evaluate(evalObj);
assertNull( result,"Invalid payment script should be null for payment destination");
}
@Test
public void BitcoinScriptPaymentPatternAnalyzerUDFNull() {
BitcoinScriptPaymentPatternAnalyzerUDF bsppaUDF = new BitcoinScriptPaymentPatternAnalyzerUDF();
assertNull( bsppaUDF.evaluate(null),"Null argument to UDF returns null");
}
@Test
public void BitcoinTransactionHashUDFInvalidArguments() throws HiveException {
final BitcoinTransactionHashUDF bthUDF = new BitcoinTransactionHashUDF();
UDFArgumentLengthException exNull = assertThrows(UDFArgumentLengthException.class, ()->bthUDF.initialize(null), "Exception is thrown in case of null parameter");
UDFArgumentLengthException exLen = assertThrows(UDFArgumentLengthException.class, ()->bthUDF.initialize(new ObjectInspector[2]), "Exception is thrown in case of invalid length parameter");
StringObjectInspector[] testStringOI = new StringObjectInspector[1];
testStringOI[0]=PrimitiveObjectInspectorFactory.javaStringObjectInspector;
UDFArgumentException wrongType = assertThrows(UDFArgumentException.class, ()->bthUDF.initialize(testStringOI), "Exception is thrown in case of invalid type of parameter");
}
@Test
public void BitcoinTransactionHashUDFNull() throws HiveException {
BitcoinTransactionHashUDF bthUDF = new BitcoinTransactionHashUDF();
ObjectInspector[] arguments = new ObjectInspector[1];
arguments[0] = ObjectInspectorFactory.getReflectionObjectInspector(BitcoinBlock.class,ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
bthUDF.initialize(arguments);
assertNull(bthUDF.evaluate(null),"Null argument to UDF returns null");
}
@Test
public void BitcoinTransactionHashUDFWriteable() throws HiveException {
BitcoinTransactionHashUDF bthUDF = new BitcoinTransactionHashUDF();
ObjectInspector[] arguments = new ObjectInspector[1];
arguments[0] = ObjectInspectorFactory.getReflectionObjectInspector(HiveBitcoinTransaction.class,ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
bthUDF.initialize(arguments);
// create BitcoinTransaction
// reconstruct the transaction from the genesis block
int version=1;
byte[] inCounter = new byte[]{0x01};
byte[] previousTransactionHash = new byte[]{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
long previousTxOutIndex = 4294967295L;
byte[] txInScriptLength = new byte[]{(byte)0x4D};
byte[] txInScript= new byte[]{(byte)0x04,(byte)0xFF,(byte)0xFF,(byte)0x00,(byte)0x1D,(byte)0x01,(byte)0x04,(byte)0x45,(byte)0x54,(byte)0x68,(byte)0x65,(byte)0x20,(byte)0x54,(byte)0x69,(byte)0x6D,(byte)0x65,(byte)0x73,(byte)0x20,(byte)0x30,(byte)0x33,(byte)0x2F,(byte)0x4A,(byte)0x61,(byte)0x6E,(byte)0x2F,(byte)0x32,(byte)0x30,(byte)0x30,(byte)0x39,(byte)0x20,(byte)0x43,(byte)0x68,(byte)0x61,(byte)0x6E,(byte)0x63,(byte)0x65,(byte)0x6C,(byte)0x6C,(byte)0x6F,(byte)0x72,(byte)0x20,(byte)0x6F,(byte)0x6E,(byte)0x20,(byte)0x62,(byte)0x72,(byte)0x69,(byte)0x6E,(byte)0x6B,(byte)0x20,(byte)0x6F,(byte)0x66,(byte)0x20,(byte)0x73,(byte)0x65,(byte)0x63,(byte)0x6F,(byte)0x6E,(byte)0x64,(byte)0x20,(byte)0x62,(byte)0x61,(byte)0x69,(byte)0x6C,(byte)0x6F,(byte)0x75,(byte)0x74,(byte)0x20,(byte)0x66,(byte)0x6F,(byte)0x72,(byte)0x20,(byte)0x62,(byte)0x61,(byte)0x6E,(byte)0x6B,(byte)0x73};
long seqNo=4294967295L;
byte[] outCounter = new byte[]{0x01};
long value=5000000000L;
byte[] txOutScriptLength=new byte[]{(byte)0x43};
byte[] txOutScript=new byte[]{(byte)0x41,(byte)0x04,(byte)0x67,(byte)0x8A,(byte)0xFD,(byte)0xB0,(byte)0xFE,(byte)0x55,(byte)0x48,(byte)0x27,(byte)0x19,(byte)0x67,(byte)0xF1,(byte)0xA6,(byte)0x71,(byte)0x30,(byte)0xB7,(byte)0x10,(byte)0x5C,(byte)0xD6,(byte)0xA8,(byte)0x28,(byte)0xE0,(byte)0x39,(byte)0x09,(byte)0xA6,(byte)0x79,(byte)0x62,(byte)0xE0,(byte)0xEA,(byte)0x1F,(byte)0x61,(byte)0xDE,(byte)0xB6,(byte)0x49,(byte)0xF6,(byte)0xBC,(byte)0x3F,(byte)0x4C,(byte)0xEF,(byte)0x38,(byte)0xC4,(byte)0xF3,(byte)0x55,(byte)0x04,(byte)0xE5,(byte)0x1E,(byte)0xC1,(byte)0x12,(byte)0xDE,(byte)0x5C,(byte)0x38,(byte)0x4D,(byte)0xF7,(byte)0xBA,(byte)0x0B,(byte)0x8D,(byte)0x57,(byte)0x8A,(byte)0x4C,(byte)0x70,(byte)0x2B,(byte)0x6B,(byte)0xF1,(byte)0x1D,(byte)0x5F,(byte)0xAC};
int lockTime = 0;
List<BitcoinTransactionInput> genesisInput = new ArrayList<BitcoinTransactionInput>(1);
genesisInput.add(new BitcoinTransactionInput(previousTransactionHash,previousTxOutIndex,txInScriptLength,txInScript,seqNo));
List<HiveBitcoinTransactionOutput> genesisOutput = new ArrayList<HiveBitcoinTransactionOutput>(1);
genesisOutput.add(new HiveBitcoinTransactionOutput(HiveDecimal.create(BigInteger.valueOf(value)),txOutScriptLength,txOutScript));
HiveBitcoinTransaction genesisTransaction = new HiveBitcoinTransaction(version,inCounter,genesisInput,outCounter,genesisOutput,lockTime);
byte[] expectedHash = BitcoinUtil.reverseByteArray(new byte[]{(byte)0x4A,(byte)0x5E,(byte)0x1E,(byte)0x4B,(byte)0xAA,(byte)0xB8,(byte)0x9F,(byte)0x3A,(byte)0x32,(byte)0x51,(byte)0x8A,(byte)0x88,(byte)0xC3,(byte)0x1B,(byte)0xC8,(byte)0x7F,(byte)0x61,(byte)0x8F,(byte)0x76,(byte)0x67,(byte)0x3E,(byte)0x2C,(byte)0xC7,(byte)0x7A,(byte)0xB2,(byte)0x12,(byte)0x7B,(byte)0x7A,(byte)0xFD,(byte)0xED,(byte)0xA3,(byte)0x3B});
GenericUDF.DeferredObject[] doa = new GenericUDF.DeferredObject[1];
doa[0]=new GenericUDF.DeferredJavaObject(genesisTransaction);
BytesWritable bw = (BytesWritable) bthUDF.evaluate(doa);
assertArrayEquals( expectedHash,bw.copyBytes(),"BitcoinTransaction object genesis transaction hash from UDF");
}
@Test
public void BitcoinTransactionHashUDFObjectInspector() throws HiveException {
BitcoinTransactionHashUDF bthUDF = new BitcoinTransactionHashUDF();
ObjectInspector[] arguments = new ObjectInspector[1];
arguments[0] = ObjectInspectorFactory.getReflectionObjectInspector(TestBitcoinTransaction.class,ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
bthUDF.initialize(arguments);
// create BitcoinTransaction
// reconstruct the transaction from the genesis block
int version=1;
byte[] inCounter = new byte[]{0x01};
byte[] previousTransactionHash = new byte[]{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
long previousTxOutIndex = 4294967295L;
byte[] txInScriptLength = new byte[]{(byte)0x4D};
byte[] txInScript= new byte[]{(byte)0x04,(byte)0xFF,(byte)0xFF,(byte)0x00,(byte)0x1D,(byte)0x01,(byte)0x04,(byte)0x45,(byte)0x54,(byte)0x68,(byte)0x65,(byte)0x20,(byte)0x54,(byte)0x69,(byte)0x6D,(byte)0x65,(byte)0x73,(byte)0x20,(byte)0x30,(byte)0x33,(byte)0x2F,(byte)0x4A,(byte)0x61,(byte)0x6E,(byte)0x2F,(byte)0x32,(byte)0x30,(byte)0x30,(byte)0x39,(byte)0x20,(byte)0x43,(byte)0x68,(byte)0x61,(byte)0x6E,(byte)0x63,(byte)0x65,(byte)0x6C,(byte)0x6C,(byte)0x6F,(byte)0x72,(byte)0x20,(byte)0x6F,(byte)0x6E,(byte)0x20,(byte)0x62,(byte)0x72,(byte)0x69,(byte)0x6E,(byte)0x6B,(byte)0x20,(byte)0x6F,(byte)0x66,(byte)0x20,(byte)0x73,(byte)0x65,(byte)0x63,(byte)0x6F,(byte)0x6E,(byte)0x64,(byte)0x20,(byte)0x62,(byte)0x61,(byte)0x69,(byte)0x6C,(byte)0x6F,(byte)0x75,(byte)0x74,(byte)0x20,(byte)0x66,(byte)0x6F,(byte)0x72,(byte)0x20,(byte)0x62,(byte)0x61,(byte)0x6E,(byte)0x6B,(byte)0x73};
long seqNo=4294967295L;
byte[] outCounter = new byte[]{0x01};
long value=5000000000L;
byte[] txOutScriptLength=new byte[]{(byte)0x43};
byte[] txOutScript=new byte[]{(byte)0x41,(byte)0x04,(byte)0x67,(byte)0x8A,(byte)0xFD,(byte)0xB0,(byte)0xFE,(byte)0x55,(byte)0x48,(byte)0x27,(byte)0x19,(byte)0x67,(byte)0xF1,(byte)0xA6,(byte)0x71,(byte)0x30,(byte)0xB7,(byte)0x10,(byte)0x5C,(byte)0xD6,(byte)0xA8,(byte)0x28,(byte)0xE0,(byte)0x39,(byte)0x09,(byte)0xA6,(byte)0x79,(byte)0x62,(byte)0xE0,(byte)0xEA,(byte)0x1F,(byte)0x61,(byte)0xDE,(byte)0xB6,(byte)0x49,(byte)0xF6,(byte)0xBC,(byte)0x3F,(byte)0x4C,(byte)0xEF,(byte)0x38,(byte)0xC4,(byte)0xF3,(byte)0x55,(byte)0x04,(byte)0xE5,(byte)0x1E,(byte)0xC1,(byte)0x12,(byte)0xDE,(byte)0x5C,(byte)0x38,(byte)0x4D,(byte)0xF7,(byte)0xBA,(byte)0x0B,(byte)0x8D,(byte)0x57,(byte)0x8A,(byte)0x4C,(byte)0x70,(byte)0x2B,(byte)0x6B,(byte)0xF1,(byte)0x1D,(byte)0x5F,(byte)0xAC};
int lockTime = 0;
List<TestBitcoinTransactionInput> genesisInput = new ArrayList<TestBitcoinTransactionInput>(1);
genesisInput.add(new TestBitcoinTransactionInput(previousTransactionHash,previousTxOutIndex,txInScriptLength,txInScript,seqNo));
List<TestBitcoinTransactionOutput> genesisOutput = new ArrayList<TestBitcoinTransactionOutput>(1);
genesisOutput.add(new TestBitcoinTransactionOutput(HiveDecimal.create(BigInteger.valueOf(value)),txOutScriptLength,txOutScript));
TestBitcoinTransaction genesisTransaction = new TestBitcoinTransaction(version,inCounter,genesisInput,outCounter,genesisOutput,lockTime);
byte[] expectedHash = BitcoinUtil.reverseByteArray(new byte[]{(byte)0x4A,(byte)0x5E,(byte)0x1E,(byte)0x4B,(byte)0xAA,(byte)0xB8,(byte)0x9F,(byte)0x3A,(byte)0x32,(byte)0x51,(byte)0x8A,(byte)0x88,(byte)0xC3,(byte)0x1B,(byte)0xC8,(byte)0x7F,(byte)0x61,(byte)0x8F,(byte)0x76,(byte)0x67,(byte)0x3E,(byte)0x2C,(byte)0xC7,(byte)0x7A,(byte)0xB2,(byte)0x12,(byte)0x7B,(byte)0x7A,(byte)0xFD,(byte)0xED,(byte)0xA3,(byte)0x3B});
GenericUDF.DeferredObject[] doa = new GenericUDF.DeferredObject[1];
doa[0]=new GenericUDF.DeferredJavaObject(genesisTransaction);
BytesWritable bw = (BytesWritable) bthUDF.evaluate(doa);
assertArrayEquals( expectedHash,bw.copyBytes(),"BitcoinTransaction struct transaction hash from UDF");
}
@Test
public void BitcoinTransactionHashSegwitUDFInvalidArguments() throws HiveException {
BitcoinTransactionHashSegwitUDF bthUDF = new BitcoinTransactionHashSegwitUDF();
UDFArgumentLengthException exNull = assertThrows(UDFArgumentLengthException.class, ()->bthUDF.initialize(null), "Exception is thrown in case of null parameter");
UDFArgumentLengthException exLen = assertThrows(UDFArgumentLengthException.class, ()->bthUDF.initialize(new ObjectInspector[2]), "Exception is thrown in case of invalid length parameter");
StringObjectInspector[] testStringOI = new StringObjectInspector[1];
testStringOI[0]=PrimitiveObjectInspectorFactory.javaStringObjectInspector;
UDFArgumentException wrongType = assertThrows(UDFArgumentException.class, ()->bthUDF.initialize(testStringOI), "Exception is thrown in case of invalid type of parameter");
}
@Test
public void BitcoinTransactionHashSegwitUDFNull() throws HiveException {
BitcoinTransactionHashSegwitUDF bthUDF = new BitcoinTransactionHashSegwitUDF();
ObjectInspector[] arguments = new ObjectInspector[1];
arguments[0] = ObjectInspectorFactory.getReflectionObjectInspector(BitcoinBlock.class,ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
bthUDF.initialize(arguments);
assertNull(bthUDF.evaluate(null),"Null argument to UDF returns null");
}
@Test
public void BitcoinTransactionHashSegwitUDFWriteable() throws HiveException {
BitcoinTransactionHashSegwitUDF bthUDF = new BitcoinTransactionHashSegwitUDF();
ObjectInspector[] arguments = new ObjectInspector[1];
arguments[0] = ObjectInspectorFactory.getReflectionObjectInspector(HiveBitcoinTransaction.class,ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
bthUDF.initialize(arguments);
// create BitcoinTransaction
int version=2;
byte marker=0x00;
byte flag=0x01;
byte[] inCounter = new byte[]{0x01};
byte[] previousTransactionHash = new byte[]{(byte)0x07,(byte)0x21,(byte)0x35,(byte)0x23,(byte)0x6D,(byte)0x2E,(byte)0xBC,(byte)0x78,(byte)0xB6,(byte)0xAC,(byte)0xE1,(byte)0x88,(byte)0x97,(byte)0x03,(byte)0xB1,(byte)0x84,(byte)0x85,(byte)0x52,(byte)0x87,(byte)0x12,(byte)0xBD,(byte)0x70,(byte)0xE0,(byte)0x7F,(byte)0x4A,(byte)0x90,(byte)0x11,(byte)0x40,(byte)0xDE,(byte)0x38,(byte)0xA2,(byte)0xE8};
long previousTxOutIndex = 1L;
byte[] txInScriptLength = new byte[]{(byte)0x17};
byte[] txInScript= new byte[]{(byte)0x16,(byte)0x00,(byte)0x14,(byte)0x4D,(byte)0x4D,(byte)0x83,(byte)0xED,(byte)0x5F,(byte)0x10,(byte)0x7B,(byte)0x8D,(byte)0x45,(byte)0x1E,(byte)0x59,(byte)0xA0,(byte)0x43,(byte)0x1A,(byte)0x13,(byte)0x92,(byte)0x79,(byte)0x6B,(byte)0x26,(byte)0x04};
long seqNo=4294967295L;
byte[] outCounter = new byte[]{0x02};
long value_1=1009051983L;
byte[] txOutScriptLength_1=new byte[]{(byte)0x17};
byte[] txOutScript_1=new byte[]{(byte)0xA9,(byte)0x14,(byte)0xF0,(byte)0x50,(byte)0xC5,(byte)0x91,(byte)0xEA,(byte)0x98,(byte)0x26,(byte)0x73,(byte)0xCC,(byte)0xED,(byte)0xF5,(byte)0x21,(byte)0x13,(byte)0x65,(byte)0x7B,(byte)0x67,(byte)0x83,(byte)0x03,(byte)0xE6,(byte)0xA1,(byte)0x87};
long value_2=59801109L;
byte[] txOutScriptLength_2=new byte[]{(byte)0x19};
byte[] txOutScript_2=new byte[]{(byte)0x76,(byte)0xA9,(byte)0x14,(byte)0xFB,(byte)0x2E,(byte)0x13,(byte)0x83,(byte)0x5E,(byte)0x39,(byte)0x88,(byte)0xC7,(byte)0x8F,(byte)0x76,(byte)0x0D,(byte)0x4A,(byte)0xC8,(byte)0x1E,(byte)0x04,(byte)0xEA,(byte)0xF1,(byte)0x94,(byte)0xEA,(byte)0x92,(byte)0x88,(byte)0xAC};
// there is only one input so we have only one list of stack items containing 2 items in this case
byte[] noOfStackItems = new byte[]{0x02};
byte[] segwitnessLength_1=new byte[]{(byte)0x48};
byte[] segwitnessScript_1 = new byte[]{(byte)0x30,(byte)0x45,(byte)0x02,(byte)0x21,(byte)0x00,(byte)0xBB,(byte)0x5F,(byte)0x78,(byte)0xE8,(byte)0xA1,(byte)0xBA,(byte)0x5E,(byte)0x14,(byte)0x26,(byte)0x1B,(byte)0x0A,(byte)0xD3,(byte)0x95,(byte)0x56,(byte)0xAF,(byte)0x9B,(byte)0x21,(byte)0xD9,(byte)0x1F,(byte)0x67,(byte)0x5D,(byte)0x38,(byte)0xC8,(byte)0xCD,(byte)0xAD,(byte)0x7E,(byte)0x7F,(byte)0x5D,(byte)0x21,(byte)0x00,(byte)0x4A,(byte)0xBD,(byte)0x02,(byte)0x20,(byte)0x4C,(byte)0x1E,(byte)0xAC,(byte)0xF1,(byte)0xF9,(byte)0xAC,(byte)0x1D,(byte)0xCC,(byte)0x61,(byte)0x63,(byte)0xF2,(byte)0x07,(byte)0xFC,(byte)0xBC,(byte)0x49,(byte)0x8B,(byte)0x32,(byte)0x4C,(byte)0xBE,(byte)0xF5,(byte)0x7F,(byte)0x83,(byte)0x9F,(byte)0xA2,(byte)0xC2,(byte)0x55,(byte)0x57,(byte)0x4B,(byte)0x2F,(byte)0x37,(byte)0x19,(byte)0xBC,(byte)0x01};
byte[] segwitnessLength_2=new byte[]{(byte)0x21};
byte[] segwitnessScript_2 = new byte[]{(byte)0x03,(byte)0xC5,(byte)0x3F,(byte)0xEA,(byte)0x9A,(byte)0xE5,(byte)0x61,(byte)0xB6,(byte)0x05,(byte)0x74,(byte)0xB2,(byte)0xD5,(byte)0x10,(byte)0x27,(byte)0x3F,(byte)0x7C,(byte)0x51,(byte)0x60,(byte)0x69,(byte)0x7E,(byte)0xB4,(byte)0x7B,(byte)0x48,(byte)0x8E,(byte)0x95,(byte)0xAD,(byte)0x62,(byte)0x91,(byte)0xBB,(byte)0xCB,(byte)0x5E,(byte)0x43,(byte)0xA2};
int lockTime = 0;
List<BitcoinTransactionInput> randomScriptWitnessInput = new ArrayList<BitcoinTransactionInput>(1);
randomScriptWitnessInput.add(new BitcoinTransactionInput(previousTransactionHash,previousTxOutIndex,txInScriptLength,txInScript,seqNo));
List<HiveBitcoinTransactionOutput> randomScriptWitnessOutput = new ArrayList<HiveBitcoinTransactionOutput>(2);
randomScriptWitnessOutput.add(new HiveBitcoinTransactionOutput(HiveDecimal.create(BigInteger.valueOf(value_1)),txOutScriptLength_1,txOutScript_1));
randomScriptWitnessOutput.add(new HiveBitcoinTransactionOutput(HiveDecimal.create(BigInteger.valueOf(value_2)),txOutScriptLength_2,txOutScript_2));
List<BitcoinScriptWitnessItem> randomScriptWitnessSWI = new ArrayList<BitcoinScriptWitnessItem>(1);
List<BitcoinScriptWitness> randomScriptWitnessSW = new ArrayList<BitcoinScriptWitness>(2);
randomScriptWitnessSW.add(new BitcoinScriptWitness(segwitnessLength_1,segwitnessScript_1));
randomScriptWitnessSW.add(new BitcoinScriptWitness(segwitnessLength_2,segwitnessScript_2));
randomScriptWitnessSWI.add(new BitcoinScriptWitnessItem(noOfStackItems,randomScriptWitnessSW));
HiveBitcoinTransaction randomScriptWitnessTransaction = new HiveBitcoinTransaction(marker,flag,version,inCounter,randomScriptWitnessInput,outCounter,randomScriptWitnessOutput,randomScriptWitnessSWI,lockTime);
//74700E2CE030013E2E10FCFD06DF99C7826E41C725CA5C467660BFA4874F65BF
byte[] expectedHashSegwit = BitcoinUtil.reverseByteArray(new byte[]{(byte)0x74,(byte)0x70,(byte)0x0E,(byte)0x2C,(byte)0xE0,(byte)0x30,(byte)0x01,(byte)0x3E,(byte)0x2E,(byte)0x10,(byte)0xFC,(byte)0xFD,(byte)0x06,(byte)0xDF,(byte)0x99,(byte)0xC7,(byte)0x82,(byte)0x6E,(byte)0x41,(byte)0xC7,(byte)0x25,(byte)0xCA,(byte)0x5C,(byte)0x46,(byte)0x76,(byte)0x60,(byte)0xBF,(byte)0xA4,(byte)0x87,(byte)0x4F,(byte)0x65,(byte)0xBF});
GenericUDF.DeferredObject[] doa = new GenericUDF.DeferredObject[1];
doa[0]=new GenericUDF.DeferredJavaObject(randomScriptWitnessTransaction);
BytesWritable bw = (BytesWritable) bthUDF.evaluate(doa);
assertArrayEquals( expectedHashSegwit,bw.copyBytes(),"BitcoinTransaction object random scriptwitness transaction hash segwit from UDF");
}
@Test
public void BitcoinTransactionHashSegwitUDFObjectInspector() throws HiveException {
BitcoinTransactionHashSegwitUDF bthUDF = new BitcoinTransactionHashSegwitUDF();
ObjectInspector[] arguments = new ObjectInspector[1];
arguments[0] = ObjectInspectorFactory.getReflectionObjectInspector(TestBitcoinTransaction.class,ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
bthUDF.initialize(arguments);
// create Segwit transaction
int version=2;
byte marker=0x00;
byte flag=0x01;
byte[] inCounter = new byte[]{0x01};
byte[] previousTransactionHash = new byte[]{(byte)0x07,(byte)0x21,(byte)0x35,(byte)0x23,(byte)0x6D,(byte)0x2E,(byte)0xBC,(byte)0x78,(byte)0xB6,(byte)0xAC,(byte)0xE1,(byte)0x88,(byte)0x97,(byte)0x03,(byte)0xB1,(byte)0x84,(byte)0x85,(byte)0x52,(byte)0x87,(byte)0x12,(byte)0xBD,(byte)0x70,(byte)0xE0,(byte)0x7F,(byte)0x4A,(byte)0x90,(byte)0x11,(byte)0x40,(byte)0xDE,(byte)0x38,(byte)0xA2,(byte)0xE8};
long previousTxOutIndex = 1L;
byte[] txInScriptLength = new byte[]{(byte)0x17};
byte[] txInScript= new byte[]{(byte)0x16,(byte)0x00,(byte)0x14,(byte)0x4D,(byte)0x4D,(byte)0x83,(byte)0xED,(byte)0x5F,(byte)0x10,(byte)0x7B,(byte)0x8D,(byte)0x45,(byte)0x1E,(byte)0x59,(byte)0xA0,(byte)0x43,(byte)0x1A,(byte)0x13,(byte)0x92,(byte)0x79,(byte)0x6B,(byte)0x26,(byte)0x04};
long seqNo=4294967295L;
byte[] outCounter = new byte[]{0x02};
long value_1=1009051983L;
byte[] txOutScriptLength_1=new byte[]{(byte)0x17};
byte[] txOutScript_1=new byte[]{(byte)0xA9,(byte)0x14,(byte)0xF0,(byte)0x50,(byte)0xC5,(byte)0x91,(byte)0xEA,(byte)0x98,(byte)0x26,(byte)0x73,(byte)0xCC,(byte)0xED,(byte)0xF5,(byte)0x21,(byte)0x13,(byte)0x65,(byte)0x7B,(byte)0x67,(byte)0x83,(byte)0x03,(byte)0xE6,(byte)0xA1,(byte)0x87};
long value_2=59801109L;
byte[] txOutScriptLength_2=new byte[]{(byte)0x19};
byte[] txOutScript_2=new byte[]{(byte)0x76,(byte)0xA9,(byte)0x14,(byte)0xFB,(byte)0x2E,(byte)0x13,(byte)0x83,(byte)0x5E,(byte)0x39,(byte)0x88,(byte)0xC7,(byte)0x8F,(byte)0x76,(byte)0x0D,(byte)0x4A,(byte)0xC8,(byte)0x1E,(byte)0x04,(byte)0xEA,(byte)0xF1,(byte)0x94,(byte)0xEA,(byte)0x92,(byte)0x88,(byte)0xAC};
// there is only one input so we have only one list of stack items containing 2 items in this case
byte[] noOfStackItems = new byte[]{0x02};
byte[] segwitnessLength_1=new byte[]{(byte)0x48};
byte[] segwitnessScript_1 = new byte[]{(byte)0x30,(byte)0x45,(byte)0x02,(byte)0x21,(byte)0x00,(byte)0xBB,(byte)0x5F,(byte)0x78,(byte)0xE8,(byte)0xA1,(byte)0xBA,(byte)0x5E,(byte)0x14,(byte)0x26,(byte)0x1B,(byte)0x0A,(byte)0xD3,(byte)0x95,(byte)0x56,(byte)0xAF,(byte)0x9B,(byte)0x21,(byte)0xD9,(byte)0x1F,(byte)0x67,(byte)0x5D,(byte)0x38,(byte)0xC8,(byte)0xCD,(byte)0xAD,(byte)0x7E,(byte)0x7F,(byte)0x5D,(byte)0x21,(byte)0x00,(byte)0x4A,(byte)0xBD,(byte)0x02,(byte)0x20,(byte)0x4C,(byte)0x1E,(byte)0xAC,(byte)0xF1,(byte)0xF9,(byte)0xAC,(byte)0x1D,(byte)0xCC,(byte)0x61,(byte)0x63,(byte)0xF2,(byte)0x07,(byte)0xFC,(byte)0xBC,(byte)0x49,(byte)0x8B,(byte)0x32,(byte)0x4C,(byte)0xBE,(byte)0xF5,(byte)0x7F,(byte)0x83,(byte)0x9F,(byte)0xA2,(byte)0xC2,(byte)0x55,(byte)0x57,(byte)0x4B,(byte)0x2F,(byte)0x37,(byte)0x19,(byte)0xBC,(byte)0x01};
byte[] segwitnessLength_2=new byte[]{(byte)0x21};
byte[] segwitnessScript_2 = new byte[]{(byte)0x03,(byte)0xC5,(byte)0x3F,(byte)0xEA,(byte)0x9A,(byte)0xE5,(byte)0x61,(byte)0xB6,(byte)0x05,(byte)0x74,(byte)0xB2,(byte)0xD5,(byte)0x10,(byte)0x27,(byte)0x3F,(byte)0x7C,(byte)0x51,(byte)0x60,(byte)0x69,(byte)0x7E,(byte)0xB4,(byte)0x7B,(byte)0x48,(byte)0x8E,(byte)0x95,(byte)0xAD,(byte)0x62,(byte)0x91,(byte)0xBB,(byte)0xCB,(byte)0x5E,(byte)0x43,(byte)0xA2};
int lockTime = 0;
List<TestBitcoinTransactionInput> randomScriptWitnessInput = new ArrayList<TestBitcoinTransactionInput>(1);
randomScriptWitnessInput.add(new TestBitcoinTransactionInput(previousTransactionHash,previousTxOutIndex,txInScriptLength,txInScript,seqNo));
List<TestBitcoinTransactionOutput> randomScriptWitnessOutput = new ArrayList<TestBitcoinTransactionOutput>(2);
randomScriptWitnessOutput.add(new TestBitcoinTransactionOutput(HiveDecimal.create(BigInteger.valueOf(value_1)),txOutScriptLength_1,txOutScript_1));
randomScriptWitnessOutput.add(new TestBitcoinTransactionOutput(HiveDecimal.create(BigInteger.valueOf(value_2)),txOutScriptLength_2,txOutScript_2));
List<TestBitcoinScriptWitnessItem> randomScriptWitnessSWI = new ArrayList<TestBitcoinScriptWitnessItem>(1);
List<TestBitcoinScriptWitness> randomScriptWitnessSW = new ArrayList<TestBitcoinScriptWitness>(2);
randomScriptWitnessSW.add(new TestBitcoinScriptWitness(segwitnessLength_1,segwitnessScript_1));
randomScriptWitnessSW.add(new TestBitcoinScriptWitness(segwitnessLength_2,segwitnessScript_2));
randomScriptWitnessSWI.add(new TestBitcoinScriptWitnessItem(noOfStackItems,randomScriptWitnessSW));
TestBitcoinTransaction randomScriptWitnessTransaction = new TestBitcoinTransaction(marker,flag,version,inCounter,randomScriptWitnessInput,outCounter,randomScriptWitnessOutput,randomScriptWitnessSWI,lockTime);
//74700E2CE030013E2E10FCFD06DF99C7826E41C725CA5C467660BFA4874F65BF
byte[] expectedHashSegwit = BitcoinUtil.reverseByteArray(new byte[]{(byte)0x74,(byte)0x70,(byte)0x0E,(byte)0x2C,(byte)0xE0,(byte)0x30,(byte)0x01,(byte)0x3E,(byte)0x2E,(byte)0x10,(byte)0xFC,(byte)0xFD,(byte)0x06,(byte)0xDF,(byte)0x99,(byte)0xC7,(byte)0x82,(byte)0x6E,(byte)0x41,(byte)0xC7,(byte)0x25,(byte)0xCA,(byte)0x5C,(byte)0x46,(byte)0x76,(byte)0x60,(byte)0xBF,(byte)0xA4,(byte)0x87,(byte)0x4F,(byte)0x65,(byte)0xBF});
GenericUDF.DeferredObject[] doa = new GenericUDF.DeferredObject[1];
doa[0]=new GenericUDF.DeferredJavaObject(randomScriptWitnessTransaction);
BytesWritable bw = (BytesWritable) bthUDF.evaluate(doa);
assertArrayEquals( expectedHashSegwit,bw.copyBytes(),"BitcoinTransaction struct transaction hash segwit from UDF");
}
}
| java | Apache-2.0 | b2df90b216a6024b3179c3afaa6f2bcfc975784c | 2026-01-05T02:40:55.994732Z | false |
ZuInnoTe/hadoopcryptoledger | https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/hiveudf/src/test/java/org/zuinnote/hadoop/bitcoin/hive/udf/TestBitcoinScriptWitnessItem.java | hiveudf/src/test/java/org/zuinnote/hadoop/bitcoin/hive/udf/TestBitcoinScriptWitnessItem.java | /**
* Copyright 2017 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.zuinnote.hadoop.bitcoin.hive.udf;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.List;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Writable;
public class TestBitcoinScriptWitnessItem implements Writable {
private BytesWritable stackItemCounter;
private List<TestBitcoinScriptWitness> scriptWitnessList;
public TestBitcoinScriptWitnessItem(byte[] stackItemCounter, List<TestBitcoinScriptWitness> scriptWitnessList) {
this.stackItemCounter=new BytesWritable(stackItemCounter);
this.scriptWitnessList=scriptWitnessList;
}
public BytesWritable getStackItemCounter() {
return this.stackItemCounter;
}
public List<TestBitcoinScriptWitness> getScriptWitnessList() {
return this.scriptWitnessList;
}
@Override
public void write(DataOutput out) throws IOException {
throw new UnsupportedOperationException("write unsupported");
}
@Override
public void readFields(DataInput in) throws IOException {
throw new UnsupportedOperationException("read unsupported");
}
}
| java | Apache-2.0 | b2df90b216a6024b3179c3afaa6f2bcfc975784c | 2026-01-05T02:40:55.994732Z | false |
ZuInnoTe/hadoopcryptoledger | https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/hiveudf/src/test/java/org/zuinnote/hadoop/bitcoin/hive/udf/TestBitcoinScriptWitness.java | hiveudf/src/test/java/org/zuinnote/hadoop/bitcoin/hive/udf/TestBitcoinScriptWitness.java | /**
* Copyright 2017 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.zuinnote.hadoop.bitcoin.hive.udf;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Writable;
public class TestBitcoinScriptWitness implements Writable {
private BytesWritable witnessScriptLength;
private BytesWritable witnessScript;
public TestBitcoinScriptWitness(byte[] witnessScriptLength,byte[] witnessScript) {
this.witnessScriptLength=new BytesWritable(witnessScriptLength);
this.witnessScript=new BytesWritable(witnessScript);
}
public BytesWritable getWitnessScriptLength() {
return this.witnessScriptLength;
}
public BytesWritable getWitnessScript() {
return this.witnessScript;
}
@Override
public void write(DataOutput out) throws IOException {
throw new UnsupportedOperationException("write unsupported");
}
@Override
public void readFields(DataInput in) throws IOException {
throw new UnsupportedOperationException("read unsupported");
}
}
| java | Apache-2.0 | b2df90b216a6024b3179c3afaa6f2bcfc975784c | 2026-01-05T02:40:55.994732Z | false |
ZuInnoTe/hadoopcryptoledger | https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/hiveudf/src/test/java/org/zuinnote/hadoop/bitcoin/hive/udf/TestBitcoinTransactionOutput.java | hiveudf/src/test/java/org/zuinnote/hadoop/bitcoin/hive/udf/TestBitcoinTransactionOutput.java | /**
* Copyright 2016 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.zuinnote.hadoop.bitcoin.hive.udf;
import java.io.Serializable;
import java.math.BigInteger;
import org.apache.hadoop.hive.common.type.HiveDecimal;
import org.apache.hadoop.io.*;
public class TestBitcoinTransactionOutput implements Serializable {
/**
*
*/
private static final long serialVersionUID = 2854570631540937753L;
private HiveDecimal value;
private BytesWritable txOutScriptLength;
private BytesWritable txOutScript;
public TestBitcoinTransactionOutput(HiveDecimal value, byte[] txOutScriptLength, byte[] txOutScript) {
this.value= value;
this.txOutScriptLength=new BytesWritable(txOutScriptLength);
this.txOutScript=new BytesWritable(txOutScript);
}
public HiveDecimal getValue() {
return this.value;
}
public BytesWritable getTxOutScriptLength() {
return this.txOutScriptLength;
}
public BytesWritable getTxOutScript() {
return this.txOutScript;
}
}
| java | Apache-2.0 | b2df90b216a6024b3179c3afaa6f2bcfc975784c | 2026-01-05T02:40:55.994732Z | false |
ZuInnoTe/hadoopcryptoledger | https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/hiveudf/src/test/java/org/zuinnote/hadoop/bitcoin/hive/udf/TestBitcoinTransactionInput.java | hiveudf/src/test/java/org/zuinnote/hadoop/bitcoin/hive/udf/TestBitcoinTransactionInput.java | /**
* Copyright 2016 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.zuinnote.hadoop.bitcoin.hive.udf;
import java.io.Serializable;
import org.apache.hadoop.io.*;
public class TestBitcoinTransactionInput implements Serializable {
/**
*
*/
private static final long serialVersionUID = 283893453189295979L;
private BytesWritable prevTransactionHash;
private LongWritable previousTxOutIndex;
private BytesWritable txInScriptLength;
private BytesWritable txInScript;
private LongWritable seqNo;
public TestBitcoinTransactionInput(byte[] prevTransactionHash, long previousTxOutIndex, byte[] txInScriptLength, byte[] txInScript, long seqNo) {
this.prevTransactionHash=new BytesWritable(prevTransactionHash);
this.previousTxOutIndex=new LongWritable(previousTxOutIndex);
this.txInScriptLength=new BytesWritable(txInScriptLength);
this.txInScript=new BytesWritable(txInScript);
this.seqNo=new LongWritable(seqNo);
}
public BytesWritable getPrevTransactionHash() {
return this.prevTransactionHash;
}
public LongWritable getPreviousTxOutIndex() {
return this.previousTxOutIndex;
}
public BytesWritable getTxInScriptLength() {
return this.txInScriptLength;
}
public BytesWritable getTxInScript() {
return this.txInScript;
}
public LongWritable getSeqNo() {
return this.seqNo;
}
}
| java | Apache-2.0 | b2df90b216a6024b3179c3afaa6f2bcfc975784c | 2026-01-05T02:40:55.994732Z | false |
ZuInnoTe/hadoopcryptoledger | https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/hiveudf/src/test/java/org/zuinnote/hadoop/ethereum/hive/udf/TestEthereumTransaction.java | hiveudf/src/test/java/org/zuinnote/hadoop/ethereum/hive/udf/TestEthereumTransaction.java | /**
* Copyright 2017 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.zuinnote.hadoop.ethereum.hive.udf;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.math.BigInteger;
import org.apache.hadoop.io.Writable;
import org.zuinnote.hadoop.ethereum.format.common.EthereumTransaction;
/**
*
*
*/
public class TestEthereumTransaction implements Writable {
private byte[] nonce;
private BigInteger value;
private byte[] valueRaw;
private byte[] receiveAddress;
private BigInteger gasPrice;
private byte[] gasPriceRaw;
private BigInteger gasLimit;
private byte[] gasLimitRaw;
private byte[] data;
private byte[] sig_v;
private byte[] sig_r;
private byte[] sig_s;
public TestEthereumTransaction() {
// please use setter to set the data
}
@Override
public void write(DataOutput out) throws IOException {
throw new UnsupportedOperationException("write unsupported");
}
@Override
public void readFields(DataInput in) throws IOException {
throw new UnsupportedOperationException("readFields unsupported");
}
public byte[] getNonce() {
return nonce;
}
public void setNonce(byte[] nonce) {
this.nonce = nonce;
}
public BigInteger getValue() {
return value;
}
public void setValue(BigInteger value) {
this.value = value;
}
public byte[] getReceiveAddress() {
return receiveAddress;
}
public void setReceiveAddress(byte[] receiveAddress) {
this.receiveAddress = receiveAddress;
}
public BigInteger getGasPrice() {
return gasPrice;
}
public void setGasPrice(BigInteger gasPrice) {
this.gasPrice = gasPrice;
}
public BigInteger getGasLimit() {
return gasLimit;
}
public void setGasLimit(BigInteger gasLimit) {
this.gasLimit = gasLimit;
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public void set(EthereumTransaction newTransaction) {
this.nonce=newTransaction.getNonce();
this.value=newTransaction.getValue();
this.valueRaw=newTransaction.getValueRaw();
this.receiveAddress=newTransaction.getReceiveAddress();
this.gasPrice=newTransaction.getGasPrice();
this.gasPriceRaw=newTransaction.getGasPriceRaw();
this.gasLimit=newTransaction.getGasLimit();
this.gasLimitRaw=newTransaction.getGasLimitRaw();
this.data=newTransaction.getData();
this.sig_v=newTransaction.getSig_v();
this.sig_r=newTransaction.getSig_r();
this.sig_s=newTransaction.getSig_s();
}
public byte[] getSig_v() {
return sig_v;
}
public void setSig_v(byte[] sig_v) {
this.sig_v = sig_v;
}
public byte[] getSig_r() {
return sig_r;
}
public void setSig_r(byte[] sig_r) {
this.sig_r = sig_r;
}
public byte[] getSig_s() {
return sig_s;
}
public void setSig_s(byte[] sig_s) {
this.sig_s = sig_s;
}
public byte[] getValueRaw() {
return valueRaw;
}
public void setValueRaw(byte[] valueRaw) {
this.valueRaw = valueRaw;
}
public byte[] getGasLimitRaw() {
return gasLimitRaw;
}
public void setGasLimitRaw(byte[] gasLimitRaw) {
this.gasLimitRaw = gasLimitRaw;
}
public byte[] getGasPriceRaw() {
return gasPriceRaw;
}
public void setGasPriceRaw(byte[] gasPriceRaw) {
this.gasPriceRaw = gasPriceRaw;
}
}
| java | Apache-2.0 | b2df90b216a6024b3179c3afaa6f2bcfc975784c | 2026-01-05T02:40:55.994732Z | false |
ZuInnoTe/hadoopcryptoledger | https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/hiveudf/src/test/java/org/zuinnote/hadoop/ethereum/hive/udf/EthereumUDFTest.java | hiveudf/src/test/java/org/zuinnote/hadoop/ethereum/hive/udf/EthereumUDFTest.java | /**
* Copyright 2017 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.zuinnote.hadoop.ethereum.hive.udf;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import org.apache.hadoop.hive.common.type.HiveDecimal;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.IntWritable;
import org.junit.jupiter.api.Test;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.zuinnote.hadoop.ethereum.format.common.EthereumBlock;
import org.zuinnote.hadoop.ethereum.format.common.EthereumBlockReader;
import org.zuinnote.hadoop.ethereum.format.common.EthereumTransaction;
import org.zuinnote.hadoop.ethereum.format.exception.EthereumBlockReadException;
import org.zuinnote.hadoop.ethereum.hive.datatypes.HiveEthereumTransaction;
/**
*
*
*/
public class EthereumUDFTest {
static final int DEFAULT_BUFFERSIZE=64*1024;
static final int DEFAULT_MAXSIZE_ETHEREUMBLOCK=1 * 1024 * 1024;
@Test
public void checkTestDataBlock1346406Available() {
ClassLoader classLoader = getClass().getClassLoader();
String fileName="eth1346406.bin";
String fileNameGenesis=classLoader.getResource(fileName).getFile();
assertNotNull("Test Data File \""+fileName+"\" is not null in resource path",fileNameGenesis);
File file = new File(fileNameGenesis);
assertTrue( file.exists(),"Test Data File \""+fileName+"\" exists");
assertFalse( file.isDirectory(),"Test Data File \""+fileName+"\" is not a directory");
}
@Test
public void EthereumGetChainIdUDFNull() throws HiveException {
EthereumGetChainIdUDF egcidUDF = new EthereumGetChainIdUDF();
ObjectInspector[] arguments = new ObjectInspector[1];
arguments[0] = ObjectInspectorFactory.getReflectionObjectInspector(EthereumTransaction.class,ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
egcidUDF.initialize(arguments);
assertNull(egcidUDF.evaluate(null),"Null argument to UDF returns null");
}
@Test
public void EthereumGetSendAddressUDFNull() throws HiveException {
EthereumGetSendAddressUDF egsaUDF = new EthereumGetSendAddressUDF();
ObjectInspector[] arguments = new ObjectInspector[2];
arguments[0] = ObjectInspectorFactory.getReflectionObjectInspector(EthereumTransaction.class,ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
arguments[1] = PrimitiveObjectInspectorFactory.javaIntObjectInspector;
egsaUDF.initialize(arguments);
assertNull(egsaUDF.evaluate(null),"Null argument to UDF returns null");
}
@Test
public void EthereumGetTransactionHashUDFNull() throws HiveException {
EthereumGetTransactionHashUDF egthUDF = new EthereumGetTransactionHashUDF();
ObjectInspector[] arguments = new ObjectInspector[1];
arguments[0] = ObjectInspectorFactory.getReflectionObjectInspector(EthereumTransaction.class,ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
egthUDF.initialize(arguments);
assertNull(egthUDF.evaluate(null),"Null argument to UDF returns null");
}
@Test
public void EthereumGetChainIdUDFWritable() throws HiveException, IOException, EthereumBlockReadException {
// initialize object inspector
EthereumGetChainIdUDF egcidUDF = new EthereumGetChainIdUDF();
ObjectInspector[] arguments = new ObjectInspector[1];
arguments[0] = ObjectInspectorFactory.getReflectionObjectInspector(HiveEthereumTransaction.class,ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
egcidUDF.initialize(arguments);
// load test data
ClassLoader classLoader = getClass().getClassLoader();
String fileName="eth1346406.bin";
String fileNameBlock=classLoader.getResource(fileName).getFile();
File file = new File(fileNameBlock);
boolean direct=false;
FileInputStream fin = new FileInputStream(file);
EthereumBlockReader ebr = null;
try {
ebr = new EthereumBlockReader(fin,this.DEFAULT_MAXSIZE_ETHEREUMBLOCK, this.DEFAULT_BUFFERSIZE,direct);
EthereumBlock eblock = ebr.readBlock();
List<EthereumTransaction> eTrans = eblock.getEthereumTransactions();
// validate UDFs
HiveEthereumTransaction trans0 = EthereumUDFTest.convertToHiveEthereumTransaction(eTrans.get(0));
assertNull(egcidUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans0)}),"Block 1346406 Transaction 1 is Ethereum MainNet");
HiveEthereumTransaction trans1 = EthereumUDFTest.convertToHiveEthereumTransaction(eTrans.get(1));
assertNull(egcidUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans1)}),"Block 1346406 Transaction 2 is Ethereum MainNet");
HiveEthereumTransaction trans2 = EthereumUDFTest.convertToHiveEthereumTransaction(eTrans.get(2));
assertNull(egcidUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans2)}),"Block 1346406 Transaction 3 is Ethereum MainNet");
HiveEthereumTransaction trans3 = EthereumUDFTest.convertToHiveEthereumTransaction(eTrans.get(3));
assertNull(egcidUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans3)}),"Block 1346406 Transaction 4 is Ethereum MainNet");
HiveEthereumTransaction trans4 = EthereumUDFTest.convertToHiveEthereumTransaction(eTrans.get(4));
assertNull(egcidUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans4)}),"Block 1346406 Transaction 5 is Ethereum MainNet");
HiveEthereumTransaction trans5 = EthereumUDFTest.convertToHiveEthereumTransaction(eTrans.get(5));
assertNull(egcidUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans5)}),"Block 1346406 Transaction 6 is Ethereum MainNet");
}
finally {
if (ebr!=null) {
ebr.close();
}
}
}
@Test
public void EthereumGetChainIdUDFObjectInspector() throws HiveException, IOException, EthereumBlockReadException {
// initialize object inspector
EthereumGetChainIdUDF egcidUDF = new EthereumGetChainIdUDF();
ObjectInspector[] arguments = new ObjectInspector[1];
arguments[0] = ObjectInspectorFactory.getReflectionObjectInspector(TestEthereumTransaction.class,ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
egcidUDF.initialize(arguments);
// load test data
ClassLoader classLoader = getClass().getClassLoader();
String fileName="eth1346406.bin";
String fileNameBlock=classLoader.getResource(fileName).getFile();
File file = new File(fileNameBlock);
boolean direct=false;
FileInputStream fin = new FileInputStream(file);
EthereumBlockReader ebr = null;
try {
ebr = new EthereumBlockReader(fin,this.DEFAULT_MAXSIZE_ETHEREUMBLOCK, this.DEFAULT_BUFFERSIZE,direct);
EthereumBlock eblock = ebr.readBlock();
List<EthereumTransaction> eTrans = eblock.getEthereumTransactions();
// validate UDFs
EthereumTransaction transOrig0 = eTrans.get(0);
TestEthereumTransaction trans0 = new TestEthereumTransaction();
trans0.set(transOrig0);
assertNull(egcidUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans0)}),"Block 1346406 Transaction 1 is Ethereum MainNet");
EthereumTransaction transOrig1 = eTrans.get(1);
TestEthereumTransaction trans1 = new TestEthereumTransaction();
trans1.set(transOrig1);
assertNull(egcidUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans1)}),"Block 1346406 Transaction 2 is Ethereum MainNet");
EthereumTransaction transOrig2 = eTrans.get(2);
TestEthereumTransaction trans2 = new TestEthereumTransaction();
trans2.set(transOrig2);
assertNull(egcidUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans2)}),"Block 1346406 Transaction 3 is Ethereum MainNet");
EthereumTransaction transOrig3 = eTrans.get(3);
TestEthereumTransaction trans3 = new TestEthereumTransaction();
trans3.set(transOrig3);
assertNull(egcidUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans3)}),"Block 1346406 Transaction 4 is Ethereum MainNet");
EthereumTransaction transOrig4 = eTrans.get(4);
TestEthereumTransaction trans4 = new TestEthereumTransaction();
trans4.set(transOrig4);
assertNull(egcidUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans4)}),"Block 1346406 Transaction 5 is Ethereum MainNet");
EthereumTransaction transOrig5 = eTrans.get(5);
TestEthereumTransaction trans5 = new TestEthereumTransaction();
trans5.set(transOrig5);
assertNull(egcidUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans5)}),"Block 1346406 Transaction 6 is Ethereum MainNet");
}
finally {
if (ebr!=null) {
ebr.close();
}
}
}
@Test
public void EthereumGetSendAddressUDFWritable() throws HiveException, IOException, EthereumBlockReadException {
// initialize object inspector
EthereumGetSendAddressUDF egsaUDF = new EthereumGetSendAddressUDF();
ObjectInspector[] arguments = new ObjectInspector[2];
arguments[0] = ObjectInspectorFactory.getReflectionObjectInspector(HiveEthereumTransaction.class,ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
arguments[1] = PrimitiveObjectInspectorFactory.javaIntObjectInspector;
egsaUDF.initialize(arguments);
// load test data
ClassLoader classLoader = getClass().getClassLoader();
String fileName="eth1346406.bin";
String fileNameBlock=classLoader.getResource(fileName).getFile();
File file = new File(fileNameBlock);
boolean direct=false;
FileInputStream fin = new FileInputStream(file);
EthereumBlockReader ebr = null;
try {
ebr = new EthereumBlockReader(fin,this.DEFAULT_MAXSIZE_ETHEREUMBLOCK, this.DEFAULT_BUFFERSIZE,direct);
EthereumBlock eblock = ebr.readBlock();
List<EthereumTransaction> eTrans = eblock.getEthereumTransactions();
// validate UDFs
HiveEthereumTransaction trans0 = EthereumUDFTest.convertToHiveEthereumTransaction(eTrans.get(0));
byte[] expectedSentAddress = new byte[] {(byte)0x39,(byte)0x42,(byte)0x4b,(byte)0xd2,(byte)0x8a,(byte)0x22,(byte)0x23,(byte)0xda,(byte)0x3e,(byte)0x14,(byte)0xbf,(byte)0x79,(byte)0x3c,(byte)0xf7,(byte)0xf8,(byte)0x20,(byte)0x8e,(byte)0xe9,(byte)0x98,(byte)0x0a};
assertArrayEquals(expectedSentAddress,((BytesWritable)egsaUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans0),new GenericUDF.DeferredJavaObject(new IntWritable(1))})).copyBytes(),"Block 1346406 Transaction 1 send address is correctly calculated");
HiveEthereumTransaction trans1 = EthereumUDFTest.convertToHiveEthereumTransaction(eTrans.get(1));
expectedSentAddress = new byte[] {(byte)0x4b,(byte)0xb9,(byte)0x60,(byte)0x91,(byte)0xee,(byte)0x9d,(byte)0x80,(byte)0x2e,(byte)0xd0,(byte)0x39,(byte)0xc4,(byte)0xd1,(byte)0xa5,(byte)0xf6,(byte)0x21,(byte)0x6f,(byte)0x90,(byte)0xf8,(byte)0x1b,(byte)0x01};
assertArrayEquals(expectedSentAddress,((BytesWritable)egsaUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans1),new GenericUDF.DeferredJavaObject(new IntWritable(1))})).copyBytes(),"Block 1346406 Transaction 2 send address is correctly calculated");
HiveEthereumTransaction trans2 = EthereumUDFTest.convertToHiveEthereumTransaction(eTrans.get(2));
expectedSentAddress = new byte[] {(byte)0x63,(byte)0xa9,(byte)0x97,(byte)0x5b,(byte)0xa3,(byte)0x1b,(byte)0x0b,(byte)0x96,(byte)0x26,(byte)0xb3,(byte)0x43,(byte)0x00,(byte)0xf7,(byte)0xf6,(byte)0x27,(byte)0x14,(byte)0x7d,(byte)0xf1,(byte)0xf5,(byte)0x26};
assertArrayEquals(expectedSentAddress,((BytesWritable)egsaUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans2),new GenericUDF.DeferredJavaObject(new IntWritable(1))})).copyBytes(),"Block 1346406 Transaction 3 send address is correctly calculated");
HiveEthereumTransaction trans3 = EthereumUDFTest.convertToHiveEthereumTransaction(eTrans.get(3));
expectedSentAddress = new byte[] {(byte)0x63,(byte)0xa9,(byte)0x97,(byte)0x5b,(byte)0xa3,(byte)0x1b,(byte)0x0b,(byte)0x96,(byte)0x26,(byte)0xb3,(byte)0x43,(byte)0x00,(byte)0xf7,(byte)0xf6,(byte)0x27,(byte)0x14,(byte)0x7d,(byte)0xf1,(byte)0xf5,(byte)0x26};
assertArrayEquals(expectedSentAddress,((BytesWritable)egsaUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans3),new GenericUDF.DeferredJavaObject(new IntWritable(1))})).copyBytes(),"Block 1346406 Transaction 4 send address is correctly calculated");
HiveEthereumTransaction trans4 = EthereumUDFTest.convertToHiveEthereumTransaction(eTrans.get(4));
expectedSentAddress = new byte[] {(byte)0x63,(byte)0xa9,(byte)0x97,(byte)0x5b,(byte)0xa3,(byte)0x1b,(byte)0x0b,(byte)0x96,(byte)0x26,(byte)0xb3,(byte)0x43,(byte)0x00,(byte)0xf7,(byte)0xf6,(byte)0x27,(byte)0x14,(byte)0x7d,(byte)0xf1,(byte)0xf5,(byte)0x26};
assertArrayEquals(expectedSentAddress,((BytesWritable)egsaUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans4),new GenericUDF.DeferredJavaObject(new IntWritable(1))})).copyBytes(),"Block 1346406 Transaction 5 send address is correctly calculated");
HiveEthereumTransaction trans5 = EthereumUDFTest.convertToHiveEthereumTransaction(eTrans.get(5));
expectedSentAddress = new byte[] {(byte)0x63,(byte)0xa9,(byte)0x97,(byte)0x5b,(byte)0xa3,(byte)0x1b,(byte)0x0b,(byte)0x96,(byte)0x26,(byte)0xb3,(byte)0x43,(byte)0x00,(byte)0xf7,(byte)0xf6,(byte)0x27,(byte)0x14,(byte)0x7d,(byte)0xf1,(byte)0xf5,(byte)0x26};
assertArrayEquals(expectedSentAddress,((BytesWritable)egsaUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans5),new GenericUDF.DeferredJavaObject(new IntWritable(1))})).copyBytes(),"Block 1346406 Transaction 6 send address is correctly calculated");
}
finally {
if (ebr!=null) {
ebr.close();
}
}
}
@Test
public void EthereumGetSendAddressUDFObjectInspector() throws HiveException, IOException, EthereumBlockReadException {
// initialize object inspector
EthereumGetSendAddressUDF egsaUDF = new EthereumGetSendAddressUDF();
ObjectInspector[] arguments = new ObjectInspector[2];
arguments[0] = ObjectInspectorFactory.getReflectionObjectInspector(TestEthereumTransaction.class,ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
arguments[1] = PrimitiveObjectInspectorFactory.javaIntObjectInspector;
egsaUDF.initialize(arguments);
// load test data
ClassLoader classLoader = getClass().getClassLoader();
String fileName="eth1346406.bin";
String fileNameBlock=classLoader.getResource(fileName).getFile();
File file = new File(fileNameBlock);
boolean direct=false;
FileInputStream fin = new FileInputStream(file);
EthereumBlockReader ebr = null;
try {
ebr = new EthereumBlockReader(fin,this.DEFAULT_MAXSIZE_ETHEREUMBLOCK, this.DEFAULT_BUFFERSIZE,direct);
EthereumBlock eblock = ebr.readBlock();
List<EthereumTransaction> eTrans = eblock.getEthereumTransactions();
// validate UDFs
EthereumTransaction transOrig0 = eTrans.get(0);
TestEthereumTransaction trans0 = new TestEthereumTransaction();
trans0.set(transOrig0);
byte[] expectedSentAddress = new byte[] {(byte)0x39,(byte)0x42,(byte)0x4b,(byte)0xd2,(byte)0x8a,(byte)0x22,(byte)0x23,(byte)0xda,(byte)0x3e,(byte)0x14,(byte)0xbf,(byte)0x79,(byte)0x3c,(byte)0xf7,(byte)0xf8,(byte)0x20,(byte)0x8e,(byte)0xe9,(byte)0x98,(byte)0x0a};
assertArrayEquals(expectedSentAddress,((BytesWritable)egsaUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans0),new GenericUDF.DeferredJavaObject(new IntWritable(1))})).copyBytes(),"Block 1346406 Transaction 1 send address is correctly calculated");
EthereumTransaction transOrig1 = eTrans.get(1);
TestEthereumTransaction trans1 = new TestEthereumTransaction();
trans1.set(transOrig1);
expectedSentAddress = new byte[] {(byte)0x4b,(byte)0xb9,(byte)0x60,(byte)0x91,(byte)0xee,(byte)0x9d,(byte)0x80,(byte)0x2e,(byte)0xd0,(byte)0x39,(byte)0xc4,(byte)0xd1,(byte)0xa5,(byte)0xf6,(byte)0x21,(byte)0x6f,(byte)0x90,(byte)0xf8,(byte)0x1b,(byte)0x01};
assertArrayEquals(expectedSentAddress,((BytesWritable)egsaUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans1),new GenericUDF.DeferredJavaObject(new IntWritable(1))})).copyBytes(),"Block 1346406 Transaction 2 send address is correctly calculated");
EthereumTransaction transOrig2 = eTrans.get(2);
TestEthereumTransaction trans2 = new TestEthereumTransaction();
trans2.set(transOrig2);
expectedSentAddress = new byte[] {(byte)0x63,(byte)0xa9,(byte)0x97,(byte)0x5b,(byte)0xa3,(byte)0x1b,(byte)0x0b,(byte)0x96,(byte)0x26,(byte)0xb3,(byte)0x43,(byte)0x00,(byte)0xf7,(byte)0xf6,(byte)0x27,(byte)0x14,(byte)0x7d,(byte)0xf1,(byte)0xf5,(byte)0x26};
assertArrayEquals(expectedSentAddress,((BytesWritable)egsaUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans2),new GenericUDF.DeferredJavaObject(new IntWritable(1))})).copyBytes(),"Block 1346406 Transaction 3 send address is correctly calculated");
EthereumTransaction transOrig3 = eTrans.get(3);
TestEthereumTransaction trans3 = new TestEthereumTransaction();
trans3.set(transOrig3);
expectedSentAddress = new byte[] {(byte)0x63,(byte)0xa9,(byte)0x97,(byte)0x5b,(byte)0xa3,(byte)0x1b,(byte)0x0b,(byte)0x96,(byte)0x26,(byte)0xb3,(byte)0x43,(byte)0x00,(byte)0xf7,(byte)0xf6,(byte)0x27,(byte)0x14,(byte)0x7d,(byte)0xf1,(byte)0xf5,(byte)0x26};
assertArrayEquals(expectedSentAddress,((BytesWritable)egsaUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans3),new GenericUDF.DeferredJavaObject(new IntWritable(1))})).copyBytes(),"Block 1346406 Transaction 4 send address is correctly calculated");
EthereumTransaction transOrig4 = eTrans.get(4);
TestEthereumTransaction trans4 = new TestEthereumTransaction();
trans4.set(transOrig4);
expectedSentAddress = new byte[] {(byte)0x63,(byte)0xa9,(byte)0x97,(byte)0x5b,(byte)0xa3,(byte)0x1b,(byte)0x0b,(byte)0x96,(byte)0x26,(byte)0xb3,(byte)0x43,(byte)0x00,(byte)0xf7,(byte)0xf6,(byte)0x27,(byte)0x14,(byte)0x7d,(byte)0xf1,(byte)0xf5,(byte)0x26};
assertArrayEquals(expectedSentAddress,((BytesWritable)egsaUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans4),new GenericUDF.DeferredJavaObject(new IntWritable(1))})).copyBytes(),"Block 1346406 Transaction 5 send address is correctly calculated");
EthereumTransaction transOrig5 = eTrans.get(5);
TestEthereumTransaction trans5 = new TestEthereumTransaction();
trans5.set(transOrig5);
expectedSentAddress = new byte[] {(byte)0x63,(byte)0xa9,(byte)0x97,(byte)0x5b,(byte)0xa3,(byte)0x1b,(byte)0x0b,(byte)0x96,(byte)0x26,(byte)0xb3,(byte)0x43,(byte)0x00,(byte)0xf7,(byte)0xf6,(byte)0x27,(byte)0x14,(byte)0x7d,(byte)0xf1,(byte)0xf5,(byte)0x26};
assertArrayEquals(expectedSentAddress,((BytesWritable)egsaUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans5),new GenericUDF.DeferredJavaObject(new IntWritable(1))})).copyBytes(),"Block 1346406 Transaction 6 send address is correctly calculated");
}
finally {
if (ebr!=null) {
ebr.close();
}
}
}
@Test
public void EthereumGetTransactionHashUDFWritable() throws HiveException, IOException, EthereumBlockReadException {
// initialize object inspector
EthereumGetTransactionHashUDF egthUDF = new EthereumGetTransactionHashUDF();
ObjectInspector[] arguments = new ObjectInspector[1];
arguments[0] = ObjectInspectorFactory.getReflectionObjectInspector(HiveEthereumTransaction.class,ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
egthUDF.initialize(arguments);
// load test data
ClassLoader classLoader = getClass().getClassLoader();
String fileName="eth1346406.bin";
String fileNameBlock=classLoader.getResource(fileName).getFile();
File file = new File(fileNameBlock);
boolean direct=false;
FileInputStream fin = new FileInputStream(file);
EthereumBlockReader ebr = null;
try {
ebr = new EthereumBlockReader(fin,this.DEFAULT_MAXSIZE_ETHEREUMBLOCK, this.DEFAULT_BUFFERSIZE,direct);
EthereumBlock eblock = ebr.readBlock();
List<EthereumTransaction> eTrans = eblock.getEthereumTransactions();
// validate UDFs
HiveEthereumTransaction trans0 = EthereumUDFTest.convertToHiveEthereumTransaction(eTrans.get(0));
byte[] expectedHash = new byte[] {(byte)0xe2,(byte)0x7e,(byte)0x92,(byte)0x88,(byte)0xe2,(byte)0x9c,(byte)0xc8,(byte)0xeb,(byte)0x78,(byte)0xf9,(byte)0xf7,(byte)0x68,(byte)0xd8,(byte)0x9b,(byte)0xf1,(byte)0xcd,(byte)0x4b,(byte)0x68,(byte)0xb7,(byte)0x15,(byte)0xa3,(byte)0x8b,(byte)0x95,(byte)0xd4,(byte)0x6d,(byte)0x77,(byte)0x86,(byte)0x18,(byte)0xcb,(byte)0x10,(byte)0x4d,(byte)0x58};
assertArrayEquals(expectedHash,((BytesWritable)egthUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans0)})).copyBytes(),"Block 1346406 Transaction 1 hash is correctly calculated");
HiveEthereumTransaction trans1 = EthereumUDFTest.convertToHiveEthereumTransaction(eTrans.get(1));
expectedHash = new byte[] {(byte)0x7a,(byte)0x23,(byte)0x2a,(byte)0xa2,(byte)0xae,(byte)0x6a,(byte)0x5e,(byte)0x1f,(byte)0x32,(byte)0xca,(byte)0x3a,(byte)0xc9,(byte)0x3f,(byte)0x4f,(byte)0xdb,(byte)0x77,(byte)0x98,(byte)0x3e,(byte)0x93,(byte)0x2b,(byte)0x38,(byte)0x09,(byte)0x93,(byte)0x56,(byte)0x44,(byte)0x42,(byte)0x08,(byte)0xc6,(byte)0x9d,(byte)0x40,(byte)0x86,(byte)0x81};
assertArrayEquals(expectedHash,((BytesWritable)egthUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans1)})).copyBytes(),"Block 1346406 Transaction 2 hash is correctly calculated");
HiveEthereumTransaction trans2 = EthereumUDFTest.convertToHiveEthereumTransaction(eTrans.get(2));
expectedHash = new byte[] {(byte)0x14,(byte)0x33,(byte)0xe3,(byte)0xcb,(byte)0x66,(byte)0x2f,(byte)0x66,(byte)0x8d,(byte)0x87,(byte)0xb8,(byte)0x35,(byte)0x55,(byte)0x34,(byte)0x5a,(byte)0x20,(byte)0xcc,(byte)0xf8,(byte)0x70,(byte)0x6f,(byte)0x25,(byte)0x21,(byte)0x49,(byte)0x18,(byte)0xe2,(byte)0xf8,(byte)0x1f,(byte)0xe3,(byte)0xd2,(byte)0x1c,(byte)0x9d,(byte)0x5b,(byte)0x23};
assertArrayEquals(expectedHash,((BytesWritable)egthUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans2)})).copyBytes(),"Block 1346406 Transaction 3 hash is correctly calculated");
HiveEthereumTransaction trans3 = EthereumUDFTest.convertToHiveEthereumTransaction(eTrans.get(3));
expectedHash = new byte[] {(byte)0x39,(byte)0x22,(byte)0xf7,(byte)0xf6,(byte)0x0a,(byte)0x33,(byte)0xa1,(byte)0x2d,(byte)0x13,(byte)0x9d,(byte)0x67,(byte)0xfa,(byte)0x53,(byte)0x30,(byte)0xdb,(byte)0xfd,(byte)0xba,(byte)0x42,(byte)0xa4,(byte)0xb7,(byte)0x67,(byte)0x29,(byte)0x6e,(byte)0xff,(byte)0x64,(byte)0x15,(byte)0xee,(byte)0xa3,(byte)0x2d,(byte)0x8a,(byte)0x7b,(byte)0x2b};
assertArrayEquals(expectedHash,((BytesWritable)egthUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans3)})).copyBytes(),"Block 1346406 Transaction 4 hash is correctly calculated");
HiveEthereumTransaction trans4 = EthereumUDFTest.convertToHiveEthereumTransaction(eTrans.get(4));
expectedHash = new byte[] {(byte)0xbb,(byte)0x7c,(byte)0xaa,(byte)0x23,(byte)0x38,(byte)0x5a,(byte)0x0f,(byte)0x73,(byte)0x75,(byte)0x3f,(byte)0x9e,(byte)0x28,(byte)0xd8,(byte)0xf0,(byte)0x60,(byte)0x2f,(byte)0xe2,(byte)0xe7,(byte)0x2d,(byte)0x87,(byte)0xe1,(byte)0xe0,(byte)0x95,(byte)0x52,(byte)0x75,(byte)0x28,(byte)0xd1,(byte)0x44,(byte)0x88,(byte)0x5d,(byte)0x6b,(byte)0x51};
assertArrayEquals(expectedHash,((BytesWritable)egthUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans4)})).copyBytes(),"Block 1346406 Transaction 5 hash is correctly calculated");
HiveEthereumTransaction trans5 = EthereumUDFTest.convertToHiveEthereumTransaction(eTrans.get(5));
expectedHash = new byte[] {(byte)0xbc,(byte)0xde,(byte)0x6f,(byte)0x49,(byte)0x84,(byte)0x2c,(byte)0x6d,(byte)0x73,(byte)0x8d,(byte)0x64,(byte)0x32,(byte)0x8f,(byte)0x78,(byte)0x09,(byte)0xb1,(byte)0xd4,(byte)0x9b,(byte)0xf0,(byte)0xff,(byte)0x3f,(byte)0xfa,(byte)0x46,(byte)0x0f,(byte)0xdd,(byte)0xd2,(byte)0x7f,(byte)0xd4,(byte)0x2b,(byte)0x7a,(byte)0x01,(byte)0xfc,(byte)0x9a};
assertArrayEquals(expectedHash,((BytesWritable)egthUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans5)})).copyBytes(),"Block 1346406 Transaction 6 hash is correctly calculated");
}
finally {
if (ebr!=null) {
ebr.close();
}
}
}
@Test
public void EthereumGetTransactionHashUDFObjectInspector() throws HiveException, IOException, EthereumBlockReadException {
// initialize object inspector
EthereumGetTransactionHashUDF egthUDF = new EthereumGetTransactionHashUDF();
ObjectInspector[] arguments = new ObjectInspector[1];
arguments[0] = ObjectInspectorFactory.getReflectionObjectInspector(TestEthereumTransaction.class,ObjectInspectorFactory.ObjectInspectorOptions.JAVA);
egthUDF.initialize(arguments);
// load test data
ClassLoader classLoader = getClass().getClassLoader();
String fileName="eth1346406.bin";
String fileNameBlock=classLoader.getResource(fileName).getFile();
File file = new File(fileNameBlock);
boolean direct=false;
FileInputStream fin = new FileInputStream(file);
EthereumBlockReader ebr = null;
try {
ebr = new EthereumBlockReader(fin,this.DEFAULT_MAXSIZE_ETHEREUMBLOCK, this.DEFAULT_BUFFERSIZE,direct);
EthereumBlock eblock = ebr.readBlock();
List<EthereumTransaction> eTrans = eblock.getEthereumTransactions();
// validate UDFs
EthereumTransaction transOrig0 = eTrans.get(0);
TestEthereumTransaction trans0 = new TestEthereumTransaction();
trans0.set(transOrig0);
byte[] expectedHash = new byte[] {(byte)0xe2,(byte)0x7e,(byte)0x92,(byte)0x88,(byte)0xe2,(byte)0x9c,(byte)0xc8,(byte)0xeb,(byte)0x78,(byte)0xf9,(byte)0xf7,(byte)0x68,(byte)0xd8,(byte)0x9b,(byte)0xf1,(byte)0xcd,(byte)0x4b,(byte)0x68,(byte)0xb7,(byte)0x15,(byte)0xa3,(byte)0x8b,(byte)0x95,(byte)0xd4,(byte)0x6d,(byte)0x77,(byte)0x86,(byte)0x18,(byte)0xcb,(byte)0x10,(byte)0x4d,(byte)0x58};
assertArrayEquals(expectedHash,((BytesWritable)egthUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans0)})).copyBytes(),"Block 1346406 Transaction 1 hash is correctly calculated");
EthereumTransaction transOrig1 = eTrans.get(1);
TestEthereumTransaction trans1 = new TestEthereumTransaction();
trans1.set(transOrig1);
expectedHash = new byte[] {(byte)0x7a,(byte)0x23,(byte)0x2a,(byte)0xa2,(byte)0xae,(byte)0x6a,(byte)0x5e,(byte)0x1f,(byte)0x32,(byte)0xca,(byte)0x3a,(byte)0xc9,(byte)0x3f,(byte)0x4f,(byte)0xdb,(byte)0x77,(byte)0x98,(byte)0x3e,(byte)0x93,(byte)0x2b,(byte)0x38,(byte)0x09,(byte)0x93,(byte)0x56,(byte)0x44,(byte)0x42,(byte)0x08,(byte)0xc6,(byte)0x9d,(byte)0x40,(byte)0x86,(byte)0x81};
assertArrayEquals(expectedHash,((BytesWritable)egthUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans1)})).copyBytes(),"Block 1346406 Transaction 2 hash is correctly calculated");
EthereumTransaction transOrig2 = eTrans.get(2);
TestEthereumTransaction trans2 = new TestEthereumTransaction();
trans2.set(transOrig2);
expectedHash = new byte[] {(byte)0x14,(byte)0x33,(byte)0xe3,(byte)0xcb,(byte)0x66,(byte)0x2f,(byte)0x66,(byte)0x8d,(byte)0x87,(byte)0xb8,(byte)0x35,(byte)0x55,(byte)0x34,(byte)0x5a,(byte)0x20,(byte)0xcc,(byte)0xf8,(byte)0x70,(byte)0x6f,(byte)0x25,(byte)0x21,(byte)0x49,(byte)0x18,(byte)0xe2,(byte)0xf8,(byte)0x1f,(byte)0xe3,(byte)0xd2,(byte)0x1c,(byte)0x9d,(byte)0x5b,(byte)0x23};
assertArrayEquals(expectedHash,((BytesWritable)egthUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans2)})).copyBytes(),"Block 1346406 Transaction 3 hash is correctly calculated");
EthereumTransaction transOrig3 = eTrans.get(3);
TestEthereumTransaction trans3 = new TestEthereumTransaction();
trans3.set(transOrig3);
expectedHash = new byte[] {(byte)0x39,(byte)0x22,(byte)0xf7,(byte)0xf6,(byte)0x0a,(byte)0x33,(byte)0xa1,(byte)0x2d,(byte)0x13,(byte)0x9d,(byte)0x67,(byte)0xfa,(byte)0x53,(byte)0x30,(byte)0xdb,(byte)0xfd,(byte)0xba,(byte)0x42,(byte)0xa4,(byte)0xb7,(byte)0x67,(byte)0x29,(byte)0x6e,(byte)0xff,(byte)0x64,(byte)0x15,(byte)0xee,(byte)0xa3,(byte)0x2d,(byte)0x8a,(byte)0x7b,(byte)0x2b};
assertArrayEquals(expectedHash,((BytesWritable)egthUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans3)})).copyBytes(),"Block 1346406 Transaction 4 hash is correctly calculated");
EthereumTransaction transOrig4 = eTrans.get(4);
TestEthereumTransaction trans4 = new TestEthereumTransaction();
trans4.set(transOrig4);
expectedHash = new byte[] {(byte)0xbb,(byte)0x7c,(byte)0xaa,(byte)0x23,(byte)0x38,(byte)0x5a,(byte)0x0f,(byte)0x73,(byte)0x75,(byte)0x3f,(byte)0x9e,(byte)0x28,(byte)0xd8,(byte)0xf0,(byte)0x60,(byte)0x2f,(byte)0xe2,(byte)0xe7,(byte)0x2d,(byte)0x87,(byte)0xe1,(byte)0xe0,(byte)0x95,(byte)0x52,(byte)0x75,(byte)0x28,(byte)0xd1,(byte)0x44,(byte)0x88,(byte)0x5d,(byte)0x6b,(byte)0x51};
assertArrayEquals(expectedHash,((BytesWritable)egthUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans4)})).copyBytes(),"Block 1346406 Transaction 5 hash is correctly calculated");
EthereumTransaction transOrig5 = eTrans.get(5);
TestEthereumTransaction trans5 = new TestEthereumTransaction();
trans5.set(transOrig5);
expectedHash = new byte[] {(byte)0xbc,(byte)0xde,(byte)0x6f,(byte)0x49,(byte)0x84,(byte)0x2c,(byte)0x6d,(byte)0x73,(byte)0x8d,(byte)0x64,(byte)0x32,(byte)0x8f,(byte)0x78,(byte)0x09,(byte)0xb1,(byte)0xd4,(byte)0x9b,(byte)0xf0,(byte)0xff,(byte)0x3f,(byte)0xfa,(byte)0x46,(byte)0x0f,(byte)0xdd,(byte)0xd2,(byte)0x7f,(byte)0xd4,(byte)0x2b,(byte)0x7a,(byte)0x01,(byte)0xfc,(byte)0x9a};
assertArrayEquals(expectedHash,((BytesWritable)egthUDF.evaluate(new GenericUDF.DeferredObject[] {new GenericUDF.DeferredJavaObject(trans5)})).copyBytes(),"Block 1346406 Transaction 6 hash is correctly calculated");
}
finally {
if (ebr!=null) {
ebr.close();
}
}
}
/***
* Helper function to convert EthereumTransaction to HiveEthereumTransaction
*
* @param transaction
* @return
*/
private static HiveEthereumTransaction convertToHiveEthereumTransaction(EthereumTransaction transaction) {
HiveEthereumTransaction newTransaction = new HiveEthereumTransaction();
newTransaction.setNonce(transaction.getNonce());
newTransaction.setValue(HiveDecimal.create(transaction.getValue()));
newTransaction.setValueRaw(transaction.getValueRaw());
newTransaction.setReceiveAddress(transaction.getReceiveAddress());
newTransaction.setGasPrice(HiveDecimal.create(transaction.getGasPrice()));
newTransaction.setGasPriceRaw(transaction.getGasPriceRaw());
newTransaction.setGasLimit(HiveDecimal.create(transaction.getGasLimit()));
newTransaction.setGasLimitRaw(transaction.getGasLimitRaw());
newTransaction.setData(transaction.getData());
newTransaction.setSig_v(transaction.getSig_v());
newTransaction.setSig_r(transaction.getSig_r());
| java | Apache-2.0 | b2df90b216a6024b3179c3afaa6f2bcfc975784c | 2026-01-05T02:40:55.994732Z | true |
ZuInnoTe/hadoopcryptoledger | https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/hiveudf/src/main/java/org/zuinnote/hadoop/namecoin/hive/udf/NamecoinExtractFieldUDF.java | hiveudf/src/main/java/org/zuinnote/hadoop/namecoin/hive/udf/NamecoinExtractFieldUDF.java | /**
* Copyright 2017 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.zuinnote.hadoop.namecoin.hive.udf;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.BinaryObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.zuinnote.hadoop.namecoin.format.common.NamecoinUtil;
public class NamecoinExtractFieldUDF extends GenericUDF {
private static final Log LOG = LogFactory.getLog(NamecoinExtractFieldUDF.class.getName());
private BinaryObjectInspector wboi;
/**
*
* Initialize HiveUDF and create object inspectors. It requires that the argument length is = 1 and that the ObjectInspector of arguments[0] is of type org.apache.hadoop.hive.serde2.objectinspector.primitive.WritableBinaryObjectInspector
*
* @param arguments array of length 1 containing one WritableBinaryObjectInspector
*
* @return ObjectInspector that is able to parse the result of the evaluate method of the UDF (List Object Inspector for Strings)
*
* @throws org.apache.hadoop.hive.ql.exec.UDFArgumentException in case the first argument is not of WritableBinaryObjectInspector
* @throws org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException in case the number of arguments is != 1
*
*/
@Override
public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException {
if (arguments==null) {
throw new UDFArgumentLengthException("namecoinExtractField only takes one argument: Binary ");
}
if (arguments.length != 1) {
throw new UDFArgumentLengthException("namecoinExtractField only takes one argument: Binary ");
}
if (!(arguments[0] instanceof BinaryObjectInspector)) {
throw new UDFArgumentException("first argument must be a Binary containing a Namecoin script");
}
// these are only used for bitcointransaction structs exported to other formats, such as ORC
this.wboi = (BinaryObjectInspector)arguments[0];
// the UDF returns the hash value of a BitcoinTransaction as byte array
return ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.writableStringObjectInspector);
}
/**
*
* Analyzes txOutScript (ScriptPubKey) of an output of a Namecoin Transaction to determine the key (usually the domain name or identity) and the value (more information, such as subdomains, ips etc.)
*
* @param arguments array of length 1 containing one object of type Binary representing the txOutScript of a Namecoin firstupdate or update operation
*
* @return Array (List) of size 2, where the first item is the domain name and the second item contains more information, such as subdomains, in JSON format
*
* @throws org.apache.hadoop.hive.ql.metadata.HiveException in case an internal HiveError occurred
*/
@Override
public Object evaluate(DeferredObject[] arguments) throws HiveException {
if ((arguments==null) || (arguments.length!=1)) {
return null;
}
byte[] txOutScript = wboi.getPrimitiveJavaObject(arguments[0].get());
String[] nameField= NamecoinUtil.extractNamecoinField(txOutScript);
if (nameField==null) {
return null;
}
Text[] nameFieldText= new Text[nameField.length];
for (int i=0;i<nameField.length;i++) {
nameFieldText[i]=new Text(nameField[i]);
}
return new ArrayList<Text>(Arrays.asList(nameFieldText));
}
/**
*
* @param children
* @return
*/
@Override
public String getDisplayString(String[] children) {
return "hclNamecoinExtractField()";
}
}
| java | Apache-2.0 | b2df90b216a6024b3179c3afaa6f2bcfc975784c | 2026-01-05T02:40:55.994732Z | false |
ZuInnoTe/hadoopcryptoledger | https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/hiveudf/src/main/java/org/zuinnote/hadoop/namecoin/hive/udf/NamecoinGetNameOperationUDF.java | hiveudf/src/main/java/org/zuinnote/hadoop/namecoin/hive/udf/NamecoinGetNameOperationUDF.java | /**
* Copyright 2017 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.zuinnote.hadoop.namecoin.hive.udf;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.zuinnote.hadoop.namecoin.format.common.NamecoinUtil;
public class NamecoinGetNameOperationUDF extends UDF {
private static final Log LOG = LogFactory.getLog(NamecoinGetNameOperationUDF.class.getName());
/**
* Analyzes txOutScript (ScriptPubKey) of an output of a Namecoin Transaction to determine the name operation (if any)
*
* @param input BytesWritable containing a txOutScript of a Namecoin Transaction
* @return Text containing the type of name operation, cf. NamecoinUtil.getNameOperation
*/
public Text evaluate(BytesWritable input) {
String nameOperation= NamecoinUtil.getNameOperation(input.copyBytes());
return new Text(nameOperation);
}
}
| java | Apache-2.0 | b2df90b216a6024b3179c3afaa6f2bcfc975784c | 2026-01-05T02:40:55.994732Z | false |
ZuInnoTe/hadoopcryptoledger | https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/hiveudf/src/main/java/org/zuinnote/hadoop/bitcoin/hive/udf/BitcoinTransactionHashSegwitUDF.java | hiveudf/src/main/java/org/zuinnote/hadoop/bitcoin/hive/udf/BitcoinTransactionHashSegwitUDF.java | /**
* Copyright 2016 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.zuinnote.hadoop.bitcoin.hive.udf;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hive.common.type.HiveDecimal;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StructField;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveDecimalObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.WritableBinaryObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.WritableByteObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.WritableIntObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.WritableLongObjectInspector;
import org.apache.hadoop.io.BytesWritable;
import org.zuinnote.hadoop.bitcoin.format.common.BitcoinTransaction;
import org.zuinnote.hadoop.bitcoin.format.common.BitcoinTransactionInput;
import org.zuinnote.hadoop.bitcoin.format.common.BitcoinTransactionOutput;
import org.zuinnote.hadoop.bitcoin.format.common.BitcoinScriptWitness;
import org.zuinnote.hadoop.bitcoin.format.common.BitcoinScriptWitnessItem;
import org.zuinnote.hadoop.bitcoin.format.common.BitcoinUtil;
import org.zuinnote.hadoop.bitcoin.hive.datatypes.HiveBitcoinTransaction;
/*
* Generic UDF to calculate the hash value of a transaction (wtxid). It cannot be used to create a graph of transactions
*
*
*/
@Description(
name = "hclBitcoinTransactionHashSegwit",
value = "_FUNC_(Struct<BitcoinTransaction>) - calculates the hash of a BitcoinTransaction with segwit (wtxid) and returns it as byte array",
extended = "Example:\n" +
" > SELECT hclBitcoinTransactionHashSegwit(transactions[0]) FROM BitcoinBlockChain LIMIT 1;\n")
public class BitcoinTransactionHashSegwitUDF extends GenericUDF {
private static final Log LOG = LogFactory.getLog(BitcoinTransactionHashUDF.class.getName());
private StructObjectInspector soi;
private WritableByteObjectInspector wbyoi;
private WritableBinaryObjectInspector wboi;
private WritableIntObjectInspector wioi;
private WritableLongObjectInspector wloi;
private HiveDecimalObjectInspector hdoi;
/**
* Returns the display representation of the function
*
* @param arg0 arguments
*
*/
@Override
public String getDisplayString(String[] arg0) {
return "hclBitcoinTransactionHashSegwit()";
}
/**
*
* Initialize HiveUDF and create object inspectors. It requires that the argument length is = 1 and that the ObjectInspector of arguments[0] is of type StructObjectInspector
*
* @param arguments array of length 1 containing one StructObjectInspector
*
* @return ObjectInspector that is able to parse the result of the evaluate method of the UDF (BinaryWritable)
*
* @throws org.apache.hadoop.hive.ql.exec.UDFArgumentException in case the first argument is not of StructObjectInspector
* @throws org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException in case the number of arguments is != 1
*
*/
@Override
public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException {
if (arguments==null) {
throw new UDFArgumentLengthException("bitcoinTransactionHash only takes one argument: Struct<BitcoinTransaction> ");
}
if (arguments.length != 1) {
throw new UDFArgumentLengthException("bitcoinTransactionHash only takes one argument: Struct<BitcoinTransaction> ");
}
if (!(arguments[0] instanceof StructObjectInspector)) {
throw new UDFArgumentException("first argument must be a Struct containing a BitcoinTransaction");
}
this.soi = (StructObjectInspector)arguments[0];
// these are only used for bitcointransaction structs exported to other formats, such as ORC
this.wboi = PrimitiveObjectInspectorFactory.writableBinaryObjectInspector;
this.wioi = PrimitiveObjectInspectorFactory.writableIntObjectInspector;
this.wloi = PrimitiveObjectInspectorFactory.writableLongObjectInspector;
this.wbyoi = PrimitiveObjectInspectorFactory.writableByteObjectInspector;
this.hdoi = PrimitiveObjectInspectorFactory.javaHiveDecimalObjectInspector;
// the UDF returns the hash value of a BitcoinTransaction as byte array
return PrimitiveObjectInspectorFactory.writableBinaryObjectInspector;
}
/**
* This method evaluates a given Object (of type BitcoinTransaction) or a struct which has all necessary fields corresponding to a BitcoinTransaction. The first case occurs, if the UDF evaluates data represented in a table provided by the HiveSerde as part of the hadoocryptoledger library. The second case occurs, if BitcoinTransaction data has been imported in a table in another format, such as ORC or Parquet.
*
* @param arguments array of length 1 containing one object of type BitcoinTransaction or a Struct representing a BitcoinTransaction
*
* @return BytesWritable containing a byte array with the double hash of the BitcoinTransaction
*
* @throws org.apache.hadoop.hive.ql.metadata.HiveException in case an itnernal HiveError occurred
*/
@Override
public Object evaluate(DeferredObject[] arguments) throws HiveException {
if ((arguments==null) || (arguments.length!=1)) {
return null;
}
BitcoinTransaction bitcoinTransaction;
if (arguments[0].get() instanceof HiveBitcoinTransaction) { // this happens if the table is in the original file format
bitcoinTransaction = BitcoinUDFUtil.convertToBitcoinTransaction((HiveBitcoinTransaction)arguments[0].get());
} else { // this happens if the table has been imported into a more optimized analytics format, such as ORC. However, usually we expect that the first case will be used mostly (the hash is generated during extraction from the input format)
// check if all bitcointransaction fields are available <struct<version:int,incounter:binary,outcounter:binary,listofinputs:array<struct<prevtransactionhash:binary,previoustxoutindex:bigint,txinscriptlength:binary,txinscript:binary,seqno:bigint>>,listofoutputs:array<struct<value:bigint,txoutscriptlength:binary,txoutscript:binary>>,locktime:int>
Object originalObject=arguments[0].get();
StructField versionSF=soi.getStructFieldRef("version");
StructField markerSF=soi.getStructFieldRef("marker");
StructField flagSF=soi.getStructFieldRef("flag");
StructField incounterSF=soi.getStructFieldRef("incounter");
StructField outcounterSF=soi.getStructFieldRef("outcounter");
StructField listofinputsSF=soi.getStructFieldRef("listofinputs");
StructField listofoutputsSF=soi.getStructFieldRef("listofoutputs");
StructField listofscriptwitnessitemSF=soi.getStructFieldRef("listofscriptwitnessitem");
StructField locktimeSF=soi.getStructFieldRef("locktime");
boolean inputsNull = (incounterSF==null) || (listofinputsSF==null);
boolean outputsNull = (outcounterSF==null) || (listofoutputsSF==null);
boolean otherAttributeNull = (versionSF==null) || (locktimeSF==null);
boolean segwitInformationNull = (markerSF==null) || (flagSF==null) || (listofscriptwitnessitemSF==null);
if (inputsNull || outputsNull || otherAttributeNull || segwitInformationNull) {
LOG.info("Structure does not correspond to BitcoinTransaction");
return null;
}
int version = wioi.get(soi.getStructFieldData(originalObject,versionSF));
byte marker = wbyoi.get(soi.getStructFieldData(originalObject, markerSF));
byte flag = wbyoi.get(soi.getStructFieldData(originalObject, flagSF));
byte[] inCounter = wboi.getPrimitiveJavaObject(soi.getStructFieldData(originalObject,incounterSF));
byte[] outCounter = wboi.getPrimitiveJavaObject(soi.getStructFieldData(originalObject,outcounterSF));
int locktime = wioi.get(soi.getStructFieldData(originalObject,locktimeSF));
Object listofinputsObject = soi.getStructFieldData(originalObject,listofinputsSF);
ListObjectInspector loiInputs=(ListObjectInspector)listofinputsSF.getFieldObjectInspector();
List<BitcoinTransactionInput> listOfInputsArray = readListOfInputsFromTable(loiInputs,listofinputsObject);
Object listofoutputsObject = soi.getStructFieldData(originalObject,listofoutputsSF);
ListObjectInspector loiOutputs=(ListObjectInspector)listofoutputsSF.getFieldObjectInspector();
List<BitcoinTransactionOutput> listOfOutputsArray = readListOfOutputsFromTable(loiOutputs,listofoutputsObject);
Object listofscriptwitnessitemObject = soi.getStructFieldData(originalObject,listofscriptwitnessitemSF);
ListObjectInspector loiScriptWitnessItem=(ListObjectInspector)listofscriptwitnessitemSF.getFieldObjectInspector();
List<BitcoinScriptWitnessItem> listOfScriptWitnessitemArray = readListOfBitcoinScriptWitnessFromTable(loiScriptWitnessItem,listofscriptwitnessitemObject);
bitcoinTransaction = new BitcoinTransaction(marker, flag, version,inCounter,listOfInputsArray,outCounter,listOfOutputsArray,listOfScriptWitnessitemArray,locktime);
}
byte[] transactionHash=null;
try {
transactionHash = BitcoinUtil.getTransactionHashSegwit(bitcoinTransaction);
} catch (IOException ioe) {
LOG.error(ioe);
throw new HiveException(ioe.toString());
}
return new BytesWritable(transactionHash);
}
/**
* Read list of Bitcoin transaction inputs from a table in Hive in any format (e.g. ORC, Parquet)
*
* @param loi ObjectInspector for processing the Object containing a list
* @param listOfInputsObject object containing the list of inputs to a Bitcoin Transaction
*
* @return a list of BitcoinTransactionInputs
*
*/
private List<BitcoinTransactionInput> readListOfInputsFromTable(ListObjectInspector loi, Object listOfInputsObject) {
int listLength=loi.getListLength(listOfInputsObject);
List<BitcoinTransactionInput> result = new ArrayList<>(listLength);
StructObjectInspector listOfInputsElementObjectInspector = (StructObjectInspector)loi.getListElementObjectInspector();
for (int i=0;i<listLength;i++) {
Object currentlistofinputsObject = loi.getListElement(listOfInputsObject,i);
StructField prevtransactionhashSF = listOfInputsElementObjectInspector.getStructFieldRef("prevtransactionhash");
StructField previoustxoutindexSF = listOfInputsElementObjectInspector.getStructFieldRef("previoustxoutindex");
StructField txinscriptlengthSF = listOfInputsElementObjectInspector.getStructFieldRef("txinscriptlength");
StructField txinscriptSF = listOfInputsElementObjectInspector.getStructFieldRef("txinscript");
StructField seqnoSF = listOfInputsElementObjectInspector.getStructFieldRef("seqno");
boolean prevFieldsNull = (prevtransactionhashSF==null) || (previoustxoutindexSF==null);
boolean inFieldsNull = (txinscriptlengthSF==null) || (txinscriptSF==null);
boolean otherAttribNull = seqnoSF==null;
if (prevFieldsNull || inFieldsNull || otherAttribNull) {
LOG.warn("Invalid BitcoinTransactionInput detected at position "+i);
return new ArrayList<>();
}
byte[] currentPrevTransactionHash = wboi.getPrimitiveJavaObject(listOfInputsElementObjectInspector.getStructFieldData(currentlistofinputsObject,prevtransactionhashSF));
long currentPreviousTxOutIndex = wloi.get(listOfInputsElementObjectInspector.getStructFieldData(currentlistofinputsObject,previoustxoutindexSF));
byte[] currentTxInScriptLength= wboi.getPrimitiveJavaObject(listOfInputsElementObjectInspector.getStructFieldData(currentlistofinputsObject,txinscriptlengthSF));
byte[] currentTxInScript= wboi.getPrimitiveJavaObject(listOfInputsElementObjectInspector.getStructFieldData(currentlistofinputsObject,txinscriptSF));
long currentSeqNo = wloi.get(listOfInputsElementObjectInspector.getStructFieldData(currentlistofinputsObject,seqnoSF));
BitcoinTransactionInput currentBitcoinTransactionInput = new BitcoinTransactionInput(currentPrevTransactionHash,currentPreviousTxOutIndex,currentTxInScriptLength,currentTxInScript,currentSeqNo);
result.add(currentBitcoinTransactionInput);
}
return result;
}
/**
* Read list of Bitcoin transaction outputs from a table in Hive in any format (e.g. ORC, Parquet)
*
* @param loi ObjectInspector for processing the Object containing a list
* @param listOfOutputsObject object containing the list of outputs to a Bitcoin Transaction
*
* @return a list of BitcoinTransactionOutputs
*
*/
private List<BitcoinTransactionOutput> readListOfOutputsFromTable(ListObjectInspector loi, Object listOfOutputsObject) {
int listLength=loi.getListLength(listOfOutputsObject);
List<BitcoinTransactionOutput> result=new ArrayList<>(listLength);
StructObjectInspector listOfOutputsElementObjectInspector = (StructObjectInspector)loi.getListElementObjectInspector();
for (int i=0;i<listLength;i++) {
Object currentListOfOutputsObject = loi.getListElement(listOfOutputsObject,i);
StructField valueSF = listOfOutputsElementObjectInspector.getStructFieldRef("value");
StructField txoutscriptlengthSF = listOfOutputsElementObjectInspector.getStructFieldRef("txoutscriptlength");
StructField txoutscriptSF = listOfOutputsElementObjectInspector.getStructFieldRef("txoutscript");
if ((valueSF==null) || (txoutscriptlengthSF==null) || (txoutscriptSF==null)) {
LOG.warn("Invalid BitcoinTransactionOutput detected at position "+i);
return new ArrayList<>();
}
HiveDecimal currentValue=hdoi.getPrimitiveJavaObject(listOfOutputsElementObjectInspector.getStructFieldData(currentListOfOutputsObject,valueSF));
byte[] currentTxOutScriptLength=wboi.getPrimitiveJavaObject(listOfOutputsElementObjectInspector.getStructFieldData(currentListOfOutputsObject,txoutscriptlengthSF));
byte[] currentTxOutScript=wboi.getPrimitiveJavaObject(listOfOutputsElementObjectInspector.getStructFieldData(currentListOfOutputsObject,txoutscriptSF));
BitcoinTransactionOutput currentBitcoinTransactionOutput = new BitcoinTransactionOutput(currentValue.bigDecimalValue().toBigIntegerExact(),currentTxOutScriptLength,currentTxOutScript);
result.add(currentBitcoinTransactionOutput);
}
return result;
}
/**
* Read list of Bitcoin ScriptWitness items from a table in Hive in any format (e.g. ORC, Parquet)
*
* @param loi ObjectInspector for processing the Object containing a list
* @param listOfScriptWitnessItemObject object containing the list of scriptwitnessitems of a Bitcoin Transaction
*
* @return a list of BitcoinScriptWitnessItem
*
*/
private List<BitcoinScriptWitnessItem> readListOfBitcoinScriptWitnessFromTable(ListObjectInspector loi, Object listOfScriptWitnessItemObject) {
int listLength=loi.getListLength(listOfScriptWitnessItemObject);
List<BitcoinScriptWitnessItem> result = new ArrayList<>(listLength);
StructObjectInspector listOfScriptwitnessItemElementObjectInspector = (StructObjectInspector)loi.getListElementObjectInspector();
for (int i=0;i<listLength;i++) {
Object currentlistofscriptwitnessitemObject = loi.getListElement(listOfScriptWitnessItemObject,i);
StructField stackitemcounterSF = listOfScriptwitnessItemElementObjectInspector.getStructFieldRef("stackitemcounter");
StructField scriptwitnesslistSF = listOfScriptwitnessItemElementObjectInspector.getStructFieldRef("scriptwitnesslist");
boolean scriptwitnessitemNull = (stackitemcounterSF==null) || (scriptwitnesslistSF==null) ;
if (scriptwitnessitemNull) {
LOG.warn("Invalid BitcoinScriptWitnessItem detected at position "+i);
return new ArrayList<>();
}
byte[] stackItemCounter = wboi.getPrimitiveJavaObject(listOfScriptwitnessItemElementObjectInspector.getStructFieldData(currentlistofscriptwitnessitemObject,stackitemcounterSF));
Object listofscriptwitnessObject = soi.getStructFieldData(currentlistofscriptwitnessitemObject,scriptwitnesslistSF);
ListObjectInspector loiScriptWitness=(ListObjectInspector)scriptwitnesslistSF.getFieldObjectInspector();
StructObjectInspector listOfScriptwitnessElementObjectInspector = (StructObjectInspector)loiScriptWitness.getListElementObjectInspector();
int listWitnessLength = loiScriptWitness.getListLength(listofscriptwitnessObject);
List<BitcoinScriptWitness> currentScriptWitnessList = new ArrayList<>(listWitnessLength);
for (int j=0;j<listWitnessLength;j++) {
Object currentlistofscriptwitnessObject = loi.getListElement(listofscriptwitnessObject,j);
StructField witnessscriptlengthSF = listOfScriptwitnessElementObjectInspector.getStructFieldRef("witnessscriptlength");
StructField witnessscriptSF = listOfScriptwitnessElementObjectInspector.getStructFieldRef("witnessscript");
boolean scriptwitnessNull = (witnessscriptlengthSF==null) || (witnessscriptSF==null);
if (scriptwitnessNull) {
LOG.warn("Invalid BitcoinScriptWitness detected at position "+j+ "for BitcoinScriptWitnessItem "+i);
return new ArrayList<>();
}
byte[] scriptWitnessLength = wboi.getPrimitiveJavaObject(listOfScriptwitnessElementObjectInspector.getStructFieldData(currentlistofscriptwitnessObject,witnessscriptlengthSF));
byte[] scriptWitness = wboi.getPrimitiveJavaObject(listOfScriptwitnessElementObjectInspector.getStructFieldData(currentlistofscriptwitnessObject,witnessscriptSF));
currentScriptWitnessList.add(new BitcoinScriptWitness(scriptWitnessLength,scriptWitness));
}
BitcoinScriptWitnessItem currentBitcoinScriptWitnessItem = new BitcoinScriptWitnessItem(stackItemCounter,currentScriptWitnessList);
result.add(currentBitcoinScriptWitnessItem);
}
return result;
}
} | java | Apache-2.0 | b2df90b216a6024b3179c3afaa6f2bcfc975784c | 2026-01-05T02:40:55.994732Z | false |
ZuInnoTe/hadoopcryptoledger | https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/hiveudf/src/main/java/org/zuinnote/hadoop/bitcoin/hive/udf/BitcoinUDFUtil.java | hiveudf/src/main/java/org/zuinnote/hadoop/bitcoin/hive/udf/BitcoinUDFUtil.java | /**
* Copyright 2018 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.zuinnote.hadoop.bitcoin.hive.udf;
import java.util.ArrayList;
import java.util.List;
import org.zuinnote.hadoop.bitcoin.format.common.BitcoinTransaction;
import org.zuinnote.hadoop.bitcoin.format.common.BitcoinTransactionOutput;
import org.zuinnote.hadoop.bitcoin.hive.datatypes.HiveBitcoinTransaction;
import org.zuinnote.hadoop.bitcoin.hive.datatypes.HiveBitcoinTransactionOutput;
/**
*
*
*/
public class BitcoinUDFUtil {
/***
* Convert HiveBitcoinTransaction to BitcoinTransaction (e.g. to get HashValue)
*
* @param transaction HiveBitcoinTransaction
* @return transaction in BitcoinTransaction format
*/
public static BitcoinTransaction convertToBitcoinTransaction(HiveBitcoinTransaction transaction) {
List<BitcoinTransactionOutput> newTransactionsOutputList = new ArrayList<>();
for (int j = 0; j < transaction.getListOfOutputs().size(); j++) {
HiveBitcoinTransactionOutput currentOutput = transaction.getListOfOutputs().get(j);
newTransactionsOutputList.add(new BitcoinTransactionOutput(currentOutput.getValue().bigDecimalValue().toBigIntegerExact(),
currentOutput.getTxOutScriptLength(), currentOutput.getTxOutScript()));
}
BitcoinTransaction result = new BitcoinTransaction(transaction.getMarker(),transaction.getFlag(),transaction.getVersion(), transaction.getInCounter(), transaction.getListOfInputs(), transaction.getOutCounter(), newTransactionsOutputList, transaction.getBitcoinScriptWitness(), transaction.getLockTime());
return result;
}
}
| java | Apache-2.0 | b2df90b216a6024b3179c3afaa6f2bcfc975784c | 2026-01-05T02:40:55.994732Z | false |
ZuInnoTe/hadoopcryptoledger | https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/hiveudf/src/main/java/org/zuinnote/hadoop/bitcoin/hive/udf/BitcoinTransactionHashUDF.java | hiveudf/src/main/java/org/zuinnote/hadoop/bitcoin/hive/udf/BitcoinTransactionHashUDF.java | /**
* Copyright 2016 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.zuinnote.hadoop.bitcoin.hive.udf;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.common.type.HiveDecimal;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveDecimalObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.WritableBinaryObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.WritableIntObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.WritableLongObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StructField;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.zuinnote.hadoop.bitcoin.format.common.*;
import org.zuinnote.hadoop.bitcoin.hive.datatypes.HiveBitcoinTransaction;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
/*
* Generic UDF to calculate the hash value of a transaction (txid). It can be used to create a graph of transactions (cf. https://en.bitcoin.it/wiki/Transaction#general_format_.28inside_a_block.29_of_each_input_of_a_transaction_-_Txin)
*
*
*/
@Description(
name = "hclBitcoinTransactionHash",
value = "_FUNC_(Struct<BitcoinTransaction>) - calculates the hash of a BitcoinTransaction (txid) and returns it as byte array",
extended = "Example:\n" +
" > SELECT hclBitcoinTransactionHash(transactions[0]) FROM BitcoinBlockChain LIMIT 1;\n")
public class BitcoinTransactionHashUDF extends GenericUDF {
private static final Log LOG = LogFactory.getLog(BitcoinTransactionHashUDF.class.getName());
private StructObjectInspector soi;
private WritableBinaryObjectInspector wboi;
private WritableIntObjectInspector wioi;
private WritableLongObjectInspector wloi;
private HiveDecimalObjectInspector hdoi;
/**
* Returns the display representation of the function
*
* @param arg0 arguments
*
*/
@Override
public String getDisplayString(String[] arg0) {
return "hclBitcoinTransactionHash()";
}
/**
*
* Initialize HiveUDF and create object inspectors. It requires that the argument length is = 1 and that the ObjectInspector of arguments[0] is of type StructObjectInspector
*
* @param arguments array of length 1 containing one StructObjectInspector
*
* @return ObjectInspector that is able to parse the result of the evaluate method of the UDF (BinaryWritable)
*
* @throws org.apache.hadoop.hive.ql.exec.UDFArgumentException in case the first argument is not of StructObjectInspector
* @throws org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException in case the number of arguments is != 1
*
*/
@Override
public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException {
if (arguments==null) {
throw new UDFArgumentLengthException("bitcoinTransactionHash only takes one argument: Struct<BitcoinTransaction> ");
}
if (arguments.length != 1) {
throw new UDFArgumentLengthException("bitcoinTransactionHash only takes one argument: Struct<BitcoinTransaction> ");
}
if (!(arguments[0] instanceof StructObjectInspector)) {
throw new UDFArgumentException("first argument must be a Struct containing a BitcoinTransaction");
}
this.soi = (StructObjectInspector)arguments[0];
// these are only used for bitcointransaction structs exported to other formats, such as ORC
this.wboi = PrimitiveObjectInspectorFactory.writableBinaryObjectInspector;
this.wioi = PrimitiveObjectInspectorFactory.writableIntObjectInspector;
this.wloi = PrimitiveObjectInspectorFactory.writableLongObjectInspector;
this.hdoi = PrimitiveObjectInspectorFactory.javaHiveDecimalObjectInspector;
// the UDF returns the hash value of a BitcoinTransaction as byte array
return PrimitiveObjectInspectorFactory.writableBinaryObjectInspector;
}
/**
* This method evaluates a given Object (of type BitcoinTransaction) or a struct which has all necessary fields corresponding to a BitcoinTransaction. The first case occurs, if the UDF evaluates data represented in a table provided by the HiveSerde as part of the hadoocryptoledger library. The second case occurs, if BitcoinTransaction data has been imported in a table in another format, such as ORC or Parquet.
*
* @param arguments array of length 1 containing one object of type BitcoinTransaction or a Struct representing a BitcoinTransaction
*
* @return BytesWritable containing a byte array with the double hash of the BitcoinTransaction
*
* @throws org.apache.hadoop.hive.ql.metadata.HiveException in case an internal HiveError occurred
*/
@Override
public Object evaluate(DeferredObject[] arguments) throws HiveException {
if ((arguments==null) || (arguments.length!=1)) {
return null;
}
BitcoinTransaction bitcoinTransaction;
if (arguments[0].get() instanceof HiveBitcoinTransaction) { // this happens if the table is in the original file format
bitcoinTransaction = BitcoinUDFUtil.convertToBitcoinTransaction((HiveBitcoinTransaction)arguments[0].get());
} else { // this happens if the table has been imported into a more optimized analytics format, such as ORC. However, usually we expect that the first case will be used mostly (the hash is generated during extraction from the input format)
// check if all bitcointransaction fields are available <struct<version:int,incounter:binary,outcounter:binary,listofinputs:array<struct<prevtransactionhash:binary,previoustxoutindex:bigint,txinscriptlength:binary,txinscript:binary,seqno:bigint>>,listofoutputs:array<struct<value:bigint,txoutscriptlength:binary,txoutscript:binary>>,locktime:int>
Object originalObject=arguments[0].get();
StructField versionSF=soi.getStructFieldRef("version");
StructField incounterSF=soi.getStructFieldRef("incounter");
StructField outcounterSF=soi.getStructFieldRef("outcounter");
StructField listofinputsSF=soi.getStructFieldRef("listofinputs");
StructField listofoutputsSF=soi.getStructFieldRef("listofoutputs");
StructField locktimeSF=soi.getStructFieldRef("locktime");
boolean inputsNull = (incounterSF==null) || (listofinputsSF==null);
boolean outputsNull = (outcounterSF==null) || (listofoutputsSF==null);
boolean otherAttributeNull = (versionSF==null) || (locktimeSF==null);
if (inputsNull || outputsNull || otherAttributeNull) {
LOG.warn("Structure does not correspond to BitcoinTransaction");
return null;
}
int version = wioi.get(soi.getStructFieldData(originalObject,versionSF));
byte[] inCounter = wboi.getPrimitiveJavaObject(soi.getStructFieldData(originalObject,incounterSF));
byte[] outCounter = wboi.getPrimitiveJavaObject(soi.getStructFieldData(originalObject,outcounterSF));
int locktime = wioi.get(soi.getStructFieldData(originalObject,locktimeSF));
Object listofinputsObject = soi.getStructFieldData(originalObject,listofinputsSF);
ListObjectInspector loiInputs=(ListObjectInspector)listofinputsSF.getFieldObjectInspector();
List<BitcoinTransactionInput> listOfInputsArray = readListOfInputsFromTable(loiInputs,listofinputsObject);
Object listofoutputsObject = soi.getStructFieldData(originalObject,listofoutputsSF);
ListObjectInspector loiOutputs=(ListObjectInspector)listofoutputsSF.getFieldObjectInspector();
List<BitcoinTransactionOutput> listOfOutputsArray = readListOfOutputsFromTable(loiOutputs,listofoutputsObject);
bitcoinTransaction = new BitcoinTransaction(version,inCounter,listOfInputsArray,outCounter,listOfOutputsArray,locktime);
}
byte[] transactionHash=null;
try {
transactionHash = BitcoinUtil.getTransactionHash(bitcoinTransaction);
} catch (IOException ioe) {
LOG.error(ioe);
throw new HiveException(ioe.toString());
}
return new BytesWritable(transactionHash);
}
/**
* Read list of Bitcoin transaction inputs from a table in Hive in any format (e.g. ORC, Parquet)
*
* @param loi ObjectInspector for processing the Object containing a list
* @param listOfInputsObject object containing the list of inputs to a Bitcoin Transaction
*
* @return a list of BitcoinTransactionInputs
*
*/
private List<BitcoinTransactionInput> readListOfInputsFromTable(ListObjectInspector loi, Object listOfInputsObject) {
int listLength=loi.getListLength(listOfInputsObject);
List<BitcoinTransactionInput> result = new ArrayList<>(listLength);
StructObjectInspector listOfInputsElementObjectInspector = (StructObjectInspector)loi.getListElementObjectInspector();
for (int i=0;i<listLength;i++) {
Object currentlistofinputsObject = loi.getListElement(listOfInputsObject,i);
StructField prevtransactionhashSF = listOfInputsElementObjectInspector.getStructFieldRef("prevtransactionhash");
StructField previoustxoutindexSF = listOfInputsElementObjectInspector.getStructFieldRef("previoustxoutindex");
StructField txinscriptlengthSF = listOfInputsElementObjectInspector.getStructFieldRef("txinscriptlength");
StructField txinscriptSF = listOfInputsElementObjectInspector.getStructFieldRef("txinscript");
StructField seqnoSF = listOfInputsElementObjectInspector.getStructFieldRef("seqno");
boolean prevFieldsNull = (prevtransactionhashSF==null) || (previoustxoutindexSF==null);
boolean inFieldsNull = (txinscriptlengthSF==null) || (txinscriptSF==null);
boolean otherAttribNull = seqnoSF==null;
if (prevFieldsNull || inFieldsNull || otherAttribNull) {
LOG.warn("Invalid BitcoinTransactionInput detected at position "+i);
return new ArrayList<>();
}
byte[] currentPrevTransactionHash = wboi.getPrimitiveJavaObject(listOfInputsElementObjectInspector.getStructFieldData(currentlistofinputsObject,prevtransactionhashSF));
long currentPreviousTxOutIndex = wloi.get(listOfInputsElementObjectInspector.getStructFieldData(currentlistofinputsObject,previoustxoutindexSF));
byte[] currentTxInScriptLength= wboi.getPrimitiveJavaObject(listOfInputsElementObjectInspector.getStructFieldData(currentlistofinputsObject,txinscriptlengthSF));
byte[] currentTxInScript= wboi.getPrimitiveJavaObject(listOfInputsElementObjectInspector.getStructFieldData(currentlistofinputsObject,txinscriptSF));
long currentSeqNo = wloi.get(listOfInputsElementObjectInspector.getStructFieldData(currentlistofinputsObject,seqnoSF));
BitcoinTransactionInput currentBitcoinTransactionInput = new BitcoinTransactionInput(currentPrevTransactionHash,currentPreviousTxOutIndex,currentTxInScriptLength,currentTxInScript,currentSeqNo);
result.add(currentBitcoinTransactionInput);
}
return result;
}
/**
* Read list of Bitcoin transaction outputs from a table in Hive in any format (e.g. ORC, Parquet)
*
* @param loi ObjectInspector for processing the Object containing a list
* @param listOfOutputsObject object containing the list of outputs to a Bitcoin Transaction
*
* @return a list of BitcoinTransactionOutputs
*
*/
private List<BitcoinTransactionOutput> readListOfOutputsFromTable(ListObjectInspector loi, Object listOfOutputsObject) {
int listLength=loi.getListLength(listOfOutputsObject);
List<BitcoinTransactionOutput> result=new ArrayList<>(listLength);
StructObjectInspector listOfOutputsElementObjectInspector = (StructObjectInspector)loi.getListElementObjectInspector();
for (int i=0;i<listLength;i++) {
Object currentListOfOutputsObject = loi.getListElement(listOfOutputsObject,i);
StructField valueSF = listOfOutputsElementObjectInspector.getStructFieldRef("value");
StructField txoutscriptlengthSF = listOfOutputsElementObjectInspector.getStructFieldRef("txoutscriptlength");
StructField txoutscriptSF = listOfOutputsElementObjectInspector.getStructFieldRef("txoutscript");
if ((valueSF==null) || (txoutscriptlengthSF==null) || (txoutscriptSF==null)) {
LOG.warn("Invalid BitcoinTransactionOutput detected at position "+i);
return new ArrayList<>();
}
HiveDecimal currentValue=hdoi.getPrimitiveJavaObject(listOfOutputsElementObjectInspector.getStructFieldData(currentListOfOutputsObject,valueSF));
byte[] currentTxOutScriptLength=wboi.getPrimitiveJavaObject(listOfOutputsElementObjectInspector.getStructFieldData(currentListOfOutputsObject,txoutscriptlengthSF));
byte[] currentTxOutScript=wboi.getPrimitiveJavaObject(listOfOutputsElementObjectInspector.getStructFieldData(currentListOfOutputsObject,txoutscriptSF));
BitcoinTransactionOutput currentBitcoinTransactionOutput = new BitcoinTransactionOutput(currentValue.bigDecimalValue().toBigIntegerExact(),currentTxOutScriptLength,currentTxOutScript);
result.add(currentBitcoinTransactionOutput);
}
return result;
}
}
| java | Apache-2.0 | b2df90b216a6024b3179c3afaa6f2bcfc975784c | 2026-01-05T02:40:55.994732Z | false |
ZuInnoTe/hadoopcryptoledger | https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/hiveudf/src/main/java/org/zuinnote/hadoop/bitcoin/hive/udf/BitcoinScriptPaymentPatternAnalyzerUDF.java | hiveudf/src/main/java/org/zuinnote/hadoop/bitcoin/hive/udf/BitcoinScriptPaymentPatternAnalyzerUDF.java | /**
* Copyright 2016 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.zuinnote.hadoop.bitcoin.hive.udf;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import org.zuinnote.hadoop.bitcoin.format.common.*;
/*
* UDF to extract the destination (cf. https://en.bitcoin.it/wiki/Transaction#general_format_.28inside_a_block.29_of_each_input_of_a_transaction_-_Txin)
*
*
*/
@Description(
name = "hclBitcoinScriptPattern",
value = "_FUNC_(BINARY) - extracts information about the destination of a transaction based on txOutScript",
extended = "Example:\n" +
" > SELECT hclBitcoinScriptPattern(expout.txoutscript) FROM (select * from BitcoinBlockchain LATERAL VIEW explode(transactions) exploded_transactions as exptran) transaction_table LATERAL VIEW explode (exptran.listofoutputs) exploded_outputs as expout;\n")
public class BitcoinScriptPaymentPatternAnalyzerUDF extends UDF {
private static final Log LOG = LogFactory.getLog(BitcoinScriptPaymentPatternAnalyzerUDF.class.getName());
/**
** Analyzes txOutScript (ScriptPubKey) of an output of a Bitcoin Transaction to determine the payment destination
*
* @param input BytesWritable containing a txOutScript of a Bitcoin Transaction
*
* @return Text containing the type of the output of the transaction, cf. BitcoinScriptPatternParser of the hadoopcryptoledger inputformat
*
*/
public Text evaluate(BytesWritable input) {
if (input==null) {
LOG.debug("Input is null");
return null;
}
String paymentDestination = BitcoinScriptPatternParser.getPaymentDestination(input.copyBytes());
if (paymentDestination==null) {
LOG.debug("Payment destination is null");
return null;
}
return new Text(paymentDestination);
}
}
| java | Apache-2.0 | b2df90b216a6024b3179c3afaa6f2bcfc975784c | 2026-01-05T02:40:55.994732Z | false |
ZuInnoTe/hadoopcryptoledger | https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/hiveudf/src/main/java/org/zuinnote/hadoop/ethereum/hive/udf/EthereumUDFUtil.java | hiveudf/src/main/java/org/zuinnote/hadoop/ethereum/hive/udf/EthereumUDFUtil.java | /**
* Copyright 2017 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.zuinnote.hadoop.ethereum.hive.udf;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructField;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.zuinnote.hadoop.ethereum.format.common.EthereumTransaction;
import org.zuinnote.hadoop.ethereum.hive.datatypes.HiveEthereumTransaction;
/**
* Utility class for Hive UDFs for Ethereum
*
*/
public class EthereumUDFUtil {
private static final Log LOG = LogFactory.getLog(EthereumUDFUtil.class.getName());
private StructObjectInspector soi;
/**
*
*
* @param soi ObjectInspector provided by Hive UDF
*/
public EthereumUDFUtil(StructObjectInspector soi) {
this.soi = soi;
}
/**
* Create an object of type EthereumTransaction from any HiveTable
*
* @param row Object
* @return EthereumTransaction corresponding to object
*/
public EthereumTransaction getEthereumTransactionFromObject(Object row) {
EthereumTransaction result=null;
if (row instanceof HiveEthereumTransaction) { // this is the case if you use the EthereumBlockSerde
result=EthereumUDFUtil.convertToEthereumTransaction((HiveEthereumTransaction) row);
} else { // this is the case if you have imported the EthereumTransaction in any other Hive supported format, such as ORC or Parquet
StructField nonceSF=soi.getStructFieldRef("nonce");
StructField valueSF=soi.getStructFieldRef("valueRaw");
StructField receiveAddressSF=soi.getStructFieldRef("receiveAddress");
StructField gasPriceSF=soi.getStructFieldRef("gasPriceRaw");
StructField gasLimitSF=soi.getStructFieldRef("gasLimitRaw");
StructField dataSF=soi.getStructFieldRef("data");
StructField sigVSF=soi.getStructFieldRef("sig_v");
StructField sigRSF=soi.getStructFieldRef("sig_r");
StructField sigSSF=soi.getStructFieldRef("sig_s");
boolean baseNull = (nonceSF==null) || (valueSF==null)|| (receiveAddressSF==null);
boolean gasDataNull = (gasPriceSF==null) || (gasLimitSF==null)|| (dataSF==null);
boolean sigNull = (sigVSF==null) || (sigRSF==null)|| (sigSSF==null);
if (baseNull || gasDataNull || sigNull) {
LOG.error("Structure does not correspond to EthereumTransaction. You need the fields nonce, valueRaw, reciveAddress, gasPriceRaw, gasLimitRaw, data, sig_v, sig_r, sig_s");
return null;
}
byte[] nonce = (byte[]) soi.getStructFieldData(row,nonceSF);
byte[] valueRaw = (byte[]) soi.getStructFieldData(row,valueSF);
byte[] receiveAddress = (byte[]) soi.getStructFieldData(row,receiveAddressSF);
byte[] gasPriceRaw =(byte[]) soi.getStructFieldData(row,gasPriceSF);
byte[] gasLimitRaw = (byte[]) soi.getStructFieldData(row,gasLimitSF);
byte[] data = (byte[]) soi.getStructFieldData(row,dataSF);
byte[] sig_v = (byte[]) soi.getStructFieldData(row,sigVSF);
byte[] sig_r = (byte[]) soi.getStructFieldData(row,sigRSF);
byte[] sig_s = (byte[]) soi.getStructFieldData(row,sigSSF);
result=new EthereumTransaction();
result.setNonce(nonce);
result.setValueRaw(valueRaw);
result.setReceiveAddress(receiveAddress);
result.setGasPriceRaw(gasPriceRaw);
result.setGasLimitRaw(gasLimitRaw);
result.setData(data);
result.setSig_v(sig_v);
result.setSig_r(sig_r);
result.setSig_s(sig_s);
}
return result;
}
/**
* Convert HiveEthereumTransaction to Ethereum Transaction
*
* @param transaction in HiveEthereumTransaction format
* @return transaction in EthereumTransactionFormat
*/
public static EthereumTransaction convertToEthereumTransaction(HiveEthereumTransaction transaction) {
EthereumTransaction result = new EthereumTransaction();
// note we set only the raw values, the other ones can be automatically dervied by the EthereumTransaction class if needed. This avoids conversion issues for large numbers
result.setNonce(transaction.getNonce());
result.setValueRaw(transaction.getValueRaw());
result.setReceiveAddress(transaction.getReceiveAddress());
result.setGasPriceRaw(transaction.getGasPriceRaw());
result.setGasLimitRaw(transaction.getGasLimitRaw());
result.setData(transaction.getData());
result.setSig_v(transaction.getSig_v());
result.setSig_r(transaction.getSig_r());
result.setSig_s(transaction.getSig_s());
return result;
}
}
| java | Apache-2.0 | b2df90b216a6024b3179c3afaa6f2bcfc975784c | 2026-01-05T02:40:55.994732Z | false |
ZuInnoTe/hadoopcryptoledger | https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/hiveudf/src/main/java/org/zuinnote/hadoop/ethereum/hive/udf/EthereumGetSendAddressUDF.java | hiveudf/src/main/java/org/zuinnote/hadoop/ethereum/hive/udf/EthereumGetSendAddressUDF.java | /**
* Copyright 2017 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.zuinnote.hadoop.ethereum.hive.udf;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.IntObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.IntWritable;
import org.zuinnote.hadoop.ethereum.format.common.EthereumTransaction;
import org.zuinnote.hadoop.ethereum.format.common.EthereumUtil;
@Description(
name = "hclEthereumGetSendAddress",
value = "_FUNC_(Struct<EthereumTransaction>, INT chainid) - calculates the sendAddress (from) of a EthereumTransaction and returns a byte array",
extended = "Example:\n" +
" > SELECT hclEthereumGetSendAddress(ethereumTransactions[0], 1) FROM EthereumBlockChain LIMIT 1;\n")
public class EthereumGetSendAddressUDF extends GenericUDF {
private static final Log LOG = LogFactory.getLog(EthereumGetSendAddressUDF.class.getName());
private EthereumUDFUtil ethereumUDFUtil;
@Override
public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException {
if (arguments==null) {
throw new UDFArgumentLengthException("ethereumGetSendAddress only takes two arguments: Struct<EthereumTransction>, INT chainId ");
}
if (arguments.length != 2) {
throw new UDFArgumentLengthException("ethereumGetSendAddress only takes two arguments: Struct<EthereumTransction>, INT chainId ");
}
if (!(arguments[0] instanceof StructObjectInspector)) {
throw new UDFArgumentException("first argument must be a Struct containing a EthereumTransction");
}
if (!(arguments[1] instanceof IntObjectInspector)) {
throw new UDFArgumentException("second argument must be an int with the chainId");
}
this.ethereumUDFUtil=new EthereumUDFUtil((StructObjectInspector) arguments[0]);
return PrimitiveObjectInspectorFactory.writableBinaryObjectInspector;
}
@Override
public Object evaluate(DeferredObject[] arguments) throws HiveException {
if ((arguments==null) || (arguments.length!=2)) {
return null;
}
EthereumTransaction eTrans = this.ethereumUDFUtil.getEthereumTransactionFromObject(arguments[0].get());
byte[] sendAddress=EthereumUtil.getSendAddress(eTrans, ((IntWritable)arguments[1].get()).get());
if (sendAddress==null) {
return null;
}
return new BytesWritable(sendAddress);
}
@Override
public String getDisplayString(String[] children) {
return "hclEthereumGetSendAddress()";
}
}
| java | Apache-2.0 | b2df90b216a6024b3179c3afaa6f2bcfc975784c | 2026-01-05T02:40:55.994732Z | false |
ZuInnoTe/hadoopcryptoledger | https://github.com/ZuInnoTe/hadoopcryptoledger/blob/b2df90b216a6024b3179c3afaa6f2bcfc975784c/hiveudf/src/main/java/org/zuinnote/hadoop/ethereum/hive/udf/EthereumGetTransactionHashUDF.java | hiveudf/src/main/java/org/zuinnote/hadoop/ethereum/hive/udf/EthereumGetTransactionHashUDF.java | /**
* Copyright 2017 ZuInnoTe (Jörn Franke) <zuinnote@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.zuinnote.hadoop.ethereum.hive.udf;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF.DeferredObject;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.io.BytesWritable;
import org.zuinnote.hadoop.ethereum.format.common.EthereumTransaction;
import org.zuinnote.hadoop.ethereum.format.common.EthereumUtil;
@Description(
name = "hclEthereumGetTransactionHash",
value = "_FUNC_(Struct<EthereumTransaction>) - calculates the transaction hash of a EthereumTransaction and returns a byte array",
extended = "Example:\n" +
" > SELECT hclEthereumGetTransactionHash(ethereumTransactions[0]) FROM EthereumBlockChain LIMIT 1;\n")
public class EthereumGetTransactionHashUDF extends GenericUDF {
private static final Log LOG = LogFactory.getLog(EthereumGetTransactionHashUDF.class.getName());
private EthereumUDFUtil ethereumUDFUtil;
@Override
public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException {
if (arguments==null) {
throw new UDFArgumentLengthException("ethereumGetTransactionHash only takes one argument: Struct<EthereumTransction> ");
}
if (arguments.length != 1) {
throw new UDFArgumentLengthException("ethereumGetTransactionHash only takes one argument: Struct<EthereumTransction> ");
}
if (!(arguments[0] instanceof StructObjectInspector)) {
throw new UDFArgumentException("first argument must be a Struct containing a EthereumTransction");
}
this.ethereumUDFUtil=new EthereumUDFUtil((StructObjectInspector) arguments[0]);
return PrimitiveObjectInspectorFactory.writableBinaryObjectInspector;
}
@Override
public Object evaluate(DeferredObject[] arguments) throws HiveException {
if ((arguments==null) || (arguments.length!=1)) {
return null;
}
EthereumTransaction eTrans = this.ethereumUDFUtil.getEthereumTransactionFromObject(arguments[0].get());
byte[] transactionHash=EthereumUtil.getTransactionHash(eTrans);
if (transactionHash==null) {
return null;
}
return new BytesWritable(transactionHash);
}
@Override
public String getDisplayString(String[] children) {
return "hclEthereumGetTransactionHash()";
}
}
| java | Apache-2.0 | b2df90b216a6024b3179c3afaa6f2bcfc975784c | 2026-01-05T02:40:55.994732Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.