You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@juneau.apache.org by ja...@apache.org on 2026/03/09 15:15:39 UTC
(juneau) branch master updated: BSON support
This is an automated email from the ASF dual-hosted git repository.
jamesbognar pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/juneau.git
The following commit(s) were added to refs/heads/master by this push:
new 3e8778f309 BSON support
3e8778f309 is described below
commit 3e8778f30912e3ff91b04e15ec0ce4329d5726c4
Author: James Bognar <ja...@salesforce.com>
AuthorDate: Mon Mar 9 11:15:35 2026 -0400
BSON support
---
.../src/main/java/org/apache/juneau/Context.java | 7 +-
.../apache/juneau/bson/BsonBeanPropertyMeta.java | 49 +
.../java/org/apache/juneau/bson/BsonClassMeta.java | 40 +
.../org/apache/juneau/bson/BsonDecimal128.java | 228 +++++
.../org/apache/juneau/bson/BsonInputStream.java | 387 +++++++
.../org/apache/juneau/bson/BsonMetaProvider.java | 45 +
.../org/apache/juneau/bson/BsonOutputStream.java | 327 ++++++
.../java/org/apache/juneau/bson/BsonParser.java | 259 +++++
.../org/apache/juneau/bson/BsonParserSession.java | 275 +++++
.../org/apache/juneau/bson/BsonSerializer.java | 332 ++++++
.../apache/juneau/bson/BsonSerializerSession.java | 317 ++++++
.../main/java/org/apache/juneau/bson/DataType.java | 100 ++
.../org/apache/juneau/bson/annotation/Bson.java | 70 ++
.../juneau/bson/annotation/BsonAnnotation.java | 170 ++++
.../apache/juneau/bson/annotation/BsonConfig.java | 80 ++
.../bson/annotation/BsonConfigAnnotation.java | 80 ++
.../juneau/bson/annotation/package-info.java | 20 +
.../java/org/apache/juneau/bson/package-info.java | 47 +
.../java/org/apache/juneau/marshaller/Bson.java | 216 ++++
.../org/apache/juneau/msgpack/MsgPackParser.java | 14 +
.../apache/juneau/msgpack/MsgPackSerializer.java | 16 +
.../org/apache/juneau/parser/ParserSession.java | 2 +
.../org/apache/juneau/rest/client/RestClient.java | 17 +
.../org/apache/juneau/rest/client/RestRequest.java | 13 +
.../apache/juneau/rest/mock/MockRestClient.java | 6 +
.../apache/juneau/rest/mock/MockRestRequest.java | 6 +
.../juneau/rest/config/BasicUniversalConfig.java | 3 +
.../juneau/a/rttests/JsonMaps_RoundTripTest.java | 2 +-
.../juneau/a/rttests/RoundTripTest_Base.java | 5 +
.../apache/juneau/bson/BsonArrayDebug_Test.java | 55 +
.../apache/juneau/bson/BsonCompatibility_Test.java | 123 +++
.../org/apache/juneau/bson/BsonEdgeCases_Test.java | 100 ++
.../apache/juneau/bson/BsonInputStream_Test.java | 64 ++
.../org/apache/juneau/bson/BsonIntArray_Test.java | 101 ++
.../org/apache/juneau/bson/BsonMediaType_Test.java | 50 +
.../apache/juneau/bson/BsonOutputStream_Test.java | 195 ++++
.../org/apache/juneau/bson/BsonParser_Test.java | 77 ++
.../org/apache/juneau/bson/BsonRoundTrip_Test.java | 118 +++
.../apache/juneau/bson/BsonSerializer_Test.java | 113 +++
.../apache/juneau/bson/BsonTrimStrings_Test.java | 53 +
.../bson/annotation/BsonAnnotation_Test.java | 101 ++
.../apache/juneau/hjson/HjsonTokenizer_Test.java | 76 +-
.../org/apache/juneau/marshaller/Bson_Test.java | 89 ++
todo/4_bson_implementation.md | 1065 --------------------
todo/TODO.md | 4 +-
45 files changed, 4403 insertions(+), 1114 deletions(-)
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/Context.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/Context.java
index ec7a9dd7cd..fc8a986891 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/Context.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/Context.java
@@ -401,11 +401,12 @@ public abstract class Context {
* applied as properties to this builder. These annotations include:
* <ul class='javatreec'>
* <li class ='ja'>{@link BeanConfig}
+ * <li class ='ja'>{@link BsonConfig}
* <li class ='ja'>{@link CsvConfig}
* <li class ='ja'>{@link HtmlConfig}
- * <li class ='ja'>{@link HtmlDocConfig}
- * <li class ='ja'>{@link HjsonConfig}
- * <li class ='ja'>{@link IniConfig}
+ * <li class ='ja'>{@link HtmlDocConfig}
+ * <li class ='ja'>{@link HjsonConfig}
+ * <li class ='ja'>{@link IniConfig}
* <li class ='ja'>{@link JsonConfig}
* <li class ='ja'>{@link JsonlConfig}
* <li class ='ja'>{@link JsonSchemaConfig}
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonBeanPropertyMeta.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonBeanPropertyMeta.java
new file mode 100644
index 0000000000..e1bd1f223b
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonBeanPropertyMeta.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson;
+
+import org.apache.juneau.*;
+
+/**
+ * Metadata on bean properties specific to the BSON serializers and parsers pulled from the {@link org.apache.juneau.bson.annotation.Bson @Bson}
+ * annotation on the bean property.
+ *
+ * <h5 class='section'>See Also:</h5><ul>
+ * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/BsonBasics">BSON Basics</a>
+ * </ul>
+ */
+public class BsonBeanPropertyMeta extends ExtendedBeanPropertyMeta {
+
+ /**
+ * Default instance.
+ */
+ public static final BsonBeanPropertyMeta DEFAULT = new BsonBeanPropertyMeta();
+
+ /**
+ * Constructor.
+ *
+ * @param bpm The metadata of the bean property of this additional metadata.
+ * @param bp BSON metadata provider (for finding information about other artifacts).
+ */
+ public BsonBeanPropertyMeta(BeanPropertyMeta bpm, BsonMetaProvider bp) {
+ super(bpm);
+ }
+
+ private BsonBeanPropertyMeta() {
+ super(null);
+ }
+}
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonClassMeta.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonClassMeta.java
new file mode 100644
index 0000000000..614ad2746e
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonClassMeta.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson;
+
+import org.apache.juneau.*;
+
+/**
+ * Metadata on classes specific to the BSON serializers and parsers pulled from the {@link org.apache.juneau.bson.annotation.Bson @Bson} annotation on
+ * the class.
+ *
+ * <h5 class='section'>See Also:</h5><ul>
+ * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/BsonBasics">BSON Basics</a>
+ * </ul>
+ */
+public class BsonClassMeta extends ExtendedClassMeta {
+
+ /**
+ * Constructor.
+ *
+ * @param cm The class that this annotation is defined on.
+ * @param bp BSON metadata provider (for finding information about other artifacts).
+ */
+ public BsonClassMeta(ClassMeta<?> cm, BsonMetaProvider bp) {
+ super(cm);
+ }
+}
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonDecimal128.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonDecimal128.java
new file mode 100644
index 0000000000..86a6c1ebf8
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonDecimal128.java
@@ -0,0 +1,228 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.math.MathContext;
+
+/**
+ * IEEE 754-2008 Decimal128 BID (Binary Integer Decimal) encoding for BSON.
+ *
+ * <p>
+ * Supports conversion between <code>BigDecimal</code> and the 16-byte BSON Decimal128 format.
+ * Used by {@link BsonSerializer} and {@link BsonParser} for decimal values.
+ *
+ * <h5 class='section'>See Also:</h5><ul>
+ * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/BsonBasics">BSON Basics</a>
+ * <li class='link'><a class="doclink" href="https://bsonspec.org/spec.html">BSON Specification</a>
+ * </ul>
+ */
+public final class BsonDecimal128 {
+
+ private static final MathContext DECIMAL128 = new MathContext(34);
+ private static final long SIGN_BIT_MASK = 1L << 63;
+ private static final long INFINITY_MASK = 0x7800000000000000L;
+ private static final long NaN_MASK = 0x7c00000000000000L;
+ private static final int MIN_EXPONENT = -6176;
+ private static final int MAX_EXPONENT = 6111;
+ private static final int EXPONENT_OFFSET = 6176;
+ private static final int MAX_BIT_LENGTH = 113;
+ private static final BigInteger TEN = new BigInteger("10");
+ private static final BigInteger ZERO = BigInteger.ZERO;
+ private static final BigInteger ONE = BigInteger.ONE;
+
+ private final long high;
+ private final long low;
+
+ private BsonDecimal128(long high, long low) {
+ this.high = high;
+ this.low = low;
+ }
+
+ /**
+ * Creates a Decimal128 from the given high and low 64-bit values (IEEE 754-2008 BID encoding).
+ *
+ * @param high The high-order 64 bits.
+ * @param low The low-order 64 bits.
+ * @return The Decimal128 instance.
+ */
+ public static BsonDecimal128 fromIEEE754BIDEncoding(long high, long low) {
+ return new BsonDecimal128(high, low);
+ }
+
+ /**
+ * Creates a Decimal128 from the given BigDecimal.
+ *
+ * @param value The decimal value.
+ * @return The Decimal128 instance.
+ * @throws NumberFormatException If the value is out of Decimal128 range.
+ */
+ public static BsonDecimal128 fromBigDecimal(BigDecimal value) {
+ return new BsonDecimal128(value, value.signum() == -1);
+ }
+
+ private BsonDecimal128(BigDecimal initialValue, boolean isNegative) {
+ var value = clampAndRound(initialValue);
+ long localHigh = 0;
+ long localLow = 0;
+
+ int exponent = -value.scale();
+ if (exponent < MIN_EXPONENT || exponent > MAX_EXPONENT)
+ throw new NumberFormatException("Exponent out of Decimal128 range: " + exponent);
+
+ if (value.unscaledValue().bitLength() > MAX_BIT_LENGTH)
+ throw new NumberFormatException("Significand out of Decimal128 range");
+
+ var significand = value.unscaledValue().abs();
+ int bitLength = significand.bitLength();
+
+ for (var i = 0; i < Math.min(64, bitLength); i++)
+ if (significand.testBit(i))
+ localLow |= 1L << i;
+
+ for (var i = 64; i < bitLength; i++)
+ if (significand.testBit(i))
+ localHigh |= 1L << (i - 64);
+
+ long biasedExponent = exponent + EXPONENT_OFFSET;
+ localHigh |= biasedExponent << 49;
+
+ if (value.signum() == -1 || isNegative)
+ localHigh |= SIGN_BIT_MASK;
+
+ this.high = localHigh;
+ this.low = localLow;
+ }
+
+ private static BigDecimal clampAndRound(BigDecimal initialValue) {
+ var value = initialValue;
+ if (-initialValue.scale() > MAX_EXPONENT) {
+ int diff = -initialValue.scale() - MAX_EXPONENT;
+ if (initialValue.unscaledValue().equals(ZERO))
+ value = new BigDecimal(initialValue.unscaledValue(), -MAX_EXPONENT);
+ else if (diff + initialValue.precision() > 34)
+ throw new NumberFormatException("Exponent out of Decimal128 range: " + initialValue);
+ else {
+ var multiplier = TEN.pow(diff);
+ value = new BigDecimal(initialValue.unscaledValue().multiply(multiplier), initialValue.scale() + diff);
+ }
+ } else if (-initialValue.scale() < MIN_EXPONENT) {
+ int diff = initialValue.scale() + MIN_EXPONENT;
+ int undiscardedPrecision = ensureExactRounding(initialValue, diff);
+ var divisor = undiscardedPrecision == 0 ? ONE : TEN.pow(diff);
+ value = new BigDecimal(initialValue.unscaledValue().divide(divisor), initialValue.scale() - diff);
+ } else {
+ value = initialValue.round(DECIMAL128);
+ int extraPrecision = initialValue.precision() - value.precision();
+ if (extraPrecision > 0)
+ ensureExactRounding(initialValue, extraPrecision);
+ }
+ return value;
+ }
+
+ private static int ensureExactRounding(BigDecimal initialValue, int extraPrecision) {
+ var significand = initialValue.unscaledValue().abs().toString();
+ int undiscardedPrecision = Math.max(0, significand.length() - extraPrecision);
+ for (var i = undiscardedPrecision; i < significand.length(); i++)
+ if (significand.charAt(i) != '0')
+ throw new NumberFormatException("Conversion to Decimal128 would require inexact rounding: " + initialValue);
+ return undiscardedPrecision;
+ }
+
+ /**
+ * Returns the high-order 64 bits.
+ *
+ * @return The high bits.
+ */
+ public long getHigh() {
+ return high;
+ }
+
+ /**
+ * Returns the low-order 64 bits.
+ *
+ * @return The low bits.
+ */
+ public long getLow() {
+ return low;
+ }
+
+ /**
+ * Converts to BigDecimal.
+ *
+ * @return The equivalent BigDecimal.
+ * @throws ArithmeticException If the value is NaN, Infinity, or negative zero.
+ */
+ public BigDecimal toBigDecimal() {
+ if (isNaN())
+ throw new ArithmeticException("NaN cannot be converted to BigDecimal");
+ if (isInfinite())
+ throw new ArithmeticException("Infinity cannot be converted to BigDecimal");
+
+ var bd = toBigDecimalNoNegativeZeroCheck();
+ if (isNegative() && bd.signum() == 0)
+ throw new ArithmeticException("Negative zero cannot be converted to BigDecimal");
+ return bd;
+ }
+
+ private boolean isNaN() {
+ return (high & NaN_MASK) == NaN_MASK;
+ }
+
+ private boolean isInfinite() {
+ return (high & INFINITY_MASK) == INFINITY_MASK;
+ }
+
+ private boolean isNegative() {
+ return (high & SIGN_BIT_MASK) == SIGN_BIT_MASK;
+ }
+
+ private boolean twoHighestCombinationBitsAreSet() {
+ return (high & 3L << 61) == 3L << 61;
+ }
+
+ private int getExponent() {
+ if (twoHighestCombinationBitsAreSet())
+ return (int)((high & 0x1fffe00000000000L) >>> 47) - EXPONENT_OFFSET;
+ return (int)((high & 0x7fff800000000000L) >>> 49) - EXPONENT_OFFSET;
+ }
+
+ private BigDecimal toBigDecimalNoNegativeZeroCheck() {
+ int scale = -getExponent();
+ if (twoHighestCombinationBitsAreSet())
+ return BigDecimal.valueOf(0, scale);
+ return new BigDecimal(new BigInteger(isNegative() ? -1 : 1, getSignificandBytes()), scale);
+ }
+
+ private byte[] getSignificandBytes() {
+ var bytes = new byte[15];
+ long mask = 0xFF;
+ for (var i = 14; i >= 7; i--) {
+ bytes[i] = (byte)((low & mask) >>> ((14 - i) << 3));
+ mask <<= 8;
+ }
+ mask = 0xFF;
+ for (var i = 6; i >= 1; i--) {
+ bytes[i] = (byte)((high & mask) >>> ((6 - i) << 3));
+ mask <<= 8;
+ }
+ bytes[0] = (byte)((high & 0x0001000000000000L) >>> 48);
+ return bytes;
+ }
+
+}
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonInputStream.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonInputStream.java
new file mode 100644
index 0000000000..9a56466b36
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonInputStream.java
@@ -0,0 +1,387 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson;
+
+import static org.apache.juneau.commons.utils.ThrowableUtils.*;
+
+import java.io.*;
+import java.math.*;
+import java.nio.charset.*;
+
+import org.apache.juneau.parser.*;
+
+/**
+ * Specialized input stream for parsing BSON (Binary JSON) streams.
+ *
+ * <p>
+ * BSON uses little-endian byte order for all multi-byte values.
+ *
+ * <h5 class='section'>Notes:</h5><ul>
+ * <li class='note'>
+ * This class is not intended for external use.
+ * </ul>
+ *
+ * <h5 class='section'>See Also:</h5><ul>
+ * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/BsonBasics">BSON Basics</a>
+ * </ul>
+ */
+public class BsonInputStream extends ParserInputStream {
+
+ private static final Charset UTF8 = StandardCharsets.UTF_8;
+
+ private int pushback = -1;
+
+ /**
+ * Constructor.
+ *
+ * @param pipe The parser input.
+ * @throws IOException Thrown by underlying stream.
+ */
+ protected BsonInputStream(ParserPipe pipe) throws IOException {
+ super(pipe);
+ }
+
+ @Override
+ public int read() throws IOException {
+ if (pushback >= 0) {
+ var b = pushback;
+ pushback = -1;
+ return b;
+ }
+ return super.read();
+ }
+
+ /**
+ * Pushes back one byte for the next read.
+ */
+ private void pushBack(int b) {
+ pushback = b & 0xFF;
+ }
+
+ /**
+ * Reads a 4-byte little-endian integer.
+ *
+ * @return The 32-bit value.
+ * @throws IOException If the stream ends prematurely.
+ */
+ public int readLE4() throws IOException {
+ var b1 = read();
+ var b2 = read();
+ var b3 = read();
+ var b4 = read();
+ if (b4 < 0)
+ throw ioex("Unexpected end of BSON stream");
+ return (b1 & 0xFF) | ((b2 & 0xFF) << 8) | ((b3 & 0xFF) << 16) | ((b4 & 0xFF) << 24);
+ }
+
+ /**
+ * Reads an 8-byte little-endian long.
+ *
+ * @return The 64-bit value.
+ * @throws IOException If the stream ends prematurely.
+ */
+ public long readLE8() throws IOException {
+ var lo = readLE4() & 0xFFFFFFFFL;
+ var hi = readLE4() & 0xFFFFFFFFL;
+ return lo | (hi << 32);
+ }
+
+ /**
+ * Reads the document size (int32) from the stream.
+ *
+ * @return The document size in bytes.
+ * @throws IOException If the stream ends prematurely.
+ */
+ public int readDocumentSize() throws IOException {
+ return readLE4();
+ }
+
+ /**
+ * Reads the 1-byte element type.
+ *
+ * @return The BSON type byte (0x01-0x13, 0x7F, 0xFF).
+ * @throws IOException If the stream ends prematurely.
+ */
+ public int readElementType() throws IOException {
+ var b = read();
+ if (b < 0)
+ throw ioex("Unexpected end of BSON stream");
+ return b & 0xFF;
+ }
+
+ /**
+ * Reads a cstring (null-terminated UTF-8).
+ *
+ * @return The element name.
+ * @throws IOException If the stream ends prematurely.
+ */
+ public String readElementName() throws IOException {
+ return readCString();
+ }
+
+ /**
+ * Reads a cstring (UTF-8 bytes until 0x00).
+ *
+ * @return The string value.
+ * @throws IOException If the stream ends prematurely.
+ */
+ public String readCString() throws IOException {
+ var baos = new ByteArrayOutputStream();
+ int b;
+ while ((b = read()) >= 0 && b != 0)
+ baos.write(b);
+ if (b < 0)
+ throw ioex("Unexpected end of BSON stream");
+ return new String(baos.toByteArray(), UTF8);
+ }
+
+ /**
+ * Returns whether the next byte is the document terminator (0x00).
+ *
+ * @return <jk>true</jk> if next byte is 0x00, <jk>false</jk> otherwise.
+ * @throws IOException If the stream ends prematurely.
+ */
+ public boolean isDocumentEnd() throws IOException {
+ var b = read();
+ if (b >= 0)
+ pushBack(b);
+ return b == 0x00;
+ }
+
+ /**
+ * Consumes the document terminator byte (0x00).
+ *
+ * @throws IOException If the stream ends prematurely or byte is not 0x00.
+ */
+ public void readDocumentTerminator() throws IOException {
+ var b = read();
+ if (b != 0x00)
+ throw ioex("Expected document terminator, got {0}", b);
+ }
+
+ /**
+ * Reads an IEEE 754 double (8 bytes, little-endian).
+ *
+ * @return The double value.
+ * @throws IOException If the stream ends prematurely.
+ */
+ public double readDouble() throws IOException {
+ return Double.longBitsToDouble(readLE8());
+ }
+
+ /**
+ * Reads a 32-bit integer (4 bytes, little-endian).
+ *
+ * @return The integer value.
+ * @throws IOException If the stream ends prematurely.
+ */
+ public int readInt32() throws IOException {
+ return readLE4();
+ }
+
+ /**
+ * Reads a 64-bit integer (8 bytes, little-endian).
+ *
+ * @return The long value.
+ * @throws IOException If the stream ends prematurely.
+ */
+ public long readInt64() throws IOException {
+ return readLE8();
+ }
+
+ /**
+ * Reads a boolean (1 byte: 0x00=false, 0x01=true).
+ *
+ * @return The boolean value.
+ * @throws IOException If the stream ends prematurely.
+ */
+ public boolean readBoolean() throws IOException {
+ var b = read();
+ if (b < 0)
+ throw ioex("Unexpected end of BSON stream");
+ return b != 0;
+ }
+
+ /**
+ * Reads a BSON string (int32 length + UTF-8 + 0x00).
+ *
+ * @return The string value.
+ * @throws IOException If the stream ends prematurely.
+ */
+ public String readString() throws IOException {
+ var len = readLE4();
+ if (len <= 0)
+ throw ioex("Invalid BSON string length: {0}", len);
+ var bytes = new byte[len - 1]; // length includes null
+ for (var i = 0; i < bytes.length; i++) {
+ var b = read();
+ if (b < 0)
+ throw ioex("Unexpected end of BSON stream");
+ bytes[i] = (byte)b;
+ }
+ var term = read();
+ if (term != 0x00)
+ throw ioex("Expected string terminator, got {0}", term);
+ return new String(bytes, UTF8);
+ }
+
+ /**
+ * Reads BSON binary (int32 length + subtype + bytes).
+ *
+ * @return The binary data.
+ * @throws IOException If the stream ends prematurely.
+ */
+ public byte[] readBinary() throws IOException {
+ var len = readLE4();
+ var subtype = read();
+ if (subtype < 0)
+ throw ioex("Unexpected end of BSON stream");
+ var bytes = new byte[len];
+ for (var i = 0; i < len; i++) {
+ var b = read();
+ if (b < 0)
+ throw ioex("Unexpected end of BSON stream");
+ bytes[i] = (byte)b;
+ }
+ return bytes;
+ }
+
+ /**
+ * Reads BSON datetime (int64, UTC millis since epoch).
+ *
+ * @return The UTC millis since epoch.
+ * @throws IOException If the stream ends prematurely.
+ */
+ public long readDateTime() throws IOException {
+ return readLE8();
+ }
+
+ /**
+ * Reads ObjectId (12 bytes) as 24-character hex string.
+ *
+ * @return The ObjectId as hex string.
+ * @throws IOException If the stream ends prematurely.
+ */
+ public String readObjectId() throws IOException {
+ var bytes = new byte[12];
+ for (var i = 0; i < 12; i++) {
+ var b = read();
+ if (b < 0)
+ throw ioex("Unexpected end of BSON stream");
+ bytes[i] = (byte)b;
+ }
+ var sb = new StringBuilder(24);
+ for (var b : bytes)
+ sb.append(String.format("%02x", b & 0xFF));
+ return sb.toString();
+ }
+
+ /**
+ * Reads BSON decimal128 (16 bytes, IEEE 754-2008) as BigDecimal.
+ *
+ * @return The decimal value.
+ * @throws IOException If the stream ends prematurely.
+ */
+ public BigDecimal readDecimal128() throws IOException {
+ var bytes = new byte[16];
+ for (var i = 0; i < 16; i++) {
+ var b = read();
+ if (b < 0)
+ throw ioex("Unexpected end of BSON stream");
+ bytes[i] = (byte)b;
+ }
+ return decodeDecimal128(bytes);
+ }
+
+ /**
+ * Skips a value of the given BSON type.
+ *
+ * @param type The BSON type byte (0x01-0x13, 0x7F, 0xFF).
+ * @throws IOException If the stream ends prematurely.
+ */
+ public void skipValue(int type) throws IOException {
+ switch (type) {
+ case 0x01 -> readLE8();
+ case 0x02 -> {
+ var len = readLE4();
+ skip(len);
+ }
+ case 0x03, 0x04 -> {
+ var size = readLE4();
+ skip(size - 4);
+ }
+ case 0x05 -> {
+ var len = readLE4();
+ read();
+ skip(len);
+ }
+ case 0x06 -> { }
+ case 0x07 -> skip(12);
+ case 0x08 -> read();
+ case 0x09 -> readLE8();
+ case 0x0A -> { }
+ case 0x0B -> {
+ readCString();
+ readCString();
+ }
+ case 0x0C -> {
+ readString();
+ skip(12);
+ }
+ case 0x0D -> readString();
+ case 0x0E -> readString();
+ case 0x0F -> {
+ var len = readLE4();
+ skip(len - 4);
+ }
+ case 0x10 -> readLE4();
+ case 0x11 -> readLE8();
+ case 0x12 -> readLE8();
+ case 0x13 -> skip(16);
+ case 0x7F, 0xFF -> { }
+ default -> throw ioex("Unknown BSON type: {0}", type);
+ }
+ }
+
+ private void skip(int n) throws IOException {
+ for (var i = 0; i < n; i++)
+ if (read() < 0)
+ throw ioex("Unexpected end of BSON stream");
+ }
+
+ /**
+ * Decodes IEEE 754-2008 decimal128 bytes to BigDecimal.
+ *
+ * <p>
+ * Bytes are little-endian: bytes 0-7 = low 64 bits, bytes 8-15 = high 64 bits.
+ * Matches {@link BsonOutputStream#writeDecimal128} output.
+ */
+ private static BigDecimal decodeDecimal128(byte[] bytes) {
+ if (bytes.length != 16)
+ throw new IllegalArgumentException("Decimal128 must be 16 bytes");
+ var low = readLE8From(bytes, 0);
+ var high = readLE8From(bytes, 8);
+ return BsonDecimal128.fromIEEE754BIDEncoding(high, low).toBigDecimal();
+ }
+
+ private static long readLE8From(byte[] bytes, int offset) {
+ return ((long)(bytes[offset + 7] & 0xFF) << 56) | ((long)(bytes[offset + 6] & 0xFF) << 48)
+ | ((long)(bytes[offset + 5] & 0xFF) << 40) | ((long)(bytes[offset + 4] & 0xFF) << 32)
+ | ((long)(bytes[offset + 3] & 0xFF) << 24) | ((long)(bytes[offset + 2] & 0xFF) << 16)
+ | ((long)(bytes[offset + 1] & 0xFF) << 8) | (bytes[offset] & 0xFF);
+ }
+}
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonMetaProvider.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonMetaProvider.java
new file mode 100644
index 0000000000..9cd695a5de
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonMetaProvider.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson;
+
+import org.apache.juneau.*;
+
+/**
+ * Interface for providing access to {@link BsonClassMeta} and {@link BsonBeanPropertyMeta} objects.
+ *
+ * <h5 class='section'>See Also:</h5><ul>
+ * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/BsonBasics">BSON Basics</a>
+ * </ul>
+ */
+public interface BsonMetaProvider {
+
+ /**
+ * Returns the language-specific metadata on the specified bean property.
+ *
+ * @param bpm The bean property to return the metadata on.
+ * @return The metadata.
+ */
+ BsonBeanPropertyMeta getBsonBeanPropertyMeta(BeanPropertyMeta bpm);
+
+ /**
+ * Returns the language-specific metadata on the specified class.
+ *
+ * @param cm The class to return the metadata on.
+ * @return The metadata.
+ */
+ BsonClassMeta getBsonClassMeta(ClassMeta<?> cm);
+}
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonOutputStream.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonOutputStream.java
new file mode 100644
index 0000000000..b61a804740
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonOutputStream.java
@@ -0,0 +1,327 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson;
+
+import java.io.*;
+import java.math.*;
+import java.nio.charset.*;
+
+import org.apache.juneau.serializer.*;
+
+/**
+ * Specialized output stream for serializing BSON (Binary JSON) streams.
+ *
+ * <p>
+ * BSON uses little-endian byte order for all multi-byte values. Documents are length-prefixed: the total
+ * byte count (int32) must appear before the content. Since the size is unknown until all elements are written,
+ * each document is buffered in a {@link ByteArrayOutputStream} child. When complete, the size is calculated
+ * and <c>[int32 size][content][0x00]</c> is written to the parent stream.
+ *
+ * <h5 class='section'>Notes:</h5><ul>
+ * <li class='note'>
+ * This class is not intended for external use.
+ * </ul>
+ *
+ * <h5 class='section'>See Also:</h5><ul>
+ * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/BsonBasics">BSON Basics</a>
+ * </ul>
+ */
+@SuppressWarnings({
+ "resource" // OutputStream resource managed by calling code
+})
+public class BsonOutputStream extends OutputStream {
+
+ private static final Charset UTF8 = StandardCharsets.UTF_8;
+ private static final byte BINARY_SUBTYPE_GENERIC = 0x00;
+ private static final byte DOCUMENT_TERMINATOR = 0x00;
+
+ private final OutputStream os;
+ private ByteArrayOutputStream buffer;
+ private boolean inDocument;
+
+ /**
+ * Constructor.
+ *
+ * @param os The output stream being wrapped.
+ */
+ public BsonOutputStream(OutputStream os) {
+ this.os = os;
+ }
+
+ @Override /* Overridden from OutputStream */
+ public void write(int b) {
+ try {
+ target().write(b);
+ } catch (IOException e) {
+ throw new SerializeException(e);
+ }
+ }
+
+ @Override /* Overridden from OutputStream */
+ public void write(byte[] b) {
+ if (b != null && b.length > 0)
+ write(b, 0, b.length);
+ }
+
+ @Override /* Overridden from OutputStream */
+ public void write(byte[] b, int off, int len) {
+ try {
+ target().write(b, off, len);
+ } catch (IOException e) {
+ throw new SerializeException(e);
+ }
+ }
+
+ private OutputStream target() {
+ return buffer != null ? buffer : os;
+ }
+
+ /**
+ * Begin buffering a new document.
+ */
+ public void startDocument() {
+ buffer = new ByteArrayOutputStream();
+ inDocument = true;
+ }
+
+ /**
+ * Finalize the current document and return the bytes (int32 size + content + 0x00).
+ *
+ * @return The complete document bytes.
+ */
+ public byte[] endDocument() {
+ if (buffer == null)
+ return new byte[0];
+ buffer.write(DOCUMENT_TERMINATOR);
+ var content = buffer.toByteArray();
+ // size = 4 (int32) + content length
+ var size = 4 + content.length;
+ var result = new byte[size];
+ writeLE4To(result, 0, size);
+ System.arraycopy(content, 0, result, 4, content.length);
+ buffer = null;
+ inDocument = false;
+ return result;
+ }
+
+ /**
+ * Finalize the current document and write it to the parent stream.
+ *
+ * @param parent The parent output stream.
+ */
+ public void writeDocumentTo(OutputStream parent) {
+ var bytes = endDocument();
+ try {
+ parent.write(bytes);
+ } catch (IOException e) {
+ throw new SerializeException(e);
+ }
+ }
+
+ /**
+ * Writes a BSON element header (type byte + cstring name).
+ *
+ * @param type The BSON type code.
+ * @param name The element name (cstring).
+ */
+ public void writeElement(int type, String name) {
+ write(type & 0xFF);
+ writeCString(name);
+ }
+
+ /**
+ * Writes a 4-byte little-endian integer.
+ *
+ * @param value The 32-bit value.
+ */
+ public void writeLE4(int value) {
+ write(value & 0xFF);
+ write((value >> 8) & 0xFF);
+ write((value >> 16) & 0xFF);
+ write((value >> 24) & 0xFF);
+ }
+
+ /**
+ * Writes a 4-byte little-endian integer to a byte array.
+ */
+ static void writeLE4To(byte[] buf, int offset, int value) {
+ buf[offset] = (byte)(value & 0xFF);
+ buf[offset + 1] = (byte)((value >> 8) & 0xFF);
+ buf[offset + 2] = (byte)((value >> 16) & 0xFF);
+ buf[offset + 3] = (byte)((value >> 24) & 0xFF);
+ }
+
+ /**
+ * Writes an 8-byte little-endian long.
+ *
+ * @param value The 64-bit value.
+ */
+ public void writeLE8(long value) {
+ write((int)(value & 0xFF));
+ write((int)((value >> 8) & 0xFF));
+ write((int)((value >> 16) & 0xFF));
+ write((int)((value >> 24) & 0xFF));
+ write((int)((value >> 32) & 0xFF));
+ write((int)((value >> 40) & 0xFF));
+ write((int)((value >> 48) & 0xFF));
+ write((int)((value >> 56) & 0xFF));
+ }
+
+ /**
+ * Writes an IEEE 754 double (8 bytes, little-endian).
+ *
+ * @param value The double value.
+ */
+ public void writeDouble(double value) {
+ writeLE8(Double.doubleToLongBits(value));
+ }
+
+ /**
+ * Writes a 32-bit integer (4 bytes, little-endian).
+ *
+ * @param value The integer value.
+ */
+ public void writeInt32(int value) {
+ writeLE4(value);
+ }
+
+ /**
+ * Writes a 64-bit integer (8 bytes, little-endian).
+ *
+ * @param value The long value.
+ */
+ public void writeInt64(long value) {
+ writeLE8(value);
+ }
+
+ /**
+ * Writes a boolean (1 byte: 0x00=false, 0x01=true).
+ *
+ * @param value The boolean value.
+ */
+ public void writeBoolean(boolean value) {
+ write(value ? 0x01 : 0x00);
+ }
+
+ /**
+ * Writes BSON null (no value bytes).
+ */
+ public void writeNull() {
+ // Type byte only, no value
+ }
+
+ /**
+ * Writes a BSON string (int32 length + UTF-8 bytes + 0x00).
+ *
+ * @param value The string to write (treated as empty if <jk>null</jk>).
+ */
+ public void writeString(String value) {
+ if (value == null)
+ value = "";
+ var bytes = value.getBytes(UTF8);
+ // BSON string length includes trailing null
+ writeLE4(bytes.length + 1);
+ write(bytes);
+ write(DOCUMENT_TERMINATOR);
+ }
+
+ /**
+ * Writes a cstring (UTF-8 bytes + 0x00, no length prefix).
+ *
+ * @param value The string to write (treated as empty if <jk>null</jk>).
+ */
+ public void writeCString(String value) {
+ if (value == null)
+ value = "";
+ for (var i = 0; i < value.length(); i++)
+ if (value.charAt(i) == 0)
+ throw new SerializeException("CString must not contain null bytes");
+ write(value.getBytes(UTF8));
+ write(DOCUMENT_TERMINATOR);
+ }
+
+ /**
+ * Writes BSON binary (int32 length + subtype byte + raw bytes).
+ *
+ * @param data The raw bytes (subtype 0x00 generic).
+ */
+ public void writeBinary(byte[] data) {
+ if (data == null)
+ data = new byte[0];
+ writeLE4(data.length);
+ write(BINARY_SUBTYPE_GENERIC);
+ write(data);
+ }
+
+ /**
+ * Writes BSON datetime (int64, UTC milliseconds since epoch).
+ *
+ * @param millis The UTC milliseconds since epoch.
+ */
+ public void writeDateTime(long millis) {
+ writeLE8(millis);
+ }
+
+ /**
+ * Writes BSON decimal128 (16 bytes, IEEE 754-2008) from BigDecimal.
+ *
+ * @param value The decimal value.
+ */
+ public void writeDecimal128(BigDecimal value) {
+ if (value == null)
+ value = BigDecimal.ZERO;
+ var d128 = BsonDecimal128.fromBigDecimal(value);
+ writeLE8(d128.getLow());
+ writeLE8(d128.getHigh());
+ }
+
+ /**
+ * Creates a child BsonOutputStream for buffering a nested document.
+ *
+ * @return A new child stream (no parent; use {@link #writeChildDocument} to embed).
+ */
+ public BsonOutputStream createChild() {
+ return new BsonOutputStream(null);
+ }
+
+ /**
+ * Writes the child document's content as an embedded document to this stream.
+ *
+ * @param child The child stream (must have been finalized via endDocument).
+ */
+ public void writeChildDocument(BsonOutputStream child) {
+ // Child buffers to its own ByteArrayOutputStream; we need to write [size][content][0x00]
+ // Child.endDocument() returns [size][content] with 0x00 already in content
+ // So we just need to write the child's endDocument() result
+ var bytes = child.endDocument();
+ // bytes already has size prefix and terminator from endDocument
+ try {
+ target().write(bytes);
+ } catch (IOException e) {
+ throw new SerializeException(e);
+ }
+ }
+
+ /**
+ * Returns whether we are currently buffering a document.
+ *
+ * @return <jk>true</jk> if buffering, <jk>false</jk> otherwise.
+ */
+ public boolean isInDocument() {
+ return inDocument;
+ }
+}
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonParser.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonParser.java
new file mode 100644
index 0000000000..0cb70953e6
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonParser.java
@@ -0,0 +1,259 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson;
+
+import static org.apache.juneau.commons.utils.AssertionUtils.*;
+import static org.apache.juneau.commons.utils.Utils.*;
+
+import java.util.*;
+import java.util.concurrent.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.commons.collections.*;
+import org.apache.juneau.parser.*;
+
+/**
+ * Parses BSON (Binary JSON) into POJO models.
+ *
+ * <h5 class='section'>Media types:</h5>
+ *
+ * Handles <c>Content-Type</c> types: <bc>application/bson</bc>
+ *
+ * <h5 class='topic'>Description</h5>
+ * <p>
+ * BSON-to-Java type mapping:
+ * <ul class='spaced-list'>
+ * <li>BSON document (0x03) → bean or {@link java.util.Map}
+ * <li>BSON array (0x04) → {@link java.util.Collection} or Java array (numeric string keys ignored)
+ * <li>BSON string (0x02) → {@link String}; coerced to types parseable from string
+ * <li>BSON boolean (0x08) → {@link Boolean}
+ * <li>BSON int32 (0x10) → {@code int}; coerced to {@code long}, {@code short}, {@code byte} as needed
+ * <li>BSON int64 (0x12) → {@code long}; coerced to {@code int} if target is {@code int}
+ * <li>BSON double (0x01) → {@code double}; coerced to {@code float}
+ * <li>BSON datetime (0x09) → {@link java.util.Date}, {@link java.util.Calendar}, {@link java.time.Instant}, or
+ * {@code long} (millis)
+ * <li>BSON binary (0x05) → {@code byte[]}
+ * <li>BSON decimal128 (0x13) → {@link java.math.BigDecimal}
+ * <li>BSON null (0x0A) → {@code null}
+ * <li>BSON ObjectId (0x07) → 24-character hex {@link String}
+ * <li>Deprecated/unsupported types → silently skipped
+ * </ul>
+ *
+ * <h5 class='section'>Notes:</h5><ul>
+ * <li class='note'>This class is thread safe and reusable.
+ * </ul>
+ *
+ * <h5 class='section'>Limitations:</h5><ul>
+ * <li>BSON requires a top-level document. Standalone scalars are wrapped as <c>{value: x}</c>.
+ * <li>Map keys must be strings. Non-string keys use <c>toString()</c>. Null keys use a configurable placeholder.
+ * <li>ObjectId (0x07) is read-only; parsed as 24-character hex strings.
+ * <li>Deprecated types (Undefined, DBPointer, Symbol, JS with Scope) are silently skipped.
+ * <li>MongoDB-internal types (JavaScript, Timestamp, MinKey, MaxKey) are not supported.
+ * <li>BSON is binary; <c>SpacedHex</c> and <c>Base64</c> subclasses accept text-encoded input.
+ * </ul>
+ *
+ * <h5 class='section'>See Also:</h5><ul>
+ * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/BsonBasics">BSON Basics</a>
+ * </ul>
+ */
+@SuppressWarnings({
+ "java:S110", // Inheritance depth acceptable for this class hierarchy
+ "java:S115", // Constants use UPPER_snakeCase naming convention
+})
+public class BsonParser extends InputStreamParser implements BsonMetaProvider {
+
+ // Argument name constants for assertArgNotNull
+ private static final String ARG_copyFrom = "copyFrom";
+
+ /** Default parser, string input encoded as BASE64. */
+ public static class Base64 extends BsonParser {
+
+ /**
+ * Constructor.
+ *
+ * @param builder The builder for this object.
+ */
+ public Base64(Builder builder) {
+ super(builder.binaryFormat(BinaryFormat.BASE64));
+ }
+ }
+
+ /**
+ * Builder class.
+ */
+ public static class Builder extends InputStreamParser.Builder {
+
+ private static final Cache<HashKey,BsonParser> CACHE = Cache.of(HashKey.class, BsonParser.class).build();
+
+ private String nullKeyString = "<NULL>";
+
+ /**
+ * Constructor, default settings.
+ */
+ protected Builder() {
+ consumes("application/bson");
+ nullKeyString = env("BsonParser.nullKeyString", "<NULL>");
+ }
+
+ /**
+ * Copy constructor.
+ *
+ * @param copyFrom The builder to copy from.
+ */
+ protected Builder(Builder copyFrom) {
+ super(assertArgNotNull(ARG_copyFrom, copyFrom));
+ nullKeyString = copyFrom.nullKeyString;
+ }
+
+ /**
+ * Copy constructor.
+ *
+ * @param copyFrom The bean to copy from.
+ */
+ protected Builder(BsonParser copyFrom) {
+ super(assertArgNotNull(ARG_copyFrom, copyFrom));
+ nullKeyString = copyFrom.nullKeyString;
+ }
+
+ @Override /* InputStreamParser.Builder */
+ public Builder binaryFormat(BinaryFormat value) {
+ super.binaryFormat(value);
+ return this;
+ }
+
+ /**
+ * The string used to represent <jk>null</jk> map keys in BSON documents.
+ *
+ * <p>
+ * BSON document field names cannot be <jk>null</jk>. When parsing a field with this name,
+ * it is stored with <jk>null</jk> as the key in the target map.
+ *
+ * @param value The placeholder string for null keys. Default is <js>"<NULL>"</js>.
+ * @return This object.
+ */
+ public Builder nullKeyString(String value) {
+ nullKeyString = value == null ? "<NULL>" : value;
+ return this;
+ }
+
+ @Override /* Parser.Builder */
+ public Builder trimStrings() {
+ super.trimStrings();
+ return this;
+ }
+
+ @Override /* Parser.Builder */
+ public Builder trimStrings(boolean value) {
+ super.trimStrings(value);
+ return this;
+ }
+
+ @Override /* Context.Builder */
+ public BsonParser build() {
+ return cache(CACHE).build(BsonParser.class);
+ }
+
+ @Override /* Context.Builder */
+ public HashKey hashKey() {
+ return HashKey.of(super.hashKey(), nullKeyString);
+ }
+
+ @Override /* Context.Builder */
+ public Builder copy() {
+ return new Builder(this);
+ }
+ }
+
+ /** Default parser, string input encoded as spaced-hex. */
+ public static class SpacedHex extends BsonParser {
+
+ /**
+ * Constructor.
+ *
+ * @param builder The builder for this object.
+ */
+ public SpacedHex(Builder builder) {
+ super(builder.binaryFormat(BinaryFormat.SPACED_HEX));
+ }
+ }
+
+ /** Default parser, all default settings. */
+ public static final BsonParser DEFAULT = new BsonParser(create());
+ /** Default parser, spaced-hex string input. */
+ public static final BsonParser DEFAULT_SPACED_HEX = new SpacedHex(create());
+ /** Default parser, BASE64 string input. */
+ public static final BsonParser DEFAULT_BASE64 = new Base64(create());
+
+ /**
+ * Creates a new builder for this object.
+ *
+ * @return A new builder.
+ */
+ public static Builder create() {
+ return new Builder();
+ }
+
+ private final Map<ClassMeta<?>,BsonClassMeta> bsonClassMetas = new ConcurrentHashMap<>();
+ private final Map<BeanPropertyMeta,BsonBeanPropertyMeta> bsonBeanPropertyMetas = new ConcurrentHashMap<>();
+ private final String nullKeyString;
+
+ /**
+ * Constructor.
+ *
+ * @param builder The builder for this object.
+ */
+ public BsonParser(Builder builder) {
+ super(builder);
+ nullKeyString = builder.nullKeyString;
+ }
+
+ @Override /* Context */
+ public Builder copy() {
+ return new Builder(this);
+ }
+
+ @Override /* Context */
+ public BsonParserSession.Builder createSession() {
+ return BsonParserSession.create(this);
+ }
+
+ @Override /* BsonMetaProvider */
+ public BsonBeanPropertyMeta getBsonBeanPropertyMeta(BeanPropertyMeta bpm) {
+ if (bpm == null)
+ return BsonBeanPropertyMeta.DEFAULT;
+ return bsonBeanPropertyMetas.computeIfAbsent(bpm, k -> new BsonBeanPropertyMeta(k.getDelegateFor(), this));
+ }
+
+ @Override /* BsonMetaProvider */
+ public BsonClassMeta getBsonClassMeta(ClassMeta<?> cm) {
+ return bsonClassMetas.computeIfAbsent(cm, k -> new BsonClassMeta(k, this));
+ }
+
+ @Override /* Context */
+ public BsonParserSession getSession() {
+ return createSession().build();
+ }
+
+ /**
+ * Returns the string used to represent <jk>null</jk> map keys in BSON documents.
+ *
+ * @return The null key placeholder string.
+ */
+ public String getNullKeyString() {
+ return nullKeyString;
+ }
+}
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonParserSession.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonParserSession.java
new file mode 100644
index 0000000000..41baec1bf7
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonParserSession.java
@@ -0,0 +1,275 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson;
+
+import static org.apache.juneau.commons.utils.AssertionUtils.*;
+import static org.apache.juneau.commons.utils.Utils.*;
+
+import java.io.*;
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.collections.*;
+import org.apache.juneau.commons.reflect.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.swap.*;
+
+/**
+ * Session object that lives for the duration of a single use of {@link BsonParser}.
+ *
+ * <h5 class='section'>Notes:</h5><ul>
+ * <li class='warn'>This class is not thread safe and is typically discarded after one use.
+ * </ul>
+ *
+ * <h5 class='section'>See Also:</h5><ul>
+ * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/BsonBasics">BSON Basics</a>
+ * </ul>
+ */
+@SuppressWarnings({
+ "rawtypes",
+ "unchecked",
+ "java:S115",
+ "java:S3776",
+ "java:S6541"
+})
+public class BsonParserSession extends InputStreamParserSession {
+
+ private static final String ARG_ctx = "ctx";
+
+ /**
+ * Builder class.
+ */
+ public static class Builder extends InputStreamParserSession.Builder {
+
+ private final String nullKeyString;
+
+ /**
+ * Constructor
+ *
+ * @param ctx The context creating this session.
+ */
+ protected Builder(BsonParser ctx) {
+ super(assertArgNotNull(ARG_ctx, ctx));
+ nullKeyString = ctx.getNullKeyString();
+ }
+
+ @Override
+ public BsonParserSession build() {
+ return new BsonParserSession(this);
+ }
+ }
+
+ /**
+ * Creates a new builder for a {@link BsonParserSession}.
+ *
+ * @param ctx The BSON parser context creating this session.
+ * @return A new builder.
+ */
+ public static Builder create(BsonParser ctx) {
+ return new Builder(assertArgNotNull(ARG_ctx, ctx));
+ }
+
+ private final String nullKeyString;
+
+ protected BsonParserSession(Builder builder) {
+ super(builder);
+ nullKeyString = builder.nullKeyString;
+ }
+
+ private String trimKey(String name) {
+ return isTrimStrings() && nn(name) ? name.trim() : name;
+ }
+
+ private Object readTypedValue(BsonInputStream is, int elementType, ClassMeta<?> targetType, Object outer, BeanPropertyMeta pMeta) throws IOException, ParseException, ExecutableException {
+ Object o = switch (elementType) {
+ case 0x01 -> is.readDouble();
+ case 0x02 -> trim(is.readString());
+ case 0x03 -> parseDocument(is, targetType, outer, pMeta);
+ case 0x04 -> parseArray(is, targetType, outer, pMeta);
+ case 0x05 -> is.readBinary();
+ case 0x07 -> is.readObjectId();
+ case 0x08 -> is.readBoolean();
+ case 0x09 -> is.readDateTime();
+ case 0x0A -> null;
+ case 0x10 -> is.readInt32();
+ case 0x12 -> is.readInt64();
+ case 0x13 -> is.readDecimal128();
+ default -> {
+ is.skipValue(elementType);
+ yield null;
+ }
+ };
+ if (nn(outer) && nn(o))
+ setParent(targetType, o, outer);
+ return o;
+ }
+
+ private <T> T parseDocument(BsonInputStream is, ClassMeta<?> eType, Object outer, BeanPropertyMeta pMeta) throws IOException, ParseException, ExecutableException {
+ is.readDocumentSize();
+ if (eType == null)
+ eType = object();
+
+ var swap = (ObjectSwap<T,Object>)eType.getSwap(this);
+ var builder = (BuilderSwap<T,Object>)eType.getBuilderSwap(this);
+ ClassMeta<?> sType = nn(builder) ? builder.getBuilderClassMeta(this) : (nn(swap) ? swap.getSwapClassMeta(this) : eType);
+
+ // Do not recurse for Optional here - BSON wraps non-bean/map roots as {"value":x}.
+ // We must parse the document first, then unwrap via the map.size()==1 / "value" path below.
+ var wrapInOptional = eType.isOptional();
+ if (sType.isOptional())
+ sType = eType.getElementType();
+
+ setCurrentClass(sType);
+
+ Object result;
+ // Skip map path for Optional - we need fallback to unwrap {"value":x}
+ if (!eType.isOptional() && sType.isMap()) {
+ var map = sType.canCreateNewInstance(outer) ? (Map)sType.newInstance(outer) : newGenericMap(sType);
+ while (!is.isDocumentEnd()) {
+ var et = is.readElementType();
+ var name = is.readElementName();
+ var key = name.equals(nullKeyString) ? null : trimKey(name);
+ var value = readTypedValue(is, et, sType.getValueType(), map, pMeta);
+ setName(sType.getValueType(), value, key);
+ map.put(key, value);
+ }
+ is.readDocumentTerminator();
+ var raw = map instanceof JsonMap ? cast((JsonMap)map, pMeta, eType) : map;
+ // Convert JsonMap to target map type (TreeMap, LinkedHashMap, etc.) when needed
+ if (eType.isMap() && raw instanceof Map mr && !eType.inner().isInstance(raw))
+ result = convertToMemberType(null, mr, eType);
+ else
+ result = raw;
+ } else if (!eType.isOptional() && (nn(builder) || sType.canCreateNewBean(outer))) {
+ var beanMap = builder == null ? newBeanMap(outer, sType.inner()) : toBeanMap(builder.create(this, eType));
+ while (!is.isDocumentEnd()) {
+ var et = is.readElementType();
+ var name = is.readElementName();
+ var key = trimKey(name);
+ var bpm = beanMap.getPropertyMeta(key);
+ Object value;
+ if ("_type".equals(name)) {
+ value = readTypedValue(is, et, string(), null, null);
+ if (nn(value))
+ beanMap = applyTypeProperty(beanMap, value.toString(), eType);
+ } else if (bpm != null) {
+ value = readTypedValue(is, et, bpm.getClassMeta(), beanMap.getBean(false), bpm);
+ setName(bpm.getClassMeta(), value, key);
+ try {
+ bpm.set(beanMap, key, value);
+ } catch (BeanRuntimeException e) {
+ onBeanSetterException(nn(pMeta) ? pMeta : bpm, e);
+ throw e;
+ }
+ } else {
+ onUnknownProperty(key, beanMap, readTypedValue(is, et, object(), null, null));
+ }
+ }
+ is.readDocumentTerminator();
+ result = builder == null ? beanMap.getBean() : builder.build(this, beanMap.getBean(), eType);
+ } else {
+ // Fallback: read document elements. Handles scalar, array, Optional roots (all wrapped as {"value":x}).
+ // Do NOT call parseArray here - at root the next bytes are type+name of first element, not array doc.
+ var map = new JsonMap(this);
+ while (!is.isDocumentEnd()) {
+ var et = is.readElementType();
+ var name = is.readElementName();
+ var key = name.equals(nullKeyString) ? null : trimKey(name);
+ map.put(key, readTypedValue(is, et, "value".equals(name) ? eType : object(), map, null));
+ }
+ is.readDocumentTerminator();
+ // Unwrap {"value":x} when target is Optional or when scalar-like (BSON root wrap convention)
+ if (map.size() == 1 && map.containsKey("value")) {
+ var wrapped = map.get("value");
+ if (eType.isOptional() || (!sType.isMap() && !sType.isBean() && !sType.isObject())
+ || (wrapped == null && sType.isObject())) {
+ result = convertToMemberType(null, wrapped, eType);
+ if (eType.isOptional())
+ wrapInOptional = false; // convertToMemberType already wrapped
+ } else {
+ var castResult = cast(map, pMeta, eType);
+ result = (eType.isMap() && castResult instanceof Map && !eType.inner().isInstance(castResult))
+ ? convertToMemberType(null, castResult, eType) : castResult;
+ }
+ } else {
+ var castResult = cast(map, pMeta, eType);
+ result = (eType.isMap() && castResult instanceof Map && !eType.inner().isInstance(castResult))
+ ? convertToMemberType(null, castResult, eType) : castResult;
+ }
+ }
+ // Final fallback: when target is Optional and we have map with "value", unwrap
+ if (eType.isOptional() && result instanceof Map m && m.size() == 1 && m.containsKey("value")) {
+ result = convertToMemberType(null, m.get("value"), eType);
+ wrapInOptional = false; // convertToMemberType already wrapped
+ }
+ // Convert JsonMap to target Map type (TreeMap, LinkedHashMap, etc.) when needed
+ if (eType.isMap() && result instanceof Map m2 && !eType.inner().isInstance(result))
+ result = convertToMemberType(null, m2, eType);
+ // Unswap when result is in swapped form (e.g. JsonMap for bean with Map swap, String for Class).
+ // Skip when convertToMemberType already produced normal form (e.g. Class from String).
+ if (nn(swap) && nn(result) && swap.isSwappedObject(result))
+ result = unswap(swap, result, eType);
+ return (T)(wrapInOptional ? opt(result) : result);
+ }
+
+ private BeanMap<?> applyTypeProperty(BeanMap<?> beanMap, String typeName, ClassMeta<?> eType) throws ExecutableException {
+ var cm = getBeanRegistry().getClassMeta(typeName);
+ if (nn(cm) && nn(eType) && eType.isAssignableFrom(cm))
+ return toBeanMap(newBean(cm.inner()));
+ return beanMap;
+ }
+
+ private Object parseArray(BsonInputStream is, ClassMeta<?> eType, Object outer, BeanPropertyMeta pMeta) throws IOException, ParseException, ExecutableException {
+ is.readDocumentSize();
+ if (eType == null)
+ eType = object();
+
+ var sType = eType;
+ // Do not recurse for Optional - parse array elements with inner type, wrap at end
+ if (sType.isOptional())
+ sType = eType.getElementType();
+
+ // Array types (String[], int[][], etc.) must use a Collection to gather elements; toArray() converts at the end.
+ // ClassMeta.newInstance() for array types returns an empty array, not a Collection - never use it for arrays.
+ // Only use sType.newInstance() for actual Collection types (List, Set, etc.).
+ Collection coll;
+ if (sType.isArray() || sType.isArgs() || sType.inner().isArray())
+ coll = new JsonList(this);
+ else {
+ var instance = sType.canCreateNewInstance(outer) ? sType.newInstance(outer) : null;
+ coll = (instance instanceof Collection c) ? c : new JsonList(this);
+ }
+ var elementType = def(sType.getElementType(), object());
+
+ while (!is.isDocumentEnd()) {
+ var et = is.readElementType();
+ is.readElementName();
+ coll.add(readTypedValue(is, et, elementType, coll, null));
+ }
+ is.readDocumentTerminator();
+
+ Object result = sType.isArray() || sType.isArgs() ? toArray(sType, coll) : coll;
+ return eType.isOptional() ? opt(result) : result;
+ }
+
+ @Override
+ protected <T> T doParse(ParserPipe pipe, ClassMeta<T> type) throws IOException, ParseException, ExecutableException {
+ try (var is = new BsonInputStream(pipe)) {
+ return (T)parseDocument(is, type, getOuter(), null);
+ }
+ }
+}
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonSerializer.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonSerializer.java
new file mode 100644
index 0000000000..0161a00a07
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonSerializer.java
@@ -0,0 +1,332 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson;
+
+import static org.apache.juneau.commons.utils.AssertionUtils.*;
+import static org.apache.juneau.commons.utils.Utils.*;
+
+import java.util.*;
+import java.util.concurrent.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.commons.collections.*;
+import org.apache.juneau.serializer.*;
+
+/**
+ * Serializes POJO models to BSON (Binary JSON).
+ *
+ * <h5 class='section'>Media types:</h5>
+ *
+ * Handles <c>Accept</c> types: <bc>application/bson</bc>
+ * <p>
+ * Produces <c>Content-Type</c> types: <bc>application/bson</bc>
+ *
+ * <h5 class='topic'>Description</h5>
+ * <p>
+ * Java-to-BSON type mapping:
+ * <ul class='spaced-list'>
+ * <li>Maps and beans → BSON document (type 0x03)
+ * <li>Collections and arrays → BSON array (type 0x04, document with numeric string keys)
+ * <li>{@link String} / {@link Enum} → BSON string (type 0x02)
+ * <li>{@link Boolean} → BSON boolean (type 0x08)
+ * <li>{@code int} / {@code short} / {@code byte} → BSON int32 (type 0x10)
+ * <li>{@code long} → BSON int64 (type 0x12)
+ * <li>{@code float} / {@code double} → BSON double (type 0x01)
+ * <li>{@link java.util.Date} / {@link java.util.Calendar} / {@link java.time.Instant} → BSON datetime (type 0x09) when
+ * {@code writeDatesAsDatetime=true}; otherwise ISO 8601 string
+ * <li>{@link java.time.Duration} → ISO 8601 duration string
+ * <li>{@code byte[]} → BSON binary (type 0x05, subtype 0x00)
+ * <li>{@link java.math.BigDecimal} / {@link java.math.BigInteger} → BSON decimal128 (type 0x13)
+ * <li>{@code null} → BSON null (type 0x0A)
+ * <li>All other types → fallback to {@code toString()} as string
+ * </ul>
+ *
+ * <h5 class='section'>Notes:</h5><ul>
+ * <li class='note'>This class is thread safe and reusable.
+ * </ul>
+ *
+ * <h5 class='section'>Limitations:</h5><ul>
+ * <li>BSON requires a top-level document. Standalone scalars, collections, and arrays are wrapped as <c>{value: x}</c>.
+ * <li>Map keys must be strings. Non-string keys use <c>toString()</c>. Null keys use a configurable placeholder.
+ * <li>ObjectId (0x07) is not generated; parsing returns 24-character hex strings.
+ * <li>Deprecated types (Undefined, DBPointer, Symbol, JS with Scope) are skipped during parsing.
+ * <li>MongoDB-internal types (JavaScript, Timestamp, MinKey, MaxKey) are not supported.
+ * <li>BSON is binary; <c>SpacedHex</c> and <c>Base64</c> subclasses provide text-encodable output.
+ * </ul>
+ *
+ * <h5 class='section'>Example:</h5>
+ * <p class='bjava'>
+ * <jc>// Serialize a POJO to BSON</jc>
+ * byte[] <jv>bson</jv> = BsonSerializer.<jsf>DEFAULT</jsf>.serialize(<jv>someObject</jv>);
+ *
+ * <jc>// Create a serializer that writes dates as ISO 8601 strings instead of BSON datetime</jc>
+ * BsonSerializer <jv>s</jv> = BsonSerializer.<jsm>create</jsm>().writeDatesAsDatetime(<jk>false</jk>).build();
+ *
+ * <jc>// Or use the marshaller for convenience</jc>
+ * <jv>bson</jv> = Bson.<jsm>of</jsm>(<jv>someObject</jv>);
+ * </p>
+ *
+ * <h5 class='section'>See Also:</h5><ul>
+ * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/BsonBasics">BSON Basics</a>
+ * </ul>
+ */
+@SuppressWarnings({
+ "java:S110", // Inheritance depth acceptable for this class hierarchy
+ "java:S115", // Constants use UPPER_snakeCase naming convention
+})
+public class BsonSerializer extends OutputStreamSerializer implements BsonMetaProvider {
+
+ // Argument name constants for assertArgNotNull
+ private static final String ARG_builder = "builder";
+ private static final String ARG_copyFrom = "copyFrom";
+
+ // Property name constants
+ private static final String PROP_addBeanTypesBson = "addBeanTypesBson";
+ private static final String PROP_nullKeyString = "nullKeyString";
+ private static final String PROP_writeDatesAsDatetime = "writeDatesAsDatetime";
+
+ /** Default serializer, BASE64 string output. */
+ public static class Base64 extends BsonSerializer {
+
+ /**
+ * Constructor.
+ *
+ * @param builder The builder for this object.
+ */
+ public Base64(Builder builder) {
+ super(assertArgNotNull(ARG_builder, builder).binaryFormat(BinaryFormat.BASE64));
+ }
+ }
+
+ /**
+ * Builder class.
+ */
+ public static class Builder extends OutputStreamSerializer.Builder {
+
+ private static final Cache<HashKey,BsonSerializer> CACHE = Cache.of(HashKey.class, BsonSerializer.class).build();
+
+ private boolean addBeanTypesBson;
+ private String nullKeyString = "<NULL>";
+ private boolean writeDatesAsDatetime = true;
+
+ /**
+ * Constructor, default settings.
+ */
+ protected Builder() {
+ produces("application/bson");
+ accept("application/bson");
+ addBeanTypesBson = env("BsonSerializer.addBeanTypesBson", false);
+ nullKeyString = env("BsonSerializer.nullKeyString", "<NULL>");
+ writeDatesAsDatetime = env("BsonSerializer.writeDatesAsDatetime", true);
+ }
+
+ /**
+ * Copy constructor.
+ *
+ * @param copyFrom The builder to copy from.
+ */
+ protected Builder(Builder copyFrom) {
+ super(assertArgNotNull(ARG_copyFrom, copyFrom));
+ addBeanTypesBson = copyFrom.addBeanTypesBson;
+ nullKeyString = copyFrom.nullKeyString;
+ writeDatesAsDatetime = copyFrom.writeDatesAsDatetime;
+ }
+
+ /**
+ * Copy constructor.
+ *
+ * @param copyFrom The bean to copy from.
+ */
+ protected Builder(BsonSerializer copyFrom) {
+ super(assertArgNotNull(ARG_copyFrom, copyFrom));
+ addBeanTypesBson = copyFrom.addBeanTypesBson;
+ nullKeyString = copyFrom.nullKeyString;
+ writeDatesAsDatetime = copyFrom.writeDatesAsDatetime;
+ }
+
+ /**
+ * Add <js>"_type"</js> properties when needed.
+ *
+ * @param value The value for this setting.
+ * @return This object.
+ */
+ public Builder addBeanTypesBson(boolean value) {
+ addBeanTypesBson = value;
+ return this;
+ }
+
+ /**
+ * The string used to represent <jk>null</jk> map keys in BSON documents.
+ *
+ * <p>
+ * BSON document field names cannot be <jk>null</jk>. When serializing a {@link Map} with a <jk>null</jk> key,
+ * this string is used as the field name. When parsing, a field with this name is stored with <jk>null</jk>
+ * as the key.
+ *
+ * @param value The placeholder string for null keys. Default is <js>"<NULL>"</js>.
+ * @return This object.
+ */
+ public Builder nullKeyString(String value) {
+ nullKeyString = value == null ? "<NULL>" : value;
+ return this;
+ }
+
+ /**
+ * Use BSON datetime type for dates. When <jk>false</jk>, dates are serialized as ISO-8601 strings.
+ *
+ * @param value The value for this setting.
+ * @return This object.
+ */
+ public Builder writeDatesAsDatetime(boolean value) {
+ writeDatesAsDatetime = value;
+ return this;
+ }
+
+ @Override /* OutputStreamSerializer.Builder */
+ public Builder binaryFormat(BinaryFormat value) {
+ super.binaryFormat(value);
+ return this;
+ }
+
+ @Override /* Serializer.Builder */
+ public Builder keepNullProperties() {
+ super.keepNullProperties();
+ return this;
+ }
+
+ @Override /* Serializer.Builder */
+ public Builder keepNullProperties(boolean value) {
+ super.keepNullProperties(value);
+ return this;
+ }
+
+ @Override /* Serializer.Builder */
+ public Builder addRootType() {
+ super.addRootType();
+ return this;
+ }
+
+ @Override /* Serializer.Builder */
+ public Builder addRootType(boolean value) {
+ super.addRootType(value);
+ return this;
+ }
+
+ @Override /* Context.Builder */
+ public BsonSerializer build() {
+ return cache(CACHE).build(BsonSerializer.class);
+ }
+
+ @Override /* Context.Builder */
+ public HashKey hashKey() {
+ return HashKey.of(super.hashKey(), addBeanTypesBson, nullKeyString, writeDatesAsDatetime);
+ }
+
+ @Override /* Context.Builder */
+ public Builder copy() {
+ return new Builder(this);
+ }
+ }
+
+ /** Default serializer, spaced-hex string output. */
+ public static class SpacedHex extends BsonSerializer {
+
+ /**
+ * Constructor.
+ *
+ * @param builder The builder for this object.
+ */
+ public SpacedHex(Builder builder) {
+ super(builder.binaryFormat(BinaryFormat.SPACED_HEX));
+ }
+ }
+
+ /** Default serializer, all default settings. */
+ public static final BsonSerializer DEFAULT = new BsonSerializer(create());
+ /** Default serializer, spaced-hex string output. */
+ public static final BsonSerializer DEFAULT_SPACED_HEX = new SpacedHex(create());
+ /** Default serializer, BASE64 string output. */
+ public static final BsonSerializer DEFAULT_BASE64 = new Base64(create());
+
+ /**
+ * Creates a new builder for this object.
+ *
+ * @return A new builder.
+ */
+ public static Builder create() {
+ return new Builder();
+ }
+
+ protected final boolean addBeanTypesBson;
+ protected final String nullKeyString;
+ protected final boolean writeDatesAsDatetime;
+
+ private final Map<BeanPropertyMeta,BsonBeanPropertyMeta> bsonBeanPropertyMetas = new ConcurrentHashMap<>();
+ private final Map<ClassMeta<?>,BsonClassMeta> bsonClassMetas = new ConcurrentHashMap<>();
+
+ /**
+ * Constructor.
+ *
+ * @param builder The builder for this object.
+ */
+ public BsonSerializer(Builder builder) {
+ super(builder);
+ addBeanTypesBson = builder.addBeanTypesBson;
+ nullKeyString = builder.nullKeyString;
+ writeDatesAsDatetime = builder.writeDatesAsDatetime;
+ }
+
+ @Override /* Context */
+ public Builder copy() {
+ return new Builder(this);
+ }
+
+ @Override /* Context */
+ public BsonSerializerSession.Builder createSession() {
+ return BsonSerializerSession.create(this);
+ }
+
+ @Override /* BsonMetaProvider */
+ public BsonBeanPropertyMeta getBsonBeanPropertyMeta(BeanPropertyMeta bpm) {
+ if (bpm == null)
+ return BsonBeanPropertyMeta.DEFAULT;
+ return bsonBeanPropertyMetas.computeIfAbsent(bpm, k -> new BsonBeanPropertyMeta(k.getDelegateFor(), this));
+ }
+
+ @Override /* BsonMetaProvider */
+ public BsonClassMeta getBsonClassMeta(ClassMeta<?> cm) {
+ return bsonClassMetas.computeIfAbsent(cm, k -> new BsonClassMeta(k, this));
+ }
+
+ @Override /* Context */
+ public BsonSerializerSession getSession() {
+ return createSession().build();
+ }
+
+ @Override
+ protected final boolean isAddBeanTypes() {
+ return addBeanTypesBson || super.isAddBeanTypes();
+ }
+
+ @Override /* OutputStreamSerializer */
+ protected FluentMap<String,Object> properties() {
+ return super.properties()
+ .a(PROP_addBeanTypesBson, addBeanTypesBson)
+ .a(PROP_nullKeyString, nullKeyString)
+ .a(PROP_writeDatesAsDatetime, writeDatesAsDatetime);
+ }
+}
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonSerializerSession.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonSerializerSession.java
new file mode 100644
index 0000000000..e31b813cf4
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/BsonSerializerSession.java
@@ -0,0 +1,317 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson;
+
+import static org.apache.juneau.bson.DataType.*;
+import static org.apache.juneau.commons.utils.AssertionUtils.*;
+import static org.apache.juneau.commons.utils.Utils.*;
+
+import java.io.*;
+import java.math.*;
+import java.time.*;
+import java.time.temporal.Temporal;
+import java.util.*;
+import java.util.function.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.serializer.*;
+import org.apache.juneau.utils.Iso8601Utils;
+
+/**
+ * Session object that lives for the duration of a single use of {@link BsonSerializer}.
+ *
+ * <h5 class='section'>Notes:</h5><ul>
+ * <li class='warn'>This class is not thread safe and is typically discarded after one use.
+ * </ul>
+ *
+ * <h5 class='section'>See Also:</h5><ul>
+ * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/BsonBasics">BSON Basics</a>
+ * </ul>
+ */
+@SuppressWarnings({
+ "resource", // Output streams managed by calling code
+ "rawtypes", // Raw types necessary for generic type handling
+ "java:S110", // Inheritance depth acceptable for serializer session hierarchy
+ "java:S115", // Constants use UPPER_snakeCase convention
+ "java:S3776" // Cognitive complexity acceptable for serialization dispatch logic
+})
+public class BsonSerializerSession extends OutputStreamSerializerSession {
+
+ private static final String ARG_ctx = "ctx";
+
+ /**
+ * Builder class.
+ */
+ public static class Builder extends OutputStreamSerializerSession.Builder {
+
+ private BsonSerializer ctx;
+
+ /**
+ * Constructor
+ *
+ * @param ctx The context creating this session.
+ */
+ protected Builder(BsonSerializer ctx) {
+ super(assertArgNotNull(ARG_ctx, ctx));
+ this.ctx = ctx;
+ }
+
+ @Override
+ public BsonSerializerSession build() {
+ return new BsonSerializerSession(this);
+ }
+ }
+
+ /**
+ * Creates a new builder for this object.
+ *
+ * @param ctx The context creating this session.
+ * @return A new builder.
+ */
+ public static Builder create(BsonSerializer ctx) {
+ return new Builder(assertArgNotNull(ARG_ctx, ctx));
+ }
+
+ private static BsonOutputStream getBsonOutputStream(SerializerPipe out) throws IOException {
+ Object output = out.getRawOutput();
+ if (output instanceof BsonOutputStream output2)
+ return output2;
+ var os = new BsonOutputStream(out.getOutputStream());
+ out.setOutputStream(os);
+ return os;
+ }
+
+ private final BsonSerializer ctx;
+
+ protected BsonSerializerSession(Builder builder) {
+ super(builder);
+ ctx = builder.ctx;
+ }
+
+ private void writeElement(BsonOutputStream out, String name, Object o, ClassMeta<?> eType, BeanPropertyMeta pMeta) throws SerializeException {
+ if (o == null) {
+ out.writeElement(NULL.value, name);
+ return;
+ }
+ if (eType == null)
+ eType = object();
+
+ var aType = push2(name, o, eType);
+ if (aType == null) {
+ out.writeElement(NULL.value, name);
+ pop();
+ return;
+ }
+
+ if (isOptional(aType)) {
+ o = getOptionalValue(o);
+ eType = getOptionalType(eType);
+ aType = getClassMetaForObject(o, object());
+ }
+
+ var sType = aType;
+ var swap = aType.getSwap(this);
+ if (nn(swap)) {
+ o = swap(swap, o);
+ sType = swap.getSwapClassMeta(this);
+ if (sType.isObject())
+ sType = getClassMetaForObject(o);
+ }
+
+ if (o == null || (sType.isChar() && ((Character)o).charValue() == 0)) {
+ out.writeElement(NULL.value, name);
+ } else if (sType.isBoolean()) {
+ out.writeElement(BOOLEAN.value, name);
+ out.writeBoolean((Boolean)o);
+ } else if (sType.isNumber()) {
+ if (sType.inner() == int.class || sType.inner() == short.class || sType.inner() == byte.class
+ || sType.inner() == Integer.class || sType.inner() == Short.class || sType.inner() == Byte.class) {
+ out.writeElement(INT32.value, name);
+ out.writeInt32(((Number)o).intValue());
+ } else if (sType.inner() == long.class || sType.inner() == Long.class) {
+ out.writeElement(INT64.value, name);
+ out.writeInt64(((Number)o).longValue());
+ } else if (sType.inner() == BigDecimal.class) {
+ out.writeElement(DECIMAL128.value, name);
+ out.writeDecimal128((BigDecimal)o);
+ } else if (sType.inner() == BigInteger.class) {
+ out.writeElement(DECIMAL128.value, name);
+ out.writeDecimal128(new BigDecimal((BigInteger)o));
+ } else {
+ out.writeElement(DOUBLE.value, name);
+ out.writeDouble(((Number)o).doubleValue());
+ }
+ } else if (sType.isDateOrCalendarOrTemporal() && ctx.writeDatesAsDatetime) {
+ out.writeElement(DATETIME.value, name);
+ out.writeDateTime(toEpochMillis(o));
+ } else if (sType.isDateOrCalendarOrTemporal() && !ctx.writeDatesAsDatetime) {
+ out.writeElement(STRING.value, name);
+ out.writeString(Iso8601Utils.format(o, sType, getTimeZone()));
+ } else if (sType.isDuration()) {
+ out.writeElement(STRING.value, name);
+ out.writeString(o.toString());
+ } else if (sType.isBean()) {
+ out.writeElement(DOCUMENT.value, name);
+ var child = out.createChild();
+ child.startDocument();
+ serializeBeanMap(child, toBeanMap(o), getBeanTypeName(this, eType, aType, pMeta));
+ out.writeChildDocument(child);
+ } else if (sType.isUri() || (nn(pMeta) && pMeta.isUri())) {
+ out.writeElement(STRING.value, name);
+ out.writeString(resolveUri(o.toString()));
+ } else if (sType.isMap()) {
+ if (o instanceof BeanMap o2) {
+ out.writeElement(DOCUMENT.value, name);
+ var child = out.createChild();
+ child.startDocument();
+ serializeBeanMap(child, o2, getBeanTypeName(this, eType, aType, pMeta));
+ out.writeChildDocument(child);
+ } else {
+ out.writeElement(DOCUMENT.value, name);
+ var child = out.createChild();
+ child.startDocument();
+ serializeMap(child, (Map)o, eType);
+ out.writeChildDocument(child);
+ }
+ } else if (sType.isByteArray()) {
+ out.writeElement(BINARY.value, name);
+ out.writeBinary((byte[])o);
+ } else if (sType.isCollection() || sType.isArray()) {
+ out.writeElement(ARRAY.value, name);
+ var child = out.createChild();
+ child.startDocument();
+ serializeArray(child, sType.isArray() ? toList(sType.inner(), o) : (Collection)o, eType);
+ out.writeChildDocument(child);
+ } else if (sType.isStreamable()) {
+ out.writeElement(ARRAY.value, name);
+ var child = out.createChild();
+ child.startDocument();
+ serializeArray(child, toListFromStreamable(o, sType), eType);
+ out.writeChildDocument(child);
+ } else if (sType.isCharSequence() || sType.isChar() || sType.isEnum()) {
+ out.writeElement(STRING.value, name);
+ out.writeString(trim(o));
+ } else {
+ out.writeElement(STRING.value, name);
+ out.writeString(toString(o));
+ }
+ pop();
+ }
+
+ private void serializeBeanMap(BsonOutputStream out, BeanMap<?> m, String typeName) throws SerializeException {
+ Predicate<Object> checkNull = x -> isKeepNullProperties() || nn(x);
+ var values = new ArrayList<BeanPropertyValue>();
+
+ if (nn(typeName)) {
+ var pm = m.getMeta().getTypeProperty();
+ if (pm != null)
+ values.add(new BeanPropertyValue(pm, pm.getName(), typeName, null));
+ }
+
+ m.forEachValue(checkNull, (pMeta, key, value, thrown) -> {
+ if (nn(thrown)) {
+ onBeanGetterException(pMeta, thrown);
+ return;
+ }
+ var p = new BeanPropertyValue(pMeta, key, value, null);
+ if (!isKeepNullProperties() && willRecurse(p))
+ return;
+ values.add(p);
+ });
+
+ for (var x : values) {
+ var pMeta = x.getMeta();
+ if (pMeta.canRead())
+ writeElement(out, x.getName(), x.getValue(), x.getClassMeta(), pMeta);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private void serializeArray(BsonOutputStream out, Collection c, ClassMeta<?> type) throws SerializeException {
+ var elementType = type.getElementType();
+ c = sort(c);
+ var idx = 0;
+ for (var x : c)
+ writeElement(out, String.valueOf(idx++), x, elementType, null);
+ }
+
+ @SuppressWarnings("unchecked")
+ private void serializeMap(BsonOutputStream out, Map m, ClassMeta<?> type) throws SerializeException {
+ var valueType = type.getValueType();
+ var keyType = type.getKeyType();
+ m = sort(m);
+ for (Map.Entry<?,?> entry : ((Map<?,?>)m).entrySet()) {
+ var key = generalize(entry.getKey(), keyType);
+ var name = (key == null) ? ctx.nullKeyString : trim(key);
+ writeElement(out, name, entry.getValue(), valueType, null);
+ }
+ }
+
+ private static long toEpochMillis(Object o) {
+ if (o instanceof java.util.Date d)
+ return d.getTime();
+ if (o instanceof java.util.Calendar c)
+ return c.getTimeInMillis();
+ if (o instanceof Instant i)
+ return i.toEpochMilli();
+ if (o instanceof Temporal t)
+ return Instant.from(t).toEpochMilli();
+ return 0L;
+ }
+
+ private boolean willRecurse(BeanPropertyValue v) throws SerializeException {
+ var aType = push2(v.getName(), v.getValue(), v.getClassMeta());
+ if (nn(aType))
+ pop();
+ return aType == null;
+ }
+
+ @Override
+ protected void doSerialize(SerializerPipe out, Object o) throws IOException, SerializeException {
+ var bsonOut = getBsonOutputStream(out);
+ bsonOut.startDocument();
+
+ var eType = getExpectedRootType(o);
+ var aType = push2("root", o, eType);
+ ClassMeta<?> sType = aType;
+ if (nn(aType)) {
+ var swap = aType.getSwap(this);
+ if (nn(swap)) {
+ o = swap(swap, o);
+ sType = swap.getSwapClassMeta(this);
+ }
+ }
+
+ if (sType != null && sType.isBean()) {
+ pop();
+ serializeBeanMap(bsonOut, toBeanMap(o), getBeanTypeName(this, eType, sType, null));
+ } else if (sType != null && sType.isMap() && !(o instanceof BeanMap)) {
+ pop();
+ serializeMap(bsonOut, (Map)o, eType);
+ } else {
+ pop();
+ writeElement(bsonOut, "value", o, eType, null);
+ }
+
+ bsonOut.writeDocumentTo(out.getOutputStream());
+ }
+
+ @Override
+ protected boolean isAddBeanTypes() {
+ return ctx.isAddBeanTypes();
+ }
+}
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/DataType.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/DataType.java
new file mode 100644
index 0000000000..b27b06cfda
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/DataType.java
@@ -0,0 +1,100 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson;
+
+/**
+ * BSON element type codes per the
+ * <a class="doclink" href="https://bsonspec.org/spec.html">BSON Specification 1.1</a>.
+ *
+ * <h5 class='section'>See Also:</h5><ul>
+ * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/BsonBasics">BSON Basics</a>
+ * </ul>
+ */
+public enum DataType {
+
+ /** 64-bit IEEE 754 double. */
+ DOUBLE(0x01),
+ /** UTF-8 string. */
+ STRING(0x02),
+ /** Embedded document. */
+ DOCUMENT(0x03),
+ /** Array (document with numeric keys). */
+ ARRAY(0x04),
+ /** Binary data. */
+ BINARY(0x05),
+ /** Deprecated undefined. */
+ UNDEFINED(0x06),
+ /** MongoDB ObjectId (12 bytes). */
+ OBJECT_ID(0x07),
+ /** Boolean. */
+ BOOLEAN(0x08),
+ /** UTC datetime (int64 millis). */
+ DATETIME(0x09),
+ /** Null value. */
+ NULL(0x0A),
+ /** Regular expression. */
+ REGEX(0x0B),
+ /** Deprecated DBPointer. */
+ DB_POINTER(0x0C),
+ /** JavaScript code. */
+ JAVASCRIPT(0x0D),
+ /** Deprecated symbol. */
+ SYMBOL(0x0E),
+ /** JavaScript with scope. */
+ JS_WITH_SCOPE(0x0F),
+ /** 32-bit integer. */
+ INT32(0x10),
+ /** MongoDB timestamp. */
+ TIMESTAMP(0x11),
+ /** 64-bit integer. */
+ INT64(0x12),
+ /** IEEE 754-2008 decimal128. */
+ DECIMAL128(0x13),
+ /** MinKey (sort order). */
+ MIN_KEY(0xFF),
+ /** MaxKey (sort order). */
+ MAX_KEY(0x7F);
+
+ private static final DataType[] BY_VALUE;
+
+ static {
+ var max = 256;
+ BY_VALUE = new DataType[max];
+ for (var dt : values()) {
+ var v = dt.value & 0xFF;
+ if (v < max)
+ BY_VALUE[v] = dt;
+ }
+ }
+
+ final int value;
+
+ DataType(int value) {
+ this.value = value;
+ }
+
+ /**
+ * Returns the DataType for the given byte value.
+ *
+ * @param b The byte value (0x01-0x13, 0x7F, 0xFF).
+ * @return The corresponding DataType, or <jk>null</jk> if unknown.
+ */
+ public static DataType fromByte(int b) {
+ var v = b & 0xFF;
+ return v < BY_VALUE.length ? BY_VALUE[v] : null;
+ }
+}
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/annotation/Bson.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/annotation/Bson.java
new file mode 100644
index 0000000000..a358615982
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/annotation/Bson.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson.annotation;
+
+import static java.lang.annotation.ElementType.*;
+import static java.lang.annotation.RetentionPolicy.*;
+
+import java.lang.annotation.*;
+
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.bson.*;
+
+/**
+ * Annotation that can be applied to classes, fields, and methods to tweak how they are handled by {@link BsonSerializer} and {@link BsonParser}.
+ *
+ * <p>
+ * Can be used in the following locations:
+ * <ul>
+ * <li>Marshalled classes/methods/fields.
+ * <li><ja>@Rest</ja>-annotated classes and <ja>@RestOp</ja>-annotated methods when an {@link #on()} value is specified.
+ * </ul>
+ *
+ * <h5 class='section'>See Also:</h5><ul>
+ * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/BsonBasics">BSON Basics</a>
+ * </ul>
+ */
+@Documented
+@Target({ TYPE, FIELD, METHOD })
+@Retention(RUNTIME)
+@Inherited
+@Repeatable(BsonAnnotation.Array.class)
+@ContextApply(BsonAnnotation.Apply.class)
+public @interface Bson {
+
+ /**
+ * Optional description for the exposed API.
+ *
+ * @return The annotation value.
+ * @since 9.2.0
+ */
+ String[] description() default {};
+
+ /**
+ * Dynamically apply this annotation to the specified classes/methods/fields.
+ *
+ * @return The annotation value.
+ */
+ String[] on() default {};
+
+ /**
+ * Dynamically apply this annotation to the specified classes.
+ *
+ * @return The annotation value.
+ */
+ Class<?>[] onClass() default {};
+}
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/annotation/BsonAnnotation.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/annotation/BsonAnnotation.java
new file mode 100644
index 0000000000..611ad5864d
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/annotation/BsonAnnotation.java
@@ -0,0 +1,170 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson.annotation;
+
+import static java.lang.annotation.ElementType.*;
+import static java.lang.annotation.RetentionPolicy.*;
+import static org.apache.juneau.commons.utils.CollectionUtils.*;
+
+import java.lang.annotation.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.commons.annotation.*;
+import org.apache.juneau.commons.reflect.*;
+import org.apache.juneau.svl.*;
+
+/**
+ * Utility classes and methods for the {@link Bson @Bson} annotation.
+ *
+ * <h5 class='section'>See Also:</h5><ul>
+ * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/BsonBasics">BSON Basics</a>
+ * </ul>
+ */
+public class BsonAnnotation {
+
+ /**
+ * Prevents instantiation.
+ */
+ private BsonAnnotation() {}
+
+ /**
+ * Applies targeted {@link Bson} annotations to a {@link Context.Builder}.
+ */
+ public static class Apply extends AnnotationApplier<Bson,Context.Builder> {
+
+ /**
+ * Constructor.
+ *
+ * @param vr The resolver for resolving values in annotations.
+ */
+ public Apply(VarResolverSession vr) {
+ super(Bson.class, Context.Builder.class, vr);
+ }
+
+ @Override
+ public void apply(AnnotationInfo<Bson> ai, Context.Builder b) {
+ Bson a = ai.inner();
+ if (isEmptyArray(a.on()) && isEmptyArray(a.onClass()))
+ return;
+ b.annotations(copy(a, vr()));
+ }
+ }
+
+ /**
+ * A collection of {@link Bson @Bson} annotations.
+ */
+ @Documented
+ @Target({ METHOD, TYPE })
+ @Retention(RUNTIME)
+ @Inherited
+ public static @interface Array {
+
+ /**
+ * The child annotations.
+ *
+ * @return The annotation value.
+ */
+ Bson[] value();
+ }
+
+ /**
+ * Creates a copy of the specified annotation.
+ *
+ * @param a The annotation to copy.
+ * @param r The var resolver for resolving any variables.
+ * @return A copy of the specified annotation.
+ */
+ public static Bson copy(Bson a, VarResolverSession r) {
+ var b = BsonAnnotation.create().on(r.resolve(a.on()));
+ if (a.onClass().length > 0)
+ b = b.onClass(a.onClass());
+ if (a.description().length > 0)
+ b = b.description(a.description());
+ return b.build();
+ }
+
+ /**
+ * Instantiates a new builder for this class.
+ *
+ * @return A new builder object.
+ */
+ public static BsonAnnotation.Builder create() {
+ return new BsonAnnotation.Builder();
+ }
+
+ /**
+ * Builder class.
+ */
+ public static class Builder extends AppliedAnnotationObject.BuilderTMF {
+
+ private String[] description = {};
+
+ /**
+ * Constructor.
+ */
+ protected Builder() {
+ super(Bson.class);
+ }
+
+ /**
+ * Instantiates a new {@link Bson @Bson} object initialized with this builder.
+ *
+ * @return A new {@link Bson @Bson} object.
+ */
+ public Bson build() {
+ return new BsonAnnotation.Object(this);
+ }
+
+ /**
+ * Sets the description property.
+ *
+ * @param value The new value.
+ * @return This object.
+ */
+ public Builder description(String...value) {
+ description = value;
+ return this;
+ }
+
+ @Override /* AppliedAnnotationObject.Builder */
+ public Builder on(String...value) {
+ super.on(value);
+ return this;
+ }
+
+ @Override /* AppliedAnnotationObject.BuilderT */
+ public Builder onClass(Class<?>...value) {
+ super.onClass(value);
+ return this;
+ }
+ }
+
+ private static class Object extends AppliedOnClassAnnotationObject implements Bson {
+
+ private final String[] description;
+
+ Object(BsonAnnotation.Builder b) {
+ super(b);
+ description = copyOf(b.description);
+ }
+
+ @Override /* Bson */
+ public String[] description() {
+ return description;
+ }
+ }
+}
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/annotation/BsonConfig.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/annotation/BsonConfig.java
new file mode 100644
index 0000000000..39723e5daf
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/annotation/BsonConfig.java
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson.annotation;
+
+import static java.lang.annotation.ElementType.*;
+import static java.lang.annotation.RetentionPolicy.*;
+
+import java.lang.annotation.*;
+
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.bson.*;
+
+/**
+ * Annotation for specifying config properties defined in {@link BsonSerializer} and {@link BsonParser}.
+ *
+ * <p>
+ * Used primarily for specifying bean configuration properties on REST classes and methods.
+ *
+ * <h5 class='section'>See Also:</h5><ul>
+ * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/BsonBasics">BSON Basics</a>
+ * </ul>
+ */
+@Target({ TYPE, METHOD })
+@Retention(RUNTIME)
+@Inherited
+@ContextApply({ BsonConfigAnnotation.SerializerApply.class, BsonConfigAnnotation.ParserApply.class })
+public @interface BsonConfig {
+
+ /**
+ * Add <js>"_type"</js> properties when needed.
+ *
+ * <p>
+ * If <js>"true"</js>, then <js>"_type"</js> properties will be added to beans if their type cannot be inferred
+ * through reflection.
+ *
+ * <ul class='values'>
+ * <li><js>"true"</js>
+ * <li><js>"false"</js> (default)
+ * </ul>
+ *
+ * @return The annotation value.
+ */
+ String addBeanTypes() default "";
+
+ /**
+ * Use BSON datetime type for {@link java.util.Date}/{@link java.util.Calendar}/{@link java.time.Instant}.
+ *
+ * <p>
+ * If <js>"true"</js>, dates are serialized as BSON datetime (type 0x09). If <js>"false"</js>, dates are serialized as ISO-8601 strings.
+ *
+ * <ul class='values'>
+ * <li><js>"true"</js> (default)
+ * <li><js>"false"</js>
+ * </ul>
+ *
+ * @return The annotation value.
+ */
+ String writeDatesAsDatetime() default "";
+
+ /**
+ * Optional rank for this config.
+ *
+ * @return The annotation value.
+ */
+ int rank() default 0;
+}
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/annotation/BsonConfigAnnotation.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/annotation/BsonConfigAnnotation.java
new file mode 100644
index 0000000000..7d724265e5
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/annotation/BsonConfigAnnotation.java
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson.annotation;
+
+import org.apache.juneau.*;
+import org.apache.juneau.commons.reflect.*;
+import org.apache.juneau.bson.*;
+import org.apache.juneau.svl.*;
+
+/**
+ * Utility classes and methods for the {@link BsonConfig @BsonConfig} annotation.
+ *
+ * <h5 class='section'>See Also:</h5><ul>
+ * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/BsonBasics">BSON Basics</a>
+ * </ul>
+ */
+public class BsonConfigAnnotation {
+
+ /**
+ * Prevents instantiation.
+ */
+ private BsonConfigAnnotation() {}
+
+ /**
+ * Applies {@link BsonConfig} annotations to a {@link BsonParser.Builder}.
+ */
+ public static class ParserApply extends AnnotationApplier<BsonConfig,BsonParser.Builder> {
+
+ /**
+ * Constructor.
+ *
+ * @param vr The resolver for resolving values in annotations.
+ */
+ public ParserApply(VarResolverSession vr) {
+ super(BsonConfig.class, BsonParser.Builder.class, vr);
+ }
+
+ @Override
+ public void apply(AnnotationInfo<BsonConfig> ai, BsonParser.Builder b) {
+ // No-op for parser
+ }
+ }
+
+ /**
+ * Applies {@link BsonConfig} annotations to a {@link BsonSerializer.Builder}.
+ */
+ public static class SerializerApply extends AnnotationApplier<BsonConfig,BsonSerializer.Builder> {
+
+ /**
+ * Constructor.
+ *
+ * @param vr The resolver for resolving values in annotations.
+ */
+ public SerializerApply(VarResolverSession vr) {
+ super(BsonConfig.class, BsonSerializer.Builder.class, vr);
+ }
+
+ @Override
+ public void apply(AnnotationInfo<BsonConfig> ai, BsonSerializer.Builder b) {
+ BsonConfig a = ai.inner();
+
+ bool(a.addBeanTypes()).ifPresent(b::addBeanTypesBson);
+ bool(a.writeDatesAsDatetime()).ifPresent(b::writeDatesAsDatetime);
+ }
+ }
+}
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/annotation/package-info.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/annotation/package-info.java
new file mode 100644
index 0000000000..05a93ef393
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/annotation/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+/**
+ * BSON Marshalling Annotations
+ */
+package org.apache.juneau.bson.annotation;
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/package-info.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/package-info.java
new file mode 100644
index 0000000000..06d08fa32d
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/package-info.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+/**
+ * BSON (Binary JSON) marshalling support.
+ *
+ * <p>
+ * BSON is a binary serialization format used by MongoDB. It extends JSON with additional types
+ * (datetime, binary, 32-bit/64-bit integers, decimal128) and uses little-endian byte order.
+ *
+ * <p>
+ * Juneau provides {@link org.apache.juneau.bson.BsonSerializer} and {@link org.apache.juneau.bson.BsonParser} for
+ * serialization and parsing, plus {@link org.apache.juneau.marshaller.Bson} for a combined API.
+ *
+ * <h5 class='section'>Type mapping (summary)</h5>
+ * <ul class='spaced-list'>
+ * <li>Beans/maps → BSON document (0x03)
+ * <li>Collections/arrays → BSON array (0x04)
+ * <li>Strings/enums → BSON string (0x02)
+ * <li>Numbers → int32 (0x10), int64 (0x12), double (0x01), or decimal128 (0x13)
+ * <li>Dates → BSON datetime (0x09) or ISO 8601 string
+ * <li>{@code byte[]} → BSON binary (0x05)
+ * </ul>
+ *
+ * <p>
+ * Compared to MsgPack: BSON is length-prefixed and little-endian; supports typed integers (int32/int64),
+ * native datetime, and decimal128. Compared to JSON: BSON is binary and more compact for typed data.
+ *
+ * <h5 class='section'>See Also:</h5><ul>
+ * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/BsonBasics">BSON Basics</a>
+ * <li class='link'><a class="doclink" href="https://bsonspec.org/spec.html">BSON Specification</a>
+ * </ul>
+ */
+package org.apache.juneau.bson;
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshaller/Bson.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshaller/Bson.java
new file mode 100644
index 0000000000..659d825cda
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/marshaller/Bson.java
@@ -0,0 +1,216 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.marshaller;
+
+import java.io.*;
+import java.lang.reflect.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.bson.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+
+/**
+ * A pairing of a {@link BsonSerializer} and {@link BsonParser} into a single class with convenience read/write methods.
+ *
+ * <p>
+ * The general idea is to combine a single serializer and parser inside a simplified API for reading and writing POJOs.
+ *
+ * <h5 class='figure'>Examples:</h5>
+ * <p class='bjava'>
+ * <jc>// Using instance.</jc>
+ * Bson <jv>bson</jv> = <jk>new</jk> Bson();
+ * MyPojo <jv>myPojo</jv> = <jv>bson</jv>.read(<jv>bytes</jv>, MyPojo.<jk>class</jk>);
+ * <jk>byte</jk>[] <jv>bytes</jv> = <jv>bson</jv>.write(<jv>myPojo</jv>);
+ * </p>
+ * <p class='bjava'>
+ * <jc>// Using DEFAULT instance.</jc>
+ * MyPojo <jv>myPojo</jv> = Bson.<jsf>DEFAULT</jsf>.read(<jv>bytes</jv>, MyPojo.<jk>class</jk>);
+ * <jk>byte</jk>[] <jv>bytes</jv> = Bson.<jsf>DEFAULT</jsf>.write(<jv>myPojo</jv>);
+ * </p>
+ *
+ * <h5 class='section'>See Also:</h5><ul>
+ * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/Marshallers">Marshallers</a>
+ * </ul>
+ */
+public class Bson extends StreamMarshaller {
+
+ /**
+ * Default reusable instance.
+ */
+ public static final Bson DEFAULT = new Bson();
+
+ /**
+ * Serializes a Java object to BSON bytes.
+ *
+ * <p>
+ * A shortcut for calling <c><jsf>DEFAULT</jsf>.write(<jv>object</jv>)</c>.
+ *
+ * @param object The object to serialize.
+ * @return
+ * The serialized object.
+ * @throws SerializeException If a problem occurred trying to convert the output.
+ */
+ public static byte[] of(Object object) throws SerializeException {
+ return DEFAULT.write(object);
+ }
+
+ /**
+ * Serializes a Java object to an output.
+ *
+ * <p>
+ * A shortcut for calling <c><jsf>DEFAULT</jsf>.write(<jv>output</jv>)</c>.
+ *
+ * @param object The object to serialize.
+ * @param output
+ * The output object.
+ * <br>Can be any of the following types:
+ * <ul>
+ * <li>{@link OutputStream}
+ * <li>{@link File}
+ * </ul>
+ * @return The output object.
+ * @throws SerializeException If a problem occurred trying to convert the output.
+ * @throws IOException Thrown by underlying stream.
+ */
+ public static Object of(Object object, Object output) throws SerializeException, IOException {
+ DEFAULT.write(object, output);
+ return output;
+ }
+
+ /**
+ * Parses BSON input to the specified type.
+ *
+ * <p>
+ * A shortcut for calling <c><jsf>DEFAULT</jsf>.read(<jv>input</jv>, <jv>type</jv>)</c>.
+ *
+ * @param <T> The class type of the object being created.
+ * @param input The input.
+ * @param type The object type to create.
+ * @return The parsed object.
+ * @throws ParseException Malformed input encountered.
+ */
+ public static <T> T to(byte[] input, Class<T> type) throws ParseException {
+ return DEFAULT.read(input, type);
+ }
+
+ /**
+ * Parses BSON input to the specified Java type.
+ *
+ * <p>
+ * A shortcut for calling <c><jsf>DEFAULT</jsf>.read(<jv>input</jv>, <jv>type</jv>, <jv>args</jv>)</c>.
+ *
+ * @param <T> The class type of the object to create.
+ * @param input The input.
+ * @param type
+ * The object type to create.
+ * <br>Can be any of the following: {@link ClassMeta}, {@link Class}, {@link ParameterizedType}, {@link GenericArrayType}
+ * @param args
+ * The type arguments of the class if it's a collection or map.
+ * <br>Can be any of the following: {@link ClassMeta}, {@link Class}, {@link ParameterizedType}, {@link GenericArrayType}
+ * <br>Ignored if the main type is not a map or collection.
+ * @return The parsed object.
+ * @throws ParseException Malformed input encountered.
+ * @see BeanSession#getClassMeta(Type,Type...) for argument syntax for maps and collections.
+ */
+ public static <T> T to(byte[] input, Type type, Type...args) throws ParseException {
+ return DEFAULT.read(input, type, args);
+ }
+
+ /**
+ * Parses a BSON input object to the specified Java type.
+ *
+ * <p>
+ * A shortcut for calling <c><jsf>DEFAULT</jsf>.read(<jv>input</jv>, <jv>type</jv>)</c>.
+ *
+ * @param <T> The class type of the object being created.
+ * @param input
+ * The input.
+ * <br>Can be any of the following types:
+ * <ul>
+ * <li><jk>null</jk>
+ * <li>{@link InputStream}
+ * <li><code><jk>byte</jk>[]</code>
+ * <li>{@link File}
+ * <li>{@link CharSequence} containing encoded bytes according to the {@link org.apache.juneau.parser.InputStreamParser.Builder#binaryFormat(BinaryFormat)} setting.
+ * </ul>
+ * @param type The object type to create.
+ * @return The parsed object.
+ * @throws ParseException Malformed input encountered.
+ * @throws IOException Thrown by underlying stream.
+ */
+ public static <T> T to(Object input, Class<T> type) throws ParseException, IOException {
+ return DEFAULT.read(input, type);
+ }
+
+ /**
+ * Parses a BSON input object to the specified Java type.
+ *
+ * <p>
+ * A shortcut for calling <c><jsf>DEFAULT</jsf>.read(<jv>input</jv>, <jv>type</jv>, <jv>args</jv>)</c>.
+ *
+ * @param <T> The class type of the object to create.
+ * @param input
+ * The input.
+ * <br>Can be any of the following types:
+ * <ul>
+ * <li><jk>null</jk>
+ * <li>{@link InputStream}
+ * <li><code><jk>byte</jk>[]</code>
+ * <li>{@link File}
+ * <li>{@link CharSequence} containing encoded bytes according to the {@link org.apache.juneau.parser.InputStreamParser.Builder#binaryFormat(BinaryFormat)} setting.
+ * </ul>
+ * @param type
+ * The object type to create.
+ * <br>Can be any of the following: {@link ClassMeta}, {@link Class}, {@link ParameterizedType}, {@link GenericArrayType}
+ * @param args
+ * The type arguments of the class if it's a collection or map.
+ * <br>Can be any of the following: {@link ClassMeta}, {@link Class}, {@link ParameterizedType}, {@link GenericArrayType}
+ * <br>Ignored if the main type is not a map or collection.
+ * @return The parsed object.
+ * @throws ParseException Malformed input encountered.
+ * @throws IOException If an I/O error occurs.
+ * @see BeanSession#getClassMeta(Type,Type...) for argument syntax for maps and collections.
+ */
+ public static <T> T to(Object input, Type type, Type...args) throws ParseException, IOException {
+ return DEFAULT.read(input, type, args);
+ }
+
+ /**
+ * Constructor.
+ *
+ * <p>
+ * Uses {@link BsonSerializer#DEFAULT} and {@link BsonParser#DEFAULT}.
+ */
+ public Bson() {
+ this(BsonSerializer.DEFAULT, BsonParser.DEFAULT);
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param s
+ * The serializer to use for serializing output.
+ * <br>Must not be <jk>null</jk>.
+ * @param p
+ * The parser to use for parsing input.
+ * <br>Must not be <jk>null</jk>.
+ */
+ public Bson(BsonSerializer s, BsonParser p) {
+ super(s, p);
+ }
+}
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/msgpack/MsgPackParser.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/msgpack/MsgPackParser.java
index 1e872a3e65..f950a740ab 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/msgpack/MsgPackParser.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/msgpack/MsgPackParser.java
@@ -35,6 +35,20 @@ import org.apache.juneau.parser.*;
*
* Handles <c>Content-Type</c> types: <bc>octal/msgpack</bc>
*
+ * <h5 class='topic'>Description</h5>
+ * <p>
+ * MessagePack-to-Java type mapping:
+ * <ul class='spaced-list'>
+ * <li>MessagePack map → bean or {@link java.util.Map}
+ * <li>MessagePack array → {@link java.util.Collection} or Java array
+ * <li>MessagePack string → {@link String}; coerced to types parseable from string
+ * <li>MessagePack boolean → {@link Boolean}
+ * <li>MessagePack int → {@link Integer}; coerced to {@link Long}, {@link Short}, {@link Byte} as needed
+ * <li>MessagePack float → {@link Float} or {@link Double}
+ * <li>MessagePack binary → {@code byte[]}
+ * <li>MessagePack nil → {@code null}
+ * </ul>
+ *
* <h5 class='section'>Notes:</h5><ul>
* <li class='note'>This class is thread safe and reusable.
* </ul>
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/msgpack/MsgPackSerializer.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/msgpack/MsgPackSerializer.java
index 5ad5d7535c..833d96a17b 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/msgpack/MsgPackSerializer.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/msgpack/MsgPackSerializer.java
@@ -38,6 +38,22 @@ import org.apache.juneau.serializer.*;
* <p>
* Produces <c>Content-Type</c> types: <bc>octal/msgpack</bc>
*
+ * <h5 class='topic'>Description</h5>
+ * <p>
+ * Java-to-MessagePack type mapping:
+ * <ul class='spaced-list'>
+ * <li>Maps and beans → MessagePack map type
+ * <li>Collections and arrays → MessagePack array type
+ * <li>{@link String} / {@link Enum} → MessagePack string type
+ * <li>{@link Boolean} → MessagePack boolean type
+ * <li>{@link Number} (int, long, float, double, etc.) → MessagePack number type (variable-length int or float)
+ * <li>{@link java.util.Date} / {@link java.util.Calendar} / {@link java.time.Instant} → ISO 8601 string
+ * <li>{@link java.time.Duration} → ISO 8601 duration string
+ * <li>{@code byte[]} → MessagePack binary type
+ * <li>{@code null} → MessagePack nil type
+ * <li>All other types → fallback to {@code toString()} as string
+ * </ul>
+ *
* <h5 class='section'>Notes:</h5><ul>
* <li class='note'>This class is thread safe and reusable.
* </ul>
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/parser/ParserSession.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/parser/ParserSession.java
index 34d1c75a15..5d512ed2e4 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/parser/ParserSession.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/parser/ParserSession.java
@@ -256,6 +256,8 @@ public class ParserSession extends BeanSession {
"rawtypes" // Raw types necessary for generic parent property handling
})
protected static final void setParent(ClassMeta<?> cm, Object o, Object parent) throws ExecutableException {
+ if (cm == null)
+ return;
Property m = cm.getParentProperty();
if (nn(m) && m.canWrite())
m.set(o, parent);
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestClient.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestClient.java
index f6bd8f43ba..3acc3d07d6 100644
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestClient.java
+++ b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestClient.java
@@ -84,6 +84,7 @@ import org.apache.juneau.json.*;
import org.apache.juneau.jsonl.*;
import org.apache.juneau.markdown.*;
import org.apache.juneau.marshaller.*;
+import org.apache.juneau.bson.*;
import org.apache.juneau.msgpack.*;
import org.apache.juneau.oapi.*;
import org.apache.juneau.objecttools.*;
@@ -251,6 +252,7 @@ import org.apache.juneau.xml.*;
* <li class='jm'>{@link Builder#xml() xml()}
* <li class='jm'>{@link Builder#html() html()}
* <li class='jm'>{@link Builder#plainText() plainText()}
+ * <li class='jm'>{@link Builder#bson() bson()}
* <li class='jm'>{@link Builder#msgPack() msgPack()}
* <li class='jm'>{@link Builder#uon() uon()}
* <li class='jm'>{@link Builder#urlEnc() urlEnc()}
@@ -3572,6 +3574,19 @@ public class RestClient extends BeanContextable implements HttpClient, Closeable
return headers(Accept.of(value), ContentType.of(value));
}
+ /**
+ * Convenience method for specifying BSON as the marshalling transmission media type.
+ *
+ * <p>
+ * BSON (Binary JSON) is the format used by MongoDB. Identical to calling
+ * <c>serializer(BsonSerializer.<jk>class</jk>).parser(BsonParser.<jk>class</jk>)</c>.
+ *
+ * @return This object.
+ */
+ public Builder bson() {
+ return serializer(BsonSerializer.class).parser(BsonParser.class);
+ }
+
/**
* Convenience method for specifying MessagePack as the marshalling transmission media type.
*
@@ -5584,6 +5599,7 @@ public class RestClient extends BeanContextable implements HttpClient, Closeable
UonSerializer.class,
UrlEncodingSerializer.class,
OpenApiSerializer.class,
+ BsonSerializer.class,
MsgPackSerializer.class,
PlainTextSerializer.class,
TomlSerializer.class,
@@ -5601,6 +5617,7 @@ public class RestClient extends BeanContextable implements HttpClient, Closeable
UonParser.class,
UrlEncodingParser.class,
OpenApiParser.class,
+ BsonParser.class,
MsgPackParser.class,
PlainTextParser.class,
TomlParser.class,
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestRequest.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestRequest.java
index b236c3ce0e..9263dfebec 100644
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestRequest.java
+++ b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestRequest.java
@@ -57,6 +57,7 @@ import org.apache.juneau.http.header.ContentType;
import org.apache.juneau.http.part.*;
import org.apache.juneau.http.resource.*;
import org.apache.juneau.httppart.*;
+import org.apache.juneau.bson.*;
import org.apache.juneau.json.*;
import org.apache.juneau.msgpack.*;
import org.apache.juneau.oapi.*;
@@ -1402,6 +1403,18 @@ public class RestRequest extends BeanSession implements HttpUriRequest, Configur
return header(Accept.of(value)).header(ContentType.of(value));
}
+ /**
+ * Convenience method for specifying BSON as the marshalling transmission media type for this request only.
+ *
+ * <p>
+ * Identical to calling <c>serializer(BsonSerializer.<jk>class</jk>).parser(BsonParser.<jk>class</jk>)</c>.
+ *
+ * @return This object.
+ */
+ public RestRequest bson() {
+ return serializer(BsonSerializer.class).parser(BsonParser.class);
+ }
+
/**
* Convenience method for specifying MessagePack as the marshalling transmission media type for this request only.
*
diff --git a/juneau-rest/juneau-rest-mock/src/main/java/org/apache/juneau/rest/mock/MockRestClient.java b/juneau-rest/juneau-rest-mock/src/main/java/org/apache/juneau/rest/mock/MockRestClient.java
index c0d924e92e..7db4455375 100644
--- a/juneau-rest/juneau-rest-mock/src/main/java/org/apache/juneau/rest/mock/MockRestClient.java
+++ b/juneau-rest/juneau-rest-mock/src/main/java/org/apache/juneau/rest/mock/MockRestClient.java
@@ -1044,6 +1044,12 @@ public class MockRestClient extends RestClient implements HttpClientConnection {
return this;
}
+ @Override /* Overridden from Builder */
+ public Builder bson() {
+ super.bson();
+ return this;
+ }
+
@Override /* Overridden from Builder */
public Builder msgPack() {
super.msgPack();
diff --git a/juneau-rest/juneau-rest-mock/src/main/java/org/apache/juneau/rest/mock/MockRestRequest.java b/juneau-rest/juneau-rest-mock/src/main/java/org/apache/juneau/rest/mock/MockRestRequest.java
index 9828c3aa95..118465356f 100644
--- a/juneau-rest/juneau-rest-mock/src/main/java/org/apache/juneau/rest/mock/MockRestRequest.java
+++ b/juneau-rest/juneau-rest-mock/src/main/java/org/apache/juneau/rest/mock/MockRestRequest.java
@@ -686,6 +686,12 @@ public class MockRestRequest extends org.apache.juneau.rest.client.RestRequest {
return this;
}
+ @Override /* Overridden from RestRequest */
+ public MockRestRequest bson() {
+ super.bson();
+ return this;
+ }
+
@Override /* Overridden from RestRequest */
public MockRestRequest msgPack() {
super.msgPack();
diff --git a/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/config/BasicUniversalConfig.java b/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/config/BasicUniversalConfig.java
index 7c4a96efe6..8ab57847d4 100644
--- a/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/config/BasicUniversalConfig.java
+++ b/juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/config/BasicUniversalConfig.java
@@ -23,6 +23,7 @@ import org.apache.juneau.html.*;
import org.apache.juneau.html.annotation.*;
import org.apache.juneau.json.*;
import org.apache.juneau.jsonl.*;
+import org.apache.juneau.bson.*;
import org.apache.juneau.msgpack.*;
import org.apache.juneau.oapi.*;
import org.apache.juneau.plaintext.*;
@@ -152,6 +153,7 @@ import org.apache.juneau.xml.*;
UonSerializer.class,
UrlEncodingSerializer.class,
OpenApiSerializer.class,
+ BsonSerializer.class,
MsgPackSerializer.class,
SoapXmlSerializer.class,
PlainTextSerializer.class,
@@ -174,6 +176,7 @@ import org.apache.juneau.xml.*;
UonParser.class,
UrlEncodingParser.class,
OpenApiParser.class,
+ BsonParser.class,
MsgPackParser.class,
PlainTextParser.class,
CsvParser.class,
diff --git a/juneau-utest/src/test/java/org/apache/juneau/a/rttests/JsonMaps_RoundTripTest.java b/juneau-utest/src/test/java/org/apache/juneau/a/rttests/JsonMaps_RoundTripTest.java
index 95de00c0cb..0ede5e7c4d 100755
--- a/juneau-utest/src/test/java/org/apache/juneau/a/rttests/JsonMaps_RoundTripTest.java
+++ b/juneau-utest/src/test/java/org/apache/juneau/a/rttests/JsonMaps_RoundTripTest.java
@@ -67,7 +67,7 @@ class JsonMaps_RoundTripTest extends RoundTripTest_Base {
this.f2 = m.getInt("f2");
}
public JsonMap swap(BeanSession session) {
- return JsonMap.of("f1",f1,"f2",f2);
+ return JsonMap.of("f1", f1, "f2", f2);
}
}
}
\ No newline at end of file
diff --git a/juneau-utest/src/test/java/org/apache/juneau/a/rttests/RoundTripTest_Base.java b/juneau-utest/src/test/java/org/apache/juneau/a/rttests/RoundTripTest_Base.java
index 2a724bcbdf..0f1cf39bf3 100644
--- a/juneau-utest/src/test/java/org/apache/juneau/a/rttests/RoundTripTest_Base.java
+++ b/juneau-utest/src/test/java/org/apache/juneau/a/rttests/RoundTripTest_Base.java
@@ -31,6 +31,7 @@ import org.apache.juneau.xml.*;
import org.apache.juneau.yaml.*;
import org.apache.juneau.hjson.*;
import org.apache.juneau.markdown.*;
+import org.apache.juneau.bson.*;
/**
* Tests designed to serialize and parse objects to make sure we end up
@@ -153,6 +154,10 @@ public abstract class RoundTripTest_Base extends TestBase {
.parser(JsonParser.create())
.skipIf(o -> o instanceof Double d && (d.isNaN() || d.isInfinite()))
.build(),
+ tester(26, "Bson - default")
+ .serializer(BsonSerializer.create().keepNullProperties().addBeanTypes().addRootType())
+ .parser(BsonParser.create())
+ .build(),
};
static RoundTrip_Tester[] testers() {
diff --git a/juneau-utest/src/test/java/org/apache/juneau/bson/BsonArrayDebug_Test.java b/juneau-utest/src/test/java/org/apache/juneau/bson/BsonArrayDebug_Test.java
new file mode 100644
index 0000000000..2b24291944
--- /dev/null
+++ b/juneau-utest/src/test/java/org/apache/juneau/bson/BsonArrayDebug_Test.java
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson;
+
+import static org.apache.juneau.commons.utils.CollectionUtils.*;
+
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+
+/** Debug test to inspect BSON output for arrays. Disabled to avoid stdout noise during normal test runs. */
+@Disabled("Debug test - prints hex dumps for manual inspection; run manually when needed")
+class BsonArrayDebug_Test {
+
+ @Test
+ void dumpIntArrayBson() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().addBeanTypes().addRootType().build();
+ var bytes = s.serialize(ints(1, 2, 3));
+ // Print hex to see structure
+ var sb = new StringBuilder();
+ for (var i = 0; i < Math.min(bytes.length, 80); i++) {
+ sb.append(String.format("%02x ", bytes[i] & 0xFF));
+ if ((i + 1) % 16 == 0) sb.append("\n");
+ }
+ System.out.println("First 80 bytes (hex):");
+ System.out.println(sb);
+ }
+
+ @Test
+ void dumpJsonListBson() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().addBeanTypes().addRootType().build();
+ var x = new org.apache.juneau.collections.JsonList("['abc',123]");
+ var bytes = s.serialize(x);
+ var sb = new StringBuilder();
+ for (var i = 0; i < Math.min(bytes.length, 100); i++) {
+ sb.append(String.format("%02x ", bytes[i] & 0xFF));
+ if ((i + 1) % 16 == 0) sb.append("\n");
+ }
+ System.out.println("JsonList BSON (hex):");
+ System.out.println(sb);
+ }
+}
diff --git a/juneau-utest/src/test/java/org/apache/juneau/bson/BsonCompatibility_Test.java b/juneau-utest/src/test/java/org/apache/juneau/bson/BsonCompatibility_Test.java
new file mode 100644
index 0000000000..76803aaa1e
--- /dev/null
+++ b/juneau-utest/src/test/java/org/apache/juneau/bson/BsonCompatibility_Test.java
@@ -0,0 +1,123 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.math.*;
+
+import org.apache.juneau.TestBase;
+import org.apache.juneau.collections.*;
+import org.junit.jupiter.api.*;
+
+/**
+ * Compatibility tests for BSON: verifies parsing of BSON bytes and round-trip
+ * with standard BSON structure.
+ */
+class BsonCompatibility_Test extends TestBase {
+
+ @Test
+ void a01_parseMinimalDocument() throws Exception {
+ // BSON: { } - size(4)=5, type+name+terminator, doc terminator
+ // 05 00 00 00 00
+ var bytes = new byte[] { 0x05, 0x00, 0x00, 0x00, 0x00 };
+ var p = BsonParser.create().build();
+ var result = p.parse(bytes, JsonMap.class);
+ assertNotNull(result);
+ assertTrue(result.isEmpty());
+ }
+
+ @Test
+ void a02_parseDocumentWithString() throws Exception {
+ // BSON: { "a": "foo" } - size includes the 4-byte size field
+ // Content: 1(type) + 2("a\0") + 4(len) + 4("foo\0") + 1(doc end) = 12
+ // Size = 4 + 12 = 16
+ var bytes = new byte[] {
+ 0x10, 0x00, 0x00, 0x00, // size 16
+ 0x02, 0x61, 0x00, // 0x02 + "a\0"
+ 0x04, 0x00, 0x00, 0x00, // string length 4 (incl null)
+ 0x66, 0x6f, 0x6f, 0x00, // "foo\0"
+ 0x00 // doc terminator
+ };
+ var p = BsonParser.create().build();
+ var result = p.parse(bytes, JsonMap.class);
+ assertNotNull(result);
+ assertEquals("foo", result.get("a"));
+ }
+
+ @Test
+ void a03_roundTripBigDecimalViaDecimal128() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var p = BsonParser.create().build();
+ var value = new BigDecimal("1.234567890123456789012345678901234");
+ var bytes = s.serialize(JsonMap.of("d", value));
+ var parsed = p.parse(bytes, JsonMap.class);
+ var roundTrip = (BigDecimal) parsed.get("d");
+ assertNotNull(roundTrip);
+ assertEquals(0, value.compareTo(roundTrip));
+ }
+
+ @Test
+ void a03b_roundTripBigIntegerViaDecimal128() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var p = BsonParser.create().build();
+ var value = new BigInteger("12345678901234567890");
+ var bytes = s.serialize(value);
+ var roundTrip = p.parse(bytes, BigInteger.class);
+ assertNotNull(roundTrip);
+ assertEquals(value, roundTrip);
+ }
+
+ @Test
+ void a04_serializeParseProduceConsistentStructure() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var p = BsonParser.create().build();
+ var original = JsonMap.of("x", 1, "y", "text", "z", true);
+ var bytes = s.serialize(original);
+ var parsed = p.parse(bytes, JsonMap.class);
+ assertEquals(original.get("x"), parsed.get("x"));
+ assertEquals(original.get("y"), parsed.get("y"));
+ assertEquals(original.get("z"), parsed.get("z"));
+ }
+
+ @Test
+ void j01_emptyDocumentBytes() throws Exception {
+ var expected = new byte[] { 0x05, 0x00, 0x00, 0x00, 0x00 };
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var bytes = s.serialize(JsonMap.of());
+ assertArrayEquals(expected, bytes);
+ }
+
+ @Test
+ void j02_helloWorldBytes() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var bytes = s.serialize(JsonMap.of("hello", "world"));
+ var p = BsonParser.create().build();
+ var parsed = p.parse(bytes, JsonMap.class);
+ assertEquals("world", parsed.get("hello"));
+ assertTrue(bytes.length >= 22, "BSON {hello:world} should be at least 22 bytes");
+ }
+
+ @Test
+ void j03_int32Bytes() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var bytes = s.serialize(JsonMap.of("n", 42));
+ var p = BsonParser.create().build();
+ var parsed = p.parse(bytes, JsonMap.class);
+ assertEquals(42, parsed.get("n"));
+ }
+}
diff --git a/juneau-utest/src/test/java/org/apache/juneau/bson/BsonEdgeCases_Test.java b/juneau-utest/src/test/java/org/apache/juneau/bson/BsonEdgeCases_Test.java
new file mode 100644
index 0000000000..5843769001
--- /dev/null
+++ b/juneau-utest/src/test/java/org/apache/juneau/bson/BsonEdgeCases_Test.java
@@ -0,0 +1,100 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.util.*;
+
+import org.apache.juneau.TestBase;
+import org.apache.juneau.collections.*;
+import org.junit.jupiter.api.*;
+
+/**
+ * Edge-case tests for BSON serialization and parsing.
+ */
+class BsonEdgeCases_Test extends TestBase {
+
+ @Test
+ void a01_emptyMap() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var p = BsonParser.create().build();
+ var bytes = s.serialize(JsonMap.of());
+ var result = p.parse(bytes, JsonMap.class);
+ assertNotNull(result);
+ assertTrue(result.isEmpty());
+ }
+
+ @Test
+ void a02_emptyList() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var p = BsonParser.create().build();
+ var bytes = s.serialize(List.of());
+ var result = p.parse(bytes, List.class);
+ assertNotNull(result);
+ assertTrue(result.isEmpty());
+ }
+
+ @Test
+ void a03_nullValueInMap() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var p = BsonParser.create().build();
+ var m = new JsonMap();
+ m.put("a", 1);
+ m.put("b", null);
+ var bytes = s.serialize(m);
+ var result = p.parse(bytes, JsonMap.class);
+ assertNotNull(result);
+ assertEquals(1, result.get("a"));
+ assertNull(result.get("b"));
+ }
+
+ @Test
+ void a04_nestedEmptyStructures() throws Exception {
+ Map<String, Object> m = new LinkedHashMap<>();
+ m.put("emptyMap", new LinkedHashMap<>());
+ m.put("emptyList", List.of());
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var p = BsonParser.create().build();
+ var bytes = s.serialize(m);
+ var result = p.parse(bytes, Map.class);
+ assertNotNull(result);
+ assertTrue(((Map<?,?>)result.get("emptyMap")).isEmpty());
+ assertTrue(((List<?>)result.get("emptyList")).isEmpty());
+ }
+
+ @Test
+ void a05_unicodeStrings() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var p = BsonParser.create().build();
+ var value = "café \uD83D\uDE00";
+ var bytes = s.serialize(JsonMap.of("s", value));
+ var result = p.parse(bytes, JsonMap.class);
+ assertEquals(value, result.get("s"));
+ }
+
+ @Test
+ void a06_optionalWrappedRoundTrip() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var p = BsonParser.create().build();
+ var bytes = s.serialize(java.util.Optional.of(42));
+ var result = p.parse(bytes, java.util.Optional.class);
+ assertNotNull(result);
+ assertTrue(result.isPresent());
+ assertEquals(42, result.get());
+ }
+}
diff --git a/juneau-utest/src/test/java/org/apache/juneau/bson/BsonInputStream_Test.java b/juneau-utest/src/test/java/org/apache/juneau/bson/BsonInputStream_Test.java
new file mode 100644
index 0000000000..dc9f908c58
--- /dev/null
+++ b/juneau-utest/src/test/java/org/apache/juneau/bson/BsonInputStream_Test.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.apache.juneau.TestBase;
+import org.apache.juneau.collections.JsonMap;
+import org.apache.juneau.parser.ParserPipe;
+import org.junit.jupiter.api.*;
+
+/**
+ * Tests for {@link BsonInputStream}.
+ */
+class BsonInputStream_Test extends TestBase {
+
+ @Test
+ void a01_readDocumentViaParser() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var bytes = s.serialize(JsonMap.of("x", 1, "y", "foo"));
+ try (var pipe = new ParserPipe(bytes)) {
+ try (var is = new BsonInputStream(pipe)) {
+ var size = is.readDocumentSize();
+ assertTrue(size > 0);
+ assertTrue(size <= bytes.length);
+ }
+ }
+ }
+
+ @Test
+ void a02_parseSimpleMap() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var bytes = s.serialize(JsonMap.of("a", 42, "b", "hello"));
+ var p = BsonParser.create().build();
+ var result = p.parse(bytes, JsonMap.class);
+ assertNotNull(result);
+ assertEquals(42, result.get("a"));
+ assertEquals("hello", result.get("b"));
+ }
+
+ @Test
+ void a03_parseArray() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var bytes = s.serialize(java.util.List.of(1, 2, 3));
+ var p = BsonParser.create().build();
+ var result = p.parse(bytes, java.util.List.class);
+ assertNotNull(result);
+ assertEquals(java.util.List.of(1, 2, 3), result);
+ }
+}
diff --git a/juneau-utest/src/test/java/org/apache/juneau/bson/BsonIntArray_Test.java b/juneau-utest/src/test/java/org/apache/juneau/bson/BsonIntArray_Test.java
new file mode 100644
index 0000000000..abd393040e
--- /dev/null
+++ b/juneau-utest/src/test/java/org/apache/juneau/bson/BsonIntArray_Test.java
@@ -0,0 +1,101 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson;
+
+import static org.apache.juneau.commons.utils.CollectionUtils.*;
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.math.BigDecimal;
+import java.util.List;
+
+import org.junit.jupiter.api.Test;
+
+class BsonIntArray_Test {
+
+ @Test
+ void parseListOfIntegers() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var p = BsonParser.create().build();
+ var bytes = s.serialize(list(1, 2, 3));
+ var result = p.parse(bytes, List.class);
+ assertNotNull(result);
+ assertEquals(list(1, 2, 3), result);
+ }
+
+ @Test
+ void parseToObjectReturnsMapWithValue() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var p = BsonParser.create().build();
+ var bytes = s.serialize(ints(1, 2, 3));
+ var result = p.parse(bytes, Object.class);
+ assertNotNull(result);
+ assertTrue(result instanceof java.util.Map);
+ var m = (java.util.Map<?,?>)result;
+ assertTrue(m.containsKey("value"));
+ assertNotNull(m.get("value"));
+ }
+
+ @Test
+ void parseHandBuiltBsonArray() throws Exception {
+ // Use exact bytes from serializer dump: 26 00 00 00 04 76 61 6c 75 65 00 1a 00 00 00 ...
+ var bytes = new byte[] {
+ 0x26, 0x00, 0x00, 0x00, // root size 38
+ 0x04, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x00, // 0x04 + "value\0"
+ 0x1a, 0x00, 0x00, 0x00, // array size 26
+ 0x10, 0x30, 0x00, 0x01, 0x00, 0x00, 0x00,
+ 0x10, 0x31, 0x00, 0x02, 0x00, 0x00, 0x00,
+ 0x10, 0x32, 0x00, 0x03, 0x00, 0x00, 0x00,
+ 0x00, 0x00 // array null + root null
+ };
+
+ var p = BsonParser.create().build();
+ var result = p.parse(bytes, int[].class);
+ assertNotNull(result);
+ assertArrayEquals(new int[]{1, 2, 3}, result);
+ }
+
+ @Test
+ void parseScalarRoot() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var p = BsonParser.create().build();
+ var bytes = s.serialize(42);
+ var result = p.parse(bytes, int.class);
+ assertNotNull(result);
+ assertEquals(42, result);
+ }
+
+ @Test
+ void parseIntArray() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var p = BsonParser.create().build();
+ var bytes = s.serialize(ints(1, 2, 3));
+ var result = p.parse(bytes, int[].class);
+ assertNotNull(result);
+ assertArrayEquals(new int[]{1, 2, 3}, result);
+ }
+
+ @Test
+ void bigDecimalRoundTrip() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var p = BsonParser.create().build();
+ var value = new BigDecimal("123.45");
+ var bytes = s.serialize(value);
+ var result = p.parse(bytes, BigDecimal.class);
+ assertNotNull(result);
+ assertEquals(0, value.compareTo(result), "BigDecimal round-trip via Decimal128");
+ }
+}
diff --git a/juneau-utest/src/test/java/org/apache/juneau/bson/BsonMediaType_Test.java b/juneau-utest/src/test/java/org/apache/juneau/bson/BsonMediaType_Test.java
new file mode 100644
index 0000000000..416b372e76
--- /dev/null
+++ b/juneau-utest/src/test/java/org/apache/juneau/bson/BsonMediaType_Test.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.apache.juneau.TestBase;
+import org.junit.jupiter.api.*;
+
+/**
+ * Tests for BSON media type configuration.
+ */
+class BsonMediaType_Test extends TestBase {
+
+ @Test
+ void a01_producesCorrectMediaType() {
+ var ct = BsonSerializer.DEFAULT.getResponseContentType();
+ assertEquals("application", ct.getType());
+ assertEquals("bson", ct.getSubType());
+ }
+
+ @Test
+ void a02_acceptsMediaTypes() {
+ var types = new java.util.ArrayList<String>();
+ BsonSerializer.DEFAULT.forEachAcceptMediaType(mt -> types.add(mt.getType() + "/" + mt.getSubType()));
+ assertTrue(types.stream().anyMatch(t -> t.contains("bson")), "Expected application/bson: " + types);
+ }
+
+ @Test
+ void a03_consumesMediaTypes() {
+ var types = BsonParser.DEFAULT.getMediaTypes().stream()
+ .map(mt -> mt.getType() + "/" + mt.getSubType())
+ .toList();
+ assertTrue(types.stream().anyMatch(t -> t.contains("bson")), "Expected bson types: " + types);
+ }
+}
diff --git a/juneau-utest/src/test/java/org/apache/juneau/bson/BsonOutputStream_Test.java b/juneau-utest/src/test/java/org/apache/juneau/bson/BsonOutputStream_Test.java
new file mode 100644
index 0000000000..36f4ba37f0
--- /dev/null
+++ b/juneau-utest/src/test/java/org/apache/juneau/bson/BsonOutputStream_Test.java
@@ -0,0 +1,195 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.io.*;
+import java.math.*;
+
+import org.apache.juneau.TestBase;
+import org.apache.juneau.collections.JsonMap;
+import org.junit.jupiter.api.*;
+
+/**
+ * Tests for {@link BsonOutputStream}.
+ */
+class BsonOutputStream_Test extends TestBase {
+
+ @Test
+ void a01_emptyDocument() throws Exception {
+ var out = new ByteArrayOutputStream();
+ var bson = new BsonOutputStream(out);
+ bson.startDocument();
+ var bytes = bson.endDocument();
+ assertNotNull(bytes);
+ assertTrue(bytes.length >= 5); // 4 bytes size + at least 1 terminator
+ assertEquals(0x00, bytes[4]); // Document terminator
+ }
+
+ @Test
+ void a02_simpleKeyValueDocument() throws Exception {
+ var out = new ByteArrayOutputStream();
+ var bson = new BsonOutputStream(out);
+ bson.startDocument();
+ bson.writeElement(0x02, "name"); // STRING type
+ bson.writeString("foo");
+ var bytes = bson.endDocument();
+ assertNotNull(bytes);
+ assertTrue(bytes.length > 10);
+ }
+
+ @Test
+ void a03_writePrimitives() throws Exception {
+ var out = new ByteArrayOutputStream();
+ var bson = new BsonOutputStream(out);
+ bson.startDocument();
+ bson.writeElement(0x10, "i"); // INT32
+ bson.writeInt32(42);
+ bson.writeElement(0x12, "l"); // INT64
+ bson.writeInt64(12345L);
+ bson.writeElement(0x01, "d"); // DOUBLE
+ bson.writeDouble(3.14);
+ bson.writeElement(0x08, "b"); // BOOLEAN
+ bson.writeBoolean(true);
+ var bytes = bson.endDocument();
+ assertNotNull(bytes);
+ assertTrue(bytes.length > 20);
+ }
+
+ @Test
+ void a04_writeDecimal128() throws Exception {
+ var out = new ByteArrayOutputStream();
+ var bson = new BsonOutputStream(out);
+ bson.startDocument();
+ bson.writeElement(0x13, "dec"); // DECIMAL128
+ bson.writeDecimal128(new BigDecimal("123.45"));
+ var bytes = bson.endDocument();
+ assertNotNull(bytes);
+ assertTrue(bytes.length >= 26); // size(4) + type(1) + "dec\0"(4) + 16 bytes + terminator(1)
+ }
+
+ @Test
+ void a05_roundTripViaSerializer() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var map = JsonMap.of("a", 1, "b", "foo", "c", true);
+ var bytes = s.serialize(map);
+ assertNotNull(bytes);
+ assertTrue(bytes.length > 0);
+ var p = BsonParser.create().build();
+ var parsed = p.parse(bytes, JsonMap.class);
+ assertEquals(1, parsed.getInt("a"));
+ assertEquals("foo", parsed.getString("b"));
+ assertEquals(true, parsed.getBoolean("c"));
+ }
+
+ @Test
+ void a06_writeInt64Boundary() throws Exception {
+ var out = new ByteArrayOutputStream();
+ var bson = new BsonOutputStream(out);
+ bson.startDocument();
+ bson.writeElement(0x12, "max");
+ bson.writeInt64(Long.MAX_VALUE);
+ bson.writeElement(0x12, "min");
+ bson.writeInt64(Long.MIN_VALUE);
+ var bytes = bson.endDocument();
+ assertNotNull(bytes);
+ var p = BsonParser.create().build();
+ var parsed = p.parse(bytes, JsonMap.class);
+ assertEquals(Long.MAX_VALUE, parsed.get("max"));
+ assertEquals(Long.MIN_VALUE, parsed.get("min"));
+ }
+
+ @Test
+ void a07_writeBooleanFalse() throws Exception {
+ var out = new ByteArrayOutputStream();
+ var bson = new BsonOutputStream(out);
+ bson.startDocument();
+ bson.writeElement(0x08, "flag");
+ bson.writeBoolean(false);
+ var bytes = bson.endDocument();
+ assertNotNull(bytes);
+ var p = BsonParser.create().build();
+ var parsed = p.parse(bytes, JsonMap.class);
+ assertEquals(false, parsed.get("flag"));
+ }
+
+ @Test
+ void a08_writeBinary() throws Exception {
+ var out = new ByteArrayOutputStream();
+ var bson = new BsonOutputStream(out);
+ bson.startDocument();
+ bson.writeElement(0x05, "data");
+ bson.writeBinary(new byte[] { 0x01, 0x02, 0x03 });
+ var bytes = bson.endDocument();
+ assertNotNull(bytes);
+ var p = BsonParser.create().build();
+ var parsed = p.parse(bytes, JsonMap.class);
+ assertArrayEquals(new byte[] { 0x01, 0x02, 0x03 }, (byte[])parsed.get("data"));
+ }
+
+ @Test
+ void a09_writeDateTime() throws Exception {
+ var out = new ByteArrayOutputStream();
+ var bson = new BsonOutputStream(out);
+ bson.startDocument();
+ bson.writeElement(0x09, "ts");
+ bson.writeDateTime(1700000000000L);
+ var bytes = bson.endDocument();
+ assertNotNull(bytes);
+ var p = BsonParser.create().build();
+ var parsed = p.parse(bytes, JsonMap.class);
+ assertEquals(1700000000000L, parsed.get("ts"));
+ }
+
+ @Test
+ void a10_nestedDocument() throws Exception {
+ var out = new ByteArrayOutputStream();
+ var bson = new BsonOutputStream(out);
+ bson.startDocument();
+ bson.writeElement(0x02, "name");
+ bson.writeString("outer");
+ bson.writeElement(0x03, "inner");
+ var child = bson.createChild();
+ child.startDocument();
+ child.writeElement(0x10, "x");
+ child.writeInt32(99);
+ bson.writeChildDocument(child);
+ var bytes = bson.endDocument();
+ assertNotNull(bytes);
+ var p = BsonParser.create().build();
+ var parsed = p.parse(bytes, JsonMap.class);
+ assertEquals("outer", parsed.get("name"));
+ var inner = (java.util.Map<?,?>)parsed.get("inner");
+ assertNotNull(inner);
+ assertEquals(99, inner.get("x"));
+ }
+
+ @Test
+ void a11_emptyString() throws Exception {
+ var out = new ByteArrayOutputStream();
+ var bson = new BsonOutputStream(out);
+ bson.startDocument();
+ bson.writeElement(0x02, "s");
+ bson.writeString("");
+ var bytes = bson.endDocument();
+ assertNotNull(bytes);
+ var p = BsonParser.create().build();
+ var parsed = p.parse(bytes, JsonMap.class);
+ assertEquals("", parsed.get("s"));
+ }
+}
diff --git a/juneau-utest/src/test/java/org/apache/juneau/bson/BsonParser_Test.java b/juneau-utest/src/test/java/org/apache/juneau/bson/BsonParser_Test.java
new file mode 100644
index 0000000000..a30e832482
--- /dev/null
+++ b/juneau-utest/src/test/java/org/apache/juneau/bson/BsonParser_Test.java
@@ -0,0 +1,77 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.util.*;
+
+import org.apache.juneau.TestBase;
+import org.apache.juneau.collections.*;
+import org.junit.jupiter.api.*;
+
+/**
+ * Tests for {@link BsonParser}.
+ */
+class BsonParser_Test extends TestBase {
+
+ @Test
+ void a01_parseMap() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var bytes = s.serialize(JsonMap.of("a", 42, "b", "hello"));
+ var p = BsonParser.create().build();
+ var result = p.parse(bytes, JsonMap.class);
+ assertNotNull(result);
+ assertEquals(42, result.get("a"));
+ assertEquals("hello", result.get("b"));
+ }
+
+ @Test
+ void a02_parseList() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var bytes = s.serialize(List.of(1, 2, 3));
+ var p = BsonParser.create().build();
+ var result = p.parse(bytes, List.class);
+ assertNotNull(result);
+ assertEquals(List.of(1, 2, 3), result);
+ }
+
+ @Test
+ void a03_parseFromInputStream() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var bytes = s.serialize(JsonMap.of("k", "v"));
+ var p = BsonParser.create().build();
+ try (var is = new java.io.ByteArrayInputStream(bytes)) {
+ var result = p.parse(is, JsonMap.class);
+ assertNotNull(result);
+ assertEquals("v", result.get("k"));
+ }
+ }
+
+ @Test
+ void a04_nullKeyString() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().nullKeyString("__null__").build();
+ var m = new JsonMap();
+ m.put(null, "val");
+ var bytes = s.serialize(m);
+ var p = BsonParser.create().nullKeyString("__null__").build();
+ var result = p.parse(bytes, JsonMap.class);
+ assertNotNull(result);
+ assertTrue(result.containsKey(null));
+ assertEquals("val", result.get(null));
+ }
+}
diff --git a/juneau-utest/src/test/java/org/apache/juneau/bson/BsonRoundTrip_Test.java b/juneau-utest/src/test/java/org/apache/juneau/bson/BsonRoundTrip_Test.java
new file mode 100644
index 0000000000..3eb93bcedd
--- /dev/null
+++ b/juneau-utest/src/test/java/org/apache/juneau/bson/BsonRoundTrip_Test.java
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson;
+
+import static org.apache.juneau.commons.utils.CollectionUtils.*;
+import static org.apache.juneau.junit.bct.BctAssertions.*;
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.time.*;
+import java.util.*;
+
+import org.apache.juneau.TestBase;
+import org.apache.juneau.collections.*;
+import org.junit.jupiter.api.*;
+
+/**
+ * Round-trip tests for {@link BsonSerializer} and {@link BsonParser}.
+ */
+@SuppressWarnings({
+ "unchecked" // Parser returns Object; cast to Map in tests
+})
+class BsonRoundTrip_Test extends TestBase {
+
+ @Test
+ void a01_simpleMapRoundTrip() throws Exception {
+ var a = JsonMap.of("name", "Alice", "age", 30, "active", true);
+ var bytes = BsonSerializer.create().keepNullProperties().build().serialize(a);
+ var b = (Map<String, Object>) BsonParser.create().build().parse(bytes, Map.class, String.class, Object.class);
+ assertBean(b, "name,age,active", "Alice,30,true");
+ }
+
+ @Test
+ void a02_nestedMapRoundTrip() throws Exception {
+ var addr = new LinkedHashMap<String, Object>();
+ addr.put("city", "Boston");
+ addr.put("state", "MA");
+ var a = new LinkedHashMap<String, Object>();
+ a.put("name", "Alice");
+ a.put("address", addr);
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var p = BsonParser.create().build();
+ var bytes = s.serialize(a);
+ var b = (Map<String, Object>) p.parse(bytes, Map.class, String.class, Object.class);
+ assertBean(b, "name,address{city,state}", "Alice,{Boston,MA}");
+ }
+
+ @Test
+ void a03_listRoundTrip() throws Exception {
+ var a = list(1, 2, 3);
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var p = BsonParser.create().build();
+ var bytes = s.serialize(a);
+ var b = p.parse(bytes, List.class);
+ assertEquals(a, b);
+ }
+
+ @Test
+ void a04_scalarWrappedRoundTrip() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var p = BsonParser.create().build();
+ var bytes = s.serialize(42);
+ var b = p.parse(bytes, int.class);
+ assertEquals(42, b);
+ }
+
+ @Test
+ void a05_intArrayRoundTrip() throws Exception {
+ var a = ints(1, 2, 3);
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var p = BsonParser.create().build();
+ var bytes = s.serialize(a);
+ var b = p.parse(bytes, int[].class);
+ assertArrayEquals(a, b);
+ }
+
+ @Test
+ void a06_enumRoundTrip() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var p = BsonParser.create().build();
+ var bytes = s.serialize(JsonMap.of("size", "LARGE"));
+ var b = p.parse(bytes, Map.class);
+ assertEquals("LARGE", b.get("size"));
+ }
+
+ @Test
+ void a07_dateRoundTrip() throws Exception {
+ var instant = Instant.ofEpochMilli(1700000000000L);
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var p = BsonParser.create().build();
+ var bytes = s.serialize(JsonMap.of("ts", instant));
+ var b = p.parse(bytes, Map.class);
+ assertEquals(1700000000000L, b.get("ts"));
+ }
+
+ @Test
+ void a08_byteArrayRoundTrip() throws Exception {
+ var data = new byte[] { 0x01, 0x02, 0x03 };
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var p = BsonParser.create().build();
+ var bytes = s.serialize(JsonMap.of("data", data));
+ var b = p.parse(bytes, Map.class);
+ assertArrayEquals(data, (byte[])b.get("data"));
+ }
+}
diff --git a/juneau-utest/src/test/java/org/apache/juneau/bson/BsonSerializer_Test.java b/juneau-utest/src/test/java/org/apache/juneau/bson/BsonSerializer_Test.java
new file mode 100644
index 0000000000..84e94624bb
--- /dev/null
+++ b/juneau-utest/src/test/java/org/apache/juneau/bson/BsonSerializer_Test.java
@@ -0,0 +1,113 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.io.*;
+import java.math.*;
+import java.time.*;
+import java.util.*;
+
+import org.apache.juneau.TestBase;
+import org.apache.juneau.collections.*;
+import org.junit.jupiter.api.*;
+
+/**
+ * Tests for {@link BsonSerializer}.
+ */
+class BsonSerializer_Test extends TestBase {
+
+ @Test
+ void a01_serializeMap() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var bytes = s.serialize(JsonMap.of("a", 1, "b", "foo"));
+ assertNotNull(bytes);
+ assertTrue(bytes.length > 0);
+ }
+
+ @Test
+ void a02_serializeList() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var bytes = s.serialize(List.of(1, 2, 3));
+ assertNotNull(bytes);
+ assertTrue(bytes.length > 0);
+ }
+
+ @Test
+ void a03_serializeToOutputStream() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var out = new ByteArrayOutputStream();
+ s.serialize(JsonMap.of("x", 42), out);
+ var bytes = out.toByteArray();
+ assertNotNull(bytes);
+ assertTrue(bytes.length > 0);
+ }
+
+ @Test
+ void a04_serializeBigDecimalAsDecimal128() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var p = BsonParser.create().build();
+ var value = new BigDecimal("123.45");
+ var bytes = s.serialize(value);
+ var result = p.parse(bytes, BigDecimal.class);
+ assertNotNull(result);
+ assertEquals(0, value.compareTo(result), "BigDecimal round-trip via Decimal128");
+ }
+
+ @Test
+ void a05_serializeScalarWrapsInValue() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var bytes = s.serialize("hello");
+ assertNotNull(bytes);
+ var p = BsonParser.create().build();
+ var parsed = p.parse(bytes, JsonMap.class);
+ assertTrue(parsed.containsKey("value"));
+ assertEquals("hello", parsed.get("value"));
+ }
+
+ @Test
+ void a06_serializeDateAsDatetime() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var instant = Instant.ofEpochMilli(1700000000000L);
+ var bytes = s.serialize(JsonMap.of("ts", instant));
+ var p = BsonParser.create().build();
+ var parsed = p.parse(bytes, JsonMap.class);
+ assertEquals(1700000000000L, parsed.get("ts"));
+ }
+
+ @Test
+ void a07_serializeByteArray() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var data = new byte[] { 0x01, 0x02, 0x03 };
+ var bytes = s.serialize(JsonMap.of("data", data));
+ var p = BsonParser.create().build();
+ var parsed = p.parse(bytes, JsonMap.class);
+ assertArrayEquals(data, (byte[])parsed.get("data"));
+ }
+
+ @Test
+ void a08_serializeEnum() throws Exception {
+ var s = BsonSerializer.create().keepNullProperties().build();
+ var bytes = s.serialize(JsonMap.of("size", Size.LARGE));
+ var p = BsonParser.create().build();
+ var parsed = p.parse(bytes, JsonMap.class);
+ assertEquals("LARGE", parsed.get("size"));
+ }
+
+ enum Size { SMALL, MEDIUM, LARGE }
+}
diff --git a/juneau-utest/src/test/java/org/apache/juneau/bson/BsonTrimStrings_Test.java b/juneau-utest/src/test/java/org/apache/juneau/bson/BsonTrimStrings_Test.java
new file mode 100644
index 0000000000..42ffb0193c
--- /dev/null
+++ b/juneau-utest/src/test/java/org/apache/juneau/bson/BsonTrimStrings_Test.java
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests BSON parser trimStrings behavior.
+ */
+class BsonTrimStrings_Test {
+
+ @Test
+ void testTrimStrings() throws Exception {
+ var p = BsonParser.create().build();
+ var p2 = BsonParser.create().trimStrings().build();
+ var s = BsonSerializer.create().build();
+ var in = " foo bar ";
+ // Parser without trimStrings should preserve spaces
+ var a = p.parse(s.serialize(in), String.class);
+ assertEquals(" foo bar ", a);
+ // Parser with trimStrings should trim
+ var a2 = p2.parse(s.serialize(in), String.class);
+ assertEquals("foo bar", a2);
+ }
+
+ @Test
+ void testTrimStringsWithRoundTripTesterConfig() throws Exception {
+ // Match RoundTrip_Tester BSON config exactly
+ var s = BsonSerializer.create().keepNullProperties().addBeanTypes().addRootType().build();
+ var p = BsonParser.create().build();
+ var p2 = p.copy().trimStrings().build();
+ var in = " foo bar ";
+ var a = p2.parse(s.serialize(in), String.class);
+ assertEquals("foo bar", a, "Parser with trimStrings should trim when using RoundTrip test config");
+ }
+
+}
diff --git a/juneau-utest/src/test/java/org/apache/juneau/bson/annotation/BsonAnnotation_Test.java b/juneau-utest/src/test/java/org/apache/juneau/bson/annotation/BsonAnnotation_Test.java
new file mode 100644
index 0000000000..4ea3de596b
--- /dev/null
+++ b/juneau-utest/src/test/java/org/apache/juneau/bson/annotation/BsonAnnotation_Test.java
@@ -0,0 +1,101 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.bson.annotation;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.junit.bct.BctAssertions.*;
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.bson.*;
+import org.apache.juneau.collections.*;
+import org.junit.jupiter.api.*;
+
+/**
+ * Tests for {@link BsonAnnotation} and {@link Bson @Bson} annotation.
+ */
+class BsonAnnotation_Test extends org.apache.juneau.TestBase {
+
+ Bson a1 = BsonAnnotation.create()
+ .description("a")
+ .on("b")
+ .build();
+
+ Bson a2 = BsonAnnotation.create()
+ .description("a")
+ .on("b")
+ .build();
+
+ @Test
+ void a01_basic() {
+ assertBean(a1, "description,on,onClass", "[a],[b],[]");
+ }
+
+ @Test
+ void a02_equivalency() {
+ assertEquals(a2, a1);
+ assertNotEqualsAny(a1.hashCode(), 0, -1);
+ assertEquals(a1.hashCode(), a2.hashCode());
+ }
+
+ @Test
+ void b01_equivalencyInPropertyStores() {
+ var bc1 = BeanContext.create().annotations(a1).build();
+ var bc2 = BeanContext.create().annotations(a2).build();
+ assertSame(bc1, bc2);
+ }
+
+ @org.apache.juneau.bson.annotation.Bson(description = "a", on = "b")
+ public static class D1 {}
+
+ @org.apache.juneau.bson.annotation.Bson(description = "a", on = "b")
+ public static class D2 {}
+
+ @Test
+ void d01_comparisonWithDeclarativeAnnotations() {
+ var d1 = D1.class.getAnnotationsByType(org.apache.juneau.bson.annotation.Bson.class)[0];
+ var d2 = D2.class.getAnnotationsByType(org.apache.juneau.bson.annotation.Bson.class)[0];
+ assertEqualsAll(a1, d1, d2);
+ assertEqualsAll(a1.hashCode(), d1.hashCode(), d2.hashCode());
+ }
+
+ @BsonConfig(addBeanTypes = "true")
+ public static class G1_Bean { public String name = "x"; }
+
+ @Test
+ void g01_bsonConfigAddBeanTypes() throws Exception {
+ var s = BsonSerializer.create().applyAnnotations(G1_Bean.class).keepNullProperties().build();
+ var bytes = s.serialize(new G1_Bean());
+ var p = BsonParser.create().build();
+ var parsed = p.parse(bytes, JsonMap.class);
+ assertTrue(parsed.containsKey("_type") || parsed.containsKey("name"));
+ assertEquals("x", parsed.get("name"));
+ }
+
+ @BsonConfig(writeDatesAsDatetime = "false")
+ public static class G2_Bean { public java.util.Date d = new java.util.Date(1700000000000L); }
+
+ @Test
+ void g02_writeDatesAsDatetimeFalse() throws Exception {
+ var s = BsonSerializer.create().applyAnnotations(G2_Bean.class).keepNullProperties().build();
+ var bytes = s.serialize(new G2_Bean());
+ var p = BsonParser.create().build();
+ var parsed = p.parse(bytes, JsonMap.class);
+ var d = parsed.get("d");
+ assertTrue(d instanceof String, "Date should be string when writeDatesAsDatetime=false, got: " + d.getClass().getName());
+ }
+}
diff --git a/juneau-utest/src/test/java/org/apache/juneau/hjson/HjsonTokenizer_Test.java b/juneau-utest/src/test/java/org/apache/juneau/hjson/HjsonTokenizer_Test.java
index b694690125..3229e8fd96 100644
--- a/juneau-utest/src/test/java/org/apache/juneau/hjson/HjsonTokenizer_Test.java
+++ b/juneau-utest/src/test/java/org/apache/juneau/hjson/HjsonTokenizer_Test.java
@@ -23,7 +23,12 @@ import java.io.*;
import org.apache.juneau.TestBase;
import org.apache.juneau.parser.ParserPipe;
+import java.util.stream.Stream;
+
import org.junit.jupiter.api.*;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
/**
* Tests for {@link HjsonTokenizer}.
@@ -34,29 +39,21 @@ class HjsonTokenizer_Test extends TestBase {
return new HjsonTokenizer(new StringReader(input));
}
- @Test
- void d01_quotedDouble() throws Exception {
- var t = tokenizer("\"hello\"");
- var tok = t.read();
- assertEquals(STRING, tok.type());
- assertEquals("hello", tok.stringValue());
- }
-
- @Test
- void d02_quotedSingle() throws Exception {
- var t = tokenizer("'world'");
- var tok = t.read();
- assertEquals(STRING, tok.type());
- assertEquals("world", tok.stringValue());
+ static Stream<Arguments> stringTokenTypes() {
+ return Stream.of(
+ Arguments.of("\"hello\"", STRING, "hello"),
+ Arguments.of("'world'", STRING, "world"),
+ Arguments.of("'''line1\nline2'''", MULTILINE, "line1\nline2")
+ );
}
- @Test
- void d03_multilineToken() throws Exception {
- var t = tokenizer("'''line1\nline2'''");
+ @ParameterizedTest
+ @MethodSource("stringTokenTypes")
+ void d01_to_d03_stringTokenTypes(String input, HjsonTokenizer.TokenType expectedType, String expectedValue) throws Exception {
+ var t = tokenizer(input);
var tok = t.read();
- assertEquals(MULTILINE, tok.type());
- assertTrue(tok.stringValue().contains("line1"));
- assertTrue(tok.stringValue().contains("line2"));
+ assertEquals(expectedType, tok.type());
+ assertEquals(expectedValue, tok.stringValue());
}
@Test
@@ -115,35 +112,26 @@ class HjsonTokenizer_Test extends TestBase {
assertEquals(EOF, t.read().type());
}
- @Test
- void d09_hashComment() throws Exception {
- var t = tokenizer("# comment\nx");
- t.skipWhitespaceAndComments();
- var tok = t.read();
- assertEquals(QUOTELESS, tok.type());
- assertEquals("x", tok.stringValue());
+ static Stream<Arguments> commentTypes() {
+ return Stream.of(
+ Arguments.of("# comment\nx", "x"),
+ Arguments.of("// comment\ny", "y"),
+ Arguments.of("/* block */\nz", "z")
+ );
}
- @Test
- void d10_slashComment() throws Exception {
- var t = tokenizer("// comment\ny");
- t.skipWhitespaceAndComments();
- var tok = t.read();
- assertEquals(QUOTELESS, tok.type());
- assertEquals("y", tok.stringValue());
- }
-
- @Test
- void d11_blockComment() throws Exception {
- var t = tokenizer("/* block */\nz");
+ @ParameterizedTest
+ @MethodSource("commentTypes")
+ void d09_commentTypes(String input, String expectedValue) throws Exception {
+ var t = tokenizer(input);
t.skipWhitespaceAndComments();
var tok = t.read();
assertEquals(QUOTELESS, tok.type());
- assertEquals("z", tok.stringValue());
+ assertEquals(expectedValue, tok.stringValue());
}
@Test
- void d12_multipleQuotelessWithNewlines() throws Exception {
+ void d10_multipleQuotelessWithNewlines() throws Exception {
var t = tokenizer("a\nb\nc");
var t1 = t.read();
assertEquals(QUOTELESS, t1.type());
@@ -157,7 +145,7 @@ class HjsonTokenizer_Test extends TestBase {
}
@Test
- void d13_bracelessInputFirstToken() throws Exception {
+ void d11_bracelessInputFirstToken() throws Exception {
// For "name: Bob\nage: 25", first token must be QUOTELESS "name" (not LBRACE)
var t = tokenizer("name: Bob\nage: 25");
t.skipWhitespaceAndComments();
@@ -167,8 +155,8 @@ class HjsonTokenizer_Test extends TestBase {
}
@Test
- void d14_bracelessWithParserReader() throws Exception {
- // Same test but using ParserReader (as the parser does) - must match d13
+ void d12_bracelessWithParserReader() throws Exception {
+ // Same test but using ParserReader (as the parser does) - must match d11
var pipe = new ParserPipe("name: Bob\nage: 25");
try (var r = pipe.getParserReader()) {
var t = new HjsonTokenizer(r);
diff --git a/juneau-utest/src/test/java/org/apache/juneau/marshaller/Bson_Test.java b/juneau-utest/src/test/java/org/apache/juneau/marshaller/Bson_Test.java
new file mode 100644
index 0000000000..adf432f2eb
--- /dev/null
+++ b/juneau-utest/src/test/java/org/apache/juneau/marshaller/Bson_Test.java
@@ -0,0 +1,89 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.juneau.marshaller;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.io.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.collections.*;
+import org.junit.jupiter.api.*;
+
+/**
+ * Tests for {@link Bson} marshaller.
+ */
+class Bson_Test extends TestBase {
+
+ @Test
+ void a01_of() throws Exception {
+ var map = JsonMap.of("foo", "bar", "num", 42);
+ var bytes = Bson.of(map);
+ assertNotNull(bytes);
+ assertTrue(bytes.length > 0);
+ }
+
+ @Test
+ void a02_ofToOutputStream() throws Exception {
+ var map = JsonMap.of("foo", "bar");
+ var out = new ByteArrayOutputStream();
+ Bson.of(map, out);
+ var bytes = out.toByteArray();
+ assertNotNull(bytes);
+ assertTrue(bytes.length > 0);
+ }
+
+ @Test
+ void a03_to() throws Exception {
+ var map = JsonMap.of("foo", "bar", "num", 42);
+ var bytes = Bson.of(map);
+ var parsed = Bson.to(bytes, JsonMap.class);
+ assertNotNull(parsed);
+ assertEquals("bar", parsed.get("foo"));
+ assertEquals(42, parsed.get("num"));
+ }
+
+ @Test
+ void a04_toFromInputStream() throws Exception {
+ var map = JsonMap.of("k", "v");
+ var bytes = Bson.of(map);
+ try (var is = new ByteArrayInputStream(bytes)) {
+ var parsed = Bson.to(is, JsonMap.class);
+ assertNotNull(parsed);
+ assertEquals("v", parsed.get("k"));
+ }
+ }
+
+ @Test
+ void a05_roundTrip() throws Exception {
+ var original = JsonMap.of("a", 1, "b", "hello", "c", true);
+ var bytes = Bson.of(original);
+ var roundTrip = Bson.to(bytes, JsonMap.class);
+ assertEquals(original.get("a"), roundTrip.get("a"));
+ assertEquals(original.get("b"), roundTrip.get("b"));
+ assertEquals(original.get("c"), roundTrip.get("c"));
+ }
+
+ @Test
+ void a06_defaultInstance() throws Exception {
+ var bson = Bson.DEFAULT;
+ var map = JsonMap.of("x", 1);
+ var bytes = bson.write(map);
+ var parsed = bson.read(bytes, JsonMap.class);
+ assertEquals(1, parsed.get("x"));
+ }
+}
diff --git a/todo/4_bson_implementation.md b/todo/4_bson_implementation.md
deleted file mode 100644
index 0bfc18f1e6..0000000000
--- a/todo/4_bson_implementation.md
+++ /dev/null
@@ -1,1065 +0,0 @@
-# BSON Support Implementation Plan for Apache Juneau
-
-## Overview
-
-This plan covers implementing serialization and parsing support for BSON (Binary JSON) in Juneau. BSON is the binary serialization format used by MongoDB. It is a self-describing binary format that includes field names, type tags, and length prefixes, making it richer than MsgPack (which Juneau already supports). BSON supports typed values (dates, binary data, regex, 32-bit vs 64-bit integers) which map cleanly to Java types.
-
-The implementation follows the existing MsgPack serializer/parser architecture since both are binary stream-based formats, but differs in several key areas:
-- **Little-endian byte order** (MsgPack uses big-endian)
-- **Length-prefixed documents** (total byte count precedes content, requiring buffering)
-- **Arrays encoded as documents** with numeric string keys (`"0"`, `"1"`, ...)
-- **Richer type system** (typed integers, dates, binary subtypes, regex)
-
-## Specification
-
-- **BSON Spec**: https://bsonspec.org/spec.html (Version 1.1)
-- **Media type**: `application/bson`
-- **Byte order**: Little-endian
-
----
-
-## BSON Type System and Java Mapping
-
-### BSON Element Types
-
-| Type Byte | BSON Type | Java Mapping | Notes |
-|-----------|-----------|-------------|-------|
-| `0x01` | Double (64-bit IEEE 754) | `double`, `float`, `Double`, `Float` | Floats promoted to double |
-| `0x02` | UTF-8 String | `String`, `Enum`, `CharSequence` | Length-prefixed + null-terminated |
-| `0x03` | Embedded Document | Bean, `Map<K,V>`, `JsonMap` | Recursive document encoding |
-| `0x04` | Array | `List`, `Collection`, arrays | Document with `"0"`, `"1"`, ... keys |
-| `0x05` | Binary Data | `byte[]`, `InputStream` | Subtype 0x00 (generic) |
-| `0x07` | ObjectId (12 bytes) | `String` (hex) | Read-only (parsed as hex string) |
-| `0x08` | Boolean | `boolean`, `Boolean` | 0x00=false, 0x01=true |
-| `0x09` | UTC Datetime | `Date`, `Calendar`, `Instant`, `long` | int64 millis since epoch |
-| `0x0A` | Null | `null` | No value bytes |
-| `0x10` | 32-bit Integer | `int`, `short`, `byte`, `Integer` | 4 bytes little-endian |
-| `0x12` | 64-bit Integer | `long`, `Long`, `AtomicLong` | 8 bytes little-endian |
-| `0x13` | 128-bit Decimal | `BigDecimal` | 16 bytes IEEE 754-2008 |
-
-Types NOT mapped (MongoDB-specific): Undefined (0x06, deprecated), DBPointer (0x0C, deprecated), JavaScript (0x0D), Symbol (0x0E, deprecated), JS with Scope (0x0F, deprecated), Timestamp (0x11, MongoDB internal), MinKey (0xFF), MaxKey (0x7F).
-
-### BSON Document Structure
-
-```
-document ::= int32 e_list 0x00
- ^^^^^ total byte count (including this int32 and trailing 0x00)
- ^^^^^^ zero or more elements
- ^^^^ terminating null byte
-
-element ::= type_byte e_name value
- ^^^^^^^^^ one of the type codes above
- ^^^^^^ cstring (null-terminated UTF-8)
- ^^^^^ type-dependent value encoding
-
-string ::= int32 (byte*) 0x00
- ^^^^^ byte count of string bytes + 1 (for null)
- ^^^^^^^ UTF-8 string bytes
- ^^^^ terminating null byte
-
-cstring ::= (byte*) 0x00
- ^^^^^^^ UTF-8 bytes (must NOT contain 0x00)
- ^^^^ terminating null byte
-
-binary ::= int32 subtype (byte*)
- ^^^^^ byte count
- ^^^^^^^ subtype byte
- ^^^^^^^ raw bytes
-```
-
-### Serialization Examples
-
-**Simple bean:**
-```java
-class Server { String host; int port; boolean debug; }
-// host="localhost", port=8080, debug=true
-```
-BSON encoding (shown as hex):
-```
-37 00 00 00 // document size: 55 bytes
- 02 // type: string
- 68 6F 73 74 00 // key: "host\0"
- 0A 00 00 00 // string length: 10
- 6C 6F 63 61 6C 68 6F 73 74 00 // value: "localhost\0"
- 10 // type: int32
- 70 6F 72 74 00 // key: "port\0"
- 90 1F 00 00 // value: 8080 (little-endian)
- 08 // type: boolean
- 64 65 62 75 67 00 // key: "debug\0"
- 01 // value: true
-00 // document terminator
-```
-
-**Nested bean:**
-```java
-class Config { String name; Database db; }
-class Database { String host; int port; }
-// name="myapp", db={host="localhost", port=5432}
-```
-BSON: outer document contains a type 0x03 (embedded document) element for `db`.
-
-**Collection of beans:**
-```java
-class Config { List<Server> servers; }
-```
-BSON: `servers` encoded as type 0x04 (array), which is a document with keys `"0"`, `"1"`, `"2"`, ... where each value is a type 0x03 embedded document.
-
-**Map:**
-```java
-class Config { Map<String,String> env; }
-// env={"PATH":"/usr/bin", "HOME":"/home/user"}
-```
-BSON: `env` encoded as type 0x03 (embedded document) with string entries.
-
----
-
-## Architecture
-
-BSON is a binary stream format, so it extends `OutputStreamSerializer`/`InputStreamParser` (same as MsgPack).
-
-```
-OutputStreamSerializer
- └── BsonSerializer
- └── BsonSerializerSession (uses BsonOutputStream)
-
-InputStreamParser
- └── BsonParser
- └── BsonParserSession (uses BsonInputStream)
-```
-
-### Length-Prefix Challenge
-
-BSON documents are length-prefixed: the total byte count must appear before the content. Since we don't know the size until the document is fully serialized, the implementation uses a **buffered nested document** strategy:
-
-1. Each document/sub-document is serialized into a `ByteArrayOutputStream`.
-2. Once complete, the total size (4 bytes for int32 + buffered content + 1 byte for terminator) is calculated.
-3. The int32 size, buffered bytes, and 0x00 terminator are written to the parent stream.
-
-`BsonOutputStream` manages this nesting internally, making the serialization code clean.
-
----
-
-## Files to Create
-
-All source files in `juneau-core/juneau-marshall/src/main/java/org/apache/juneau/bson/`.
-
-### 1. `BsonOutputStream.java`
-
-Extends `OutputStream`. Core binary encoder for BSON format (little-endian).
-
-```java
-package org.apache.juneau.bson;
-
-public class BsonOutputStream extends OutputStream {
-
- // Document lifecycle
- void startDocument(); // Begin buffering a new document
- byte[] endDocument(); // Finalize: returns [int32_size][content][0x00]
- void writeDocumentTo(OutputStream os); // Finalize and write to parent stream
-
- // Element header
- void writeElement(int type, String name); // Writes type byte + cstring name
-
- // Scalar value writers (little-endian)
- void writeDouble(double value); // 8 bytes IEEE 754 LE
- void writeInt32(int value); // 4 bytes LE
- void writeInt64(long value); // 8 bytes LE
- void writeBoolean(boolean value); // 1 byte: 0x00 or 0x01
- void writeNull(); // No value bytes (type byte handles it)
- void writeString(String value); // int32 length + UTF-8 bytes + 0x00
- void writeCString(String value); // UTF-8 bytes + 0x00
- void writeBinary(byte[] data); // int32 length + subtype(0x00) + bytes
- void writeDateTime(long millis); // int64 LE (UTC millis since epoch)
-
- // Sub-document and array support
- BsonOutputStream createChild(); // Creates a new buffered child stream
- void writeChildDocument(BsonOutputStream child); // Writes child's content as document
-
- // Utility
- void writeLE4(int value); // 4-byte little-endian int
- void writeLE8(long value); // 8-byte little-endian long
-}
-```
-
-The key difference from MsgPack's `MsgPackOutputStream`: BSON is **little-endian** and **length-prefixed**. Each document is buffered in a `ByteArrayOutputStream` child. When the document is finalized, the total size is prepended.
-
-### 2. `BsonInputStream.java`
-
-Extends `ParserInputStream`. Core binary decoder for BSON format.
-
-```java
-package org.apache.juneau.bson;
-
-public class BsonInputStream extends ParserInputStream {
-
- // Document reading
- int readDocumentSize(); // Reads int32 document size
- int readElementType(); // Reads 1-byte type code
- String readElementName(); // Reads cstring (null-terminated)
- boolean isDocumentEnd(); // Next byte is 0x00 (document terminator)
- void readDocumentTerminator(); // Consumes the 0x00
-
- // Value readers (little-endian)
- double readDouble(); // 8 bytes IEEE 754 LE
- int readInt32(); // 4 bytes LE
- long readInt64(); // 8 bytes LE
- boolean readBoolean(); // 1 byte
- String readString(); // int32 length + UTF-8 bytes + 0x00
- String readCString(); // UTF-8 bytes until 0x00
- byte[] readBinary(); // int32 length + subtype + bytes
- long readDateTime(); // int64 LE (millis since epoch)
- String readObjectId(); // 12 bytes → hex string
- BigDecimal readDecimal128(); // 16 bytes IEEE 754-2008
-
- // Utility
- void skipValue(int type); // Skip a value of the given type
- int readLE4(); // 4-byte little-endian int
- long readLE8(); // 8-byte little-endian long
-}
-```
-
-### 3. `DataType.java`
-
-Enum for BSON element type codes.
-
-```java
-package org.apache.juneau.bson;
-
-public enum DataType {
- DOUBLE(0x01),
- STRING(0x02),
- DOCUMENT(0x03),
- ARRAY(0x04),
- BINARY(0x05),
- OBJECT_ID(0x07),
- BOOLEAN(0x08),
- DATETIME(0x09),
- NULL(0x0A),
- REGEX(0x0B),
- INT32(0x10),
- INT64(0x12),
- DECIMAL128(0x13),
- // Deprecated/internal types included for parsing compatibility
- UNDEFINED(0x06),
- DB_POINTER(0x0C),
- JAVASCRIPT(0x0D),
- SYMBOL(0x0E),
- JS_WITH_SCOPE(0x0F),
- TIMESTAMP(0x11),
- MIN_KEY(0xFF),
- MAX_KEY(0x7F);
-
- final int value;
- static DataType fromByte(int b);
-}
-```
-
-### 4. `BsonSerializer.java`
-
-Extends `OutputStreamSerializer`. Implements `BsonMetaProvider`.
-
-```java
-package org.apache.juneau.bson;
-
-public class BsonSerializer extends OutputStreamSerializer implements BsonMetaProvider {
-
- public static final BsonSerializer DEFAULT = ...;
-
- // Inner classes for text representations (matching MsgPack pattern)
- public static class SpacedHex extends BsonSerializer { ... }
- public static class Base64 extends BsonSerializer { ... }
-
- public static class Builder extends OutputStreamSerializer.Builder {
- boolean addBeanTypesBson = false;
- boolean writeDatesAsDatetime = true; // Use BSON datetime type for Date/Calendar
-
- protected Builder() {
- produces("application/bson");
- accept("application/bson");
- }
-
- public Builder addBeanTypesBson(boolean value) { ... }
- public Builder writeDatesAsDatetime(boolean value) { ... }
- }
-
- @Override
- public BsonSerializerSession.Builder createSession() {
- return BsonSerializerSession.create(this);
- }
-}
-```
-
-Builder options:
-- `addBeanTypesBson(boolean)` -- Add `_type` property to beans when type name is known
-- `writeDatesAsDatetime(boolean)` -- Use BSON datetime type (0x09) for `Date`/`Calendar`/`Instant` (default: true). When false, dates are serialized as strings.
-
-### 5. `BsonSerializerSession.java`
-
-Extends `OutputStreamSerializerSession`. Core serialization logic.
-
-Key methods:
-- `doSerialize(SerializerPipe, Object)` -- Entry point
-- `serializeAnything(BsonOutputStream, Object, ClassMeta, String, BeanPropertyMeta)` -- Central dispatch
-- `serializeDocument(BsonOutputStream, BeanMap/Map)` -- Writes a BSON document
-- `serializeArray(BsonOutputStream, Collection)` -- Writes a BSON array (document with numeric keys)
-- `writeElement(BsonOutputStream, String, Object, ClassMeta)` -- Writes a typed element (name + value)
-
-Serialization algorithm:
-```
-serializeAnything(out, object, classMeta, attrName, beanProperty):
- if null:
- out.writeElement(0x0A, attrName) // NULL type
- return
-
- determine actual type via swaps, push recursion detection
-
- if boolean:
- out.writeElement(0x08, attrName)
- out.writeBoolean(value)
-
- else if int/short/byte:
- out.writeElement(0x10, attrName)
- out.writeInt32(value)
-
- else if long:
- out.writeElement(0x12, attrName)
- out.writeInt64(value)
-
- else if float/double:
- out.writeElement(0x01, attrName)
- out.writeDouble(value)
-
- else if String/CharSequence/Enum:
- out.writeElement(0x02, attrName)
- out.writeString(value.toString())
-
- else if sType.isDateOrCalendarOrTemporal() (and writeDatesAsDatetime):
- out.writeElement(0x09, attrName)
- out.writeDateTime(millis)
-
- else if sType.isDateOrCalendarOrTemporal() (and !writeDatesAsDatetime):
- out.writeElement(0x02, attrName)
- out.writeString(Iso8601Utils.format(value, sType, getTimeZone()))
-
- else if sType.isDuration():
- out.writeElement(0x02, attrName)
- out.writeString(value.toString()) // ISO 8601 duration: PT1H30M
-
- else if byte[]:
- out.writeElement(0x05, attrName)
- out.writeBinary(value)
-
- else if Bean:
- out.writeElement(0x03, attrName)
- child = out.createChild()
- child.startDocument()
- serializeBeanMap(child, toBeanMap(object), typeName)
- child.writeDocumentTo(out)
-
- else if Map:
- out.writeElement(0x03, attrName)
- child = out.createChild()
- child.startDocument()
- serializeMap(child, map, classMeta)
- child.writeDocumentTo(out)
-
- else if Collection/Array:
- out.writeElement(0x04, attrName)
- child = out.createChild()
- child.startDocument()
- serializeArray(child, collection)
- child.writeDocumentTo(out)
-
- else:
- out.writeElement(0x02, attrName)
- out.writeString(toString(object)) // Fallback to string
-
-serializeBeanMap(out, beanMap, typeName):
- if typeName: write _type element
- for each (key, value) in beanMap:
- if value is null: skip (or write NULL element based on config)
- writeElement(out, key, value, propertyClassMeta)
-
-serializeMap(out, map, classMeta):
- for each (key, value) in map:
- writeElement(out, toString(key), value, valueClassMeta)
-
-serializeArray(out, collection):
- index = 0
- for each item in collection:
- writeElement(out, String.valueOf(index), item, elementClassMeta)
- index++
-```
-
-The root-level serialization wraps everything in a top-level document:
-```
-doSerialize(pipe, object):
- out = new BsonOutputStream(pipe.getOutputStream())
- out.startDocument()
- if object is Bean or Map:
- serializeBeanMap/serializeMap(out, object)
- else:
- // Wrap non-document root values in {"value": x}
- writeElement(out, "value", object, classMeta)
- out.writeDocumentTo(pipe.getOutputStream())
-```
-
-### 6. `BsonParser.java`
-
-Extends `InputStreamParser`. Implements `BsonMetaProvider`.
-
-```java
-package org.apache.juneau.bson;
-
-public class BsonParser extends InputStreamParser implements BsonMetaProvider {
-
- public static final BsonParser DEFAULT = ...;
-
- public static class SpacedHex extends BsonParser { ... }
- public static class Base64 extends BsonParser { ... }
-
- public static class Builder extends InputStreamParser.Builder {
- protected Builder() {
- consumes("application/bson");
- }
- }
-
- @Override
- public BsonParserSession.Builder createSession() {
- return BsonParserSession.create(this);
- }
-}
-```
-
-### 7. `BsonParserSession.java`
-
-Extends `InputStreamParserSession`. Core parsing logic.
-
-Key methods:
-- `doParse(ParserPipe, ClassMeta)` -- Entry point
-- `parseAnything(ClassMeta, BsonInputStream)` -- Central dispatch
-- `parseDocument(BsonInputStream, ClassMeta)` -- Reads BSON document into bean or map
-- `parseArray(BsonInputStream, ClassMeta)` -- Reads BSON array into collection
-
-Parsing algorithm:
-```
-doParse(pipe, type):
- is = new BsonInputStream(pipe)
- return parseAnything(type, is)
-
-parseAnything(type, is):
- if type is Bean:
- documentSize = is.readDocumentSize()
- beanMap = newBeanMap(type)
- while not is.isDocumentEnd():
- elementType = is.readElementType()
- elementName = is.readElementName()
-
- if elementName == "_type":
- typeName = readTypedValue(is, elementType)
- // Resolve actual type, may rebuild beanMap
- else:
- bpm = beanMap.getProperty(elementName)
- if bpm != null:
- value = readTypedValue(is, elementType, bpm.getClassMeta())
- bpm.set(beanMap, elementName, value)
- else:
- handleUnknownProperty(elementName)
- skipValue(is, elementType)
- is.readDocumentTerminator()
- return beanMap.getBean()
-
- else if type is Map:
- documentSize = is.readDocumentSize()
- map = newMap(type)
- while not is.isDocumentEnd():
- elementType = is.readElementType()
- elementName = is.readElementName()
- value = readTypedValue(is, elementType, valueClassMeta)
- map.put(elementName, value)
- is.readDocumentTerminator()
- return map
-
- else if type is Collection:
- // BSON arrays are documents with "0", "1", ... keys
- documentSize = is.readDocumentSize()
- collection = newCollection(type)
- while not is.isDocumentEnd():
- elementType = is.readElementType()
- elementName = is.readElementName() // "0", "1", ... (ignored)
- value = readTypedValue(is, elementType, elementClassMeta)
- collection.add(value)
- is.readDocumentTerminator()
- return collection
-
-readTypedValue(is, elementType, targetType):
- switch elementType:
- 0x01 (DOUBLE): return is.readDouble()
- 0x02 (STRING): return is.readString()
- 0x03 (DOCUMENT): return parseAnything(targetType, is) // recursive
- 0x04 (ARRAY): return parseAnything(targetType, is) // recursive
- 0x05 (BINARY): return is.readBinary()
- 0x07 (OBJECTID): return is.readObjectId() // as hex string
- 0x08 (BOOLEAN): return is.readBoolean()
- 0x09 (DATETIME): return new Date(is.readDateTime())
- 0x0A (NULL): return null
- 0x10 (INT32): return is.readInt32()
- 0x12 (INT64): return is.readInt64()
- 0x13 (DECIMAL128): return is.readDecimal128()
- default: skipValue(is, elementType)
-```
-
-### 8. `BsonMetaProvider.java`
-
-```java
-package org.apache.juneau.bson;
-
-public interface BsonMetaProvider {
- BsonClassMeta getBsonClassMeta(ClassMeta<?> cm);
- BsonBeanPropertyMeta getBsonBeanPropertyMeta(BeanPropertyMeta bpm);
-}
-```
-
-### 9. `BsonClassMeta.java` and `BsonBeanPropertyMeta.java`
-
-Extend `ExtendedClassMeta` and `ExtendedBeanPropertyMeta`.
-
-Initially minimal (placeholder for future BSON-specific metadata).
-
-### 10. `annotation/Bson.java`
-
-```java
-@Target({TYPE, METHOD, FIELD})
-@Retention(RUNTIME)
-public @interface Bson {
- String on() default "";
- String[] onClass() default {};
-}
-```
-
-### 11. `annotation/BsonConfig.java`
-
-```java
-@Target({TYPE, METHOD})
-@Retention(RUNTIME)
-public @interface BsonConfig {
- String addBeanTypes() default "";
- String writeDatesAsDatetime() default "";
- int rank() default 0;
-}
-```
-
-### 12. `annotation/BsonAnnotation.java` and `annotation/BsonConfigAnnotation.java`
-
-Utility classes for programmatic annotation creation.
-
-### 13. `Bson.java` (Marshaller)
-
-Location: `src/main/java/org/apache/juneau/marshaller/Bson.java`
-
-Extends `StreamMarshaller`.
-
-```java
-package org.apache.juneau.marshaller;
-
-public class Bson extends StreamMarshaller {
- public static final Bson DEFAULT = new Bson();
-
- public static byte[] of(Object object) throws SerializeException { ... }
- public static <T> T to(byte[] input, Class<T> type) throws ParseException { ... }
- // ... full set of convenience methods following MsgPack pattern
-
- public Bson() { this(BsonSerializer.DEFAULT, BsonParser.DEFAULT); }
- public Bson(BsonSerializer s, BsonParser p) { super(s, p); }
-}
-```
-
-### 14. `package-info.java`
-
-Package-level Javadoc.
-
----
-
-## Files to Modify
-
-### 1. `BasicUniversalConfig.java`
-
-Add `BsonSerializer.class` to `serializers` and `BsonParser.class` to `parsers`.
-
-### 2. `BasicBsonConfig.java` (New)
-
-```java
-@Rest(
- serializers={BsonSerializer.class},
- parsers={BsonParser.class},
- defaultAccept="application/bson"
-)
-public interface BasicBsonConfig extends DefaultConfig {}
-```
-
-### 3. `RestClient.java`
-
-Add `BsonSerializer.class` and `BsonParser.class` to the `universal()` method.
-
-### 4. Context: `Context.java`
-
-Path: `juneau-core/juneau-marshall/src/main/java/org/apache/juneau/Context.java`
-
-Add `import org.apache.juneau.bson.annotation.*;` and add `{@link BsonConfig}` to the list of config annotations in the `applyAnnotations()` Javadoc (alphabetically).
-
----
-
-## Test Plan
-
-All test files in `juneau-utest/src/test/java/`.
-
-### 1. BsonOutputStream Tests: `org/apache/juneau/bson/BsonOutputStream_Test.java`
-
-Low-level binary encoding verification.
-
-- **a01_writeInt32** -- Little-endian 4-byte int encoding (0, 1, -1, MAX_VALUE, MIN_VALUE)
-- **a02_writeInt64** -- Little-endian 8-byte long encoding
-- **a03_writeDouble** -- IEEE 754 double encoding (0.0, -1.5, NaN, Infinity)
-- **a04_writeBoolean** -- 0x00 for false, 0x01 for true
-- **a05_writeString** -- Length-prefixed + null-terminated UTF-8 (empty, ASCII, Unicode)
-- **a06_writeCString** -- Null-terminated UTF-8 (no length prefix)
-- **a07_writeBinary** -- Length + subtype + raw bytes
-- **a08_writeDateTime** -- 8-byte little-endian millis
-- **a09_startEndDocument** -- Document: int32 size + content + 0x00 terminator
-- **a10_nestedDocument** -- Child documents correctly length-prefixed
-- **a11_emptyDocument** -- 5 bytes: int32(5) + 0x00
-- **a12_elementHeader** -- Type byte + cstring name encoding
-
-### 2. BsonInputStream Tests: `org/apache/juneau/bson/BsonInputStream_Test.java`
-
-Low-level binary decoding verification.
-
-- **b01_readInt32** -- Little-endian int32 decoding
-- **b02_readInt64** -- Little-endian int64 decoding
-- **b03_readDouble** -- IEEE 754 double decoding
-- **b04_readBoolean** -- Boolean byte decoding
-- **b05_readString** -- Length-prefixed + null-terminated string decoding
-- **b06_readCString** -- Null-terminated string decoding
-- **b07_readBinary** -- Binary data with subtype
-- **b08_readDateTime** -- Datetime millis decoding
-- **b09_readDocumentSize** -- Document size reading
-- **b10_readElementType** -- Type byte reading
-- **b11_readElementName** -- CString element name reading
-- **b12_isDocumentEnd** -- 0x00 terminator detection
-- **b13_readObjectId** -- 12-byte ObjectId to hex string
-- **b14_skipValue** -- Skipping values of each type
-
-### 3. Serializer Tests: `org/apache/juneau/bson/BsonSerializer_Test.java`
-
-- **c01_simpleBean** -- String, int, boolean, double properties
-- **c02_nestedBean** -- Nested bean as embedded document (type 0x03)
-- **c03_deeplyNestedBean** -- 3+ levels of document nesting
-- **c04_collectionOfStrings** -- `List<String>` as BSON array (type 0x04)
-- **c05_collectionOfIntegers** -- `List<Integer>` as BSON array
-- **c06_collectionOfBeans** -- `List<Bean>` as array of embedded documents
-- **c07_mapProperty** -- `Map<String,String>` as embedded document
-- **c08_nullValues** -- Null properties as BSON null (type 0x0A) or omitted
-- **c09_booleanValues** -- Boolean encoding (0x00/0x01)
-- **c10_intVsLong** -- `int` → int32 (0x10), `long` → int64 (0x12) type differentiation
-- **c11_floatAndDouble** -- Both map to BSON double (type 0x01)
-- **c12_dateValues** -- `Date`/`Calendar` as BSON datetime (type 0x09)
-- **c13_byteArrayValues** -- `byte[]` as BSON binary (type 0x05)
-- **c14_enumValues** -- Enums serialized as strings (type 0x02)
-- **c15_emptyBean** -- Empty document (5 bytes)
-- **c16_emptyCollections** -- Empty array document
-- **c17_objectSwaps** -- Swap transformations before encoding
-- **c18_typeName** -- `_type` property when `addBeanTypesBson` enabled
-- **c19_arrayWithNumericKeys** -- Array elements keyed as `"0"`, `"1"`, `"2"`
-- **c20_documentSizeCorrect** -- Verify int32 size prefix is accurate for various documents
-- **c21_stringEscaping** -- Strings with null bytes, Unicode, multi-byte characters
-- **c22_bigDecimal** -- `BigDecimal` as decimal128 (type 0x13)
-
-### 4. Parser Tests: `org/apache/juneau/bson/BsonParser_Test.java`
-
-- **d01_parseSimpleBean** -- Scalar elements to bean properties
-- **d02_parseNestedBean** -- Embedded document to nested bean
-- **d03_parseDeeplyNestedBean** -- Multi-level document nesting
-- **d04_parseListOfStrings** -- BSON array to `List<String>`
-- **d05_parseListOfIntegers** -- BSON array to `List<Integer>`
-- **d06_parseListOfBeans** -- Array of embedded documents to `List<Bean>`
-- **d07_parseMapProperty** -- Embedded document to `Map<String,String>`
-- **d08_parseBooleans** -- Boolean elements to boolean properties
-- **d09_parseInt32** -- int32 elements to int/short/byte properties
-- **d10_parseInt64** -- int64 elements to long properties
-- **d11_parseDouble** -- Double elements to float/double properties
-- **d12_parseString** -- String elements to String properties
-- **d13_parseDatetime** -- Datetime elements to Date/Calendar
-- **d14_parseBinary** -- Binary elements to byte[]
-- **d15_parseNull** -- Null elements to null property values
-- **d16_parseObjectId** -- ObjectId elements to hex strings
-- **d17_parseDecimal128** -- Decimal128 to BigDecimal
-- **d18_parseUnknownProperties** -- Unknown element names handled gracefully
-- **d19_parseEmptyDocument** -- 5-byte empty document
-- **d20_parseGenericMap** -- BSON document to `JsonMap` (untyped)
-- **d21_typeCoercion** -- int32 read into long property, double read into float, etc.
-
-### 5. Round-Trip Tests: `org/apache/juneau/bson/BsonRoundTrip_Test.java`
-
-- **e01_simpleBeanRoundTrip** -- All simple types round-trip
-- **e02_nestedBeanRoundTrip** -- Nested beans round-trip
-- **e03_collectionOfBeansRoundTrip** -- Bean collections round-trip
-- **e04_collectionOfStringsRoundTrip** -- String lists round-trip
-- **e05_mapRoundTrip** -- Map properties round-trip
-- **e06_enumRoundTrip** -- Enum values round-trip
-- **e07_dateRoundTrip** -- Date/Calendar round-trip through datetime
-- **e08_binaryRoundTrip** -- byte[] round-trip through binary
-- **e09_booleanRoundTrip** -- Boolean values round-trip
-- **e10_intLongRoundTrip** -- int32/int64 type preserved on round-trip
-- **e11_complexBeanRoundTrip** -- Bean with mix of all types
-- **e12_objectSwapRoundTrip** -- Swapped values round-trip
-- **e13_emptyCollectionsRoundTrip** -- Empty lists round-trip
-- **e14_nullPropertiesRoundTrip** -- Null properties round-trip
-- **e15_bigDecimalRoundTrip** -- BigDecimal round-trip through decimal128
-
-### 6. Marshaller Tests: `org/apache/juneau/marshaller/Bson_Test.java`
-
-- **f01_of** -- `Bson.of(bean)` serializes to byte[]
-- **f02_to** -- `Bson.to(bytes, Type)` parses from byte[]
-- **f03_roundTrip** -- `Bson.of()` + `Bson.to()` round-trip
-- **f04_defaultInstance** -- `Bson.DEFAULT.write()` and `Bson.DEFAULT.read()`
-
-### 7. Annotation Tests: `org/apache/juneau/bson/BsonAnnotation_Test.java`
-
-- **g01_bsonConfig** -- `@BsonConfig(addBeanTypes="true")` enables type property
-- **g02_writeDatesAsDatetime** -- `@BsonConfig(writeDatesAsDatetime="false")` writes dates as strings
-- **g03_annotationEquivalency** -- Annotation equivalency checks
-
-### 8. Edge Case Tests: `org/apache/juneau/bson/BsonEdgeCases_Test.java`
-
-- **h01_emptyInput** -- Zero-length input returns null
-- **h02_malformedDocument** -- Truncated document throws ParseException
-- **h03_wrongDocumentSize** -- Mismatched size prefix handled
-- **h04_unicodeStrings** -- Multi-byte UTF-8 in keys and values
-- **h05_veryLongStrings** -- Strings > 65KB
-- **h06_deeplyNestedDocuments** -- 10+ levels of nesting
-- **h07_cyclicReferences** -- Handled by recursion detection
-- **h08_optionalProperties** -- `Optional<T>` bean properties
-- **h09_mapWithNonStringKeys** -- Integer/enum map keys converted to strings
-- **h10_emptyString** -- Empty string correctly encoded (length=1 for null terminator)
-- **h11_maxInt32Boundary** -- int at Integer.MAX_VALUE/MIN_VALUE
-- **h12_largeDocument** -- Document with many elements (>100)
-- **h13_bsonArrayOrdering** -- Array element ordering preserved
-- **h14_deprecatedTypes** -- Parsing documents with deprecated type codes (ObjectId, Undefined)
-
-### 9. Media Type Tests: `org/apache/juneau/bson/BsonMediaType_Test.java`
-
-- **i01_producesCorrectMediaType** -- Serializer produces `application/bson`
-- **i02_consumesCorrectMediaType** -- Parser consumes `application/bson`
-- **i03_contentNegotiation** -- Correct serializer selected via Accept header
-
-### 10. Compatibility Tests: `org/apache/juneau/bson/BsonCompatibility_Test.java`
-
-Verify BSON output matches known-good encodings (reference vectors).
-
-- **j01_emptyDocumentBytes** -- `05 00 00 00 00` (5 bytes)
-- **j02_helloWorldBytes** -- `{"hello": "world"}` matches reference encoding
-- **j03_nestedDocumentBytes** -- Nested document matches reference encoding
-- **j04_arrayDocumentBytes** -- Array encoding with `"0"`, `"1"` keys matches reference
-- **j05_int32Bytes** -- Known int32 encodings verified
-- **j06_int64Bytes** -- Known int64 encodings verified
-- **j07_doubleByes** -- Known double encodings verified
-- **j08_booleanBytes** -- `08 xx 00 01` (true) and `08 xx 00 00` (false) verified
-
-### 11. Cross-Format Round-Trip Integration
-
-To achieve round-trip parity with JSON, BSON must be added to the **shared `TESTERS` array in `RoundTripTest_Base.java`** (not only to `RoundTripDateTime_Test.java`). `RoundTripTest_Base` is the base class extended by all round-trip test files, so adding BSON there automatically runs BSON through every round-trip test suite.
-
-**Primary change**: Add a `RoundTrip_Tester` entry for BSON to:
-- `juneau-utest/src/test/java/org/apache/juneau/a/rttests/RoundTripTest_Base.java`
-
-This covers all subclass test files:
-
-| Test file | What it tests |
-|---|---|
-| `SimpleObjects_RoundTripTest` | null, String, int, arrays, List, Map |
-| `PrimitivesBeans_RoundTripTest` | Beans with primitive (int, long, boolean, etc.) fields |
-| `PrimitiveObjectBeans_RoundTripTest` | Beans with boxed primitive (Integer, Long, Boolean, etc.) fields |
-| `BeanProperties_RoundTripTest` | Arrays of lists, complex generics in bean fields |
-| `RoundTripMaps_Test` | HashMap, TreeMap, LinkedHashMap, EnumMap, etc. |
-| `Generics_RoundTripTest` | Generic types with unbound/bound type variables, Pair<A,B> |
-| `OptionalObjects_RoundTripTest` | Optional<T>, OptionalInt, OptionalLong, OptionalDouble |
-| `Enum_RoundTripTest` | Java enum types as standalone values and bean fields |
-| `BeanInheritance_RoundTripTest` | Beans with class inheritance hierarchies |
-| `Records_RoundTripTest` | Java record types |
-| `Classes_RoundTripTest` | Class objects serialized as fully-qualified class name strings |
-| `ReadOnlyBeans_RoundTripTest` | Read-only beans (no setters; constructed via constructor arguments) |
-| `RoundTripTransformBeans_Test` | Beans with @Swap annotations |
-| `RoundTripDateTime_Test` | Date/time and Duration types (Instant, ZonedDateTime, LocalDate, LocalDateTime, LocalTime, OffsetDateTime, OffsetTime, Year, YearMonth, Calendar, Date, Duration, XMLGregorianCalendar) |
-| `RoundTripBeanMaps_Test` | Beans used as or containing BeanMap wrappers |
-| `RoundTripBeansWithBuilders_Test` | Beans that use builder-pattern construction |
-| `JsonMaps_RoundTripTest` | Classes with JsonMap-based constructor / toJsonMap() method |
-| `ObjectsAsStrings_RoundTripTest` | Types that parse from strings (valueOf, fromString, parse, parseString) |
-| `DTOs_RoundTripTest` | Juneau internal DTOs such as JsonSchema |
-| `BeanMaps_RoundTripTest` | BeanMap wrappers |
-| `TrimStrings_RoundTripTest` | trimStrings serializer/parser option |
-| `NameProperty_RoundTripTest` | @NameProperty annotation |
-| `ParentProperty_RoundTripTest` | @ParentProperty annotation |
-
-**Note**: `RoundTripAddClassAttrs_Test` explicitly limits itself to text-format serializers (JSON/XML/HTML/UON/UrlEncoding) and should NOT include BSON. The `_type` polymorphism feature for BSON is covered by `BsonAnnotation_Test.java` (`g01_bsonConfig`).
-
----
-
-## Documentation
-
-### 1. Javadoc
-
-All Javadoc follows the style established by `JsonSerializer`, `JsonParser`, and `Json.java` (richer than `MsgPackSerializer`/`MsgPackParser`). The precise structure for each class is specified below.
-
-#### `BsonSerializer.java`
-
-Class-level Javadoc structure (in order):
-
-1. **Summary line**: `"Serializes POJO models to BSON (Binary JSON)."`
-2. **`<h5 class='topic'>Media types</h5>`**
- - Handles `Accept` types: `application/bson`
- - Produces `Content-Type` types: `application/bson`
-3. **`<h5 class='topic'>Description</h5>`** — Java-to-BSON type mapping list using `<ul class='spaced-list'>`:
- - `Map` / bean → BSON document (type `0x03`)
- - `Collection` / array → BSON array (type `0x04`, document with numeric string keys)
- - `String` / `Enum` → BSON string (type `0x02`)
- - `boolean` → BSON boolean (type `0x08`)
- - `int` / `short` / `byte` → BSON int32 (type `0x10`)
- - `long` → BSON int64 (type `0x12`)
- - `float` / `double` → BSON double (type `0x01`)
- - `Date` / `Calendar` / `Instant` → BSON datetime (type `0x09`, UTC millis) when `writeDatesAsDatetime=true`; otherwise ISO-8601 string
- - `Duration` → ISO-8601 duration string (e.g. `PT1H30M`)
- - `byte[]` → BSON binary (type `0x05`, subtype `0x00`)
- - `BigDecimal` → BSON decimal128 (type `0x13`)
- - `null` → BSON null (type `0x0A`)
- - All other types → fallback to `toString()` as BSON string
-4. **`<h5 class='topic'>Behavior-specific subclasses</h5>`** — describes `SpacedHex` (spaced-hex text output for debugging) and `Base64` (BASE64 text output for text-channel transmission)
-5. **`<h5 class='section'>Example:</h5>`** with `<p class='bjava'>` block:
- ```java
- // Use one of the default serializers to serialize a POJO
- byte[] bson = BsonSerializer.DEFAULT.serialize(someObject);
-
- // Create a custom serializer that writes dates as ISO-8601 strings instead of BSON datetime
- BsonSerializer s = BsonSerializer.create().writeDatesAsDatetime(false).build();
-
- // Clone an existing serializer and modify it
- s = BsonSerializer.DEFAULT.copy().addBeanTypes().build();
-
- // Serialize a POJO to BSON
- byte[] bson = s.serialize(someObject);
- ```
-6. **`<h5 class='section'>Notes:</h5>`** — thread-safety note (`<li class='note'>This class is thread safe and reusable.`)
-7. **`<h5 class='section'>Limitations:</h5>`** — see Limitations section below
-8. **`<h5 class='section'>See Also:</h5>`** — link to `https://juneau.apache.org/docs/topics/BsonBasics`
-
-Inner class Javadoc (single-line):
-- `SpacedHex`: `"Default serializer, spaced-hex string output."`
-- `Base64`: `"Default serializer, BASE64 string output."`
-- `DEFAULT` field: `"Default serializer, all default settings."`
-- `DEFAULT_SPACED_HEX` field: `"Default serializer, all default settings, spaced-hex string output."`
-- `DEFAULT_BASE64` field: `"Default serializer, all default settings, BASE64 string output."`
-
-#### `BsonParser.java`
-
-Class-level Javadoc structure (in order):
-
-1. **Summary line**: `"Parses BSON (Binary JSON) into POJO models."`
-2. **`<h5 class='topic'>Media types</h5>`**
- - Handles `Content-Type` types: `application/bson`
-3. **`<h5 class='topic'>Description</h5>`** — BSON-to-Java type mapping and coercion rules using `<ul class='spaced-list'>`:
- - BSON document (0x03) → bean or `Map`
- - BSON array (0x04) → `Collection` or Java array (numeric string keys are ignored)
- - BSON string (0x02) → `String`; also coerced to any type parseable from string
- - BSON boolean (0x08) → `boolean`
- - BSON int32 (0x10) → `int`; coerced to `long`, `short`, `byte` as needed
- - BSON int64 (0x12) → `long`; coerced to `int` if target is `int`
- - BSON double (0x01) → `double`; coerced to `float`
- - BSON datetime (0x09) → `Date`, `Calendar`, `Instant`, or `long` (millis)
- - BSON binary (0x05) → `byte[]`
- - BSON decimal128 (0x13) → `BigDecimal`
- - BSON null (0x0A) → `null`
- - BSON ObjectId (0x07) → 24-character hex `String`
- - Deprecated/unsupported types → silently skipped
-4. **No Java code example block** (parsers do not show usage examples — follows `JsonParser` / `MsgPackParser` convention)
-5. **`<h5 class='section'>Notes:</h5>`** — thread-safety note
-6. **`<h5 class='section'>Limitations:</h5>`** — see Limitations section below
-7. **`<h5 class='section'>See Also:</h5>`** — link to `https://juneau.apache.org/docs/topics/BsonBasics`
-
-Inner class Javadoc (single-line):
-- `SpacedHex`: `"Default parser, string input encoded as spaced-hex."`
-- `Base64`: `"Default parser, string input encoded as BASE64."`
-- `DEFAULT` field: `"Default parser, all default settings."`
-- `DEFAULT_SPACED_HEX` field: `"Default parser, all default settings, spaced-hex string input."`
-- `DEFAULT_BASE64` field: `"Default parser, all default settings, BASE64 string input."`
-
-#### `Bson.java` (marshaller)
-
-Class-level Javadoc structure (follows `Json.java` / `MsgPack.java` pattern):
-
-1. **Summary line**: `"A pairing of a {@link BsonSerializer} and {@link BsonParser} into a single class with convenience read/write methods."`
-2. **Brief prose paragraph**: explains the simplified API for reading and writing POJOs
-3. **`<h5 class='figure'>Examples:</h5>`** with two `<p class='bjava'>` blocks:
- - Block 1 — instance usage:
- ```java
- // Using instance.
- Bson bson = new Bson();
- MyPojo myPojo = bson.read(bytes, MyPojo.class);
- byte[] bytes = bson.write(myPojo);
- ```
- - Block 2 — DEFAULT static usage:
- ```java
- // Using DEFAULT instance.
- MyPojo myPojo = Bson.DEFAULT.read(bytes, MyPojo.class);
- byte[] bytes = Bson.DEFAULT.write(myPojo);
- ```
-4. **No format output figures** — BSON is binary; spaced-hex representation would reduce readability. Omit format-output `<h5 class='figure'>` blocks (unlike `Json.java`, matching `MsgPack.java` pattern).
-5. **`<h5 class='section'>See Also:</h5>`** — link to `https://juneau.apache.org/docs/topics/Marshallers`
-
-#### `BsonOutputStream.java` / `BsonInputStream.java`
-
-Class-level Javadoc:
-- Binary encoding details and little-endian byte order rationale
-- Document buffering strategy for length prefixes (why `ByteArrayOutputStream` children are used)
-- Not public API; document intended for implementors
-
-#### Limitations (Javadoc section for `BsonSerializer` and `BsonParser`)
-
-Both `BsonSerializer` and `BsonParser` must include a `<h5 class='section'>Limitations:</h5>` section covering:
-
-| Limitation | Detail |
-|---|---|
-| Root must be a document | BSON requires a top-level document. Standalone scalars, collections, and arrays serialized as the root value are automatically wrapped as `{"_value": x}`. Round-trip is supported via this convention, but the wire format differs from standalone bean/map serialization. |
-| Map keys must be strings | BSON document field names are always strings. Non-string map keys (e.g., `Map<Integer, String>`) are converted via `toString()`, matching JSON behavior. |
-| ObjectId is read-only | BSON ObjectId values (type `0x07`) encountered during parsing are returned as 24-character hex strings. Juneau does not generate ObjectIds during serialization. |
-| Deprecated MongoDB types skipped | BSON types deprecated by MongoDB (Undefined `0x06`, DBPointer `0x0C`, Symbol `0x0E`, JS with Scope `0x0F`) are silently skipped during parsing. |
-| MongoDB-internal types unsupported | JavaScript `0x0D`, Timestamp `0x11`, MinKey `0xFF`, MaxKey `0x7F` are not supported (see Scope Exclusions section). |
-| No human-readable text output | BSON is a binary format. The `SpacedHex` and `Base64` variants provide text-encodable representations for debugging and text-channel transmission. |
-
-### 2. Package Javadoc (`package-info.java`)
-
-- What BSON is and its relationship to MongoDB
-- Complete type mapping table
-- Usage examples for serialization and parsing
-- Comparison with MsgPack (both binary, but different encodings)
-- Comparison with JSON (binary vs text, typed vs untyped integers)
-- When to use BSON vs MsgPack vs JSON
-- REST integration examples
-
-### 3. Update Release Notes
-/Users/james.bognar/git/apache/juneau/docs/pages/release-notes
-
-### 4. Update Documentation
-
-Find how existing languages are documented in the following location and update the documentation to match
-the same level of detail.
-/Users/james.bognar/git/apache/juneau/docs/pages/topics
-
-
-
----
-
-## Implementation Order
-
-1. **`DataType.java`** -- BSON type code enum
-2. **`BsonOutputStream.java`** -- Binary encoder with document buffering
-3. **`BsonInputStream.java`** -- Binary decoder
-4. **`BsonOutputStream_Test.java`** -- Verify binary encoding (12 test cases)
-5. **`BsonInputStream_Test.java`** -- Verify binary decoding (14 test cases)
-6. **`BsonSerializer.java`** and **`BsonSerializerSession.java`** -- Core serialization
-7. **`BsonParser.java`** and **`BsonParserSession.java`** -- Core parsing
-8. **`BsonMetaProvider.java`**, **`BsonClassMeta.java`**, **`BsonBeanPropertyMeta.java`** -- Metadata
-9. **`annotation/Bson.java`**, **`annotation/BsonConfig.java`** -- Annotations
-10. **`annotation/BsonAnnotation.java`**, **`annotation/BsonConfigAnnotation.java`** -- Annotation utilities
-11. **`Bson.java`** (marshaller) -- Convenience API
-12. **`package-info.java`** -- Package documentation
-12a. **`RoundTripTest_Base.java`** -- Add BSON `RoundTrip_Tester` entry to the shared `TESTERS` array (ensures all round-trip test suites include BSON before format-specific round-trip tests are written)
-13. **Serializer tests** (`BsonSerializer_Test.java`) -- 22 test cases
-14. **Parser tests** (`BsonParser_Test.java`) -- 21 test cases
-15. **Round-trip tests** (`BsonRoundTrip_Test.java`) -- 15 test cases
-16. **Compatibility tests** (`BsonCompatibility_Test.java`) -- 8 test cases
-17. **Marshaller tests** (`Bson_Test.java`)
-18. **Annotation tests** (`BsonAnnotation_Test.java`)
-19. **Edge case tests** (`BsonEdgeCases_Test.java`) -- 14 test cases
-20. **Media type tests** (`BsonMediaType_Test.java`)
-21. **REST integration** (`BasicUniversalConfig`, `BasicBsonConfig`, `RestClient`)
-22. **Context registration** (`BsonConfig`, `BsonConfigAnnotation`, `Context.java`)
-23. **Final documentation review**
-
----
-
-## Key Design Decisions
-
-### 1. Extends OutputStreamSerializer/InputStreamParser (binary format)
-
-BSON is a binary format like MsgPack. It extends `OutputStreamSerializer`/`InputStreamParser`, not `WriterSerializer`/`ReaderParser`. The implementation follows the MsgPack architecture closely.
-
-### 2. Little-endian byte order
-
-BSON uses little-endian encoding, unlike MsgPack (big-endian) and Java's native big-endian `DataOutputStream`. All multi-byte integer and float writes must reverse byte order. `BsonOutputStream.writeLE4()` and `writeLE8()` handle this.
-
-### 3. Length-prefixed documents require buffering
-
-BSON documents begin with an int32 total byte count. Since the size is unknown until all elements are written, each document is serialized into a `ByteArrayOutputStream` child. When complete, the size is calculated and the `[size][content][0x00]` is written to the parent stream. This is the primary architectural difference from MsgPack, which writes element counts (not byte counts) and doesn't require buffering.
-
-### 4. Arrays are documents with numeric string keys
-
-BSON encodes arrays as documents: `["a", "b"]` becomes `{"0": "a", "1": "b"}`. The serializer writes numeric string keys (`"0"`, `"1"`, ...). The parser recognizes BSON array type (0x04) and ignores the keys, reading values in order into a Java collection.
-
-### 5. Typed integers (int32 vs int64)
-
-Unlike MsgPack (which uses variable-length encoding) or JSON (which has only `number`), BSON distinguishes 32-bit and 64-bit integers. Java `int`/`short`/`byte` map to BSON int32 (0x10), and Java `long` maps to BSON int64 (0x12). This preserves type fidelity on round-trip.
-
-### 6. Native date support
-
-BSON has a datetime type (0x09) that stores UTC milliseconds as int64. Java `Date`, `Calendar`, and `Instant` are serialized as BSON datetime by default (`writeDatesAsDatetime=true`). This is a significant advantage over MsgPack and JSON where dates are typically serialized as strings or numbers without type distinction.
-
-Date/time types are now first-class built-in types in Juneau. The serializer dispatch checks `sType.isDateOrCalendarOrTemporal()` before `sType.isBean()`. When `writeDatesAsDatetime=false`, dates fall through to string serialization via `Iso8601Utils.format()`. `java.time.Duration` objects are serialized as ISO 8601 duration strings (e.g., `PT1H30M`) via the `sType.isDuration()` dispatch check and `o.toString()`. On the parser side, `Iso8601Utils.parse()` and `BeanSession.convertToMember [...]
-
-### 7. BigDecimal support via decimal128
-
-BSON's decimal128 type (0x13) maps naturally to Java `BigDecimal`. The 128-bit IEEE 754-2008 decimal format preserves exact decimal values without floating-point rounding, making BSON a good choice for financial applications.
-
-### 8. No external dependencies
-
-The entire BSON binary encoding/decoding is implemented in `BsonOutputStream` and `BsonInputStream`. The format is straightforward (simpler than MsgPack in some ways) -- the main complexity is the little-endian byte order and document length prefixing.
-
-### 9. MongoDB-specific types handled gracefully
-
-Types like ObjectId (0x07) are read as hex strings during parsing. Deprecated types (Undefined, DBPointer, Symbol, JS with Scope) are skipped with a warning. This allows parsing BSON documents produced by MongoDB without requiring MongoDB-specific Java types.
-
-### 10. Package name: `org.apache.juneau.bson`
-
-Matches the established format name. Media type: `application/bson`.
-
----
-
-## Iterator/Iterable/Stream Support
-
-As of 9.2.1, Juneau natively supports serialization of `Iterator`, `Iterable` (non-Collection), `Enumeration`, and `java.util.stream.Stream` types.
-
-This format uses the **materialized path**: elements are collected into a List first since the format requires knowing the array size or inspecting elements upfront.
-
-In `serializeAnything()`, add a branch after the `isCollection()/isArray()` checks:
-
-```java
-} else if (sType.isStreamable()) {
- serializeCollection(out, toListFromStreamable(o, sType), eType);
-}
-```
-
-The `toListFromStreamable()` method from `SerializerSession` handles the conversion.
-
----
-
-## Scope Exclusions
-
-The following are explicitly not included:
-
-- **MongoDB driver integration** -- No dependency on or integration with the MongoDB Java driver
-- **ObjectId generation** -- ObjectIds are read (as hex strings) but not generated
-- **DBRef resolution** -- MongoDB-specific reference resolution
-- **Encrypted BSON values** -- Binary subtype 6
-- **Compressed BSON columns** -- Binary subtype 7 (MongoDB internal)
-- **BSON vectors** -- Binary subtype 9 (AI/ML specific; could be a future addition)
-- **JavaScript code fields** -- Types 0x0D and 0x0F (MongoDB-specific)
-- **Timestamp type** -- Type 0x11 (MongoDB replication internal)
-- **MinKey/MaxKey** -- Types 0xFF/0x7F (MongoDB query internal)
diff --git a/todo/TODO.md b/todo/TODO.md
index 1e5fffdb07..1211e94aaa 100644
--- a/todo/TODO.md
+++ b/todo/TODO.md
@@ -21,4 +21,6 @@ Figure out why this needs a cast:
- prop1,prop2,prop3
- Need a better way to define serializer config values (e.g. useWhitespace) arguments through REST (Additional headers? Content-Type modifications?)
-- RestResponse needs a setSerializer() command.
\ No newline at end of file
+- RestResponse needs a setSerializer() command.
+
+- Upgrade to Jena 6.0
\ No newline at end of file