org.bson.codecs.DecoderContext Java Examples
The following examples show how to use
org.bson.codecs.DecoderContext.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JsonObjectCodecTest.java From vertx-mongo-client with Apache License 2.0 | 6 votes |
@Test public void readDocument_supportBsonBinaryUUID() { JsonObjectCodec codec = new JsonObjectCodec(options); BsonDocument bsonDocument = new BsonDocument(); UUID uuid = UUID.randomUUID(); byte[] byteUuid = ByteBuffer.allocate(16) .putLong(uuid.getMostSignificantBits()) .putLong(uuid.getLeastSignificantBits()) .array(); bsonDocument.put("test", new BsonBinary(BsonBinarySubType.UUID_STANDARD, byteUuid)); BsonDocumentReader reader = new BsonDocumentReader(bsonDocument); JsonObject result = codec.readDocument(reader, DecoderContext.builder().build()); JsonObject resultValue = result.getJsonObject("test"); assertTrue(resultValue.containsKey(JsonObjectCodec.BINARY_FIELD)); assertTrue(resultValue.containsKey(JsonObjectCodec.TYPE_FIELD)); ByteBuffer byteBuffer = ByteBuffer.wrap(resultValue.getBinary(JsonObjectCodec.BINARY_FIELD)); assertEquals(Integer.valueOf(BsonBinarySubType.UUID_STANDARD.getValue()), resultValue.getInteger(JsonObjectCodec.TYPE_FIELD)); assertEquals(uuid, new UUID(byteBuffer.getLong(), byteBuffer.getLong())); }
Example #2
Source File: CoreStitchAuth.java From stitch-android-sdk with Apache License 2.0 | 6 votes |
/** * Performs a request against Stitch using the provided {@link StitchAuthRequest} object, * and decodes the response using the provided result decoder. * * @param stitchReq The request to perform. * @return The response to the request, successful or not. */ public <T> T doAuthenticatedRequest(final StitchAuthRequest stitchReq, final Decoder<T> resultDecoder) { final Response response = doAuthenticatedRequest(stitchReq); try { final String bodyStr = IoUtils.readAllToString(response.getBody()); final JsonReader bsonReader = new JsonReader(bodyStr); // We must check this condition because the decoder will throw trying to decode null if (bsonReader.readBsonType() == BsonType.NULL) { return null; } return resultDecoder.decode(bsonReader, DecoderContext.builder().build()); } catch (final Exception e) { throw new StitchRequestException(e, StitchRequestErrorCode.DECODING_ERROR); } }
Example #3
Source File: DocumentReaderTest.java From morphia with Apache License 2.0 | 6 votes |
@Test public void nestedDatabaseRead() { getDs().getMapper().map(Parent.class, Child.class); Parent parent = new Parent(); parent.child = new Child(); getDs().save(parent); MongoCollection<Document> collection = getDocumentCollection(Parent.class); Document first = collection.find().first(); Parent decode = getMapper().getCodecRegistry().get(Parent.class) .decode(new DocumentReader(first), DecoderContext.builder().build()); Assert.assertEquals(parent, decode); }
Example #4
Source File: MorphiaMapPropertyCodecProvider.java From morphia with Apache License 2.0 | 6 votes |
@Override public Map<K, V> decode(final BsonReader reader, final DecoderContext context) { reader.readStartDocument(); Map<K, V> map = getInstance(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { final K key = (K) Conversions.convert(reader.readName(), keyType); if (reader.getCurrentBsonType() == BsonType.NULL) { map.put(key, null); reader.readNull(); } else { map.put(key, codec.decode(reader, context)); } } reader.readEndDocument(); return map; }
Example #5
Source File: ResultDecoders.java From stitch-android-sdk with Apache License 2.0 | 6 votes |
@Override public AwsS3SignPolicyResult decode( final BsonReader reader, final DecoderContext decoderContext ) { final Document document = (new DocumentCodec()).decode(reader, decoderContext); keyPresent(Fields.POLICY_FIELD, document); keyPresent(Fields.SIGNATURE_FIELD, document); keyPresent(Fields.ALGORITHM_FIELD, document); keyPresent(Fields.DATE_FIELD, document); keyPresent(Fields.CREDENTIAL_FIELD, document); return new AwsS3SignPolicyResult( document.getString(Fields.POLICY_FIELD), document.getString(Fields.SIGNATURE_FIELD), document.getString(Fields.ALGORITHM_FIELD), document.getString(Fields.DATE_FIELD), document.getString(Fields.CREDENTIAL_FIELD)); }
Example #6
Source File: ChangeEvents.java From stitch-android-sdk with Apache License 2.0 | 6 votes |
/** * Transforms a {@link ChangeEvent} into one that can be used by a user defined conflict resolver. * @param event the event to transform. * @param codec the codec to use to transform any documents specific to the collection. * @return the transformed {@link ChangeEvent} */ static CompactChangeEvent transformCompactChangeEventForUser( final CompactChangeEvent<BsonDocument> event, final Codec codec ) { return new CompactChangeEvent<>( event.getOperationType(), event.getFullDocument() == null ? null : codec.decode( sanitizeDocument(event.getFullDocument()).asBsonReader(), DecoderContext.builder().build()), event.getDocumentKey(), sanitizeUpdateDescription(event.getUpdateDescription()), event.getStitchDocumentVersion(), event.getStitchDocumentHash(), event.hasUncommittedWrites()); }
Example #7
Source File: ChangeEvents.java From stitch-android-sdk with Apache License 2.0 | 6 votes |
/** * Transforms a {@link ChangeEvent} into one that can be used by a user defined conflict resolver. * @param event the event to transform. * @param codec the codec to use to transform any documents specific to the collection. * @return the transformed {@link ChangeEvent} */ static ChangeEvent transformChangeEventForUser( final ChangeEvent<BsonDocument> event, final Codec codec ) { return new ChangeEvent<>( event.getId(), event.getOperationType(), event.getFullDocument() == null ? null : codec.decode( sanitizeDocument(event.getFullDocument()).asBsonReader(), DecoderContext.builder().build()), event.getNamespace(), event.getDocumentKey(), sanitizeUpdateDescription(event.getUpdateDescription()), event.hasUncommittedWrites()); }
Example #8
Source File: Mapper.java From morphia with Apache License 2.0 | 6 votes |
/** * Converts a Document back to a type-safe java object (POJO) * * @param <T> the type of the entity * @param type the target type * @param document the Document containing the document from mongodb * @return the new entity * @morphia.internal */ public <T> T fromDocument(final Class<T> type, final Document document) { if (document == null) { return null; } Class<T> aClass = type; if (document.containsKey(options.getDiscriminatorKey())) { aClass = getClass(document); } CodecRegistry codecRegistry = getCodecRegistry(); DocumentReader reader = new DocumentReader(document); return codecRegistry .get(aClass) .decode(reader, DecoderContext.builder().build()); }
Example #9
Source File: ResultDecoders.java From stitch-android-sdk with Apache License 2.0 | 6 votes |
@Override @SuppressWarnings("unchecked") public ChangeEvent<DocumentT> decode( final BsonReader reader, final DecoderContext decoderContext ) { final BsonDocument document = (new BsonDocumentCodec()).decode(reader, decoderContext); final ChangeEvent<BsonDocument> rawChangeEvent = ChangeEvent.fromBsonDocument(document); if (codec == null || codec.getClass().equals(BsonDocumentCodec.class)) { return (ChangeEvent<DocumentT>)rawChangeEvent; } return new ChangeEvent<>( rawChangeEvent.getId(), rawChangeEvent.getOperationType(), rawChangeEvent.getFullDocument() == null ? null : codec.decode( rawChangeEvent.getFullDocument().asBsonReader(), DecoderContext.builder().build()), rawChangeEvent.getNamespace(), rawChangeEvent.getDocumentKey(), rawChangeEvent.getUpdateDescription(), rawChangeEvent.hasUncommittedWrites()); }
Example #10
Source File: MorphiaReferenceCodec.java From morphia with Apache License 2.0 | 6 votes |
@Override public MorphiaReference decode(final BsonReader reader, final DecoderContext decoderContext) { Mapper mapper = getDatastore().getMapper(); Object value = mapper.getCodecRegistry() .get(bsonTypeClassMap.get(reader.getCurrentBsonType())) .decode(reader, decoderContext); value = processId(value, mapper, decoderContext); if (Set.class.isAssignableFrom(getTypeData().getType())) { return new SetReference<>(getDatastore(), getFieldMappedClass(), (List) value); } else if (Collection.class.isAssignableFrom(getTypeData().getType())) { return new ListReference<>(getDatastore(), getFieldMappedClass(), (List) value); } else if (Map.class.isAssignableFrom(getTypeData().getType())) { return new MapReference<>(getDatastore(), (Map) value, getFieldMappedClass()); } else { return new SingleReference<>(getDatastore(), getFieldMappedClass(), value); } }
Example #11
Source File: ResultDecoders.java From stitch-android-sdk with Apache License 2.0 | 6 votes |
public RemoteUpdateResult decode( final BsonReader reader, final DecoderContext decoderContext) { final BsonDocument document = (new BsonDocumentCodec()).decode(reader, decoderContext); keyPresent(Fields.MATCHED_COUNT_FIELD, document); keyPresent(Fields.MODIFIED_COUNT_FIELD, document); final long matchedCount = document.getNumber(Fields.MATCHED_COUNT_FIELD).longValue(); final long modifiedCount = document.getNumber(Fields.MODIFIED_COUNT_FIELD).longValue(); if (!document.containsKey(Fields.UPSERTED_ID_FIELD)) { return new RemoteUpdateResult(matchedCount, modifiedCount, null); } return new RemoteUpdateResult( matchedCount, modifiedCount, document.get(Fields.UPSERTED_ID_FIELD)); }
Example #12
Source File: BsonParserTest.java From immutables with Apache License 2.0 | 6 votes |
/** * write with Jackson read with Bson. * Inverse of {@link #bsonThenJackson(String)} */ private void jacksonThenBson(String json) throws IOException { ObjectNode toWrite = maybeWrap(mapper.readTree(json)); BasicOutputBuffer buffer = new BasicOutputBuffer(); BsonWriter writer = new BsonBinaryWriter(buffer); BsonGenerator generator = new BsonGenerator(0, writer); // write with jackson mapper.writeValue(generator, toWrite); BsonBinaryReader reader = new BsonBinaryReader(ByteBuffer.wrap(buffer.toByteArray())); // read with BSON BsonDocument actual = MongoClientSettings.getDefaultCodecRegistry() .get(BsonDocument.class) .decode(reader, DecoderContext.builder().build()); // compare results BsonDocument expected = BsonDocument.parse(toWrite.toString()); if (!expected.equals(actual)) { check(maybeUnwrap(actual)).is(maybeUnwrap(expected)); Assertions.fail("Should have failed before"); } }
Example #13
Source File: TypedArrayCodec.java From morphia with Apache License 2.0 | 6 votes |
@Override public Object decode(final BsonReader reader, final DecoderContext decoderContext) { reader.readStartArray(); List list = new ArrayList<>(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { list.add(getCodec().decode(reader, decoderContext)); } reader.readEndArray(); Object array = Array.newInstance(type, list.size()); for (int i = 0; i < list.size(); i++) { Array.set(array, i, list.get(i)); } return array; }
Example #14
Source File: JacksonCodecsTest.java From immutables with Apache License 2.0 | 5 votes |
/** * Reading directly {@link Document} */ @Test public void document() throws IOException { final CodecRegistry registry = JacksonCodecs.registryFromMapper(mapper); Document expected = new Document("a", 1); Document actual= registry.get(Document.class).decode(new BsonDocumentReader(expected.toBsonDocument(BsonDocument.class, registry)), DecoderContext.builder().build()); check(actual).is(expected); }
Example #15
Source File: ArrayCodec.java From morphia with Apache License 2.0 | 5 votes |
private Object readValue(final BsonReader reader, final DecoderContext decoderContext) { BsonType bsonType = reader.getCurrentBsonType(); if (bsonType == BsonType.NULL) { reader.readNull(); return null; } else if (bsonType == BsonType.BINARY && BsonBinarySubType.isUuid(reader.peekBinarySubType()) && reader.peekBinarySize() == 16) { return mapper.getCodecRegistry().get(UUID.class).decode(reader, decoderContext); } return mapper.getCodecRegistry().get(type.getComponentType()).decode(reader, decoderContext); }
Example #16
Source File: CollectionDecoder.java From stitch-android-sdk with Apache License 2.0 | 5 votes |
@Override public Collection<ResultT> decode(final BsonReader reader, final DecoderContext decoderContext) { final Collection<ResultT> docs = new ArrayList<>(); reader.readStartArray(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { final ResultT doc = decoder.decode(reader, decoderContext); docs.add(doc); } reader.readEndArray(); return docs; }
Example #17
Source File: TupleCodecProvider.java From immutables with Apache License 2.0 | 5 votes |
Object decode(BsonValue bson) { final Object value; if (isNullable && bson.isNull()) { // return NULL if field is nullable and BSON is null value = null; } else if (!bson.isDocument()) { value = decoder.decode(new BsonValueReader(bson), DecoderContext.builder().build()); } else { value = decoder.decode(new BsonDocumentReader(bson.asDocument()), DecoderContext.builder().build()); } return value; }
Example #18
Source File: AbstractJsonCodec.java From vertx-mongo-client with Apache License 2.0 | 5 votes |
protected O readDocument(BsonReader reader, DecoderContext ctx) { O object = newObject(); reader.readStartDocument(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { String name = reader.readName(); add(object, name, readValue(reader, ctx)); } reader.readEndDocument(); return object; }
Example #19
Source File: ObjectCodec.java From morphia with Apache License 2.0 | 5 votes |
@Override public Object decode(final BsonReader reader, final DecoderContext decoderContext) { BsonType bsonType = reader.getCurrentBsonType(); Class<?> clazz; if (bsonType == BsonType.DOCUMENT) { clazz = Document.class; String discriminatorField = mapper.getOptions().getDiscriminatorKey(); BsonReaderMark mark = reader.getMark(); reader.readStartDocument(); while (clazz.equals(Document.class) && reader.readBsonType() != BsonType.END_OF_DOCUMENT) { if (reader.readName().equals(discriminatorField)) { try { clazz = mapper.getClass(reader.readString()); } catch (CodecConfigurationException e) { throw new MappingException(e.getMessage(), e); } } else { reader.skipValue(); } } mark.reset(); } else { clazz = bsonTypeClassMap.get(bsonType); } return mapper.getCodecRegistry() .get(clazz) .decode(reader, decoderContext); }
Example #20
Source File: TupleCodecProviderTest.java From immutables with Apache License 2.0 | 5 votes |
@Test void localDate() { LocalDateHolderCriteria criteria = LocalDateHolderCriteria.localDateHolder; Query query = Query.of(TypeHolder.LocalDateHolder.class) .addProjections(Matchers.toExpression(criteria.value), Matchers.toExpression(criteria.nullable), Matchers.toExpression(criteria.optional)); Path idPath = Visitors.toPath(KeyExtractor.defaultFactory().create(TypeHolder.LocalDateHolder.class).metadata().keys().get(0)); TupleCodecProvider provider = new TupleCodecProvider(query, new MongoPathNaming(idPath, PathNaming.defaultNaming()).toExpression()); Codec<ProjectedTuple> codec = provider.get(ProjectedTuple.class, registry); LocalDate now = LocalDate.now(); final long millisEpoch = now.atStartOfDay().toInstant(ZoneOffset.UTC).toEpochMilli(); BsonDocument doc = new BsonDocument() .append("id", new BsonString("id1")) .append("value", new BsonDateTime(millisEpoch)) .append("nullable", BsonNull.VALUE) .append("optional", BsonNull.VALUE) .append("array", new BsonArray()) .append("list", new BsonArray()); ProjectedTuple tuple = codec.decode(new BsonDocumentReader(doc), DecoderContext.builder().build()); check(tuple.get(Matchers.toExpression(criteria.value))).is(now); check(tuple.get(Matchers.toExpression(criteria.nullable))).isNull(); check(tuple.get(Matchers.toExpression(criteria.optional))).is(Optional.empty()); }
Example #21
Source File: AbstractJsonCodec.java From vertx-mongo-client with Apache License 2.0 | 5 votes |
protected A readArray(BsonReader reader, DecoderContext ctx) { A array = newArray(); reader.readStartArray(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { add(array, readValue(reader, ctx)); } reader.readEndArray(); return array; }
Example #22
Source File: OptionalProvider.java From immutables with Apache License 2.0 | 5 votes |
@Override public final O decode(BsonReader reader, DecoderContext decoderContext) { if (reader.getCurrentBsonType() == BsonType.NULL) { reader.readNull(); return empty(); } return nullable(delegate.decode(reader, decoderContext)); }
Example #23
Source File: TupleCodecProvider.java From immutables with Apache License 2.0 | 5 votes |
@Override public ProjectedTuple decode(BsonReader reader, DecoderContext context) { BsonDocument doc = registry.get(BsonDocument.class).decode(reader, context); final List<Object> values = new ArrayList<>(); for (FieldDecoder field: decoders) { BsonValue bson = resolveOrNull(doc, Arrays.asList(field.mongoField.split("\\."))); values.add(field.decode(bson)); } return ProjectedTuple.of(query.projections(), values); }
Example #24
Source File: JacksonCodec.java From EDDI with Apache License 2.0 | 5 votes |
@Override public T decode(BsonReader reader, DecoderContext decoderContext) { try { RawBsonDocument document = rawBsonDocumentCodec.decode(reader, decoderContext); return bsonObjectMapper.readValue(document.getByteBuffer().array(), type); } catch (IOException e) { throw new UncheckedIOException(e); } }
Example #25
Source File: JacksonCodec.java From mongo-jackson-codec with Apache License 2.0 | 5 votes |
@Override public T decode(BsonReader reader, DecoderContext decoderContext) { try { RawBsonDocument document = rawBsonDocumentCodec.decode(reader, decoderContext); return bsonObjectMapper.readValue(document.getByteBuffer().array(), type); } catch (IOException e) { throw new UncheckedIOException(e); } }
Example #26
Source File: JacksonCodecTest.java From mongo-jackson-codec with Apache License 2.0 | 5 votes |
@Test public void testDecoding() { String idValue = "/first_blog"; BsonDocumentReader reader = new BsonDocumentReader(createBlogPostBson(idValue, testOffsetDateTime)); BlogPost blogPost = codec.decode(reader, DecoderContext.builder().build()); BlogPost expectedBlogPost = new BlogPost(); expectedBlogPost.setId(idValue); expectedBlogPost.setOffsetDateTime(testOffsetDateTime); assertEquals(expectedBlogPost, blogPost); assertEquals(testOffsetDateTime.toInstant(), blogPost.getOffsetDateTime().toInstant()); }
Example #27
Source File: PrimitiveArrayCodec.java From Prism with MIT License | 5 votes |
@Override public PrimitiveArray decode(BsonReader reader, DecoderContext decoderContext) { reader.readStartDocument(); String key = reader.readString("key"); List<Number> value = Lists.newArrayList(); if (StringUtils.equals(key, PrimitiveArray.BYTE_ARRAY_ID)) { reader.readName("value"); reader.readStartArray(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { value.add(byteCodec.decode(reader, decoderContext)); } reader.readEndArray(); } else if (StringUtils.equals(key, PrimitiveArray.INT_ARRAY_ID)) { reader.readName("value"); reader.readStartArray(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { value.add(integerCodec.decode(reader, decoderContext)); } reader.readEndArray(); } else if (StringUtils.equals(key, PrimitiveArray.LONG_ARRAY_ID)) { reader.readName("value"); reader.readStartArray(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { value.add(longCodec.decode(reader, decoderContext)); } reader.readEndArray(); } else { reader.readEndDocument(); throw new BsonInvalidOperationException("Unsupported primitive type"); } reader.readEndDocument(); return new PrimitiveArray(key, value); }
Example #28
Source File: MongoBsonUtils.java From mongowp with Apache License 2.0 | 5 votes |
public static BsonValue read(InputStream is) throws IOException { String allText = CharStreams.toString(new BufferedReader(new InputStreamReader(is, Charsets.UTF_8))); JsonReader reader = new JsonReader(allText); DecoderContext context = DecoderContext.builder().build(); return BSON_CODEC.decode(reader, context); }
Example #29
Source File: SharedFongoResource.java From baleen with Apache License 2.0 | 5 votes |
@Override protected boolean doInitialize( ResourceSpecifier aSpecifier, Map<String, Object> aAdditionalParams) throws ResourceInitializationException { // Work whether it's a list of DB Objects or a single if ("{}".equals(fongoData) || "[]".equals(fongoData) || Strings.isNullOrEmpty(fongoData)) { return true; } if (fongoData.trim().startsWith("[")) { CodecRegistry codecRegistry = CodecRegistries.fromProviders( Arrays.asList( new ValueCodecProvider(), new BsonValueCodecProvider(), new DocumentCodecProvider())); JsonReader reader = new JsonReader(fongoData); BsonArrayCodec arrayReader = new BsonArrayCodec(codecRegistry); BsonArray docArray = arrayReader.decode(reader, DecoderContext.builder().build()); for (BsonValue doc : docArray.getValues()) { fongo .getDatabase(BALEEN) .getCollection(fongoCollection) .insertOne(Document.parse(doc.asDocument().toJson())); } } else if (fongoData.trim().startsWith("{")) { Document data = Document.parse(fongoData); fongo.getDatabase(BALEEN).getCollection(fongoCollection).insertOne(data); } else { getMonitor().error("Unsupported type"); throw new ResourceInitializationException(); } return true; }
Example #30
Source File: EntityDecoder.java From morphia with Apache License 2.0 | 5 votes |
protected void decodeProperties(final BsonReader reader, final DecoderContext decoderContext, final MorphiaInstanceCreator<T> instanceCreator) { reader.readStartDocument(); EntityModel<T> classModel = morphiaCodec.getEntityModel(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { String name = reader.readName(); if (classModel.useDiscriminator() && classModel.getDiscriminatorKey().equals(name)) { reader.readString(); } else { decodeModel(reader, decoderContext, instanceCreator, classModel.getFieldModelByName(name)); } } reader.readEndDocument(); }