[JAVA-2025] Byte array encoding/decoding missmatch Created: 30/Oct/15  Updated: 03/Nov/15  Resolved: 02/Nov/15

Status: Closed
Project: Java Driver
Component/s: Codecs
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Minor - P4
Reporter: Andriy Zhdanov Assignee: Ross Lawley
Resolution: Duplicate Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Duplicate
duplicates JAVA-1292 Support binary decoding transformations Closed

 Description   

The following test fails with AssertionError: expected:<class [B> but was:<class org.bson.types.Binary>

    @Test
    public void testByteArray() {
        MongoClient mongo = new MongoClient();
        MongoDatabase db = mongo.getDatabase("mydb");
        MongoCollection<Document> collection = db.getCollection("test");
        try {
            collection.insertOne(new Document("image", "MongoDB".getBytes()));
            assertEquals(byte[].class, collection.find().first().get("image").getClass());
        } finally {
            collection.drop();
            mongo.close();
        }
    }

It appears, byte array is encoded properly with ByteArrayCodec, but is decoded to BsonBinary, by BinaryCodec.

Probably BinaryCodec should be obsoleted, and removed from ValueCodecProvider.addCodecs, and BsonTypeClassMap.addDefault() should have map.put(BsonType.BINARY, byte[].class) instead of map.put(BsonType.BINARY, Binary.class)



 Comments   
Comment by Andriy Zhdanov [ 03/Nov/15 ]

Hi Ross,

Thank you for information. I do have a workaround: replacements.put(BsonType.BINARY, byte[].class) in DocumentCodecProvider. I believe this ticket may be closed as won't fix, and will watch JAVA-1292, may be it will let do something better.

Thank you.

Comment by Ross Lawley [ 02/Nov/15 ]

Hi andriy.zhdanov,

Thanks for the ticket, I can understand your surprise in this context but this currently is the expected behaviour. The Bson Spec identifies multiple subtypes for binary data, and when returning data from the database we keep that data. Whilst we do accept byte[] for convenience, it does come back as a generic Binary class instance with the sub type information as well.

There is a ticket JAVA-1292, which looks to special case the standard type in the way you describe, please vote or watch that ticket for updates.

If you require this immediately then you could create a custom DocumentCodec following the existing one but also adding a special case for BsonBinarySubType.BINARY.

Ross

Generated at Thu Feb 08 08:56:08 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.