POJONode.java
package tools.jackson.databind.node;
import java.io.Serial;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.DoubleAccumulator;
import java.util.concurrent.atomic.DoubleAdder;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.concurrent.atomic.LongAdder;
import tools.jackson.core.*;
import tools.jackson.databind.JacksonSerializable;
import tools.jackson.databind.SerializationContext;
import tools.jackson.databind.util.ClassUtil;
/**
* Value node that contains a wrapped POJO, to be serialized as
* a JSON constructed through data mapping (usually done by
* calling {@link tools.jackson.databind.ObjectMapper}).
*/
public class POJONode
extends ValueNode
{
@Serial
private static final long serialVersionUID = 3L;
protected final Object _value;
public POJONode(Object v) { _value = v; }
/*
/**********************************************************************
/* Base class overrides
/**********************************************************************
*/
@Override
protected String _valueDesc() {
return "{POJO of type "+ClassUtil.classNameOf(_value)+"}";
}
@Override
public JsonNodeType getNodeType() {
return JsonNodeType.POJO;
}
@Override
public JsonToken asToken() { return JsonToken.VALUE_EMBEDDED_OBJECT; }
@Override
public boolean isEmbeddedValue() { return true; }
/*
/**********************************************************************
/* Overridden JsonNode methods, scalar access, non-numeric
/**********************************************************************
*/
@Override
protected Boolean _asBoolean()
{
if (_value instanceof Boolean B) {
return B;
}
if (_value == null) {
return Boolean.FALSE;
}
return null;
}
@Override
public boolean asBoolean(boolean defaultValue) {
if (_value instanceof Boolean B) {
return B;
}
// (also covers `null` case)
return defaultValue;
}
@Override
public Optional<Boolean> asBooleanOpt() {
if (_value instanceof Boolean B) {
return B ? OPT_TRUE : OPT_FALSE;
}
// (also covers `null` case)
return Optional.empty();
}
@Override
protected String _asString() {
if (_value instanceof String str) {
return str;
}
// [databind#5583]: Null to coerce into ""
if (_value == null) {
return "";
}
// 21-Mar-2025, tatu: [databind#5034] Should we consider RawValue too?
// (for now, won't)
// (also covers `null` case)
return null;
}
@Override
public String asString(String defaultValue) {
if (_value instanceof String str) {
return str;
}
// (also covers `null` case)
return defaultValue;
}
@Override
public Optional<String> asStringOpt() {
if (_value instanceof String str) {
return Optional.of(str);
}
// (also covers `null` case)
return Optional.empty();
}
/**
* As it is possible that some implementations embed byte[] as POJONode
* (despite optimal being {@link BinaryNode}), let's add support for exposing
* binary data here too.
*/
@Override
public byte[] binaryValue()
{
if (_value instanceof byte[] byteArray) {
return byteArray;
}
return super.binaryValue();
}
/*
/**********************************************************************
/* Overridden JsonNode methods, scalar access, numeric
/**********************************************************************
*/
// `shortValue()` (etc) fine as defaults (fail); but need to override `asShort()`
@Override
public short asShort() {
// First, `null` same as `NullNode`
if (_value == null) {
return 0;
}
// Next, check if the value is NOT a Number
if (!(_value instanceof Number)) {
// report coercion fail
super.asShort();
}
// Then, extract from Number
Long L = _extractAsLong();
if (L == null || L < Short.MIN_VALUE || L > Short.MAX_VALUE) {
// report range fail
_reportShortConversionRangeFail("asShort()");
}
return L.shortValue();
}
@Override
public short asShort(short defaultValue) {
// First, `null` same as `NullNode`
if (_value == null) {
return defaultValue;
}
// Next, check if the value is NOT a Number
if (!(_value instanceof Number)) {
return defaultValue;
}
// Then, extract from Number
Long L = _extractAsLong();
if (L == null || L < Short.MIN_VALUE || L > Short.MAX_VALUE) {
return defaultValue;
}
return L.shortValue();
}
@Override
public Optional<Short> asShortOpt() {
// First, `null` same as `NullNode`
if (_value == null) {
return Optional.empty();
}
// Next, check if the value is NOT a Number
if (!(_value instanceof Number)) {
return Optional.empty();
}
// Then, extract from Number
Long L = _extractAsLong();
if (L == null || L < Short.MIN_VALUE || L > Short.MAX_VALUE) {
return Optional.empty();
}
return Optional.of(L.shortValue());
}
// `intValue()` (etc) fine as defaults (fail); but need to override `asInt()`
@Override
public int asInt() {
// First, `null` same as `NullNode`
if (_value == null) {
return 0;
}
// Next, check if the value is NOT a Number
if (!(_value instanceof Number)) {
// report coercion fail
super.asInt();
}
// Then, extract from Number
Long L = _extractAsLong();
if (L == null || L < Integer.MIN_VALUE || L > Integer.MAX_VALUE) {
// report range fail
_reportIntConversionRangeFail("asInt()");
}
return L.intValue();
}
@Override
public int asInt(int defaultValue) {
// Next, check if the value is NOT a Number
// (including `null`)
if (!(_value instanceof Number)) {
return defaultValue;
}
// Then, extract from Number
Long L = _extractAsLong();
if (L == null || L < Integer.MIN_VALUE || L > Integer.MAX_VALUE) {
return defaultValue;
}
return L.intValue();
}
@Override
public OptionalInt asIntOpt() {
// Next, check if the value is NOT a Number
// (including `null`)
if (!(_value instanceof Number)) {
return OptionalInt.empty();
}
// Then, extract from Number
Long L = _extractAsLong();
if (L == null || L < Integer.MIN_VALUE || L > Integer.MAX_VALUE) {
return OptionalInt.empty();
}
return OptionalInt.of(L.intValue());
}
// `longValue()` (etc) fine as defaults (fail); but need to override `asLong()`
@Override
public long asLong() {
// First, `null` same as `NullNode`
if (_value == null) {
return 0L;
}
// Next, check if the value is NOT a Number
if (!(_value instanceof Number)) {
// report coercion fail
super.asLong();
}
// Then, extract from Number
Long L = _extractAsLong();
if (L == null) {
// report range fail
_reportLongConversionRangeFail("asLong()");
}
return L;
}
@Override
public long asLong(long defaultValue) {
// If not a Number (including `null`), return default
if (!(_value instanceof Number)) {
return defaultValue;
}
// Then, extract from Number
Long L = _extractAsLong();
if (L == null) {
return defaultValue;
}
return L;
}
@Override
public OptionalLong asLongOpt() {
// If not a Number (including `null`), return empty
if (!(_value instanceof Number)) {
return OptionalLong.empty();
}
// Then, extract from Number
Long L = _extractAsLong();
if (L == null) {
return OptionalLong.empty();
}
return OptionalLong.of(L);
}
// `bigIntegerValue()` (etc) fine as defaults (fail); but need to override `asBigInteger()`
@Override
public BigInteger asBigInteger() {
// First, `null` same as `NullNode`
if (_value == null) {
return BigInteger.ZERO;
}
// Next, check if the value is NOT a Number
if (!(_value instanceof Number)) {
// report coercion fail
super.asBigInteger();
}
// Then, extract from Number: `_extractAsBigInteger()` returns `null` for
// NaN and infinities; fail for those as `DoubleNode` does
BigInteger big = _extractAsBigInteger();
if (big == null) {
return _reportBigIntegerConversionNaNFail("asBigInteger()");
}
return big;
}
@Override
public BigInteger asBigInteger(BigInteger defaultValue) {
// If not a Number (including `null`), or scale out of range, return default
if (!(_value instanceof Number) || !_bigIntegerScaleInRange()) {
return defaultValue;
}
// Then, extract from Number; default for NaN and infinities
BigInteger big = _extractAsBigInteger();
return (big == null) ? defaultValue : big;
}
@Override
public Optional<BigInteger> asBigIntegerOpt() {
// If not a Number (including `null`), or scale out of range, return empty
if (!(_value instanceof Number) || !_bigIntegerScaleInRange()) {
return Optional.empty();
}
// Then, extract from Number; empty for NaN and infinities
return Optional.ofNullable(_extractAsBigInteger());
}
// `floatValue()` (etc) fine as defaults (fail); but need to override `asFloat()`
@Override
public float asFloat() {
// First, `null` same as `NullNode`
if (_value == null) {
return 0.0f;
}
// Next, check if the value is NOT a Number
if (!(_value instanceof Number)) {
// report coercion fail
super.asFloat();
}
// Then, extract from Number
Float F = _extractAsFloat();
if (F == null) {
// report range fail
_reportFloatConversionRangeFail("asFloat()");
}
return F;
}
@Override
public float asFloat(float defaultValue) {
// If not a Number (including `null`), return default
if (!(_value instanceof Number)) {
return defaultValue;
}
// Then, extract from Number
Float F = _extractAsFloat();
if (F == null) {
return defaultValue;
}
return F;
}
@Override
public Optional<Float> asFloatOpt() {
// If not a Number (including `null`), return empty
if (!(_value instanceof Number)) {
return Optional.empty();
}
// Then, extract from Number
Float F = _extractAsFloat();
if (F == null) {
return Optional.empty();
}
return Optional.of(F);
}
// `doubleValue()` (etc) fine as defaults (fail); but need to override `asDouble()`
@Override
public double asDouble() {
// First, `null` same as `NullNode`
if (_value == null) {
return 0.0d;
}
// Next, check if the value is NOT a Number
if (!(_value instanceof Number)) {
// report coercion fail
super.asDouble();
}
// Then, extract from Number
Double D = _extractAsDouble();
if (D == null) {
// report range fail
_reportDoubleConversionRangeFail("asDouble()");
}
return D;
}
@Override
public double asDouble(double defaultValue) {
// If not a Number (including `null`), return default
if (!(_value instanceof Number)) {
return defaultValue;
}
// Then, extract from Number
Double D = _extractAsDouble();
if (D == null) {
return defaultValue;
}
return D;
}
@Override
public OptionalDouble asDoubleOpt() {
// If not a Number (including `null`), return empty
if (!(_value instanceof Number)) {
return OptionalDouble.empty();
}
// Then, extract from Number
Double D = _extractAsDouble();
if (D == null) {
return OptionalDouble.empty();
}
return OptionalDouble.of(D);
}
// `decimalValue()` (etc) fine as defaults (fail); but need to override `asDecimal()`
@Override
public BigDecimal asDecimal() {
// First, `null` same as `NullNode`
if (_value == null) {
return BigDecimal.ZERO;
}
// Next, check if the value is NOT a Number
if (!(_value instanceof Number)) {
// report coercion fail
super.asDecimal();
}
// Then, extract from Number: `_extractAsBigDecimal()` returns `null` for
// NaN and infinities; fail for those as `DoubleNode` does
BigDecimal dec = _extractAsBigDecimal();
if (dec == null) {
return _reportBigDecimalConversionNaNFail("asDecimal()");
}
return dec;
}
@Override
public BigDecimal asDecimal(BigDecimal defaultValue) {
// If not a Number (including `null`), return default
if (!(_value instanceof Number)) {
return defaultValue;
}
// Then, extract from Number; default for NaN and infinities
BigDecimal dec = _extractAsBigDecimal();
return (dec == null) ? defaultValue : dec;
}
@Override
public Optional<BigDecimal> asDecimalOpt() {
// If not a Number (including `null`), return empty
if (!(_value instanceof Number)) {
return Optional.empty();
}
// Then, extract from Number; empty for NaN and infinities
return Optional.ofNullable(_extractAsBigDecimal());
}
// extract Long from Number, or return null if range check fails
protected Long _extractAsLong() {
if (_value instanceof Number N) {
if (N instanceof BigInteger big) {
if (big.compareTo(BI_MIN_LONG) >= 0 && big.compareTo(BI_MAX_LONG) <= 0) {
return big.longValue();
}
} else if (N instanceof BigDecimal dec) {
if (dec.compareTo(BD_MIN_LONG) >= 0 && dec.compareTo(BD_MAX_LONG) <= 0) {
return dec.longValue();
}
} else if (_isFloatingPoint(N)) {
// [databind#6474]: compare against 2^63 directly: `Long.MAX_VALUE`
// rounds up to 2^63 as `double`, which would let 2^63 pass (and clamp).
// NaN fails both comparisons.
final double d = N.doubleValue();
if (d >= -0x1p63 && d < 0x1p63) {
return (long) d;
}
} else {
return N.longValue();
}
}
return null;
}
// extract BigInteger from Number, or return null if not a Number or if
// NaN/infinity; throws `StreamConstraintsException` if `BigDecimal` scale
// magnitude exceeds limit
protected BigInteger _extractAsBigInteger() {
if (_value instanceof Number N) {
if (N instanceof BigInteger big) {
return big;
} else if (N instanceof BigDecimal dec) {
// [databind#6214]: guard against excessive scale magnitude
StreamReadConstraints.defaults().validateBigIntegerScale(dec.scale());
return dec.toBigInteger();
} else if (_isFloatingPoint(N)) {
// [databind#6474]: no `longValue()` (clamps to `long` range, NaN -> 0)
final double d = N.doubleValue();
if (!Double.isFinite(d)) {
return null;
}
return BigDecimal.valueOf(d).toBigInteger();
} else {
return BigInteger.valueOf(N.longValue());
}
}
return null;
}
// [databind#6474]: JDK floating-point `Number` types, which must not be converted
// via `longValue()` (clamps to `long` range, NaN -> 0)
private static boolean _isFloatingPoint(Number n) {
return (n instanceof Double) || (n instanceof Float)
|| (n instanceof DoubleAdder) || (n instanceof DoubleAccumulator);
}
// [databind#6476]: JDK integral `Number` types, which must be converted via
// `longValue()` (not `doubleValue()`, which loses precision above 2^53)
private static boolean _isIntegral(Number n) {
return (n instanceof Long) || (n instanceof Integer)
|| (n instanceof Short) || (n instanceof Byte)
|| (n instanceof AtomicLong) || (n instanceof AtomicInteger)
|| (n instanceof LongAdder) || (n instanceof LongAccumulator);
}
// [databind#6214]: whether conversion to `BigInteger` is within scale limit;
// called by non-throwing accessors, which need to return default/empty value
// instead of failing.
private boolean _bigIntegerScaleInRange() {
if (_value instanceof BigDecimal dec) {
final int max = StreamReadConstraints.defaults().getMaxBigIntegerScale();
final int scale = dec.scale();
return (scale >= -max) && (scale <= max);
}
return true;
}
// extract Float from Number, or return null if range check fails
protected Float _extractAsFloat() {
if (_value instanceof Number N) {
if (N instanceof Float F) {
return F;
}
float f = N.floatValue();
if (Float.isFinite(f)) {
return f;
}
}
return null;
}
// extract Double from Number, or return null if range check fails
protected Double _extractAsDouble() {
if (_value instanceof Number N) {
// [databind#6475]: floating-point values widen to `double` without loss;
// keep NaN and infinities as-is, as `DoubleNode` and `FloatNode` do
if (_isFloatingPoint(N)) {
return N.doubleValue();
}
double d = N.doubleValue();
if (Double.isFinite(d)) {
return d;
}
}
return null;
}
// extract BigDecimal from Number, or return null if range check fails
protected BigDecimal _extractAsBigDecimal() {
if (_value instanceof Number N) {
if (N instanceof BigDecimal dec) {
return dec;
} else if (N instanceof BigInteger big) {
return new BigDecimal(big);
} else if (_isIntegral(N)) {
return BigDecimal.valueOf(N.longValue());
}
// Use doubleValue() as a last resort for Float & Double (and unknown
// `Number` types, which may have a fractional part)
try {
return BigDecimal.valueOf(N.doubleValue());
} catch (IllegalArgumentException e) {
// got an NaN
}
}
return null;
}
/*
/**********************************************************************
/* Public API, serialization
/**********************************************************************
*/
@Override
public final void serialize(JsonGenerator gen, SerializationContext ctxt)
throws JacksonException
{
if (_value == null) {
ctxt.defaultSerializeNullValue(gen);
} else if (_value instanceof JacksonSerializable serializable) {
serializable.serialize(gen, ctxt);
} else {
// 25-May-2018, tatu: [databind#1991] do not call via generator but through context;
// this to preserve contextual information
ctxt.writeValue(gen, _value);
}
}
/*
/**********************************************************************
/* Extended API
/**********************************************************************
*/
/**
* Method that can be used to access the POJO this node wraps.
*/
public Object getPojo() { return _value; }
/*
/**********************************************************************
/* Overridden standard methods
/**********************************************************************
*/
@Override
public boolean equals(Object o)
{
if (o == this) return true;
if (o == null) return false;
if (o instanceof POJONode pojoNode) {
return _pojoEquals(pojoNode);
}
return false;
}
protected boolean _pojoEquals(POJONode other)
{
if (_value == null) {
return other._value == null;
}
return _value.equals(other._value);
}
@Override
public int hashCode() {
return Objects.hashCode(_value);
}
}