org.bson.BsonInt32 Java Examples

The following examples show how to use org.bson.BsonInt32. 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: MongoAdapterTest.java    From calcite with Apache License 2.0 7 votes vote down vote up
@BeforeAll
public static void setUp() throws Exception {
  MongoDatabase database = POLICY.database();

  populate(database.getCollection("zips"), MongoAdapterTest.class.getResource("/zips-mini.json"));
  populate(database.getCollection("store"), FoodmartJson.class.getResource("/store.json"));
  populate(database.getCollection("warehouse"),
      FoodmartJson.class.getResource("/warehouse.json"));

  // Manually insert data for data-time test.
  MongoCollection<BsonDocument> datatypes =  database.getCollection("datatypes")
      .withDocumentClass(BsonDocument.class);
  if (datatypes.countDocuments() > 0) {
    datatypes.deleteMany(new BsonDocument());
  }

  BsonDocument doc = new BsonDocument();
  Instant instant = LocalDate.of(2012, 9, 5).atStartOfDay(ZoneOffset.UTC).toInstant();
  doc.put("date", new BsonDateTime(instant.toEpochMilli()));
  doc.put("value", new BsonInt32(1231));
  doc.put("ownerId", new BsonString("531e7789e4b0853ddb861313"));
  datatypes.insertOne(doc);

  schema = new MongoSchema(database);
}
 
Example #2
Source File: TriggerEngine.java    From epcis with Apache License 2.0 6 votes vote down vote up
private static BsonValue converseType(String value) {
	String[] valArr = value.split("\\^");
	if (valArr.length != 2) {
		return new BsonString(value);
	}
	try {
		String type = valArr[1];
		if (type.equals("int")) {
			return new BsonInt32(Integer.parseInt(valArr[0]));
		} else if (type.equals("long")) {
			return new BsonInt64(Long.parseLong(valArr[0]));
		} else if (type.equals("double")) {
			return new BsonDouble(Double.parseDouble(valArr[0]));
		} else if (type.equals("boolean")) {
			return new BsonBoolean(Boolean.parseBoolean(valArr[0]));
		} else {
			return new BsonString(value);
		}
	} catch (NumberFormatException e) {
		return new BsonString(value);
	}
}
 
Example #3
Source File: TriggerEngine.java    From epcis with Apache License 2.0 6 votes vote down vote up
private static BsonValue converseType(String value) {
	String[] valArr = value.split("\\^");
	if (valArr.length != 2) {
		return new BsonString(value);
	}
	try {
		String type = valArr[1];
		if (type.equals("int")) {
			return new BsonInt32(Integer.parseInt(valArr[0]));
		} else if (type.equals("long")) {
			return new BsonInt64(Long.parseLong(valArr[0]));
		} else if (type.equals("double")) {
			return new BsonDouble(Double.parseDouble(valArr[0]));
		} else if (type.equals("boolean")) {
			return new BsonBoolean(Boolean.parseBoolean(valArr[0]));
		} else {
			return new BsonString(value);
		}
	} catch (NumberFormatException e) {
		return new BsonString(value);
	}
}
 
Example #4
Source File: ChronoGraph.java    From epcis with Apache License 2.0 6 votes vote down vote up
/**
 * Add an edge to the graph. The added edges requires a recommended identifier,
 * a tail vertex, an head vertex, and a label. Like adding a vertex, the
 * provided object identifier may be ignored by the implementation.
 * 
 * @param outVertexID: the vertex on the tail of the edge
 * @param inVertexID: the vertex on the head of the edge
 * @param label: the label associated with the edge
 * @return the newly created edge
 */
public ChronoEdge addEdge(final String outVertexID, final String inVertexID, final String label) {
	if (label == null)
		throw ExceptionFactory.edgeLabelCanNotBeNull();
	String edgeID = Converter.getEdgeID(outVertexID, label, inVertexID);
	BsonDocument doc = edges.find(new BsonDocument(Tokens.OUT_VERTEX, new BsonString(outVertexID))
			.append(Tokens.LABEL, new BsonString(label)).append(Tokens.IN_VERTEX, new BsonString(inVertexID)))
			.projection(new BsonDocument(Tokens.ID, new BsonInt32(0))).first();
	if (doc == null) {
		BsonDocument e = new BsonDocument();
		e.put(Tokens.OUT_VERTEX, new BsonString(outVertexID));
		e.put(Tokens.IN_VERTEX, new BsonString(inVertexID));
		e.put(Tokens.LABEL, new BsonString(label));
		edges.insertOne(e);
	}
	return new ChronoEdge(edgeID, outVertexID, inVertexID, label, this);
}
 
Example #5
Source File: DataSynchronizer.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Given a local collection, a document fetched from that collection, and its _id, ensure that
 * the document does not contain forbidden fields (currently just the document version field),
 * and remove them from the document and the local collection. If no changes are made, the
 * original document reference is returned. If changes are made, a cloned copy of the document
 * with the changes will be returned.
 *
 * @param localCollection the local MongoCollection from which the document was fetched
 * @param document the document fetched from the local collection. this argument may be mutated
 * @param documentId the _id of the fetched document (taken as an arg so that if the caller
 *                   already knows the _id, the document need not be traversed to find it)
 * @return a BsonDocument without any forbidden fields.
 */
private static BsonDocument sanitizeCachedDocument(
        final MongoCollection<BsonDocument> localCollection,
        final BsonDocument document,
        final BsonValue documentId
) {
  if (document == null) {
    return null;
  }
  if (document.containsKey(DOCUMENT_VERSION_FIELD)) {
    final BsonDocument clonedDoc = sanitizeDocument(document);

    final BsonDocument removeVersionUpdate =
            new BsonDocument("$unset",
                    new BsonDocument(DOCUMENT_VERSION_FIELD, new BsonInt32(1))
            );

    localCollection.findOneAndUpdate(getDocumentIdFilter(documentId), removeVersionUpdate);
    return clonedDoc;
  }

  return document;
}
 
Example #6
Source File: MongoUtil.java    From game-server with MIT License 6 votes vote down vote up
public static BsonValue getBsonValue(Object obj) {
    if (obj instanceof Integer) {
        return new BsonInt32((Integer) obj);
    }

    if (obj instanceof String) {
        return new BsonString((String) obj);
    }

    if (obj instanceof Long) {
        return new BsonInt64((Long) obj);
    }

    if (obj instanceof Date) {
        return new BsonDateTime(((Date) obj).getTime());
    }
    if (obj instanceof Double || obj instanceof Float) {
        return new BsonDouble((Double) obj);
    }
    return new BsonNull();

}
 
Example #7
Source File: MongoUtil.java    From game-server with MIT License 6 votes vote down vote up
public static BsonValue getBsonValue(Object obj) {
    if (obj instanceof Integer) {
        return new BsonInt32((Integer) obj);
    }

    if (obj instanceof String) {
        return new BsonString((String) obj);
    }

    if (obj instanceof Long) {
        return new BsonInt64((Long) obj);
    }

    if (obj instanceof Date) {
        return new BsonDateTime(((Date) obj).getTime());
    }
    if (obj instanceof Double || obj instanceof Float) {
        return new BsonDouble((Double) obj);
    }
    return new BsonNull();

}
 
Example #8
Source File: MongoThingsSearchUpdaterPersistence.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Source<PolicyReferenceTag, NotUsed> getPolicyReferenceTags(final Map<PolicyId, Long> policyRevisions) {
    final Bson filter =
            in(PersistenceConstants.FIELD_POLICY_ID, policyRevisions.keySet()
                    .stream()
                    .map(String::valueOf)
                    .collect(Collectors.toSet()));
    final Publisher<Document> publisher =
            collection.find(filter).projection(new Document()
                    .append(PersistenceConstants.FIELD_ID, new BsonInt32(1))
                    .append(PersistenceConstants.FIELD_POLICY_ID, new BsonInt32(1)));
    return Source.fromPublisher(publisher)
            .mapConcat(doc -> {
                final ThingId thingId = ThingId.of(doc.getString(PersistenceConstants.FIELD_ID));
                final String policyIdString = doc.getString(PersistenceConstants.FIELD_POLICY_ID);
                final PolicyId policyId = PolicyId.of(policyIdString);
                final Long revision = policyRevisions.get(policyId);
                if (revision == null) {
                    return Collections.emptyList();
                } else {
                    final PolicyTag policyTag = PolicyTag.of(policyId, revision);
                    return Collections.singletonList(PolicyReferenceTag.of(thingId, policyTag));
                }
            });
}
 
Example #9
Source File: ChronoGraph.java    From epcis with Apache License 2.0 6 votes vote down vote up
/**
 * Add an edge to the graph. The added edges requires a recommended identifier,
 * a tail vertex, an head vertex, and a label. Like adding a vertex, the
 * provided object identifier may be ignored by the implementation.
 * 
 * @param id: outVertexID|label|inVertexID
 */
public ChronoEdge getEdge(String id) {
	if (id == null)
		throw ExceptionFactory.edgeIdCanNotBeNull();

	String[] idArr = id.split("\\|");
	if (idArr.length != 3)
		return null;
	BsonDocument edgeDoc = edges.find(new BsonDocument(Tokens.OUT_VERTEX, new BsonString(idArr[0]))
			.append(Tokens.LABEL, new BsonString(idArr[1])).append(Tokens.IN_VERTEX, new BsonString(idArr[2])))
			.projection(new BsonDocument(Tokens.ID, new BsonInt32(0))).first();
	if (edgeDoc == null)
		return null;
	else
		return new ChronoEdge(id, this);
}
 
Example #10
Source File: RdbmsDeleteTest.java    From kafka-connect-mongodb with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("when valid cdc event with single field PK then correct DeleteOneModel")
public void testValidSinkDocumentSingleFieldPK() {

    BsonDocument filterDoc =
            new BsonDocument(DBCollection.ID_FIELD_NAME,
                    new BsonDocument("id",new BsonInt32(1004)));

    BsonDocument keyDoc = new BsonDocument("id",new BsonInt32(1004));
    BsonDocument valueDoc = new BsonDocument("op",new BsonString("d"));

    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 #11
Source File: MongoDbIO.java    From beam with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static List<Document> buildAutoBuckets(MongoDatabase mongoDatabase, Read spec) {
  List<Document> splitKeys = new ArrayList<>();
  MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(spec.collection());
  BsonDocument bucketAutoConfig = new BsonDocument();
  bucketAutoConfig.put("groupBy", new BsonString("$_id"));
  // 10 is the default number of buckets
  bucketAutoConfig.put("buckets", new BsonInt32(spec.numSplits() > 0 ? spec.numSplits() : 10));
  BsonDocument bucketAuto = new BsonDocument("$bucketAuto", bucketAutoConfig);
  List<BsonDocument> aggregates = new ArrayList<>();
  aggregates.add(bucketAuto);
  AggregateIterable<Document> buckets = mongoCollection.aggregate(aggregates);

  for (Document bucket : buckets) {
    Document filter = new Document();
    filter.put("_id", ((Document) bucket.get("_id")).get("min"));
    splitKeys.add(filter);
  }

  return splitKeys;
}
 
Example #12
Source File: MongoDbIOTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadWithAggregateWithLimit() throws Exception {
  List<BsonDocument> aggregates = new ArrayList<BsonDocument>();
  aggregates.add(
      new BsonDocument(
          "$match",
          new BsonDocument("country", new BsonDocument("$eq", new BsonString("England")))));
  aggregates.add(new BsonDocument("$limit", new BsonInt32(10)));

  PCollection<Document> output =
      pipeline.apply(
          MongoDbIO.read()
              .withUri("mongodb://localhost:" + port)
              .withDatabase(DATABASE)
              .withCollection(COLLECTION)
              .withQueryFn(AggregationQuery.create().withMongoDbPipeline(aggregates)));

  PAssert.thatSingleton(output.apply("Count", Count.globally())).isEqualTo(10L);

  pipeline.run();
}
 
Example #13
Source File: MongoMetadataDaoImpl.java    From eagle with Apache License 2.0 6 votes vote down vote up
/**
 * get the basic ScheduleState, and then based on the version to get all sub-part(spoutSpecs/alertSpecs/etc)
 * to form a completed ScheduleState.
 * @return the latest ScheduleState
 */
@Override
public ScheduleState getScheduleState() {
    BsonDocument sort = new BsonDocument();
    sort.append("generateTime", new BsonInt32(-1));
    ScheduleState state = scheduleStates.find().sort(sort).map(new Function<Document, ScheduleState>() {
        @Override
        public ScheduleState apply(Document t) {
            String json = t.toJson();
            try {
                return mapper.readValue(json, ScheduleState.class);
            } catch (IOException e) {
                LOG.error("deserialize config item failed!", e);
            }
            return null;
        }
    }).first();

    if (state != null) {
        String version = state.getVersion();
        // based on version, to add content from collections of spoutSpecs/alertSpecs/etc..
        state = addDetailForScheduleState(state, version);
    }

    return state;
}
 
Example #14
Source File: DocumentVersionInfo.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a BSON version document representing a new version with a new instance ID, and
 * version counter of zero.
 * @return a BsonDocument representing a synchronization version
 */
static BsonDocument getFreshVersionDocument() {
  final BsonDocument versionDoc = new BsonDocument();

  versionDoc.append(Fields.SYNC_PROTOCOL_VERSION_FIELD, new BsonInt32(1));
  versionDoc.append(Fields.INSTANCE_ID_FIELD, new BsonString(UUID.randomUUID().toString()));
  versionDoc.append(Fields.VERSION_COUNTER_FIELD, new BsonInt64(0L));

  return versionDoc;
}
 
Example #15
Source File: DocumentVersionInfo.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
public BsonDocument toBsonDocument() {
  final BsonDocument asDoc = new BsonDocument();

  asDoc.put(Fields.SYNC_PROTOCOL_VERSION_FIELD, new BsonInt32(syncProtocolVersion));
  asDoc.put(Fields.INSTANCE_ID_FIELD, new BsonString(instanceId));
  asDoc.put(Fields.VERSION_COUNTER_FIELD, new BsonInt64(versionCounter));

  return asDoc;
}
 
Example #16
Source File: ChronoGraph.java    From epcis with Apache License 2.0 5 votes vote down vote up
private void createBasicIndex() {
	// outE, out

	Document isNull = edges.listIndexes().first();
	if (isNull == null) {
		edges.createIndex(new BsonDocument(Tokens.OUT_VERTEX, new BsonInt32(1))
				.append(Tokens.LABEL, new BsonInt32(1)).append(Tokens.IN_VERTEX, new BsonInt32(1)));
		edges.createIndex(new BsonDocument(Tokens.IN_VERTEX, new BsonInt32(1))
				.append(Tokens.LABEL, new BsonInt32(1)).append(Tokens.OUT_VERTEX, new BsonInt32(1)));
	}

	isNull = edgeEvents.listIndexes().first();
	if (isNull == null) {
		edgeEvents.createIndex(
				new BsonDocument(Tokens.OUT_VERTEX, new BsonInt32(1)).append(Tokens.LABEL, new BsonInt32(1))
						.append(Tokens.TIMESTAMP, new BsonInt32(1)).append(Tokens.IN_VERTEX, new BsonInt32(1)));
		edgeEvents.createIndex(
				new BsonDocument(Tokens.IN_VERTEX, new BsonInt32(1)).append(Tokens.LABEL, new BsonInt32(1))
						.append(Tokens.TIMESTAMP, new BsonInt32(1)).append(Tokens.OUT_VERTEX, new BsonInt32(1)));
	}

	isNull = vertexEvents.listIndexes().first();
	if (isNull == null) {
		vertexEvents.createIndex(
				new BsonDocument(Tokens.VERTEX, new BsonInt32(1)).append(Tokens.TIMESTAMP, new BsonInt32(1)));
	}
}
 
Example #17
Source File: MongoQueryUtil.java    From epcis with Apache License 2.0 5 votes vote down vote up
static BsonDocument getNearQueryObject(String key, String paramValues) {

		try {
			// Prepare Query Values
			String[] paramValueArr = paramValues.split(",");
			if (paramValueArr.length < 2)
				return null;

			Double lon = Double.parseDouble(paramValueArr[0]);
			Double lat = Double.parseDouble(paramValueArr[1]);
			Integer min = null;
			if (paramValueArr.length > 2)
				min = Integer.parseInt(paramValueArr[2]);
			Integer max = null;
			if (paramValueArr.length > 3)
				max = Integer.parseInt(paramValueArr[3]);

			BsonDocument near = new BsonDocument();
			BsonDocument geometry = new BsonDocument("type", new BsonString("Point"));
			BsonArray coordinates = new BsonArray();
			coordinates.add(new BsonDouble(lon));
			coordinates.add(new BsonDouble(lat));
			geometry.put("coordinates", coordinates);
			near.put("$geometry", geometry);
			if (min != null)
				near.put("$minDistance", new BsonInt32(min));
			if (max != null)
				near.put("$maxDistance", new BsonInt32(max));

			return new BsonDocument("any." + key, new BsonDocument("$near", near));
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return null;
		}
	}
 
Example #18
Source File: JsonToBson.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public BsonValue number(final JsonNumber value) {
    return value.isInt()
            ? new BsonInt32(value.asInt())
            : value.isLong()
            ? new BsonInt64(value.asLong())
            : new BsonDouble(value.asDouble());
}
 
Example #19
Source File: GenericRecordConverterTest.java    From MongoDb-Sink-Connector with Apache License 2.0 5 votes vote down vote up
@Test
public void convertIntString() {
    expected.put("_id", "10");
    expected.put("key", new BsonInt32(10));
    expected.put("value", new BsonString("mystring"));

    SinkRecord record = new SinkRecord(null, 0, SchemaBuilder.int32().build(), 10,
            SchemaBuilder.string().build(), "mystring", 0L);
    assertEquals(expected, converter.convert(record));
}
 
Example #20
Source File: GenericRecordConverterTest.java    From MongoDb-Sink-Connector with Apache License 2.0 5 votes vote down vote up
@Test
public void convertIntBoolStringInt() {
    Schema keySchema = SchemaBuilder.struct()
            .field("a", SchemaBuilder.int32().build())
            .field("b", SchemaBuilder.bool().build())
            .build();
    Struct key = new Struct(keySchema);
    key.put("a", 10);
    key.put("b", true);

    Schema valueSchema = SchemaBuilder.struct()
            .field("c", SchemaBuilder.string().build())
            .field("d", SchemaBuilder.int32().build())
            .build();
    Struct value = new Struct(valueSchema);
    value.put("c", "mystring");
    value.put("d", 30);

    expected.put("_id", "{10-true}");
    expected.put("key", new BsonDocument()
            .append("a", new BsonInt32(10))
            .append("b", new BsonBoolean(true)));
    expected.put("value", new BsonDocument()
            .append("c", new BsonString("mystring"))
            .append("d", new BsonInt32(30)));

    SinkRecord record = new SinkRecord(null, 0, keySchema, key, valueSchema, value, 0L);
    assertEquals(expected, converter.convert(record));
}
 
Example #21
Source File: MongoWriterUtil.java    From epcis with Apache License 2.0 5 votes vote down vote up
public static BsonValue converseType(String value) {
	String[] valArr = value.split("\\^");
	if (valArr.length != 2) {
		return new BsonString(value);
	}
	try {
		String type = valArr[1];
		if (type.equals("int")) {
			return new BsonInt32(Integer.parseInt(valArr[0]));
		} else if (type.equals("long")) {
			return new BsonInt64(Long.parseLong(valArr[0]));
		} else if (type.equals("double")) {
			return new BsonDouble(Double.parseDouble(valArr[0]));
		} else if (type.equals("boolean")) {
			return new BsonBoolean(Boolean.parseBoolean(valArr[0]));
		} else if (type.equals("float")) {
			return new BsonDouble(Double.parseDouble(valArr[0]));
		} else if (type.equals("dateTime")) {
			BsonDateTime time = getBsonDateTime(valArr[0]);
			if (time != null)
				return time;
			return new BsonString(value);
		} else if (type.equals("geoPoint")) {
			BsonDocument point = getBsonGeoPoint(valArr[0]);
			if (point == null)
				return new BsonString(value);
			return point;
		} else if (type.equals("geoArea")) {
			BsonDocument area = getBsonGeoArea(valArr[0]);
			if (area == null)
				return new BsonString(value);
			return area;
		} else {
			return new BsonString(value);
		}
	} catch (NumberFormatException e) {
		return new BsonString(value);
	}
}
 
Example #22
Source File: MongoQueryUtil.java    From epcis with Apache License 2.0 5 votes vote down vote up
static BsonValue converseType(String value) {
	String[] valArr = value.split("\\^");
	if (valArr.length != 2) {
		return new BsonString(value);
	}
	try {
		String type = valArr[1].trim();
		if (type.equals("int")) {
			return new BsonInt32(Integer.parseInt(valArr[0]));
		} else if (type.equals("long")) {
			return new BsonInt64(Long.parseLong(valArr[0]));
		} else if (type.equals("double")) {
			return new BsonDouble(Double.parseDouble(valArr[0]));
		} else if (type.equals("boolean")) {
			return new BsonBoolean(Boolean.parseBoolean(valArr[0]));
		} else if (type.equals("regex")) {
			return new BsonRegularExpression("^" + valArr[0] + "$");
		} else if (type.equals("float")) {
			return new BsonDouble(Double.parseDouble(valArr[0]));
		} else if (type.equals("dateTime")) {
			BsonDateTime time = MongoQueryService.getTimeMillis(valArr[0]);
			if (time != null)
				return time;
			return new BsonString(value);
		} else {
			return new BsonString(value);
		}
	} catch (NumberFormatException e) {
		return new BsonString(value);
	}
}
 
Example #23
Source File: MongoDbHandlerTest.java    From kafka-connect-mongodb with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("when key doc contains 'id' field but value is empty then null due to tombstone")
public void testTombstoneEvent() {
    assertEquals(Optional.empty(),
            MONGODB_HANDLER_DEFAULT_MAPPING.handle(new SinkDocument(
                    new BsonDocument("id",new BsonInt32(1234)),
                        new BsonDocument())
            ),
            "tombstone event must result in Optional.empty()"
    );
}
 
Example #24
Source File: CoreDocumentSynchronizationConfig.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
BsonDocument toBsonDocument() {
  docLock.readLock().lock();
  try {
    final BsonDocument asDoc = new BsonDocument();
    asDoc.put(ConfigCodec.Fields.DOCUMENT_ID_FIELD, getDocumentId());
    asDoc.put(ConfigCodec.Fields.SCHEMA_VERSION_FIELD, new BsonInt32(1));
    asDoc.put(ConfigCodec.Fields.NAMESPACE_FIELD, new BsonString(getNamespace().toString()));
    asDoc.put(ConfigCodec.Fields.LAST_RESOLUTION_FIELD, new BsonInt64(getLastResolution()));
    if (getLastKnownRemoteVersion() != null) {
      asDoc.put(ConfigCodec.Fields.LAST_KNOWN_REMOTE_VERSION_FIELD, getLastKnownRemoteVersion());
    }
    asDoc.put(ConfigCodec.Fields.LAST_KNOWN_HASH_FIELD, new BsonInt64(lastKnownHash));

    if (lastUncommittedChangeEvent != null) {
      final BsonDocument ceDoc = lastUncommittedChangeEvent.toBsonDocument();
      final OutputBuffer outputBuffer = new BasicOutputBuffer();
      final BsonWriter innerWriter = new BsonBinaryWriter(outputBuffer);
      bsonDocumentCodec.encode(innerWriter, ceDoc, EncoderContext.builder().build());
      final BsonBinary encoded = new BsonBinary(outputBuffer.toByteArray());
      // TODO: This may put the doc above the 16MiB but ignore for now.
      asDoc.put(ConfigCodec.Fields.LAST_UNCOMMITTED_CHANGE_EVENT, encoded);
    }
    asDoc.put(ConfigCodec.Fields.IS_STALE, new BsonBoolean(isStale));
    asDoc.put(ConfigCodec.Fields.IS_PAUSED, new BsonBoolean(isPaused));
    return asDoc;
  } finally {
    docLock.readLock().unlock();
  }
}
 
Example #25
Source File: NamespaceSynchronizationConfig.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
BsonDocument toBsonDocument() {
  nsLock.readLock().lock();
  try {
    final BsonDocument asDoc = new BsonDocument();
    asDoc.put(ConfigCodec.Fields.NAMESPACE_FIELD, new BsonString(getNamespace().toString()));
    asDoc.put(ConfigCodec.Fields.SCHEMA_VERSION_FIELD, new BsonInt32(1));
    return asDoc;
  } finally {
    nsLock.readLock().unlock();
  }
}
 
Example #26
Source File: RdbmsDeleteTest.java    From kafka-connect-mongodb with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("when valid cdc event with compound PK then correct DeleteOneModel")
public void testValidSinkDocumentCompoundPK() {

    BsonDocument filterDoc =
            new BsonDocument(DBCollection.ID_FIELD_NAME,
                    new BsonDocument("idA",new BsonInt32(123))
                            .append("idB",new BsonString("ABC")));

    BsonDocument keyDoc = new BsonDocument("idA",new BsonInt32(123))
                                .append("idB",new BsonString("ABC"));
    BsonDocument valueDoc = new BsonDocument("op",new BsonString("d"));

    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 #27
Source File: MongoDbDeleteTest.java    From kafka-connect-mongodb with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("when key doc 'id' field not of type String then DataException")
public void testInvalidTypeIdFieldInKeyDocument() {
    BsonDocument keyDoc = new BsonDocument("id",new BsonInt32(1004));
    assertThrows(DataException.class,() ->
            MONGODB_DELETE.perform(new SinkDocument(keyDoc,new BsonDocument()))
    );
}
 
Example #28
Source File: MongoDbHandlerTest.java    From kafka-connect-mongodb with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("when value doc is missing operation type then DataException")
public void testMissingCdcOperationType() {
    SinkDocument cdcEvent = new SinkDocument(
            new BsonDocument("id",new BsonInt32(1234)),
            new BsonDocument("po", BsonNull.VALUE)
    );
    assertThrows(DataException.class, () ->
            MONGODB_HANDLER_DEFAULT_MAPPING.handle(cdcEvent)
    );
}
 
Example #29
Source File: MongoDbHandlerTest.java    From kafka-connect-mongodb with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("when value doc contains operation type other than string then DataException")
public void testInvalidCdcOperationType() {
    SinkDocument cdcEvent = new SinkDocument(
            new BsonDocument("id",new BsonInt32(1234)),
            new BsonDocument("op",new BsonInt32('c'))
    );
    assertThrows(DataException.class, () ->
            MONGODB_HANDLER_DEFAULT_MAPPING.handle(cdcEvent)
    );
}
 
Example #30
Source File: MongoDbHandlerTest.java    From kafka-connect-mongodb with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("when value doc contains unmapped operation type then DataException")
public void testUnmappedCdcOperationType() {
    SinkDocument cdcEvent = new SinkDocument(
            new BsonDocument("_id",new BsonInt32(1234)),
            new BsonDocument("op",new BsonString("c"))
                    .append("after",new BsonString("{_id:1234,foo:\"blah\"}"))
    );
    assertThrows(DataException.class, () ->
            MONGODB_HANDLER_EMPTY_MAPPING.handle(cdcEvent)
    );
}