org.bson.codecs.Decoder Java Examples

The following examples show how to use org.bson.codecs.Decoder. 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: MongoDBOperationExecutorInterceptorTest.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {

    interceptor = new MongoDBOperationExecutorInterceptor();

    Config.Plugin.MongoDB.TRACE_PARAM = true;

    when(enhancedInstance.getSkyWalkingDynamicField()).thenReturn("127.0.0.1:27017");

    BsonDocument document = new BsonDocument();
    document.append("name", new BsonString("by"));
    MongoNamespace mongoNamespace = new MongoNamespace("test.user");
    Decoder decoder = PowerMockito.mock(Decoder.class);
    FindOperation findOperation = new FindOperation(mongoNamespace, decoder);
    findOperation.filter(document);

    arguments = new Object[] {findOperation};
    argumentTypes = new Class[] {findOperation.getClass()};
}
 
Example #2
Source File: MongoDBInterceptorTest.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({
    "rawtypes",
    "unchecked"
})
@Before
public void setUp() throws Exception {

    interceptor = new MongoDBInterceptor();

    Config.Plugin.MongoDB.TRACE_PARAM = true;

    when(enhancedInstance.getSkyWalkingDynamicField()).thenReturn("127.0.0.1:27017");

    BsonDocument document = new BsonDocument();
    document.append("name", new BsonString("by"));
    MongoNamespace mongoNamespace = new MongoNamespace("test.user");
    Decoder decoder = PowerMockito.mock(Decoder.class);
    FindOperation findOperation = new FindOperation(mongoNamespace, decoder);
    findOperation.filter(document);

    arguments = new Object[] {findOperation};
    argumentTypes = new Class[] {findOperation.getClass()};
}
 
Example #3
Source File: StreamTestUtils.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
private static <T> Stream<T> doCreateStream(final Decoder<T> decoder,
                                            final boolean open,
                                            final String... streamContent)
    throws IOException {
  final EventStream eventStream = Mockito.mock(EventStream.class);

  final List<Event> streamEvents =
      Arrays.stream(streamContent)
          .map(c -> new Event.Builder().withData(c).build()).collect(Collectors.toList());

  final int numEvents = streamEvents.size();
  if (numEvents > 0) {
    final Object firstEvent = streamEvents.get(0);
    final Object[] subsequentEvents =
        streamEvents.subList(1, streamEvents.size()).toArray();

    doReturn(firstEvent, subsequentEvents).when(eventStream).nextEvent();
  }
  doReturn(open).when(eventStream).isOpen();

  return new Stream<>(eventStream, decoder);
}
 
Example #4
Source File: WatchOperation.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
public <ChangeEventT extends BaseChangeEvent<DocumentT>> Stream<ChangeEventT> execute(
    final CoreStitchServiceClient service
) throws InterruptedException, IOException {
  final Document args = new Document();
  args.put("database", namespace.getDatabaseName());
  args.put("collection", namespace.getCollectionName());
  args.put("useCompactEvents", useCompactEvents);

  if (ids != null) {
    args.put("ids", ids);
  } else if (matchFilter != null) {
    args.put("filter", matchFilter);
  }

  final Decoder<ChangeEventT> decoder = useCompactEvents
      ? (Decoder<ChangeEventT>) ResultDecoders.compactChangeEventDecoder(fullDocumentCodec)
      : (Decoder<ChangeEventT>) ResultDecoders.changeEventDecoder(fullDocumentCodec);

  return service.streamFunction(
      "watch",
      Collections.singletonList(args),
      decoder);
}
 
Example #5
Source File: FindOneOperation.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Construct a new instance.
 *
 * @param namespace the database and collection namespace for the operation.
 * @param decoder the decoder for the result documents.
 */
FindOneOperation(
        final MongoNamespace namespace,
        final BsonDocument filter,
        final BsonDocument projection,
        final BsonDocument sort,
        final Decoder<T> decoder) {
  notNull("namespace", namespace);
  notNull("decoder", decoder);
  notNull("filter", filter);
  this.namespace = namespace;
  this.filter = filter;
  this.projection = projection;
  this.sort = sort;
  this.decoder = decoder;
}
 
Example #6
Source File: FindOneAndModifyOperation.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Construct a new instance.
 *
 * @param namespace the database and collection namespace for the operation.
 * @param methodName the name of the findOneAndModify function to run.
 * @param filter the filter to query for the document.
 * @param update the update to apply to the resulting document.
 * @param project the projection operation to apply to the returned document.
 * @param sort the sort to use on the query before selecting the first document.
 * @param decoder the decoder for the result documents.Operations.java
 *
 */
FindOneAndModifyOperation(
        final MongoNamespace namespace,
        final String methodName,
        final BsonDocument filter,
        final BsonDocument update,
        final BsonDocument project,
        final BsonDocument sort,
        final Decoder<T> decoder) {
  notNull("namespace", namespace);
  notNull("methodName", methodName);
  notNull("filter", filter);
  notNull("update", update);
  notNull("decoder", decoder);
  this.namespace = namespace;
  this.methodName = methodName;
  this.filter = filter;
  this.update = update;
  this.project = project;
  this.sort = sort;
  this.decoder = decoder;
}
 
Example #7
Source File: CoreStitchAuth.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #8
Source File: CoreStitchAuth.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
@Override
public <T> Stream<T> openAuthenticatedStream(
    final StitchAuthRequest stitchReq,
    final Decoder<T> decoder
) throws InterruptedException {
  if (!isLoggedInInterruptibly()) {
    throw new StitchClientException(StitchClientErrorCode.MUST_AUTHENTICATE_FIRST);
  }

  final String authToken = stitchReq.getUseRefreshToken()
      ? getAuthInfo().getRefreshToken() : getAuthInfo().getAccessToken();
  try {
    return new Stream<>(
        requestClient.doStreamRequest(stitchReq.builder().withPath(
            stitchReq.getPath() + AuthStreamFields.AUTH_TOKEN + authToken
        ).build()),
        decoder
    );
  } catch (final StitchServiceException ex) {
    return handleAuthFailureForStream(ex, stitchReq, decoder);
  }
}
 
Example #9
Source File: CoreStitchAuth.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
private <T> Stream<T> handleAuthFailureForStream(
    final StitchServiceException ex,
    final StitchAuthRequest req,
    final Decoder<T> decoder
) throws InterruptedException {
  if (ex.getErrorCode() != StitchServiceErrorCode.INVALID_SESSION) {
    throw ex;
  }

  // using a refresh token implies we cannot refresh anything, so clear auth and
  // notify
  if (req.getUseRefreshToken() || !req.getShouldRefreshOnFailure()) {
    clearActiveUserAuth();
    throw ex;
  }

  tryRefreshAccessToken(req.getStartedAt());

  return openAuthenticatedStream(
      req.builder().withShouldRefreshOnFailure(false).build(), decoder);
}
 
Example #10
Source File: StitchServiceClientImpl.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public <ResultT> Task<ResultT> callFunction(
    final String name, final List<?> args, final Decoder<ResultT> resultDecoder) {
  return dispatcher.dispatchTask(
      new Callable<ResultT>() {
        @Override
        public ResultT call() {
          return proxy.callFunction(name, args, null, resultDecoder);
        }
      });
}
 
Example #11
Source File: StitchAppClientImpl.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public <ResultT> ResultT callFunction(
    final String name,
    final List<?> args,
    final Long requestTimeout,
    final Decoder<ResultT> resultDecoder) {
  return coreClient.callFunction(name, args, requestTimeout, resultDecoder);
}
 
Example #12
Source File: StitchServiceClientImpl.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public <ResultT> ResultT callFunction(
    final String name,
    final List<?> args,
    final Long requestTimeout,
    final Decoder<ResultT> resultDecoder) {
  return proxy.callFunction(name, args, requestTimeout, resultDecoder);
}
 
Example #13
Source File: CoreStitchServiceUnitTests.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testStreamFunction() throws InterruptedException, IOException {
  final Stream<Integer> stream = StreamTestUtils.createStream(new IntegerCodec(), "42");

  doReturn(stream)
      .when(requestClient)
      .openAuthenticatedStream(
          any(StitchAuthRequest.class), ArgumentMatchers.<Decoder<Integer>>any());

  final String funcName = "myFunc1";
  final List<Integer> args = Arrays.asList(1, 2, 3);
  final Document expectedRequestDoc = new Document();
  expectedRequestDoc.put("name", funcName);
  expectedRequestDoc.put("service", TEST_SERVICE_NAME);
  expectedRequestDoc.put("arguments", args);

  assertEquals(
      stream, underTest.streamFunction(
          funcName, args, new IntegerCodec()));

  final ArgumentCaptor<StitchAuthRequest> reqArgument =
      ArgumentCaptor.forClass(StitchAuthRequest.class);
  @SuppressWarnings("unchecked")
  final ArgumentCaptor<Decoder<Integer>> decArgument = ArgumentCaptor.forClass(Decoder.class);

  verify(requestClient).openAuthenticatedStream(reqArgument.capture(), decArgument.capture());
  assertEquals(reqArgument.getValue().getMethod(), Method.GET);
  assertEquals(reqArgument.getValue().getPath(),
      routes.getFunctionCallRoute() + "?stitch_request="
          + Base64.encode(expectedRequestDoc.toJson().getBytes(StandardCharsets.UTF_8)));
  assertTrue(decArgument.getValue() instanceof IntegerCodec);
  assertFalse(reqArgument.getValue().getUseRefreshToken());
}
 
Example #14
Source File: CoreStitchServiceClientImpl.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Stream<T> streamFunction(final String name,
                                    final List<?> args,
                                    final Decoder<T> decoder) throws InterruptedException {
  final Stream<T> newStream = requestClient.openAuthenticatedStream(
      getStreamServiceFunctionRequest(name, args), decoder
  );
  this.allocatedStreams.put(new WeakReference<>(newStream), Boolean.TRUE);
  return newStream;
}
 
Example #15
Source File: CoreStitchServiceClientImpl.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
public <T> T callFunction(
    final String name,
    final List<?> args,
    final @Nullable Long requestTimeout,
    final Decoder<T> resultDecoder) {
  return requestClient.doAuthenticatedRequest(
      getCallServiceFunctionRequest(name, args, requestTimeout), resultDecoder);
}
 
Example #16
Source File: CoreStitchServiceClientImpl.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
public <T> T callFunction(
    final String name,
    final List<?> args,
    final Decoder<T> resultDecoder) {
  return requestClient.doAuthenticatedRequest(
      getCallServiceFunctionRequest(name, args, null), resultDecoder);
}
 
Example #17
Source File: StitchServiceClientImpl.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public <ResultT> Task<ResultT> callFunction(
    final String name,
    final List<?> args,
    final Long requestTimeout,
    final Decoder<ResultT> resultDecoder) {
  return dispatcher.dispatchTask(
      new Callable<ResultT>() {
        @Override
        public ResultT call() {
          return proxy.callFunction(name, args, requestTimeout, resultDecoder);
        }
      });
}
 
Example #18
Source File: StitchAppClientImpl.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public <ResultT> Task<ResultT> callFunction(
    final String name,
    final List<?> args,
    final Decoder<ResultT> resultDecoder) {
  return dispatcher.dispatchTask(
      new Callable<ResultT>() {
        @Override
        public ResultT call() {
          return coreClient.callFunction(name, args, null, resultDecoder);
        }
      });
}
 
Example #19
Source File: StitchAppClientImpl.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public <ResultT> Task<ResultT> callFunction(
    final String name,
    final List<?> args,
    final Long requestTimeout,
    final Decoder<ResultT> resultDecoder) {
  return dispatcher.dispatchTask(
      new Callable<ResultT>() {
        @Override
        public ResultT call() {
          return coreClient.callFunction(name, args, requestTimeout, resultDecoder);
        }
      });
}
 
Example #20
Source File: AggregateOperation.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a new instance.
 *
 * @param namespace the database and collection namespace for the operation.
 * @param pipeline the aggregation pipeline.
 * @param decoder the decoder for the result documents.
 */
AggregateOperation(
    final MongoNamespace namespace,
    final List<BsonDocument> pipeline,
    final Decoder<T> decoder
) {
  notNull("namespace", namespace);
  notNull("pipeline", pipeline);
  notNull("decoder", decoder);
  this.namespace = namespace;
  this.pipeline = pipeline;
  this.decoder = decoder;
}
 
Example #21
Source File: FindOperation.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a new instance.
 *
 * @param namespace the database and collection namespace for the operation.
 * @param decoder the decoder for the result documents.
 */
FindOperation(final MongoNamespace namespace, final Decoder<T> decoder) {
  notNull("namespace", namespace);
  notNull("decoder", decoder);
  this.namespace = namespace;
  this.decoder = decoder;
}
 
Example #22
Source File: StreamTestUtils.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
public static <T> Stream<T> createClosedStream(final Decoder<T> decoder,
                                               final String... streamContent) throws IOException {
  return doCreateStream(decoder, false, streamContent);
}
 
Example #23
Source File: CoreAwsS3ServiceClientUnitTests.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings({"unchecked", "deprecation"})
public void testSignPolicy() {
  final CoreStitchServiceClient service = Mockito.mock(CoreStitchServiceClient.class);
  final CoreAwsS3ServiceClient client = new CoreAwsS3ServiceClient(service);

  final String bucket = "stuff";
  final String key = "myFile";
  final String acl = "public-read";
  final String contentType = "plain/text";

  final String expectedPolicy = "you shall not";
  final String expectedSignature = "yoursTruly";
  final String expectedAlgorithm = "DES-111";
  final String expectedDate = "01-101-2012";
  final String expectedCredential = "someCredential";

  Mockito.doReturn(new AwsS3SignPolicyResult(
      expectedPolicy,
      expectedSignature,
      expectedAlgorithm,
      expectedDate,
      expectedCredential))
      .when(service).callFunction(any(), any(), any(Decoder.class));

  final AwsS3SignPolicyResult result =
      client.signPolicy(bucket, key, acl, contentType);
  assertEquals(result.getPolicy(), expectedPolicy);
  assertEquals(result.getSignature(), expectedSignature);
  assertEquals(result.getAlgorithm(), expectedAlgorithm);
  assertEquals(result.getDate(), expectedDate);
  assertEquals(result.getCredential(), expectedCredential);

  final ArgumentCaptor<String> funcNameArg = ArgumentCaptor.forClass(String.class);
  final ArgumentCaptor<List> funcArgsArg = ArgumentCaptor.forClass(List.class);
  @SuppressWarnings("unchecked")
  final ArgumentCaptor<Decoder<AwsS3SignPolicyResult>> resultClassArg =
      ArgumentCaptor.forClass(Decoder.class);
  verify(service)
      .callFunction(
          funcNameArg.capture(),
          funcArgsArg.capture(),
          resultClassArg.capture());

  assertEquals("signPolicy", funcNameArg.getValue());
  assertEquals(1, funcArgsArg.getValue().size());
  final Document expectedArgs = new Document();
  expectedArgs.put("bucket", bucket);
  expectedArgs.put("key", key);
  expectedArgs.put("acl", acl);
  expectedArgs.put("contentType", contentType);
  assertEquals(expectedArgs, funcArgsArg.getValue().get(0));
  assertEquals(ResultDecoders.signPolicyResultDecoder, resultClassArg.getValue());

  // Should pass along errors
  doThrow(new IllegalArgumentException("whoops"))
      .when(service).callFunction(any(), any(), any(Decoder.class));
  assertThrows(() -> client.signPolicy(bucket, key, acl, contentType),
      IllegalArgumentException.class);
}
 
Example #24
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 #25
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 #26
Source File: StreamTestUtils.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
public static <T> Stream<T> createStream(final Decoder<T> decoder,
                                         final String... streamContent) throws IOException {
  return doCreateStream(decoder, true, streamContent);
}
 
Example #27
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 #28
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 #29
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 #30
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());
}