org.bson.BsonInt64 Java Examples

The following examples show how to use org.bson.BsonInt64. 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: 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 #2
Source File: GridFSTest.java    From mongo-java-driver-rx with Apache License 2.0 6 votes vote down vote up
private List<BsonDocument> processFiles(final BsonArray bsonArray, final List<BsonDocument> documents) {
    for (BsonValue rawDocument : bsonArray.getValues()) {
        if (rawDocument.isDocument()) {
            BsonDocument document = rawDocument.asDocument();
            if (document.get("length").isInt32()) {
                document.put("length", new BsonInt64(document.getInt32("length").getValue()));
            }
            if (document.containsKey("metadata") && document.getDocument("metadata").isEmpty()) {
                document.remove("metadata");
            }
            if (document.containsKey("aliases") && document.getArray("aliases").getValues().size() == 0) {
                document.remove("aliases");
            }
            if (document.containsKey("contentType") && document.getString("contentType").getValue().length() == 0) {
                document.remove("contentType");
            }
            documents.add(document);
        }
    }
    return documents;
}
 
Example #3
Source File: GridFSTest.java    From mongo-java-driver-reactivestreams with Apache License 2.0 6 votes vote down vote up
private List<BsonDocument> processFiles(final BsonArray bsonArray, final List<BsonDocument> documents) {
    for (BsonValue rawDocument : bsonArray.getValues()) {
        if (rawDocument.isDocument()) {
            BsonDocument document = rawDocument.asDocument();
            if (document.get("length").isInt32()) {
                document.put("length", new BsonInt64(document.getInt32("length").getValue()));
            }
            if (document.containsKey("metadata") && document.getDocument("metadata").isEmpty()) {
                document.remove("metadata");
            }
            if (document.containsKey("aliases") && document.getArray("aliases").getValues().size() == 0) {
                document.remove("aliases");
            }
            if (document.containsKey("contentType") && document.getString("contentType").getValue().length() == 0) {
                document.remove("contentType");
            }
            documents.add(document);
        }
    }
    return documents;
}
 
Example #4
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 #5
Source File: CompactChangeEvent.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Serializes this change event into a {@link BsonDocument}.
 * @return the serialized document.
 */
public BsonDocument toBsonDocument() {
  final BsonDocument asDoc = new BsonDocument();
  asDoc.put(Fields.OPERATION_TYPE_FIELD, new BsonString(getOperationType().toRemote()));
  asDoc.put(Fields.DOCUMENT_KEY_FIELD, getDocumentKey());

  if (getFullDocument() != null && (getFullDocument() instanceof BsonValue)
      && ((BsonValue) getFullDocument()).isDocument()) {
    asDoc.put(Fields.FULL_DOCUMENT_FIELD, (BsonValue) getFullDocument());
  }

  if (getUpdateDescription() != null) {
    asDoc.put(Fields.UPDATE_DESCRIPTION_FIELD, getUpdateDescription().toBsonDocument());
  }

  if (stitchDocumentVersion != null) {
    asDoc.put(Fields.STITCH_DOCUMENT_VERSION_FIELD, stitchDocumentVersion.toBsonDocument());
  }

  if (stitchDocumentHash != null) {
    asDoc.put(Fields.STITCH_DOCUMENT_HASH_FIELD, new BsonInt64(stitchDocumentHash));
  }

  asDoc.put(Fields.WRITE_PENDING_FIELD, new BsonBoolean(hasUncommittedWrites()));
  return asDoc;
}
 
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: ECReportCapture.java    From epcis with Apache License 2.0 5 votes vote down vote up
private Map<String, BsonValue> getExtensionMap(List<ECReportMemberField> fields) {
	Map<String, BsonValue> extMap = new HashMap<String, BsonValue>();
	for (int l = 0; l < fields.size(); l++) {
		ECReportMemberField field = fields.get(l);
		String key = field.getName();
		String value = field.getValue();
		String[] valArr = value.split("\\^");
		if (valArr.length != 2) {
			extMap.put(key, new BsonString(value));
			continue;
		}
		try {
			String type = valArr[1];
			if (type.equals("int")) {
				extMap.put(key, new BsonInt32(Integer.parseInt(valArr[0])));
			} else if (type.equals("long")) {
				extMap.put(key, new BsonInt64(Long.parseLong(valArr[0])));
			} else if (type.equals("double")) {
				extMap.put(key, new BsonDouble(Double.parseDouble(valArr[0])));
			} else if (type.equals("boolean")) {
				extMap.put(key, new BsonBoolean(Boolean.parseBoolean(valArr[0])));
			} else if (type.equals("dateTime")) {
				extMap.put(key, new BsonDateTime(Long.parseLong(valArr[0])));
			} else {
				extMap.put(key, new BsonString(valArr[0]));
			}
		} catch (NumberFormatException e) {
			extMap.put(key, new BsonString(valArr[0]));
		}
	}
	return extMap;
}
 
Example #9
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 #10
Source File: TypeConversionTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Test
void int64() throws IOException {
  final BsonInt32 value = new BsonInt32(42);
  check(Parsers.parserAt(value).currentToken()).is(JsonToken.VALUE_NUMBER_INT);
  check(Parsers.parserAt(new BsonInt64(64)).getNumberType()).is(JsonParser.NumberType.LONG);

  check(Parsers.parserAt(new BsonInt64(64)).getIntValue()).is(64);
  check(Parsers.parserAt(new BsonInt64(64)).getLongValue()).is(64L);
  check(Parsers.parserAt(new BsonInt64(64)).getDoubleValue()).is(64D);
  check(Parsers.parserAt(new BsonInt64(64)).getDecimalValue()).is(BigDecimal.valueOf(64));
  check(Parsers.parserAt(new BsonInt64(64)).getBigIntegerValue()).is(BigInteger.valueOf(64));
  check(Parsers.parserAt(new BsonInt64(64)).getNumberValue()).is(64L);
}
 
Example #11
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 #12
Source File: ECReportCapture.java    From epcis with Apache License 2.0 5 votes vote down vote up
private Map<String, BsonValue> getExtensionMap(List<ECReportMemberField> fields) {
	Map<String, BsonValue> extMap = new HashMap<String, BsonValue>();
	for (int l = 0; l < fields.size(); l++) {
		ECReportMemberField field = fields.get(l);
		String key = field.getName();
		String value = field.getValue();
		String[] valArr = value.split("\\^");
		if (valArr.length != 2) {
			extMap.put(key, new BsonString(value));
			continue;
		}
		try {
			String type = valArr[1];
			if (type.equals("int")) {
				extMap.put(key, new BsonInt32(Integer.parseInt(valArr[0])));
			} else if (type.equals("long")) {
				extMap.put(key, new BsonInt64(Long.parseLong(valArr[0])));
			} else if (type.equals("double")) {
				extMap.put(key, new BsonDouble(Double.parseDouble(valArr[0])));
			} else if (type.equals("boolean")) {
				extMap.put(key, new BsonBoolean(Boolean.parseBoolean(valArr[0])));
			} else if (type.equals("dateTime")) {
				extMap.put(key, new BsonDateTime(Long.parseLong(valArr[0])));
			} else {
				extMap.put(key, new BsonString(valArr[0]));
			}
		} catch (NumberFormatException e) {
			extMap.put(key, new BsonString(valArr[0]));
		}
	}
	return extMap;
}
 
Example #13
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 #14
Source File: DeserialisationTest.java    From octarine with Apache License 2.0 5 votes vote down vote up
@Test public void
deserialise_long() {
    long value = random.nextLong();
    BsonDocument doc = new BsonDocument();
    doc.put("my-value", new BsonInt64(value));
    Key<Long> longKey = Key.named("my-value");

    Record record = BsonRecordDeserialiser.builder()
            .readLong(longKey)
            .get()
            .apply(doc);
    assertEquals("wrong long value", value, (long) longKey.get(record).get());
}
 
Example #15
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 #16
Source File: TypeConversionTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Test
public void int64() throws IOException {
  BsonInt32 value = new BsonInt32(64);
  check(Jsons.readerAt(value).peek()).is(JsonToken.NUMBER);
  check(Jsons.readerAt(new BsonInt64(64)).nextInt()).is(64);
  check(Jsons.readerAt(new BsonInt64(64)).nextLong()).is(64L);
  check(Jsons.readerAt(new BsonInt64(64)).nextDouble()).is(64D);
  check(Jsons.readerAt(new BsonInt64(64)).nextString()).is("64");
}
 
Example #17
Source File: BsonReaderTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
/**
 * Reading from BSON to GSON
 */
@Test
public void bsonToGson() throws Exception {
  BsonDocument document = new BsonDocument();
  document.append("boolean", new BsonBoolean(true));
  document.append("int32", new BsonInt32(32));
  document.append("int64", new BsonInt64(64));
  document.append("double", new BsonDouble(42.42D));
  document.append("string", new BsonString("foo"));
  document.append("null", new BsonNull());
  document.append("array", new BsonArray());
  document.append("object", new BsonDocument());

  JsonElement element = TypeAdapters.JSON_ELEMENT.read(new BsonReader(new BsonDocumentReader(document)));
  check(element.isJsonObject());

  check(element.getAsJsonObject().get("boolean").getAsJsonPrimitive().isBoolean());
  check(element.getAsJsonObject().get("boolean").getAsJsonPrimitive().getAsBoolean());

  check(element.getAsJsonObject().get("int32").getAsJsonPrimitive().isNumber());
  check(element.getAsJsonObject().get("int32").getAsJsonPrimitive().getAsNumber().intValue()).is(32);

  check(element.getAsJsonObject().get("int64").getAsJsonPrimitive().isNumber());
  check(element.getAsJsonObject().get("int64").getAsJsonPrimitive().getAsNumber().longValue()).is(64L);

  check(element.getAsJsonObject().get("double").getAsJsonPrimitive().isNumber());
  check(element.getAsJsonObject().get("double").getAsJsonPrimitive().getAsNumber().doubleValue()).is(42.42D);

  check(element.getAsJsonObject().get("string").getAsJsonPrimitive().isString());
  check(element.getAsJsonObject().get("string").getAsJsonPrimitive().getAsString()).is("foo");

  check(element.getAsJsonObject().get("null").isJsonNull());
  check(element.getAsJsonObject().get("array").isJsonArray());
  check(element.getAsJsonObject().get("object").isJsonObject());
}
 
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: KafkaMetaAdder.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
@Override
public void process(final SinkDocument doc, final SinkRecord orig) {
  doc.getValueDoc()
      .ifPresent(
          vd -> {
            vd.put(
                KAFKA_META_DATA,
                new BsonString(
                    format("%s-%s-%s", orig.topic(), orig.kafkaPartition(), orig.kafkaOffset())));
            if (orig.timestampType() != null && orig.timestamp() != null) {
              vd.put(orig.timestampType().name(), new BsonInt64(orig.timestamp()));
            }
          });
}
 
Example #20
Source File: DocumentVersionInfo.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Given a DocumentVersionInfo, returns a BSON document representing the next version. This means
 * and incremented version count for a non-empty version, or a fresh version document for an
 * empty version.
 * @return a BsonDocument representing a synchronization version
 */
BsonDocument getNextVersion() {
  if (!this.hasVersion() || this.getVersionDoc() == null) {
    return getFreshVersionDocument();
  }
  final BsonDocument nextVersion = BsonUtils.copyOfDocument(this.getVersionDoc());
  nextVersion.put(
          Fields.VERSION_COUNTER_FIELD,
          new BsonInt64(this.getVersion().getVersionCounter() + 1));
  return nextVersion;
}
 
Example #21
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 #22
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 #23
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 #24
Source File: SinkFieldConverterTest.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
@TestFactory
@DisplayName("tests for int64 field conversions")
List<DynamicTest> testInt64FieldConverter() {
  SinkFieldConverter converter = new Int64FieldConverter();
  List<DynamicTest> tests = new ArrayList<>();

  asList(Long.MIN_VALUE, 0L, Long.MAX_VALUE)
      .forEach(
          el ->
              tests.add(
                  dynamicTest(
                      "conversion with " + converter.getClass().getSimpleName() + " for " + el,
                      () ->
                          assertEquals(
                              (long) el, ((BsonInt64) converter.toBson(el)).getValue()))));

  tests.add(
      dynamicTest(
          "optional type conversions",
          () -> {
            Schema valueOptionalDefault = SchemaBuilder.int64().optional().defaultValue(0L);
            assertAll(
                "checks",
                () ->
                    assertThrows(
                        DataException.class, () -> converter.toBson(null, Schema.INT64_SCHEMA)),
                () ->
                    assertEquals(
                        new BsonNull(), converter.toBson(null, Schema.OPTIONAL_INT64_SCHEMA)),
                () ->
                    assertEquals(
                        (long) valueOptionalDefault.defaultValue(),
                        ((BsonInt64) converter.toBson(null, valueOptionalDefault)).getValue()));
          }));

  return tests;
}
 
Example #25
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 #26
Source File: KafkaMetaAdder.java    From kafka-connect-mongodb with Apache License 2.0 5 votes vote down vote up
@Override
public void process(SinkDocument doc, SinkRecord orig) {

    doc.getValueDoc().ifPresent(vd -> {
        vd.put(KAFKA_META_DATA, new BsonString(orig.topic()
                + "-" + orig.kafkaPartition() + "-" + orig.kafkaOffset()));
        vd.put(orig.timestampType().name(), new BsonInt64(orig.timestamp()));
    });

    getNext().ifPresent(pp -> pp.process(doc, orig));
}
 
Example #27
Source File: Int64FieldConverter.java    From mongo-kafka with Apache License 2.0 4 votes vote down vote up
@Override
public BsonValue toBson(final Object data) {
  return new BsonInt64((Long) data);
}
 
Example #28
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 #29
Source File: CompareDetail.java    From syncer with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private static Map<String, Object> mongoDetail(MongoClient mongoClient, String db, String col, int id) {
  Document d = mongoClient.getDatabase(db).getCollection(col).find(new BsonDocument("_id", new BsonInt64(id))).first();
  return d == null ? Collections.emptyMap() : d;
}
 
Example #30
Source File: Int64FieldConverter.java    From kafka-connect-mongodb with Apache License 2.0 4 votes vote down vote up
@Override
public BsonValue toBson(Object data) {
    return new BsonInt64((Long) data);
}