org.bson.BsonObjectId Java Examples

The following examples show how to use org.bson.BsonObjectId. 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: RdbmsHandler.java    From kafka-connect-mongodb with Apache License 2.0 6 votes vote down vote up
protected static BsonDocument generateFilterDoc(BsonDocument keyDoc, BsonDocument valueDoc, OperationType opType) {
    if (keyDoc.keySet().isEmpty()) {
        if (opType.equals(OperationType.CREATE) || opType.equals(OperationType.READ)) {
            //create: no PK info in keyDoc -> generate ObjectId
            return new BsonDocument(DBCollection.ID_FIELD_NAME,new BsonObjectId());
        }
        //update or delete: no PK info in keyDoc -> take everything in 'before' field
        try {
            BsonDocument filter = valueDoc.getDocument(JSON_DOC_BEFORE_FIELD);
            if (filter.isEmpty())
                throw new BsonInvalidOperationException("value doc before field is empty");
            return filter;
        } catch(BsonInvalidOperationException exc) {
            throw new DataException("error: value doc 'before' field is empty or has invalid type" +
                    " for update/delete operation which seems severely wrong -> defensive actions taken!",exc);
        }
    }
    //build filter document composed of all PK columns
    BsonDocument pk = new BsonDocument();
    for (String f : keyDoc.keySet()) {
        pk.put(f,keyDoc.get(f));
    }
    return new BsonDocument(DBCollection.ID_FIELD_NAME,pk);
}
 
Example #2
Source File: TodoListActivity.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
private void updateTodoItemTask(final ObjectId itemId, final String newTask) {
  final BsonObjectId docId = new BsonObjectId(itemId);
  items.sync().updateOne(
      new Document("_id", docId),
      new Document("$set", new Document(TodoItem.Fields.TASK, newTask)))
      .addOnSuccessListener(result -> {
        items.sync().find(new Document("_id", docId)).first()
            .addOnSuccessListener(item -> {
              if (item == null) {
                return;
              }
              todoAdapter.updateOrAddItem(item);
            })
            .addOnFailureListener(e -> Log.e(TAG, "failed to find todo item", e));
      })
      .addOnFailureListener(e -> Log.e(TAG, "failed to insert todo item", e));
}
 
Example #3
Source File: ObjectEventWriteConverter.java    From epcis with Apache License 2.0 6 votes vote down vote up
public void capture(BsonObjectId dataID, Long eventTime, Set<String> epcList, BsonArray epcQuantities,
		String readPoint, String bizLocation, BsonArray sourceList, BsonArray destinationList) {

	ChronoGraph pg = Configuration.persistentGraph;

	if (epcList != null && !epcList.isEmpty()) {
		epcList.stream().forEach(object -> {
			MongoWriterUtil.addBasicTimestampProperties(pg, eventTime, object, readPoint, bizLocation, sourceList,
					destinationList);
			pg.addTimestampVertexProperty(object, eventTime, "data", dataID);
		});
	}

	if (epcQuantities != null && !epcQuantities.isEmpty()) {
		epcQuantities.stream().forEach(classElem -> {
			MongoWriterUtil.addBasicTimestampProperties(pg, eventTime, classElem, readPoint, bizLocation,
					sourceList, destinationList);
			pg.addTimestampVertexProperty(classElem.asDocument().getString("epcClass").getValue(), eventTime,
					"data", dataID);
		});
	}
	return;
}
 
Example #4
Source File: TransactionEventWriteConverter.java    From epcis with Apache License 2.0 6 votes vote down vote up
public void capture(BsonObjectId dataID, Long eventTime, Set<String> epcList, BsonArray epcQuantities,
		String readPoint, String bizLocation, BsonArray sourceList, BsonArray destinationList) {

	ChronoGraph pg = Configuration.persistentGraph;

	if (epcList != null && !epcList.isEmpty()) {
		epcList.stream().forEach(object -> {
			MongoWriterUtil.addBasicTimestampProperties(pg, eventTime, object, readPoint, bizLocation, sourceList,
					destinationList);
			pg.addTimestampVertexProperty(object, eventTime, "data", dataID);
		});
	}

	if (epcQuantities != null && !epcQuantities.isEmpty()) {
		epcQuantities.stream().forEach(classElem -> {
			MongoWriterUtil.addBasicTimestampProperties(pg, eventTime, classElem, readPoint, bizLocation,
					sourceList, destinationList);
			pg.addTimestampVertexProperty(classElem.asDocument().getString("epcClass").getValue(), eventTime,
					"data", dataID);
		});
	}
}
 
Example #5
Source File: SinkDocumentTest.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
@BeforeAll
static void initBsonDocs() {

  flatStructKey = new BsonDocument();
  flatStructKey.put("_id", new BsonObjectId(ObjectId.get()));
  flatStructKey.put("myBoolean", new BsonBoolean(true));
  flatStructKey.put("myInt", new BsonInt32(42));
  flatStructKey.put("myBytes", new BsonBinary(new byte[] {65, 66, 67}));
  BsonArray ba1 = new BsonArray();
  ba1.addAll(asList(new BsonInt32(1), new BsonInt32(2), new BsonInt32(3)));
  flatStructKey.put("myArray", ba1);

  flatStructValue = new BsonDocument();
  flatStructValue.put("myLong", new BsonInt64(42L));
  flatStructValue.put("myDouble", new BsonDouble(23.23d));
  flatStructValue.put("myString", new BsonString("BSON"));
  flatStructValue.put("myBytes", new BsonBinary(new byte[] {120, 121, 122}));
  BsonArray ba2 = new BsonArray();
  ba2.addAll(asList(new BsonInt32(9), new BsonInt32(8), new BsonInt32(7)));
  flatStructValue.put("myArray", ba2);

  nestedStructKey = new BsonDocument();
  nestedStructKey.put("_id", new BsonDocument("myString", new BsonString("doc")));
  nestedStructKey.put(
      "mySubDoc", new BsonDocument("mySubSubDoc", new BsonDocument("myInt", new BsonInt32(23))));

  nestedStructValue = new BsonDocument();
  nestedStructValue.put("mySubDocA", new BsonDocument("myBoolean", new BsonBoolean(false)));
  nestedStructValue.put(
      "mySubDocB",
      new BsonDocument(
          "mySubSubDocC", new BsonDocument("myString", new BsonString("some text..."))));
}
 
Example #6
Source File: EntityCodec.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
@Override
public BsonValue getDocumentId(T document) {
    Object id = idHandler.get(document);
    if (id instanceof ObjectId) return new BsonObjectId((ObjectId) id);
    if (id instanceof String) new BsonString((String) id);
    throw new Error(format("unsupported id type, id={}", id));
}
 
Example #7
Source File: TodoItem.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
static BsonDocument toBsonDocument(final TodoItem item) {
  final BsonDocument asDoc = new BsonDocument();
  asDoc.put(Fields.ID, new BsonObjectId(item.getId()));
  asDoc.put(Fields.OWNER_ID, new BsonString(item.getOwnerId()));
  asDoc.put(Fields.TASK, new BsonString(item.getTask()));
  asDoc.put(Fields.CHECKED, new BsonBoolean(item.isChecked()));
  if (item.getDoneDate() != null) {
    asDoc.put(Fields.DONE_DATE, new BsonDateTime(item.getDoneDate().getTime()));
  }
  return asDoc;
}
 
Example #8
Source File: CoreRemoteMongoCollectionImpl.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Watches specified IDs in a collection.  This convenience overload supports the use case
 * of non-{@link BsonValue} instances of {@link ObjectId} by wrapping them in
 * {@link BsonObjectId} instances for the user.
 * @param ids unique object identifiers of the IDs to watch.
 * @return the stream of change events.
 */
@Override
public Stream<ChangeEvent<DocumentT>> watch(final ObjectId... ids)
    throws InterruptedException, IOException {
  final BsonValue[] transformedIds = new BsonValue[ids.length];

  for (int i = 0; i < ids.length; i++) {
    transformedIds[i] = new BsonObjectId(ids[i]);
  }

  return watch(transformedIds);
}
 
Example #9
Source File: DeserialisationTest.java    From octarine with Apache License 2.0 5 votes vote down vote up
@Test public void
deserialise_object_id() {
    ObjectId value = new ObjectId(new Date(), random.nextInt(0xffffff));
    BsonDocument doc = new BsonDocument();
    doc.put("my-value", new BsonObjectId(value));
    Key<ObjectId> idKey = Key.named("my-value");

    Record record = BsonRecordDeserialiser.builder()
            .readObjectId(idKey)
            .get()
            .apply(doc);
    assertEquals("wrong ObjectId value", value, idKey.get(record).get());
}
 
Example #10
Source File: RdbmsHandler.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
static BsonDocument generateFilterDoc(
    final BsonDocument keyDoc, final BsonDocument valueDoc, final OperationType opType) {
  if (keyDoc.keySet().isEmpty()) {
    if (opType.equals(OperationType.CREATE) || opType.equals(OperationType.READ)) {
      // create: no PK info in keyDoc -> generate ObjectId
      return new BsonDocument(ID_FIELD, new BsonObjectId());
    }
    // update or delete: no PK info in keyDoc -> take everything in 'before' field
    try {
      BsonDocument filter = valueDoc.getDocument(JSON_DOC_BEFORE_FIELD);
      if (filter.isEmpty()) {
        throw new BsonInvalidOperationException("value doc before field is empty");
      }
      return filter;
    } catch (BsonInvalidOperationException exc) {
      throw new DataException(
          "Error: value doc 'before' field is empty or has invalid type"
              + " for update/delete operation which seems severely wrong -> defensive actions taken!",
          exc);
    }
  }
  // build filter document composed of all PK columns
  BsonDocument pk = new BsonDocument();
  for (String f : keyDoc.keySet()) {
    pk.put(f, keyDoc.get(f));
  }
  return new BsonDocument(ID_FIELD, pk);
}
 
Example #11
Source File: WritecontextTest.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
@Test
public void parseBsonArrayWithValues() throws IOException {

    BsonValue a = new BsonString("stest");
    BsonValue b = new BsonDouble(111);
    BsonValue c = new BsonBoolean(true);

    BsonDocument document = new BsonDocument()
            .append("int32", new BsonInt32(12))
            .append("int64", new BsonInt64(77L))
            .append("bo\"olean", new BsonBoolean(true))
            .append("date", new BsonDateTime(new Date().getTime()))
            .append("double", new BsonDouble(12.3))
            .append("string", new BsonString("pinpoint"))
            .append("objectId", new BsonObjectId(new ObjectId()))
            .append("code", new BsonJavaScript("int i = 10;"))
            .append("codeWithScope", new BsonJavaScriptWithScope("int x = y", new BsonDocument("y", new BsonInt32(1))))
            .append("regex", new BsonRegularExpression("^test.*regex.*xyz$", "big"))
            .append("symbol", new BsonSymbol("wow"))
            .append("timestamp", new BsonTimestamp(0x12345678, 5))
            .append("undefined", new BsonUndefined())
            .append("binary1", new BsonBinary(new byte[]{(byte) 0xe0, 0x4f, (byte) 0xd0, 0x20}))
            .append("oldBinary", new BsonBinary(BsonBinarySubType.OLD_BINARY, new byte[]{1, 1, 1, 1, 1}))
            .append("arrayInt", new BsonArray(Arrays.asList(a, b, c, new BsonInt32(7))))
            .append("document", new BsonDocument("a", new BsonInt32(77)))
            .append("dbPointer", new BsonDbPointer("db.coll", new ObjectId()))
            .append("null", new BsonNull())
            .append("decimal128", new BsonDecimal128(new Decimal128(55)));

    BasicDBObject query = new BasicDBObject();
    query.put("ComplexBson", document);

    logger.debug("document:{}", document);

    NormalizedBson stringStringValue = MongoUtil.parseBson(new Object[]{query}, true);
    logger.debug("val:{}", stringStringValue);

    List list = objectMapper.readValue("[" + stringStringValue.getNormalizedBson() + "]", List.class);
    Assert.assertEquals(list.size(), 1);
    Map<String, ?> query1Map = (Map<String, ?>) list.get(0);

    checkValue(query1Map);
}
 
Example #12
Source File: GridFSBucketImpl.java    From mongo-java-driver-reactivestreams with Apache License 2.0 4 votes vote down vote up
@Override
public GridFSUploadPublisher<ObjectId> uploadFromPublisher(final String filename, final Publisher<ByteBuffer> source,
                                               final GridFSUploadOptions options) {
    return executeUploadFromPublisher(openUploadStream(new BsonObjectId(), filename, options), source).withObjectId();
}
 
Example #13
Source File: GridFSBucketImpl.java    From mongo-java-driver-reactivestreams with Apache License 2.0 4 votes vote down vote up
@Override
public GridFSUploadPublisher<ObjectId> uploadFromPublisher(final ClientSession clientSession, final String filename,
                                                           final Publisher<ByteBuffer> source, final GridFSUploadOptions options) {
    return executeUploadFromPublisher(openUploadStream(clientSession, new BsonObjectId(), filename, options), source)
            .withObjectId();
}
 
Example #14
Source File: AggregationEventWriteConverter.java    From epcis with Apache License 2.0 4 votes vote down vote up
public void capture(BsonObjectId dataID, Long eventTime, String parentID, Set<String> childEPCs,
			BsonArray childQuantities, String readPoint, String bizLocation, BsonArray sourceList,
			BsonArray destinationList, String action) {

		ChronoGraph pg = Configuration.persistentGraph;

		// object = vid
		if (parentID != null) {
			MongoWriterUtil.addBasicTimestampProperties(pg, eventTime, parentID, readPoint, bizLocation, sourceList,
					destinationList);			
		}

		if (childEPCs != null)
			childEPCs.stream().forEach(child -> {
				MongoWriterUtil.addBasicTimestampProperties(pg, eventTime, child, readPoint, bizLocation, sourceList,
						destinationList);
			});

		if (childQuantities != null)
			childQuantities.stream().forEach(classElem -> {
				MongoWriterUtil.addBasicTimestampProperties(pg, eventTime, classElem, readPoint, bizLocation,
						sourceList, destinationList);
			});

		if (parentID != null) {
			if (childEPCs != null) {
				childEPCs.stream().forEach(child -> {
					pg.addTimestampEdgeProperties(parentID, child, "contains", eventTime,
							new BsonDocument("data", dataID).append("action", new BsonString(action)));
				});
			}

			if (childQuantities != null) {
				childQuantities.stream().forEach(classElem -> {
					String epcClass = classElem.asDocument().getString("epcClass").getValue();
					pg.addTimestampEdgeProperties(parentID, epcClass, "contains", eventTime,
							new BsonDocument("data", dataID).append("action", new BsonString(action)));
				});
			}

		}

	return;
}
 
Example #15
Source File: MongoBsonTranslator.java    From mongowp with Apache License 2.0 4 votes vote down vote up
private static ObjectId translateObjectId(com.torodb.mongowp.bson.BsonObjectId id) {
  return new ObjectId(id.toHexString());
}
 
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 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 #17
Source File: TypeConversionTest.java    From immutables with Apache License 2.0 4 votes vote down vote up
@Test
public void objectId() throws IOException {
  ObjectId id = ObjectId.get();
  check(Jsons.readerAt(new BsonObjectId(id)).peek()).is(JsonToken.STRING);
  check(Jsons.readerAt(new BsonObjectId(id)).nextString()).is(id.toHexString());
}
 
Example #18
Source File: TypeConversionTest.java    From immutables with Apache License 2.0 4 votes vote down vote up
@Test
void objectId() throws IOException {
  ObjectId id = ObjectId.get();
  check(Parsers.parserAt(new BsonObjectId(id)).getText()).is(id.toHexString());
}
 
Example #19
Source File: EntityCodecTest.java    From core-ng-project with Apache License 2.0 4 votes vote down vote up
@Test
void getDocumentId() {
    TestEntity entity = new TestEntity();
    entity.id = new ObjectId();
    assertEquals(new BsonObjectId(entity.id), entityCodec.getDocumentId(entity));
}
 
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 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 #21
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 #22
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 #23
Source File: CoreRemoteMongoCollectionUnitTests.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testUpdateMany() {
  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 BsonObjectId id = new BsonObjectId();
  doReturn(new RemoteUpdateResult(1, 1, id))
      .when(service).callFunction(any(), any(), any(Decoder.class));

  final Document expectedFilter = new Document("one", 2);
  final Document expectedUpdate = new Document("three", 4);
  RemoteUpdateResult result = coll.updateMany(expectedFilter, expectedUpdate);
  assertEquals(1, result.getMatchedCount());
  assertEquals(1, result.getModifiedCount());
  assertEquals(id, result.getUpsertedId());

  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("updateMany", funcNameArg.getValue());
  assertEquals(1, funcArgsArg.getValue().size());
  final Document expectedArgs = new Document();
  expectedArgs.put("database", "dbName1");
  expectedArgs.put("collection", "collName1");
  expectedArgs.put("query",
      expectedFilter.toBsonDocument(null, BsonUtils.DEFAULT_CODEC_REGISTRY));
  expectedArgs.put("update",
      expectedUpdate.toBsonDocument(null, BsonUtils.DEFAULT_CODEC_REGISTRY));
  expectedArgs.put("upsert", false);
  assertEquals(expectedArgs, funcArgsArg.getValue().get(0));
  assertEquals(ResultDecoders.updateResultDecoder, resultClassArg.getValue());

  result = coll.updateMany(
      expectedFilter, expectedUpdate, new RemoteUpdateOptions().upsert(true));
  assertEquals(1, result.getMatchedCount());
  assertEquals(1, result.getModifiedCount());
  assertEquals(id, result.getUpsertedId());
  verify(service, times(2))
      .callFunction(
          funcNameArg.capture(),
          funcArgsArg.capture(),
          resultClassArg.capture());

  assertEquals("updateMany", funcNameArg.getValue());
  assertEquals(1, funcArgsArg.getValue().size());
  expectedArgs.put("upsert", true);
  assertEquals(expectedArgs, funcArgsArg.getValue().get(0));
  assertEquals(ResultDecoders.updateResultDecoder, resultClassArg.getValue());

  // Should pass along errors
  doThrow(new IllegalArgumentException("whoops"))
      .when(service).callFunction(any(), any(), any(Decoder.class));
  assertThrows(() -> coll.updateMany(new Document(), new Document()),
      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 testUpdateOne() {
  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 BsonObjectId id = new BsonObjectId();
  doReturn(new RemoteUpdateResult(1, 1, id))
      .when(service).callFunction(any(), any(), any(Decoder.class));

  final Document expectedFilter = new Document("one", 2);
  final Document expectedUpdate = new Document("three", 4);
  RemoteUpdateResult result = coll.updateOne(expectedFilter, expectedUpdate);
  assertEquals(1, result.getMatchedCount());
  assertEquals(1, result.getModifiedCount());
  assertEquals(id, result.getUpsertedId());

  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("updateOne", funcNameArg.getValue());
  assertEquals(1, funcArgsArg.getValue().size());
  final Document expectedArgs = new Document();
  expectedArgs.put("database", "dbName1");
  expectedArgs.put("collection", "collName1");
  expectedArgs.put("query",
      expectedFilter.toBsonDocument(null, BsonUtils.DEFAULT_CODEC_REGISTRY));
  expectedArgs.put("update",
      expectedUpdate.toBsonDocument(null, BsonUtils.DEFAULT_CODEC_REGISTRY));
  expectedArgs.put("upsert", false);
  assertEquals(expectedArgs, funcArgsArg.getValue().get(0));
  assertEquals(ResultDecoders.updateResultDecoder, resultClassArg.getValue());

  result = coll.updateOne(expectedFilter, expectedUpdate, new RemoteUpdateOptions().upsert(true));
  assertEquals(1, result.getMatchedCount());
  assertEquals(1, result.getModifiedCount());
  assertEquals(id, result.getUpsertedId());
  verify(service, times(2))
      .callFunction(
          funcNameArg.capture(),
          funcArgsArg.capture(),
          resultClassArg.capture());

  assertEquals("updateOne", funcNameArg.getValue());
  assertEquals(1, funcArgsArg.getValue().size());
  expectedArgs.put("upsert", true);
  assertEquals(expectedArgs, funcArgsArg.getValue().get(0));
  assertEquals(ResultDecoders.updateResultDecoder, resultClassArg.getValue());

  // Should pass along errors
  doThrow(new IllegalArgumentException("whoops"))
      .when(service).callFunction(any(), any(), any(Decoder.class));
  assertThrows(() -> coll.updateOne(new Document(), new Document()),
      IllegalArgumentException.class);
}
 
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 testInsertOne() {
  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);
  final Document doc2 = new Document("three", 4);
  final BsonObjectId id1 = new BsonObjectId();
  final BsonObjectId id2 = new BsonObjectId();

  final Map<Long, BsonValue> ids = new HashMap<>();
  ids.put(0L, id1);
  ids.put(1L, id2);
  doReturn(new RemoteInsertManyResult(ids))
      .when(service).callFunction(any(), any(), any(Decoder.class));

  final RemoteInsertManyResult result = coll.insertMany(Arrays.asList(doc1, doc2));
  assertEquals(ids, result.getInsertedIds());
  assertNotEquals(ids.get(0L).asObjectId().getValue(), doc1.getObjectId("_id"));
  assertNotEquals(ids.get(1L).asObjectId().getValue(), doc2.getObjectId("_id"));

  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("insertMany", funcNameArg.getValue());
  assertEquals(1, funcArgsArg.getValue().size());
  final Document expectedArgs = new Document();
  expectedArgs.put("database", "dbName1");
  expectedArgs.put("collection", "collName1");
  expectedArgs.put("documents",
      Arrays.asList(
          doc1.toBsonDocument(null, BsonUtils.DEFAULT_CODEC_REGISTRY),
          doc2.toBsonDocument(null, BsonUtils.DEFAULT_CODEC_REGISTRY)));
  assertEquals(expectedArgs, funcArgsArg.getValue().get(0));
  assertEquals(ResultDecoders.insertManyResultDecoder, resultClassArg.getValue());

  // Should pass along errors
  doThrow(new IllegalArgumentException("whoops"))
      .when(service).callFunction(any(), any(), any(Decoder.class));
  assertThrows(() -> coll.insertMany(Collections.singletonList(new Document())),
      IllegalArgumentException.class);
}
 
Example #26
Source File: BsonOidStrategy.java    From kafka-connect-mongodb with Apache License 2.0 4 votes vote down vote up
@Override
public BsonValue generateId(SinkDocument doc, SinkRecord orig) {
    return new BsonObjectId(ObjectId.get());
}
 
Example #27
Source File: BsonOidStrategy.java    From mongo-kafka with Apache License 2.0 4 votes vote down vote up
@Override
public BsonValue generateId(final SinkDocument doc, final SinkRecord orig) {
  return new BsonObjectId(ObjectId.get());
}
 
Example #28
Source File: CoreRemoteMongoCollectionImpl.java    From stitch-android-sdk with Apache License 2.0 3 votes vote down vote up
/**
 * Watches specified IDs in a collection. Requests a stream where the full document of update
 * events, and several other unnecessary fields are omitted from the change event objects
 * returned by the server. This can save on network usage when watching large documents
 *
 * This convenience overload supports the use case
 * of non-{@link BsonValue} instances of {@link ObjectId} by wrapping them in
 * {@link BsonObjectId} instances for the user.
 *
 * @param ids unique object identifiers of the IDs to watch.
 * @return the stream of change events.
 */
@Override
public Stream<CompactChangeEvent<DocumentT>> watchCompact(final ObjectId... ids)
    throws InterruptedException, IOException {
  final BsonValue[] transformedIds = new BsonValue[ids.length];

  for (int i = 0; i < ids.length; i++) {
    transformedIds[i] = new BsonObjectId(ids[i]);
  }

  return watchCompact(transformedIds);
}