Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support List<T> and Map<String, T> components in Java records #1002

Merged
merged 4 commits into from
Sep 27, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import org.bson.codecs.Codec;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.EncoderContext;
import org.bson.codecs.Parameterizable;
import org.bson.codecs.RepresentationConfigurable;
import org.bson.codecs.configuration.CodecConfigurationException;
import org.bson.codecs.configuration.CodecRegistry;
Expand All @@ -35,6 +36,7 @@
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.RecordComponent;
import java.util.ArrayList;
import java.util.Arrays;
Expand Down Expand Up @@ -83,6 +85,10 @@ Object getValue(final Record record) throws InvocationTargetException, IllegalAc
@SuppressWarnings("deprecation")
private static Codec<?> computeCodec(final RecordComponent component, final CodecRegistry codecRegistry) {
var codec = codecRegistry.get(toWrapper(component.getType()));
if (codec instanceof Parameterizable parameterizableCodec
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is this magic? assigning variables in an if statement 🤯

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not just one but two!

&& component.getGenericType() instanceof ParameterizedType parameterizedType) {
codec = parameterizableCodec.parameterize(codecRegistry, Arrays.asList(parameterizedType.getActualTypeArguments()));
}
BsonType bsonRepresentationType = null;

if (component.isAnnotationPresent(BsonRepresentation.class)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import org.bson.codecs.DecoderContext;
import org.bson.codecs.EncoderContext;
import org.bson.codecs.configuration.CodecConfigurationException;
import org.bson.codecs.record.samples.TestRecordEmbedded;
import org.bson.codecs.record.samples.TestRecordWithDeprecatedAnnotations;
import org.bson.codecs.record.samples.TestRecordWithIllegalBsonCreatorOnConstructor;
import org.bson.codecs.record.samples.TestRecordWithIllegalBsonCreatorOnMethod;
Expand All @@ -39,13 +40,19 @@
import org.bson.codecs.record.samples.TestRecordWithIllegalBsonPropertyOnAccessor;
import org.bson.codecs.record.samples.TestRecordWithIllegalBsonPropertyOnCanonicalConstructor;
import org.bson.codecs.record.samples.TestRecordWithIllegalBsonRepresentationOnAccessor;
import org.bson.codecs.record.samples.TestRecordWithListOfListOfRecords;
import org.bson.codecs.record.samples.TestRecordWithListOfRecords;
import org.bson.codecs.record.samples.TestRecordWithMapOfListOfRecords;
import org.bson.codecs.record.samples.TestRecordWithMapOfRecords;
import org.bson.codecs.record.samples.TestRecordWithPojoAnnotations;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import org.junit.jupiter.api.Test;

import java.util.List;
import java.util.Map;

import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

Expand Down Expand Up @@ -107,6 +114,119 @@ public void testRecordWithPojoAnnotations() {
assertEquals(testRecord, decoded);
}

@Test
public void testRecordWithNestedListOfRecords() {
var codec = new RecordCodec<>(TestRecordWithListOfRecords.class,
fromProviders(new RecordCodecProvider(), Bson.DEFAULT_CODEC_REGISTRY));
var identifier = new ObjectId();
var testRecord = new TestRecordWithListOfRecords(identifier, List.of(new TestRecordEmbedded("embedded")));

var document = new BsonDocument();
var writer = new BsonDocumentWriter(document);

// when
codec.encode(writer, testRecord, EncoderContext.builder().build());

// then
assertEquals(
new BsonDocument("_id", new BsonObjectId(identifier))
.append("nestedRecords", new BsonArray(List.of(new BsonDocument("name", new BsonString("embedded"))))),
document);
assertEquals("_id", document.getFirstKey());

// when
var decoded = codec.decode(new BsonDocumentReader(document), DecoderContext.builder().build());

// then
assertEquals(testRecord, decoded);
}

@Test
public void testRecordWithNestedListOfListOfRecords() {
var codec = new RecordCodec<>(TestRecordWithListOfListOfRecords.class,
fromProviders(new RecordCodecProvider(), Bson.DEFAULT_CODEC_REGISTRY));
var identifier = new ObjectId();
var testRecord = new TestRecordWithListOfListOfRecords(identifier, List.of(List.of(new TestRecordEmbedded("embedded"))));

var document = new BsonDocument();
var writer = new BsonDocumentWriter(document);

// when
codec.encode(writer, testRecord, EncoderContext.builder().build());

// then
assertEquals(
new BsonDocument("_id", new BsonObjectId(identifier))
.append("nestedRecords",
new BsonArray(List.of(new BsonArray(List.of(new BsonDocument("name", new BsonString("embedded"))))))),
document);
assertEquals("_id", document.getFirstKey());

// when
var decoded = codec.decode(new BsonDocumentReader(document), DecoderContext.builder().build());

// then
assertEquals(testRecord, decoded);
}

@Test
public void testRecordWithNestedMapOfRecords() {
var codec = new RecordCodec<>(TestRecordWithMapOfRecords.class,
fromProviders(new RecordCodecProvider(), Bson.DEFAULT_CODEC_REGISTRY));
var identifier = new ObjectId();
var testRecord = new TestRecordWithMapOfRecords(identifier,
Map.of("first", new TestRecordEmbedded("embedded")));

var document = new BsonDocument();
var writer = new BsonDocumentWriter(document);

// when
codec.encode(writer, testRecord, EncoderContext.builder().build());

// then
assertEquals(
new BsonDocument("_id", new BsonObjectId(identifier))
.append("nestedRecords", new BsonDocument("first", new BsonDocument("name", new BsonString("embedded")))),
document);
assertEquals("_id", document.getFirstKey());

// when
var decoded = codec.decode(new BsonDocumentReader(document), DecoderContext.builder().build());

// then
assertEquals(testRecord, decoded);
}

@Test
public void testRecordWithNestedMapOfListRecords() {
var codec = new RecordCodec<>(TestRecordWithMapOfListOfRecords.class,
fromProviders(new RecordCodecProvider(), Bson.DEFAULT_CODEC_REGISTRY));
var identifier = new ObjectId();
var testRecord = new TestRecordWithMapOfListOfRecords(identifier,
Map.of("first", List.of(new TestRecordEmbedded("embedded"))));

var document = new BsonDocument();
var writer = new BsonDocumentWriter(document);

// when
codec.encode(writer, testRecord, EncoderContext.builder().build());

// then
assertEquals(
new BsonDocument("_id", new BsonObjectId(identifier))
.append("nestedRecords",
new BsonDocument("first",
new BsonArray(List.of(new BsonDocument("name", new BsonString("embedded")))))),
document);
assertEquals("_id", document.getFirstKey());

// when
var decoded = codec.decode(new BsonDocumentReader(document), DecoderContext.builder().build());

// then
assertEquals(testRecord, decoded);
}

@Test
public void testRecordWithNulls() {
var codec = new RecordCodec<>(TestRecordWithDeprecatedAnnotations.class, Bson.DEFAULT_CODEC_REGISTRY);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
* Copyright 2008-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.bson.codecs.record.samples;

public record TestRecordEmbedded(String name) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* Copyright 2008-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.bson.codecs.record.samples;

import org.bson.codecs.pojo.annotations.BsonId;
import org.bson.types.ObjectId;

import java.util.List;

public record TestRecordWithListOfListOfRecords(@BsonId ObjectId id, List<List<TestRecordEmbedded>> nestedRecords) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* Copyright 2008-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.bson.codecs.record.samples;

import org.bson.codecs.pojo.annotations.BsonId;
import org.bson.types.ObjectId;

import java.util.List;

public record TestRecordWithListOfRecords(@BsonId ObjectId id, List<TestRecordEmbedded> nestedRecords) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* Copyright 2008-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.bson.codecs.record.samples;

import org.bson.codecs.pojo.annotations.BsonId;
import org.bson.types.ObjectId;

import java.util.List;
import java.util.Map;

public record TestRecordWithMapOfListOfRecords(@BsonId ObjectId id, Map<String, List<TestRecordEmbedded>> nestedRecords) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* Copyright 2008-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.bson.codecs.record.samples;

import org.bson.codecs.pojo.annotations.BsonId;
import org.bson.types.ObjectId;

import java.util.Map;

public record TestRecordWithMapOfRecords(@BsonId ObjectId id, Map<String, TestRecordEmbedded> nestedRecords) {
}
69 changes: 69 additions & 0 deletions bson/src/main/org/bson/codecs/AbstractIterableCodec.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
* Copyright 2008-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.bson.codecs;

import org.bson.BsonReader;
import org.bson.BsonType;
import org.bson.BsonWriter;

import java.util.ArrayList;
import java.util.List;

abstract class AbstractIterableCodec<T> implements Codec<Iterable<T>> {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Extracted superclass so that the main logic can be shared between IterableCodec and the new ParameterizedIterableCodec.


abstract T readValue(BsonReader reader, DecoderContext decoderContext);

abstract void writeValue(BsonWriter writer, T cur, EncoderContext encoderContext);

@Override
public Iterable<T> decode(final BsonReader reader, final DecoderContext decoderContext) {
reader.readStartArray();

List<T> list = new ArrayList<>();
while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) {
if (reader.getCurrentBsonType() == BsonType.NULL) {
reader.readNull();
list.add(null);
} else {
list.add(readValue(reader, decoderContext));
}
}

reader.readEndArray();

return list;
}

@Override
public void encode(final BsonWriter writer, final Iterable<T> value, final EncoderContext encoderContext) {
writer.writeStartArray();
for (final T cur : value) {
if (cur == null) {
writer.writeNull();
} else {
writeValue(writer, cur, encoderContext);
}
}
writer.writeEndArray();
}

@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public Class<Iterable<T>> getEncoderClass() {
return (Class<Iterable<T>>) ((Class) Iterable.class);
}
}
Loading