org.bson.codecs.DocumentCodec Java Examples

The following examples show how to use org.bson.codecs.DocumentCodec. 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: MongoClientWrapper.java    From mongowp with Apache License 2.0 6 votes vote down vote up
@Inject
public MongoClientWrapper(MongoClientConfiguration configuration) throws
    UnreachableMongoServerException {
  try {
    MongoClientOptions options = toMongoClientOptions(configuration);
    ImmutableList<MongoCredential> credentials = toMongoCredentials(configuration);

    testAddress(configuration.getHostAndPort(), options);

    this.configuration = configuration;

    this.driverClient = new com.mongodb.MongoClient(
        new ServerAddress(
            configuration.getHostAndPort().getHostText(),
            configuration.getHostAndPort().getPort()),
        credentials,
        options
    );

    version = calculateVersion();
    codecRegistry = CodecRegistries.fromCodecs(new DocumentCodec());
    closed = false;
  } catch (com.mongodb.MongoException ex) {
    throw new UnreachableMongoServerException(configuration.getHostAndPort(), ex);
  }
}
 
Example #2
Source File: ElasticBulkService.java    From mongolastic with MIT License 6 votes vote down vote up
/**
 * Customizations for the document.toJson output.
 * <p>
 * http://mongodb.github.io/mongo-java-driver/3.0/bson/codecs/
 *
 * @return the toJson encoder.
 */
private Encoder<Document> getEncoder() {
    ArrayList<Codec<?>> codecs = new ArrayList<>();

    if (config.getElastic().getDateFormat() != null) {
        // Replace default DateCodec class to use the custom date formatter.
        codecs.add(new CustomDateCodec(config.getElastic().getDateFormat()));
    }

    if (config.getElastic().getLongToString()) {
        // Replace default LongCodec class
        codecs.add(new CustomLongCodec());
    }

    if (codecs.size() > 0) {
        BsonTypeClassMap bsonTypeClassMap = new BsonTypeClassMap();

        CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
                CodecRegistries.fromCodecs(codecs),
                MongoClient.getDefaultCodecRegistry());

        return new DocumentCodec(codecRegistry, bsonTypeClassMap);
    } else {
        return new DocumentCodec();
    }
}
 
Example #3
Source File: ResultDecoders.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: SerializableEntity.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
public Document toDocument() {
    try {
        return Document.parse(NetUtils.MAPPER.writeValueAsString(this.getBean()),
                new DocumentCodec(DatabaseManager.CODEC_REGISTRY));
    } catch (final JsonProcessingException err) {
        throw new RuntimeException(err);
    }
}
 
Example #5
Source File: ReactiveMongoNativeJavaDriverQueryExecutor.java    From mongodb-aggregate-query-support with Apache License 2.0 5 votes vote down vote up
private <T> Flux<T> adaptPipeline(QueryProvider queryProvider, Class<T> outputClass, Flux<Document> retval) {
  String key = queryProvider.getQueryResultKey();
  return retval.flatMapIterable(d -> getNestedDocumentList(key, d))
               .map(d -> d.toBsonDocument(Document.class, CodecRegistries.fromCodecs(new DocumentCodec())))
               .map((d) -> deserialize(outputClass, d))
               .doOnError(e -> LOGGER.error("Exception extracting results from document for key {}/output class {}",
                                            key, outputClass, e));
}
 
Example #6
Source File: ReactiveMongoNativeJavaDriverQueryExecutor.java    From mongodb-aggregate-query-support with Apache License 2.0 5 votes vote down vote up
private <T> Mono<T> adaptPipeline(QueryProvider queryProvider, Class<T> outputClass, Mono<Document> retval) {
  String key = queryProvider.getQueryResultKey();
  if (BeanUtils.isSimpleValueType(outputClass)) {
    return retval.map(d -> d.get(key, outputClass))
                 .doOnError(e -> LOGGER.error("Exception while extracting results from document for key {}", key, e));
  }
  return retval.map(d -> (Document) getDocumentForKey(key, d, false))
               .map(d -> d.toBsonDocument(Document.class, CodecRegistries.fromCodecs(new DocumentCodec())))
               .map((d) -> deserialize(outputClass, d))
               .doOnError(e -> LOGGER.error("Exception while extracting results from document for key {}", key, e));
}
 
Example #7
Source File: CustomType.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(
    final BsonWriter writer,
    final CustomType value,
    final EncoderContext encoderContext
) {
  final Document document = new Document();
  if (value.getId() != null) {
    document.put("_id", value.getId());
  }
  document.put("intValue", value.getIntValue());
  (new DocumentCodec()).encode(writer, document, encoderContext);
}
 
Example #8
Source File: ResultDecoders.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public AwsS3PutObjectResult decode(
    final BsonReader reader,
    final DecoderContext decoderContext
) {
  final Document document = (new DocumentCodec()).decode(reader, decoderContext);
  keyPresent(Fields.LOCATION_FIELD, document);
  return new AwsS3PutObjectResult(document.getString(Fields.LOCATION_FIELD));
}
 
Example #9
Source File: CoreUserApiKeyAuthProviderClient.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Decodes a BSON value from the given reader into an instance of the type parameter {@code T}.
 *
 * @param reader the BSON reader
 * @param decoderContext the decoder context
 * @return an instance of the type parameter {@code T}.
 */
@Override
public UserApiKey decode(final BsonReader reader, final DecoderContext decoderContext) {
  final Document document = (new DocumentCodec()).decode(reader, decoderContext);
  keyPresent(ApiKeyFields.ID, document);
  keyPresent(ApiKeyFields.NAME, document);
  keyPresent(ApiKeyFields.DISABLED, document);
  return new UserApiKey(
      document.getString(ApiKeyFields.ID),
      document.getString(ApiKeyFields.KEY),
      document.getString(ApiKeyFields.NAME),
      document.getBoolean(ApiKeyFields.DISABLED)
  );
}
 
Example #10
Source File: LumongoUtil.java    From lumongo with Apache License 2.0 4 votes vote down vote up
public static Document byteArrayToMongoDocument(byte[] byteArray) {
	BsonBinaryReader bsonReader = new BsonBinaryReader(ByteBuffer.wrap(byteArray));
	return new DocumentCodec().decode(bsonReader, DecoderContext.builder().build());
}
 
Example #11
Source File: LumongoUtil.java    From lumongo with Apache License 2.0 4 votes vote down vote up
public static byte[] mongoDocumentToByteArray(Document mongoDocument) {
	BasicOutputBuffer outputBuffer = new BasicOutputBuffer();
	BsonBinaryWriter writer = new BsonBinaryWriter(outputBuffer);
	new DocumentCodec().encode(writer, mongoDocument, EncoderContext.builder().isEncodingCollectibleDocument(true).build());
	return outputBuffer.toByteArray();
}
 
Example #12
Source File: CustomType.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
@Override
public CustomType decode(final BsonReader reader, final DecoderContext decoderContext) {
  final Document document = (new DocumentCodec()).decode(reader, decoderContext);
  return new CustomType(document.getObjectId("_id"), document.getInteger("intValue"));
}
 
Example #13
Source File: CoreStitchAuthUnitTests.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
@Test
public void testDoAuthenticatedRequestWithCustomCodecRegistry() {
  final StitchRequestClient requestClient = getMockedRequestClient();
  final StitchAuthRoutes routes = new StitchAppRoutes("my_app-12345").getAuthRoutes();
  final StitchAuth auth =
      new StitchAuth(
          requestClient,
          routes,
          new MemoryStorage());
  final CodecRegistry registry = CodecRegistries.fromRegistries(
      BsonUtils.DEFAULT_CODEC_REGISTRY,
      CodecRegistries.fromCodecs(new CustomType.Codec()));
  auth.loginWithCredentialInternal(new AnonymousCredential());

  final StitchAuthDocRequest.Builder reqBuilder = new StitchAuthDocRequest.Builder();
  reqBuilder.withPath("giveMeData");
  reqBuilder.withDocument(new Document());
  reqBuilder.withMethod(Method.POST);

  final String rawInt = "{\"$numberInt\": \"42\"}";
  // Check that primitive return types can be decoded.
  doReturn(new Response(rawInt)).when(requestClient).doRequest(any(StitchRequest.class));
  assertEquals(42, (int) auth.doAuthenticatedRequest(
      reqBuilder.build(),
      Integer.class,
      registry));
  doReturn(new Response(rawInt)).when(requestClient).doRequest(any(StitchRequest.class));
  assertEquals(42, (int) auth.doAuthenticatedRequest(
      reqBuilder.build(),
      new IntegerCodec()));

  final ObjectId expectedObjectId = new ObjectId();
  final String docRaw =
      String.format(
          "{\"_id\": {\"$oid\": \"%s\"}, \"intValue\": {\"$numberInt\": \"42\"}}",
          expectedObjectId.toHexString());

  // Check that BSON documents returned as extended JSON can be decoded into BSON
  // documents.
  doReturn(new Response(docRaw)).when(requestClient).doRequest(any(StitchRequest.class));
  Document doc = auth.doAuthenticatedRequest(reqBuilder.build(), Document.class, registry);
  assertEquals(expectedObjectId, doc.getObjectId("_id"));
  assertEquals(42, (int) doc.getInteger("intValue"));

  doReturn(new Response(docRaw)).when(requestClient).doRequest(any(StitchRequest.class));
  doc = auth.doAuthenticatedRequest(reqBuilder.build(), new DocumentCodec());
  assertEquals(expectedObjectId, doc.getObjectId("_id"));
  assertEquals(42, (int) doc.getInteger("intValue"));

  // Check that a custom type can be decoded without providing a codec, as long as that codec
  // is registered in the CoreStitchAuth's configuration.
  doReturn(new Response(docRaw)).when(requestClient).doRequest(any(StitchRequest.class));
  final CustomType ct = auth.doAuthenticatedRequest(
      reqBuilder.build(),
      CustomType.class,
      registry);
  assertEquals(expectedObjectId, ct.getId());
  assertEquals(42, ct.getIntValue());
}
 
Example #14
Source File: CoreRemoteMongoCollectionUnitTests.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testWatchCompactObjectIdIDs() throws IOException, InterruptedException {
  final CoreStitchServiceClient service = Mockito.mock(CoreStitchServiceClient.class);
  when(service.getCodecRegistry()).thenReturn(BsonUtils.DEFAULT_CODEC_REGISTRY);
  final CoreRemoteMongoClient client =
      CoreRemoteClientFactory.getClient(
          service,
          getClientInfo(),
          null);
  final CoreRemoteMongoCollection<Document> coll = getCollection(client);

  final Stream<CompactChangeEvent<Document>> mockStream = Mockito.mock(Stream.class);

  doReturn(mockStream).when(service).streamFunction(any(), any(), any(Decoder.class));

  final ObjectId[] expectedIDs = new ObjectId[] {new ObjectId(), new ObjectId(), new ObjectId()};
  coll.watchCompact(expectedIDs);

  final ArgumentCaptor<String> funcNameArg = ArgumentCaptor.forClass(String.class);
  final ArgumentCaptor<List> funcArgsArg = ArgumentCaptor.forClass(List.class);
  final ArgumentCaptor<Decoder<CompactChangeEvent>> decoderArgumentCaptor =
      ArgumentCaptor.forClass(Decoder.class);
  verify(service)
      .streamFunction(
          funcNameArg.capture(),
          funcArgsArg.capture(),
          decoderArgumentCaptor.capture());

  assertEquals("watch", funcNameArg.getValue());
  assertEquals(1, funcArgsArg.getValue().size());
  final Document expectedArgs = new Document();
  expectedArgs.put("database", "dbName1");
  expectedArgs.put("collection", "collName1");
  expectedArgs.put("ids", Arrays.stream(expectedIDs).map(BsonObjectId::new)
      .collect(Collectors.toSet()));
  expectedArgs.put("useCompactEvents", true);

  for (final Map.Entry<String, Object> entry : expectedArgs.entrySet()) {
    final Object capturedValue = ((Document)funcArgsArg.getValue().get(0)).get(entry.getKey());
    assertEquals(entry.getValue(), capturedValue);
  }
  assertEquals(ResultDecoders.compactChangeEventDecoder(new DocumentCodec()),
      decoderArgumentCaptor.getValue());
}
 
Example #15
Source File: CoreRemoteMongoCollectionUnitTests.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testWatchCompactBsonValueIDs() throws IOException, InterruptedException {
  final CoreStitchServiceClient service = Mockito.mock(CoreStitchServiceClient.class);
  when(service.getCodecRegistry()).thenReturn(BsonUtils.DEFAULT_CODEC_REGISTRY);
  final CoreRemoteMongoClient client =
      CoreRemoteClientFactory.getClient(
          service,
          getClientInfo(),
          null);
  final CoreRemoteMongoCollection<Document> coll = getCollection(client);

  final Stream<CompactChangeEvent<Document>> mockStream = Mockito.mock(Stream.class);

  doReturn(mockStream).when(service).streamFunction(any(), any(), any(Decoder.class));

  final BsonValue[] expectedIDs = new BsonValue[] {new BsonString("foobar"),
      new BsonObjectId(),
      new BsonDocument()};
  coll.watchCompact(expectedIDs);

  final ArgumentCaptor<String> funcNameArg = ArgumentCaptor.forClass(String.class);
  final ArgumentCaptor<List> funcArgsArg = ArgumentCaptor.forClass(List.class);
  final ArgumentCaptor<Decoder<CompactChangeEvent>> decoderArgumentCaptor =
      ArgumentCaptor.forClass(Decoder.class);
  verify(service)
      .streamFunction(
          funcNameArg.capture(),
          funcArgsArg.capture(),
          decoderArgumentCaptor.capture());

  assertEquals("watch", funcNameArg.getValue());
  assertEquals(1, funcArgsArg.getValue().size());
  final Document expectedArgs = new Document();
  expectedArgs.put("database", "dbName1");
  expectedArgs.put("collection", "collName1");
  expectedArgs.put("ids", new HashSet<>(Arrays.asList(expectedIDs)));
  expectedArgs.put("useCompactEvents", true);
  assertEquals(expectedArgs, funcArgsArg.getValue().get(0));
  assertEquals(ResultDecoders.compactChangeEventDecoder(new DocumentCodec()),
      decoderArgumentCaptor.getValue());
}
 
Example #16
Source File: CoreRemoteMongoCollectionUnitTests.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testWatchObjectIdIDs() throws IOException, InterruptedException {
  final CoreStitchServiceClient service = Mockito.mock(CoreStitchServiceClient.class);
  when(service.getCodecRegistry()).thenReturn(BsonUtils.DEFAULT_CODEC_REGISTRY);
  final CoreRemoteMongoClient client =
      CoreRemoteClientFactory.getClient(
          service,
          getClientInfo(),
          null);
  final CoreRemoteMongoCollection<Document> coll = getCollection(client);

  final Stream<ChangeEvent<Document>> mockStream = Mockito.mock(Stream.class);

  doReturn(mockStream).when(service).streamFunction(any(), any(), any(Decoder.class));

  final ObjectId[] expectedIDs = new ObjectId[] {new ObjectId(), new ObjectId(), new ObjectId()};
  coll.watch(expectedIDs);

  final ArgumentCaptor<String> funcNameArg = ArgumentCaptor.forClass(String.class);
  final ArgumentCaptor<List> funcArgsArg = ArgumentCaptor.forClass(List.class);
  final ArgumentCaptor<Decoder<ChangeEvent>> decoderArgumentCaptor =
      ArgumentCaptor.forClass(Decoder.class);
  verify(service)
      .streamFunction(
          funcNameArg.capture(),
          funcArgsArg.capture(),
          decoderArgumentCaptor.capture());

  assertEquals("watch", funcNameArg.getValue());
  assertEquals(1, funcArgsArg.getValue().size());
  final Document expectedArgs = new Document();
  expectedArgs.put("database", "dbName1");
  expectedArgs.put("collection", "collName1");
  expectedArgs.put("ids", Arrays.stream(expectedIDs).map(BsonObjectId::new)
      .collect(Collectors.toSet()));
  expectedArgs.put("useCompactEvents", false);

  for (final Map.Entry<String, Object> entry : expectedArgs.entrySet()) {
    final Object capturedValue = ((Document)funcArgsArg.getValue().get(0)).get(entry.getKey());
    assertEquals(entry.getValue(), capturedValue);
  }
  assertEquals(ResultDecoders.changeEventDecoder(new DocumentCodec()),
      decoderArgumentCaptor.getValue());
}
 
Example #17
Source File: CoreRemoteMongoCollectionUnitTests.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testWatchBsonValueIDs() throws IOException, InterruptedException {
  final CoreStitchServiceClient service = Mockito.mock(CoreStitchServiceClient.class);
  when(service.getCodecRegistry()).thenReturn(BsonUtils.DEFAULT_CODEC_REGISTRY);
  final CoreRemoteMongoClient client =
      CoreRemoteClientFactory.getClient(
          service,
          getClientInfo(),
          null);
  final CoreRemoteMongoCollection<Document> coll = getCollection(client);

  final Stream<ChangeEvent<Document>> mockStream = Mockito.mock(Stream.class);

  doReturn(mockStream).when(service).streamFunction(any(), any(), any(Decoder.class));

  final BsonValue[] expectedIDs = new BsonValue[] {new BsonString("foobar"),
      new BsonObjectId(),
      new BsonDocument()};
  coll.watch(expectedIDs);

  final ArgumentCaptor<String> funcNameArg = ArgumentCaptor.forClass(String.class);
  final ArgumentCaptor<List> funcArgsArg = ArgumentCaptor.forClass(List.class);
  final ArgumentCaptor<Decoder<ChangeEvent>> decoderArgumentCaptor =
      ArgumentCaptor.forClass(Decoder.class);
  verify(service)
      .streamFunction(
          funcNameArg.capture(),
          funcArgsArg.capture(),
          decoderArgumentCaptor.capture());

  assertEquals("watch", funcNameArg.getValue());
  assertEquals(1, funcArgsArg.getValue().size());
  final Document expectedArgs = new Document();
  expectedArgs.put("database", "dbName1");
  expectedArgs.put("collection", "collName1");
  expectedArgs.put("ids", new HashSet<>(Arrays.asList(expectedIDs)));
  expectedArgs.put("useCompactEvents", false);
  assertEquals(expectedArgs, funcArgsArg.getValue().get(0));
  assertEquals(ResultDecoders.changeEventDecoder(new DocumentCodec()),
      decoderArgumentCaptor.getValue());
}
 
Example #18
Source File: CoreRemoteMongoCollectionUnitTests.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testWatchWithFilter() throws IOException, InterruptedException {
  final CoreStitchServiceClient service = Mockito.mock(CoreStitchServiceClient.class);
  when(service.getCodecRegistry()).thenReturn(BsonUtils.DEFAULT_CODEC_REGISTRY);
  final CoreRemoteMongoClient client =
      CoreRemoteClientFactory.getClient(
          service,
          getClientInfo(),
          null);
  final CoreRemoteMongoCollection<Document> coll = getCollection(client);

  final Stream<ChangeEvent<Document>> mockStream = Mockito.mock(Stream.class);

  doReturn(mockStream).when(service).streamFunction(any(), any(), any(Decoder.class));

  final BsonDocument expectedFilter = new BsonDocument(
      "fullDocument.field", new BsonString("someValue"));
  coll.watchWithFilter(expectedFilter);

  final ArgumentCaptor<String> funcNameArg = ArgumentCaptor.forClass(String.class);
  final ArgumentCaptor<List> funcArgsArg = ArgumentCaptor.forClass(List.class);
  final ArgumentCaptor<Decoder<ChangeEvent>> decoderArgumentCaptor =
      ArgumentCaptor.forClass(Decoder.class);
  verify(service)
      .streamFunction(
          funcNameArg.capture(),
          funcArgsArg.capture(),
          decoderArgumentCaptor.capture());

  assertEquals("watch", funcNameArg.getValue());
  assertEquals(1, funcArgsArg.getValue().size());
  final Document expectedArgs = new Document();
  expectedArgs.put("database", "dbName1");
  expectedArgs.put("collection", "collName1");
  expectedArgs.put("useCompactEvents", false);
  expectedArgs.put("filter", expectedFilter);

  for (final Map.Entry<String, Object> entry : expectedArgs.entrySet()) {
    final Object capturedValue = ((Document)funcArgsArg.getValue().get(0)).get(entry.getKey());
    assertEquals(entry.getValue(), capturedValue);
  }
  assertEquals(ResultDecoders.changeEventDecoder(new DocumentCodec()),
      decoderArgumentCaptor.getValue());
}
 
Example #19
Source File: CoreRemoteMongoCollectionUnitTests.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testWatchFullCollection() throws IOException, InterruptedException {
  final CoreStitchServiceClient service = Mockito.mock(CoreStitchServiceClient.class);
  when(service.getCodecRegistry()).thenReturn(BsonUtils.DEFAULT_CODEC_REGISTRY);
  final CoreRemoteMongoClient client =
      CoreRemoteClientFactory.getClient(
          service,
          getClientInfo(),
          null);
  final CoreRemoteMongoCollection<Document> coll = getCollection(client);

  final Stream<ChangeEvent<Document>> mockStream = Mockito.mock(Stream.class);

  doReturn(mockStream).when(service).streamFunction(any(), any(), any(Decoder.class));

  coll.watch();

  final ArgumentCaptor<String> funcNameArg = ArgumentCaptor.forClass(String.class);
  final ArgumentCaptor<List> funcArgsArg = ArgumentCaptor.forClass(List.class);
  final ArgumentCaptor<Decoder<ChangeEvent>> decoderArgumentCaptor =
      ArgumentCaptor.forClass(Decoder.class);
  verify(service)
      .streamFunction(
          funcNameArg.capture(),
          funcArgsArg.capture(),
          decoderArgumentCaptor.capture());

  assertEquals("watch", funcNameArg.getValue());
  assertEquals(1, funcArgsArg.getValue().size());
  final Document expectedArgs = new Document();
  expectedArgs.put("database", "dbName1");
  expectedArgs.put("collection", "collName1");
  expectedArgs.put("useCompactEvents", false);

  for (final Map.Entry<String, Object> entry : expectedArgs.entrySet()) {
    final Object capturedValue = ((Document)funcArgsArg.getValue().get(0)).get(entry.getKey());
    assertEquals(entry.getValue(), capturedValue);
  }
  assertEquals(ResultDecoders.changeEventDecoder(new DocumentCodec()),
      decoderArgumentCaptor.getValue());
}
 
Example #20
Source File: CoreRemoteMongoCollectionUnitTests.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testFindOne() {
  final CoreStitchServiceClient service = Mockito.mock(CoreStitchServiceClient.class);
  when(service.getCodecRegistry()).thenReturn(BsonUtils.DEFAULT_CODEC_REGISTRY);
  final CoreRemoteMongoClient client =
          CoreRemoteClientFactory.getClient(
                  service,
                  getClientInfo(),
                  null);
  final CoreRemoteMongoCollection<Document> coll = getCollection(client);

  final Document doc1 = new Document("one", 2);
  doReturn(doc1).when(service).callFunction(any(), any(), any(Decoder.class));

  // Test simple findOne
  final Document result1 = coll.findOne();
  assertEquals(result1, doc1);

  final ArgumentCaptor<String> funcNameArg = ArgumentCaptor.forClass(String.class);
  final ArgumentCaptor<List> funcArgsArg = ArgumentCaptor.forClass(List.class);
  final ArgumentCaptor<Decoder<Collection<Document>>> resultClassArg =
          ArgumentCaptor.forClass(Decoder.class);
  verify(service)
          .callFunction(
                  funcNameArg.capture(),
                  funcArgsArg.capture(),
                  resultClassArg.capture());

  assertEquals("findOne", funcNameArg.getValue());
  assertEquals(1, funcArgsArg.getValue().size());
  final Document expectedArgs = new Document();
  expectedArgs.put("database", "dbName1");
  expectedArgs.put("collection", "collName1");
  expectedArgs.put("query", new BsonDocument());
  assertEquals(expectedArgs, funcArgsArg.getValue().get(0));
  assertEquals(DocumentCodec.class, resultClassArg.getValue().getClass());

  // Test more complicated findOne()
  final BsonDocument expectedFilter  = new BsonDocument("one", new BsonInt32(23));
  final BsonDocument expectedSort    = new BsonDocument("field1", new BsonInt32(1));
  final BsonDocument expectedProject = new BsonDocument("field2", new BsonInt32(-1));
  final RemoteFindOptions options    = new RemoteFindOptions()
          .limit(2)
          .projection(expectedProject)
          .sort(expectedSort);
  final Document result2 = coll.findOne(expectedFilter, options);
  assertEquals(result2, doc1);

  verify(service, times(2))
          .callFunction(
                  funcNameArg.capture(),
                  funcArgsArg.capture(),
                  resultClassArg.capture());

  assertEquals("findOne", funcNameArg.getValue());
  assertEquals(1, funcArgsArg.getValue().size());
  expectedArgs.put("query", expectedFilter);
  expectedArgs.put("project", expectedProject);
  expectedArgs.put("sort", expectedSort);
  assertEquals(expectedArgs, funcArgsArg.getValue().get(0));
  assertEquals(DocumentCodec.class, resultClassArg.getValue().getClass());

  // Test custom class
  doReturn(1).when(service).callFunction(any(), any(), any(Decoder.class));
  final int res = coll.findOne(expectedFilter, Integer.class);
  assertEquals(1, res);

  // Should pass along errors
  doThrow(new IllegalArgumentException("whoops"))
          .when(service).callFunction(any(), any(), any(Decoder.class));
  assertThrows(() -> coll.findOne(), IllegalArgumentException.class);
}
 
Example #21
Source File: ResultDecoders.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
@Override
public AwsSesSendResult decode(final BsonReader reader, final DecoderContext decoderContext) {
  final Document document = (new DocumentCodec()).decode(reader, decoderContext);
  keyPresent(Fields.MESSAGE_ID_FIELD, document);
  return new AwsSesSendResult(document.getString(Fields.MESSAGE_ID_FIELD));
}
 
Example #22
Source File: AwsSesSendResult.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
@Override
public AwsSesSendResult decode(final BsonReader reader, final DecoderContext decoderContext) {
  final Document document = (new DocumentCodec()).decode(reader, decoderContext);
  keyPresent(Fields.MESSAGE_ID_FIELD, document);
  return new AwsSesSendResult(document.getString(Fields.MESSAGE_ID_FIELD));
}