Java Code Examples for org.bson.BsonDocument#parse()

The following examples show how to use org.bson.BsonDocument#parse() . 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: RdbmsDeleteTest.java    From mongo-kafka with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("when valid cdc event without PK then correct DeleteOneModel")
void testValidSinkDocumentNoPK() {
  BsonDocument filterDoc = BsonDocument.parse("{text: 'misc', number: 9876, active: true}");
  BsonDocument keyDoc = new BsonDocument();
  BsonDocument valueDoc =
      BsonDocument.parse("{op: 'c', before: {text: 'misc', number: 9876, active: true}}");

  WriteModel<BsonDocument> result = RDBMS_DELETE.perform(new SinkDocument(keyDoc, valueDoc));
  assertTrue(result instanceof DeleteOneModel, "result expected to be of type DeleteOneModel");

  DeleteOneModel<BsonDocument> writeModel = (DeleteOneModel<BsonDocument>) result;
  assertTrue(
      writeModel.getFilter() instanceof BsonDocument,
      "filter expected to be of type BsonDocument");
  assertEquals(filterDoc, writeModel.getFilter());
}
 
Example 2
Source File: BsonParserTest.java    From immutables with Apache License 2.0 6 votes vote down vote up
/**
 * write with BSON read with jackson.
 * inverse of {@link #jacksonThenBson(String)}
 */
private void bsonThenJackson(String json) throws IOException {
  ObjectNode toWrite = maybeWrap(mapper.readTree(json));

  BasicOutputBuffer buffer = new BasicOutputBuffer();
  BsonWriter writer = new BsonBinaryWriter(buffer);

  // write with BSON
  BsonDocument expected = BsonDocument.parse(toWrite.toString());
  MongoClientSettings.getDefaultCodecRegistry().get(BsonDocument.class)
          .encode(writer, expected, EncoderContext.builder().build());

  BsonBinaryReader reader = new BsonBinaryReader(ByteBuffer.wrap(buffer.toByteArray()));
  IOContext ioContext = new IOContext(new BufferRecycler(), null, false);
  BsonParser parser = new BsonParser(ioContext, 0, reader);

  // read with jackson
  BsonDocument actual = BsonDocument.parse(mapper.readValue(parser, JsonNode.class).toString());

  if (!actual.equals(expected)) {
     check(maybeUnwrap(actual)).is(maybeUnwrap(expected));
     Assertions.fail("Should have failed before");
  }
}
 
Example 3
Source File: MongoDbDelete.java    From kafka-connect-mongodb with Apache License 2.0 6 votes vote down vote up
@Override
public WriteModel<BsonDocument> perform(SinkDocument doc) {

    BsonDocument keyDoc = doc.getKeyDoc().orElseThrow(
            () -> new DataException("error: key doc must not be missing for delete operation")
    );

    try {
        BsonDocument filterDoc = BsonDocument.parse(
                "{"+DBCollection.ID_FIELD_NAME+
                    ":"+keyDoc.getString(MongoDbHandler.JSON_ID_FIELD_PATH)
                            .getValue()+"}"
        );
        return new DeleteOneModel<>(filterDoc);
    } catch(Exception exc) {
        throw new DataException(exc);
    }

}
 
Example 4
Source File: IdStrategyTest.java    From mongo-kafka with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("test PartialValueStrategy with Allow List")
void testPartialValueStrategyAllowList() {
  BsonDocument valueDoc =
      BsonDocument.parse("{valuePart1: 123, valuePart2: 'ABC', valuePart3: true}");
  BsonDocument expected = BsonDocument.parse("{valuePart1: 123}");

  MongoSinkTopicConfig cfg =
      createTopicConfig(
          format(
              "{'%s': '%s', '%s': 'valuePart1'}",
              DOCUMENT_ID_STRATEGY_PARTIAL_VALUE_PROJECTION_TYPE_CONFIG,
              ALLOWLIST,
              DOCUMENT_ID_STRATEGY_PARTIAL_VALUE_PROJECTION_LIST_CONFIG));

  IdStrategy ids = new PartialValueStrategy();
  ids.configure(cfg);
  SinkDocument sd = new SinkDocument(null, valueDoc);
  BsonValue id = ids.generateId(sd, null);

  assertAll(
      "id checks",
      () -> assertTrue(id instanceof BsonDocument),
      () -> assertEquals(expected, id.asDocument()));
  assertEquals(new BsonDocument(), ids.generateId(new SinkDocument(null, null), null));
}
 
Example 5
Source File: IdStrategyTest.java    From mongo-kafka with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("test PartialValueStrategy with Block List")
void testPartialValueStrategyBlockList() {
  BsonDocument valueDoc =
      BsonDocument.parse("{valuePart1: 123, valuePart2: 'ABC', valuePart3: true}");
  BsonDocument expected = BsonDocument.parse("{valuePart2: 'ABC', valuePart3: true}");

  MongoSinkTopicConfig cfg =
      createTopicConfig(
          format(
              "{'%s': '%s', '%s': 'valuePart1'}",
              DOCUMENT_ID_STRATEGY_PARTIAL_VALUE_PROJECTION_TYPE_CONFIG,
              BLOCKLIST,
              DOCUMENT_ID_STRATEGY_PARTIAL_VALUE_PROJECTION_LIST_CONFIG));

  IdStrategy ids = new PartialValueStrategy();
  ids.configure(cfg);
  SinkDocument sd = new SinkDocument(null, valueDoc);
  BsonValue id = ids.generateId(sd, null);

  assertAll(
      "id checks",
      () -> assertTrue(id instanceof BsonDocument),
      () -> assertEquals(expected, id.asDocument()));
  assertEquals(new BsonDocument(), ids.generateId(new SinkDocument(null, null), null));
}
 
Example 6
Source File: DittoBsonJsonTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void serializeJsonWithDollarsInKeys() throws JSONException {
    final BsonDocument parse = BsonDocument.parse(JSON_WITH_DOLLAR_INKEYS);
    final JsonValue serialized = underTest.serialize(parse);

    JSONAssert.assertEquals(JSON_WITH_DOLLAR_INKEYS, serialized.toString(), true);
}
 
Example 7
Source File: MongoUserProvider.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public Maybe<User> findByUsername(String username) {
    // lowercase username since case-sensitivity feature
    final String encodedUsername = username.toLowerCase();

    String rawQuery = this.configuration.getFindUserByUsernameQuery().replaceAll("\\?", encodedUsername);
    String jsonQuery = convertToJsonString(rawQuery);
    BsonDocument query = BsonDocument.parse(jsonQuery);
    return Observable.fromPublisher(usersCollection.find(query).first()).firstElement().map(this::convert);
}
 
Example 8
Source File: MongoAuthenticationProvider.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private Maybe<Document> findUserByUsername(String username) {
    MongoCollection<Document> usersCol = this.mongoClient.getDatabase(this.configuration.getDatabase()).getCollection(this.configuration.getUsersCollection());
    String rawQuery = this.configuration.getFindUserByUsernameQuery().replaceAll("\\?", username);
    String jsonQuery = convertToJsonString(rawQuery);
    BsonDocument query = BsonDocument.parse(jsonQuery);
    return Observable.fromPublisher(usersCol.find(query).first()).firstElement();
}
 
Example 9
Source File: DittoBsonJsonTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void parseJsonWithDotsInKeys() throws JSONException {
    final BsonDocument expected = BsonDocument.parse(JSON_WITH_UNICODE_DOTS_INKEYS);
    final Object parsed = underTest.parse(JsonFactory.newObject(JSON_WITH_DOTS_INKEYS));

    assertThat(parsed).isEqualTo(expected);
}
 
Example 10
Source File: FieldProjectorTest.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
private static SinkDocument buildSinkDocumentNestedStruct() {
  BsonDocument nestedKey =
      BsonDocument.parse(
          "{ _id: 'ABC-123', myInt: 42, "
              + "subDoc1: { myString: 'BSON1', myBoolean: false }, subDoc2: { myString: 'BSON2', myBoolean: true } }");
  BsonDocument nestedValue =
      BsonDocument.parse(
          "{ _id: 'XYZ-789', myBoolean: true, "
              + "subDoc1: { myFieldA: 'some text', myFieldB: 12.34, subSubDoc: { myString: 'some text', myInt: 0, myBoolean: false } }, "
              + "subDoc2: { myFieldA: 'some text', myFieldB: 12.34, "
              + "           subSubDoc: { myBytes: { $binary: 'eHl6', $type: '00' }, "
              + "                        myArray: [{ key: 'abc', value: 123 }, { key: 'xyz', value: 987 }] } } }");
  return new SinkDocument(nestedKey, nestedValue);
}
 
Example 11
Source File: RdbmsHandlerTest.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("when value doc is null operation type then DataException")
void testNullCdcOperationType() {
  SinkDocument cdcEvent =
      new SinkDocument(BsonDocument.parse("{id: 1234}"), BsonDocument.parse("{op: null}"));
  assertThrows(DataException.class, () -> RDBMS_HANDLER_DEFAULT_MAPPING.handle(cdcEvent));
}
 
Example 12
Source File: DittoBsonJsonTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void parseJsonWithNestedUnicodeDotsInKeys() throws JSONException {
    final BsonDocument expected = BsonDocument.parse(JSON_NESTED_WITH_UNICODE_DOTS_INKEYS);
    final Object parsed = underTest.parse(JsonFactory.newObject(JSON_NESTED_WITH_DOTS_INKEYS));

    assertThat(parsed).isEqualTo(expected);
}
 
Example 13
Source File: MongoTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Executes a "find" operation on the underlying collection.
 *
 * <p>For example,
 * <code>zipsTable.find("{state: 'OR'}", "{city: 1, zipcode: 1}")</code></p>
 *
 * @param mongoDb MongoDB connection
 * @param filterJson Filter JSON string, or null
 * @param projectJson Project JSON string, or null
 * @param fields List of fields to project; or null to return map
 * @return Enumerator of results
 */
private Enumerable<Object> find(MongoDatabase mongoDb, String filterJson,
    String projectJson, List<Map.Entry<String, Class>> fields) {
  final MongoCollection collection =
      mongoDb.getCollection(collectionName);
  final Bson filter =
      filterJson == null ? null : BsonDocument.parse(filterJson);
  final Bson project =
      projectJson == null ? null : BsonDocument.parse(projectJson);
  final Function1<Document, Object> getter = MongoEnumerator.getter(fields);
  return new AbstractEnumerable<Object>() {
    public Enumerator<Object> enumerator() {
      @SuppressWarnings("unchecked") final FindIterable<Document> cursor =
          collection.find(filter).projection(project);
      return new MongoEnumerator(cursor.iterator(), getter);
    }
  };
}
 
Example 14
Source File: WriteModelStrategyTest.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName(
    "when sink document is valid for UpdateOneBusinessKeyTimestampStrategy then correct UpdateOneModel")
void testUpdateOneBusinessKeyTimestampsStrategyWithValidSinkDocument() {
  BsonDocument valueDoc =
      BsonDocument.parse("{_id: 1234, first_name: 'Grace', last_name: 'Hopper', active: false}");

  WriteModel<BsonDocument> result =
      UPDATE_ONE_TIMESTAMPS_STRATEGY.createWriteModel(new SinkDocument(null, valueDoc));
  assertTrue(result instanceof UpdateOneModel, "result expected to be of type UpdateOneModel");

  UpdateOneModel<BsonDocument> writeModel = (UpdateOneModel<BsonDocument>) result;

  // NOTE: This test case can only check:
  // i) for both fields to be available
  // ii) having the correct BSON type (BsonDateTime)
  // iii) and be initially equal
  // The exact dateTime value is not directly testable here.
  BsonDocument updateDoc = (BsonDocument) writeModel.getUpdate();

  BsonDateTime modifiedTS =
      updateDoc
          .getDocument("$set")
          .getDateTime(UpdateOneBusinessKeyTimestampStrategy.FIELD_NAME_MODIFIED_TS);
  BsonDateTime insertedTS =
      updateDoc
          .getDocument("$setOnInsert")
          .getDateTime(UpdateOneBusinessKeyTimestampStrategy.FIELD_NAME_INSERTED_TS);

  assertEquals(
      insertedTS, modifiedTS, "modified and inserted timestamps must initially be equal");
  assertTrue(
      writeModel.getFilter() instanceof BsonDocument,
      "filter expected to be of type BsonDocument");
  assertEquals(FILTER_DOC_UPDATE_TIMESTAMPS, writeModel.getFilter());
  assertTrue(writeModel.getOptions().isUpsert(), "update expected to be done in upsert mode");
}
 
Example 15
Source File: MongoOperations.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public static long count(Class<?> entityClass, String query, Object... params) {
    String bindQuery = bindFilter(entityClass, query, params);
    BsonDocument docQuery = BsonDocument.parse(bindQuery);
    MongoCollection collection = mongoCollection(entityClass);
    return collection.countDocuments(docQuery);
}
 
Example 16
Source File: ReactiveMongoOperations.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public static Uni<Long> count(Class<?> entityClass, String query, Object... params) {
    String bindQuery = bindFilter(entityClass, query, params);
    BsonDocument docQuery = BsonDocument.parse(bindQuery);
    ReactiveMongoCollection collection = mongoCollection(entityClass);
    return collection.countDocuments(docQuery);
}
 
Example 17
Source File: PanacheUpdateImpl.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
public long where(String query, Object... params) {
    String bindQuery = MongoOperations.bindFilter(entityClass, query, params);
    BsonDocument docQuery = BsonDocument.parse(bindQuery);
    return collection.updateMany(docQuery, update).getModifiedCount();
}
 
Example 18
Source File: MongoOperations.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private static PanacheUpdate executeUpdate(Class<?> entityClass, String update, Object... params) {
    String bindUpdate = bindUpdate(entityClass, update, params);
    BsonDocument docUpdate = BsonDocument.parse(bindUpdate);
    MongoCollection collection = mongoCollection(entityClass);
    return new PanacheUpdateImpl(entityClass, docUpdate, collection);
}
 
Example 19
Source File: PanacheUpdateImpl.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
public long where(String query, Map<String, Object> params) {
    String bindQuery = MongoOperations.bindFilter(entityClass, query, params);
    BsonDocument docQuery = BsonDocument.parse(bindQuery);
    return collection.updateMany(docQuery, update).getModifiedCount();
}
 
Example 20
Source File: ReactiveMongoOperations.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public static Uni<Long> delete(Class<?> entityClass, String query, Map<String, Object> params) {
    String bindQuery = bindFilter(entityClass, query, params);
    BsonDocument docQuery = BsonDocument.parse(bindQuery);
    ReactiveMongoCollection<?> collection = mongoCollection(entityClass);
    return collection.deleteMany(docQuery).map(deleteResult -> deleteResult.getDeletedCount());
}