org.bson.BsonNull Java Examples

The following examples show how to use org.bson.BsonNull. 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: AvroJsonSchemafulRecordConverter.java    From mongo-kafka with Apache License 2.0 6 votes vote down vote up
private BsonValue toBsonArray(final Schema schema, final Object value) {
  if (value == null) {
    return BsonNull.VALUE;
  }
  Schema fieldSchema = schema.valueSchema();
  BsonArray bsonArray = new BsonArray();
  List<?> myList = (List) value;
  myList.forEach(
      v -> {
        if (fieldSchema.type().isPrimitive()) {
          if (v == null) {
            bsonArray.add(BsonNull.VALUE);
          } else {
            bsonArray.add(getConverter(fieldSchema).toBson(v));
          }
        } else if (fieldSchema.type().equals(ARRAY)) {
          bsonArray.add(toBsonArray(fieldSchema, v));
        } else {
          bsonArray.add(toBsonDoc(fieldSchema, v));
        }
      });
  return bsonArray;
}
 
Example #2
Source File: FindVisitor.java    From immutables with Apache License 2.0 6 votes vote down vote up
@Override
public BsonValue visit(Constant constant) {
  Object value = constant.value();
  if (value == null) {
    return BsonNull.VALUE;
  }

  if (value instanceof Iterable) {
    return Filters.in("ignore", (Iterable<?>) value)
            .toBsonDocument(BsonDocument.class, codecRegistry)
            .get("ignore").asDocument()
            .get("$in").asArray();
  }

  return Filters.eq("ignore", value)
          .toBsonDocument(BsonDocument.class, codecRegistry)
          .get("ignore");
}
 
Example #3
Source File: TupleCodecProvider.java    From immutables with Apache License 2.0 6 votes vote down vote up
private static BsonValue resolveOrNull(BsonValue value, List<String> paths) {
  if (paths.isEmpty()) {
    return value;
  }

  if (!value.isDocument()) {
    return BsonNull.VALUE;
  }

  BsonDocument document = value.asDocument();
  final String first = paths.get(0);
  if (!document.containsKey(first)) {
    return BsonNull.VALUE;
  }

  return resolveOrNull(document.get(first), paths.subList(1, paths.size()));
}
 
Example #4
Source File: BsonWriterTest.java    From immutables with Apache License 2.0 6 votes vote down vote up
/**
 * Check that writing nulls does not cause NPE
 */
@Test
public void writeNulls() throws IOException {
  BsonDocument doc = new BsonDocument();
  BsonWriter writer = new BsonWriter(new BsonDocumentWriter(doc));
  writer.beginObject();
  writer.name("nullString"); writer.value((String) null);
  writer.name("nullBoolean"); writer.value((Boolean) null);
  writer.name("nullNumber"); writer.value((Long) null);
  writer.name("null"); writer.nullValue();
  writer.endObject();
  writer.flush();
  check(doc.get("nullString")).is(BsonNull.VALUE);
  check(doc.get("nullBoolean")).is(BsonNull.VALUE);
  check(doc.get("nullNumber")).is(BsonNull.VALUE);
  check(doc.get("null")).is(BsonNull.VALUE);
}
 
Example #5
Source File: JacksonRepoTest.java    From immutables with Apache License 2.0 6 votes vote down vote up
/**
 * persist empty Optional of Date
 */
@Test
public void nullDate() {
  final Jackson expected = ImmutableJackson.builder()
          .id(ObjectId.get())
          .prop1("prop11")
          .prop2("prop22")
          .build();

  repository.insert(expected).getUnchecked();

  final Jackson actual = repository.findAll()
          .fetchAll().getUnchecked().get(0);

  check(expected.date().asSet()).isEmpty();
  check(expected).is(actual);
  final BsonDocument doc = collection.find().first();
  check(doc.keySet()).hasContentInAnyOrder("_id", "prop1", "prop2", "date", "uuid");
  check(doc.get("date")).is(BsonNull.VALUE);
}
 
Example #6
Source File: ChronoElement.java    From epcis with Apache License 2.0 6 votes vote down vote up
/**
 * Un-assigns a key/value property from the element. The object value of the
 * removed property is returned.
 *
 * @param key the key of the property to remove from the element
 * @return the object value associated with that key prior to removal. Should be
 *         instance of BsonValue
 */
@Override
public <T> T removeProperty(final String key) {
	try {
		BsonValue value = getProperty(key);
		BsonDocument filter = new BsonDocument();
		filter.put(Tokens.ID, new BsonString(this.id));
		BsonDocument update = new BsonDocument();
		update.put("$unset", new BsonDocument(key, new BsonNull()));
		if (this instanceof ChronoVertex) {
			graph.getVertexCollection().updateOne(filter, update, new UpdateOptions().upsert(true));
			return (T) value;
		} else {
			graph.getEdgeCollection().updateOne(filter, update, new UpdateOptions().upsert(true));
			return (T) value;
		}
	} catch (MongoWriteException e) {
		throw e;
	}
}
 
Example #7
Source File: ChronoGraph.java    From epcis with Apache License 2.0 6 votes vote down vote up
public HashSet<Long> getTimestampsHashSet() {
	HashSet<Long> timestampSet = new HashSet<Long>();

	Function<BsonDateTime, Long> mapper = new Function<BsonDateTime, Long>() {
		@Override
		public Long apply(BsonDateTime val) {
			return val.getValue();
		}

	};
	edges.distinct(Tokens.TIMESTAMP, BsonDateTime.class)
			.filter(new BsonDocument(Tokens.TIMESTAMP, new BsonDocument(Tokens.FC.$ne.toString(), new BsonNull())))
			.map(mapper).into(timestampSet);

	return timestampSet;
}
 
Example #8
Source File: ChronoGraph.java    From epcis with Apache License 2.0 6 votes vote down vote up
/**
 * Return non-redundant timestamps of all graph element events
 * 
 * @return HashSet<Long> timestamps
 */
public TreeSet<Long> getTimestamps() {
	TreeSet<Long> timestampSet = new TreeSet<Long>();

	Function<BsonDateTime, Long> mapper = new Function<BsonDateTime, Long>() {
		@Override
		public Long apply(BsonDateTime val) {
			return val.getValue();
		}

	};
	edgeEvents.distinct(Tokens.TIMESTAMP, BsonDateTime.class)
			.filter(new BsonDocument(Tokens.TIMESTAMP, new BsonDocument(Tokens.FC.$ne.toString(), new BsonNull())))
			.map(mapper).into(timestampSet);
	Set<Long> vtSet = new TreeSet<Long>();

	vertexEvents.distinct(Tokens.TIMESTAMP, BsonDateTime.class)
			.filter(new BsonDocument(Tokens.TIMESTAMP, new BsonDocument(Tokens.FC.$ne.toString(), new BsonNull())))
			.map(mapper).into(vtSet);
	timestampSet.addAll(vtSet);

	return timestampSet;
}
 
Example #9
Source File: ProvidedStrategy.java    From kafka-connect-mongodb with Apache License 2.0 6 votes vote down vote up
@Override
public BsonValue generateId(SinkDocument doc, SinkRecord orig) {

    Optional<BsonDocument> bd = Optional.empty();

    if(where.equals(ProvidedIn.KEY)) {
        bd = doc.getKeyDoc();
    }

    if(where.equals(ProvidedIn.VALUE)) {
        bd = doc.getValueDoc();
    }

    BsonValue _id = bd.map(d -> d.get(DBCollection.ID_FIELD_NAME))
                .orElseThrow(() -> new DataException("error: provided id strategy is used "
                    + "but the document structure either contained no _id field or it was null"));

    if(_id instanceof BsonNull) {
        throw new DataException("error: provided id strategy used "
                + "but the document structure contained an _id of type BsonNull");
    }

    return _id;

}
 
Example #10
Source File: SinkFieldConverter.java    From kafka-connect-mongodb with Apache License 2.0 6 votes vote down vote up
public BsonValue toBson(Object data, Schema fieldSchema) {
    if(!fieldSchema.isOptional()) {

        if(data == null)
            throw new DataException("error: schema not optional but data was null");

        logger.trace("field not optional and data is '{}'",data.toString());
        return toBson(data);
    }

    if(data != null) {
        logger.trace("field optional and data is '{}'",data.toString());
        return toBson(data);
    }

    if(fieldSchema.defaultValue() != null) {
        logger.trace("field optional and no data but default value is '{}'",fieldSchema.defaultValue().toString());
        return toBson(fieldSchema.defaultValue());
    }

    logger.trace("field optional, no data and no default value thus '{}'", BsonNull.VALUE);
    return BsonNull.VALUE;
}
 
Example #11
Source File: AvroJsonSchemafulRecordConverter.java    From kafka-connect-mongodb with Apache License 2.0 6 votes vote down vote up
private BsonValue handleArrayField(List list, Field field) {
    logger.trace("handling complex type 'array' of types '{}'",
       field.schema().valueSchema().type());
    if(list==null) {
        logger.trace("no array -> adding null");
        return BsonNull.VALUE;
    }
    BsonArray array = new BsonArray();
    Schema.Type st = field.schema().valueSchema().type();
    for(Object element : list) {
        if(st.isPrimitive()) {
            array.add(getConverter(field.schema().valueSchema()).toBson(element,field.schema()));
        } else if(st == Schema.Type.ARRAY) {
            Field elementField = new Field("first", 0, field.schema().valueSchema());
            array.add(handleArrayField((List)element,elementField));
        } else {
            array.add(toBsonDoc(field.schema().valueSchema(), element));
        }
    }
    return array;
}
 
Example #12
Source File: AvroJsonSchemafulRecordConverter.java    From kafka-connect-mongodb with Apache License 2.0 6 votes vote down vote up
private void handleMapField(BsonDocument doc, Map m, Field field) {
    logger.trace("handling complex type 'map'");
    if(m==null) {
        logger.trace("no field in struct -> adding null");
        doc.put(field.name(), BsonNull.VALUE);
        return;
    }
    BsonDocument bd = new BsonDocument();
    for(Object entry : m.keySet()) {
        String key = (String)entry;
        Schema.Type valueSchemaType = field.schema().valueSchema().type();
        if(valueSchemaType.isPrimitive()) {
            bd.put(key, getConverter(field.schema().valueSchema()).toBson(m.get(key),field.schema()));
        } else if (valueSchemaType.equals(Schema.Type.ARRAY)) {
            final Field elementField = new Field(key, 0, field.schema().valueSchema());
            final List list = (List)m.get(key);
            logger.trace("adding array values to {} of type valueSchema={} value='{}'",
               elementField.name(), elementField.schema().valueSchema(), list);
            bd.put(key, handleArrayField(list, elementField));
        } else {
            bd.put(key, toBsonDoc(field.schema().valueSchema(), m.get(key)));
        }
    }
    doc.put(field.name(), bd);
}
 
Example #13
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 #14
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 #15
Source File: SinkFieldConverter.java    From mongo-kafka with Apache License 2.0 6 votes vote down vote up
public BsonValue toBson(final Object data, final Schema fieldSchema) {
  if (!fieldSchema.isOptional()) {
    if (data == null) {
      throw new DataException("Error: schema not optional but data was null");
    }
    LOGGER.trace("field not optional and data is '{}'", data.toString());
    return toBson(data);
  }

  if (data != null) {
    LOGGER.trace("field optional and data is '{}'", data.toString());
    return toBson(data);
  }

  if (fieldSchema.defaultValue() != null) {
    LOGGER.trace(
        "field optional and no data but default value is '{}'",
        fieldSchema.defaultValue().toString());
    return toBson(fieldSchema.defaultValue());
  }

  LOGGER.trace("field optional, no data and no default value thus '{}'", BsonNull.VALUE);
  return BsonNull.VALUE;
}
 
Example #16
Source File: ProvidedStrategy.java    From mongo-kafka with Apache License 2.0 6 votes vote down vote up
@Override
public BsonValue generateId(final SinkDocument doc, final SinkRecord orig) {
  Optional<BsonDocument> optionalDoc = Optional.empty();
  if (where.equals(ProvidedIn.KEY)) {
    optionalDoc = doc.getKeyDoc();
  }

  if (where.equals(ProvidedIn.VALUE)) {
    optionalDoc = doc.getValueDoc();
  }

  BsonValue id =
      optionalDoc
          .map(d -> d.get(ID_FIELD))
          .orElseThrow(
              () ->
                  new DataException(
                      "Error: provided id strategy is used but the document structure either contained"
                          + " no _id field or it was null"));

  if (id instanceof BsonNull) {
    throw new DataException(
        "Error: provided id strategy used but the document structure contained an _id of type BsonNull");
  }
  return id;
}
 
Example #17
Source File: ChronoGraph.java    From epcis with Apache License 2.0 5 votes vote down vote up
/**
 * Return an iterable to all the vertices in the graph. If this is not possible
 * for the implementation, then an UnsupportedOperationException can be thrown.
 *
 * @return an iterable reference to all vertices in the graph
 */
public Iterable<ChronoVertex> getChronoVertices() {
	HashSet<String> idSet = new HashSet<String>();
	Function<BsonString, String> mapper = new Function<BsonString, String>() {
		@Override
		public String apply(BsonString val) {
			return val.getValue();
		}

	};
	HashSet<String> outV = new HashSet<String>();
	edges.distinct(Tokens.OUT_VERTEX, BsonString.class)
			.filter(new BsonDocument(Tokens.OUT_VERTEX, new BsonDocument(Tokens.FC.$ne.toString(), new BsonNull())))
			.map(mapper).into(outV);
	idSet.addAll(outV);
	HashSet<String> inV = new HashSet<String>();
	edges.distinct(Tokens.IN_VERTEX, BsonString.class)
			.filter(new BsonDocument(Tokens.IN_VERTEX, new BsonDocument(Tokens.FC.$ne.toString(), new BsonNull())))
			.map(mapper).into(inV);
	idSet.addAll(inV);

	MongoCursor<BsonDocument> vi = vertices.find(Tokens.FLT_VERTEX_FIELD_NOT_INCLUDED)
			.projection(Tokens.PRJ_ONLY_ID).iterator();
	while (vi.hasNext()) {
		BsonDocument d = vi.next();
		idSet.add(d.getString(Tokens.ID).getValue());
	}

	HashSet<String> vertex = new HashSet<String>();
	vertices.distinct(Tokens.VERTEX, BsonString.class)
			.filter(new BsonDocument(Tokens.VERTEX, new BsonDocument(Tokens.FC.$ne.toString(), new BsonNull())))
			.map(mapper).into(vertex);
	idSet.addAll(vertex);

	return idSet.parallelStream().map(s -> new ChronoVertex(s, this)).collect(Collectors.toSet());
}
 
Example #18
Source File: JavaTimeTypeTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Test
void localDate() {
  LocalDateHolderRepository repository = new LocalDateHolderRepository(backend);
  LocalDate value = LocalDate.now();
  ImmutableLocalDateHolder holder = TypeHolder.LocalDateHolder.generator().get().withValue(value).withOptional(value).withNullable(null);
  repository.insert(holder);
  BsonDocument doc = fetch();

  BsonDateTime expected = new BsonDateTime(value.atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli());
  check(doc.get("value")).is(expected);
  check(doc.get("optional")).is(expected);
  if (doc.containsKey("nullable")) {
    check(doc.get("nullable")).is(BsonNull.VALUE);
  }
}
 
Example #19
Source File: JavaTimeTypeTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Test
void localDateTime() {
  LocalDateTimeHolderRepository repository = new LocalDateTimeHolderRepository(backend);
  LocalDateTime value = LocalDateTime.now();
  ImmutableLocalDateTimeHolder holder = TypeHolder.LocalDateTimeHolder.generator().get().withValue(value).withOptional(value).withNullable(null);
  repository.insert(holder);
  BsonDocument doc = fetch();

  BsonDateTime expected = new BsonDateTime(value.toInstant(ZoneOffset.UTC).toEpochMilli());
  check(doc.get("value")).is(expected);
  check(doc.get("optional")).is(expected);
  if (doc.containsKey("nullable")) {
    check(doc.get("nullable")).is(BsonNull.VALUE);
  }
}
 
Example #20
Source File: JavaTimeTypeTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Test
void instant() {
  InstantHolderRepository repository = new InstantHolderRepository(backend);
  Instant value = Instant.now();
  ImmutableInstantHolder holder = TypeHolder.InstantHolder.generator().get().withValue(value).withOptional(value).withNullable(null);
  repository.insert(holder);
  BsonDocument doc = fetch();

  BsonDateTime expected = new BsonDateTime(value.toEpochMilli());
  check(doc.get("value")).is(expected);
  check(doc.get("optional")).is(expected);
  if (doc.containsKey("nullable")) {
    check(doc.get("nullable")).is(BsonNull.VALUE);
  }
}
 
Example #21
Source File: BsonGeneratorTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
/**
 * Writing null values does not cause an exception
 */
@Test
void nulls() throws IOException {
  BsonDocumentWriter writer = new BsonDocumentWriter(new BsonDocument());
  BsonGenerator generator = generatorFor(writer);
  generator.writeStartObject();

  generator.writeFieldName("null");
  generator.writeNull();

  generator.writeNullField("nullField");

  generator.writeFieldName("string");
  generator.writeString((String) null);

  generator.writeFieldName("bigDecimal");
  generator.writeNumber((BigDecimal) null);

  generator.writeFieldName("bigInteger");
  generator.writeNumber((BigInteger) null);
  generator.writeEndObject();
  BsonDocument doc = writer.getDocument();
  check(doc.get("null")).is(BsonNull.VALUE);
  check(doc.get("nullField")).is(BsonNull.VALUE);
  check(doc.get("string")).is(BsonNull.VALUE);
  check(doc.get("bigDecimal")).is(BsonNull.VALUE);
  check(doc.get("bigInteger")).is(BsonNull.VALUE);
}
 
Example #22
Source File: TypeConversionTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Test
void parseExceptions() {
  Assertions.assertThrows(JsonParseException.class, () -> {
    Parsers.parserAt(new BsonBoolean(true)).getNumberValue();
  });

  Assertions.assertThrows(JsonParseException.class, () -> {
    Parsers.parserAt(new BsonBoolean(true)).getLongValue();
  });

  Assertions.assertThrows(JsonParseException.class, () -> {
    Parsers.parserAt(BsonNull.VALUE).getNumberValue();
  });

  Assertions.assertThrows(JsonParseException.class, () -> {
    Parsers.parserAt(BsonNull.VALUE).getNumberType();
  });

  Assertions.assertThrows(JsonParseException.class, () -> {
    Parsers.parserAt(new BsonInt32(42)).getBooleanValue();
  });

  Assertions.assertThrows(JsonParseException.class, () -> {
    Parsers.parserAt(new BsonBoolean(true)).getNumberType();
  });

  Assertions.assertThrows(JsonParseException.class, () -> {
    Parsers.parserAt(new BsonDateTime(42)).getBooleanValue();
  });

  Assertions.assertThrows(JsonParseException.class, () -> {
    Parsers.parserAt(new BsonTimestamp(42)).getBooleanValue();
  });
}
 
Example #23
Source File: TupleCodecProviderTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Test
void localDate() {
  LocalDateHolderCriteria criteria = LocalDateHolderCriteria.localDateHolder;

  Query query = Query.of(TypeHolder.LocalDateHolder.class)
          .addProjections(Matchers.toExpression(criteria.value),  Matchers.toExpression(criteria.nullable), Matchers.toExpression(criteria.optional));

  Path idPath = Visitors.toPath(KeyExtractor.defaultFactory().create(TypeHolder.LocalDateHolder.class).metadata().keys().get(0));
  TupleCodecProvider provider = new TupleCodecProvider(query, new MongoPathNaming(idPath, PathNaming.defaultNaming()).toExpression());
  Codec<ProjectedTuple> codec = provider.get(ProjectedTuple.class, registry);

  LocalDate now = LocalDate.now();
  final long millisEpoch = now.atStartOfDay().toInstant(ZoneOffset.UTC).toEpochMilli();

  BsonDocument doc = new BsonDocument()
          .append("id", new BsonString("id1"))
          .append("value", new BsonDateTime(millisEpoch))
          .append("nullable", BsonNull.VALUE)
          .append("optional", BsonNull.VALUE)
          .append("array", new BsonArray())
          .append("list", new BsonArray());

  ProjectedTuple tuple = codec.decode(new BsonDocumentReader(doc), DecoderContext.builder().build());

  check(tuple.get(Matchers.toExpression(criteria.value))).is(now);
  check(tuple.get(Matchers.toExpression(criteria.nullable))).isNull();
  check(tuple.get(Matchers.toExpression(criteria.optional))).is(Optional.empty());
}
 
Example #24
Source File: AvroJsonSchemafulRecordConverter.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
private BsonValue toBsonDoc(final Schema schema, final Object value) {
  if (value == null) {
    return BsonNull.VALUE;
  }
  BsonDocument doc = new BsonDocument();
  if (schema.type() == MAP) {
    Schema fieldSchema = schema.valueSchema();
    Map m = (Map) value;
    for (Object entry : m.keySet()) {
      String key = (String) entry;
      if (fieldSchema.type().isPrimitive()) {
        doc.put(key, getConverter(fieldSchema).toBson(m.get(key), fieldSchema));
      } else if (fieldSchema.type().equals(ARRAY)) {
        doc.put(key, toBsonArray(fieldSchema, m.get(key)));
      } else {
        if (m.get(key) == null) {
          doc.put(key, BsonNull.VALUE);
        } else {
          doc.put(key, toBsonDoc(fieldSchema, m.get(key)));
        }
      }
    }
  } else {
    schema.fields().forEach(f -> doc.put(f.name(), processField((Struct) value, f)));
  }
  return doc;
}
 
Example #25
Source File: AvroJsonSchemafulRecordConverter.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
private BsonValue processField(final Struct struct, final Field field) {
  LOGGER.trace("processing field '{}'", field.name());

  if (struct.get(field.name()) == null) {
    LOGGER.trace("no field in struct -> adding null");
    return BsonNull.VALUE;
  }

  if (isSupportedLogicalType(field.schema())) {
    return getConverter(field.schema()).toBson(struct.get(field), field.schema());
  }

  try {
    switch (field.schema().type()) {
      case BOOLEAN:
      case FLOAT32:
      case FLOAT64:
      case INT8:
      case INT16:
      case INT32:
      case INT64:
      case STRING:
      case BYTES:
        return handlePrimitiveField(struct, field);
      case STRUCT:
      case MAP:
        return toBsonDoc(field.schema(), struct.get(field));
      case ARRAY:
        return toBsonArray(field.schema(), struct.get(field));
      default:
        throw new DataException("unexpected / unsupported schema type " + field.schema().type());
    }
  } catch (Exception exc) {
    throw new DataException("error while processing field " + field.name(), exc);
  }
}
 
Example #26
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 #27
Source File: SinkFieldConverterTest.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
@TestFactory
@DisplayName("tests for boolean field conversions")
List<DynamicTest> testBooleanFieldConverter() {

  SinkFieldConverter converter = new BooleanFieldConverter();

  List<DynamicTest> tests = new ArrayList<>();
  asList(true, false)
      .forEach(
          el ->
              tests.add(
                  dynamicTest(
                      "conversion with " + converter.getClass().getSimpleName() + " for " + el,
                      () -> assertEquals(el, ((BsonBoolean) converter.toBson(el)).getValue()))));

  tests.add(
      dynamicTest(
          "optional type conversion checks",
          () -> {
            Schema valueOptionalDefault = SchemaBuilder.bool().optional().defaultValue(true);
            assertAll(
                "",
                () ->
                    assertThrows(
                        DataException.class, () -> converter.toBson(null, Schema.BOOLEAN_SCHEMA)),
                () ->
                    assertEquals(
                        new BsonNull(), converter.toBson(null, Schema.OPTIONAL_BOOLEAN_SCHEMA)),
                () ->
                    assertEquals(
                        valueOptionalDefault.defaultValue(),
                        converter.toBson(null, valueOptionalDefault).asBoolean().getValue()));
          }));

  return tests;
}
 
Example #28
Source File: SinkFieldConverterTest.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
@TestFactory
@DisplayName("tests for int8 field conversions")
List<DynamicTest> testInt8FieldConverter() {

  SinkFieldConverter converter = new Int8FieldConverter();

  List<DynamicTest> tests = new ArrayList<>();
  asList(Byte.MIN_VALUE, (byte) 0, Byte.MAX_VALUE)
      .forEach(
          el ->
              tests.add(
                  dynamicTest(
                      "conversion with " + converter.getClass().getSimpleName() + " for " + el,
                      () ->
                          assertEquals(
                              (int) el, ((BsonInt32) converter.toBson(el)).getValue()))));

  tests.add(
      dynamicTest(
          "optional type conversions",
          () -> {
            Schema valueOptionalDefault = SchemaBuilder.int8().optional().defaultValue((byte) 0);
            assertAll(
                "checks",
                () ->
                    assertThrows(
                        DataException.class, () -> converter.toBson(null, Schema.INT8_SCHEMA)),
                () ->
                    assertEquals(
                        new BsonNull(), converter.toBson(null, Schema.OPTIONAL_INT8_SCHEMA)),
                () ->
                    assertEquals(
                        ((Byte) valueOptionalDefault.defaultValue()).intValue(),
                        ((BsonInt32) converter.toBson(null, valueOptionalDefault)).getValue()));
          }));

  return tests;
}
 
Example #29
Source File: SinkFieldConverterTest.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
@TestFactory
@DisplayName("tests for int16 field conversions")
List<DynamicTest> testInt16FieldConverter() {

  SinkFieldConverter converter = new Int16FieldConverter();

  List<DynamicTest> tests = new ArrayList<>();
  asList(Short.MIN_VALUE, (short) 0, Short.MAX_VALUE)
      .forEach(
          el ->
              tests.add(
                  dynamicTest(
                      "conversion with " + converter.getClass().getSimpleName() + " for " + el,
                      () ->
                          assertEquals(
                              (short) el, ((BsonInt32) converter.toBson(el)).getValue()))));

  tests.add(
      dynamicTest(
          "optional type conversions",
          () -> {
            Schema valueOptionalDefault =
                SchemaBuilder.int16().optional().defaultValue((short) 0);
            assertAll(
                "checks",
                () ->
                    assertThrows(
                        DataException.class, () -> converter.toBson(null, Schema.INT16_SCHEMA)),
                () ->
                    assertEquals(
                        new BsonNull(), converter.toBson(null, Schema.OPTIONAL_INT16_SCHEMA)),
                () ->
                    assertEquals(
                        ((short) valueOptionalDefault.defaultValue()),
                        ((BsonInt32) converter.toBson(null, valueOptionalDefault)).getValue()));
          }));

  return tests;
}
 
Example #30
Source File: ChronoGraph.java    From epcis with Apache License 2.0 5 votes vote down vote up
/**
 * Return an iterable to all the vertices in the graph. If this is not possible
 * for the implementation, then an UnsupportedOperationException can be thrown.
 *
 * @return an iterable reference to all vertices in the graph
 */
public Stream<ChronoVertex> getChronoVertexStream(boolean isParallel) {
	HashSet<String> idSet = new HashSet<String>();
	Function<BsonString, String> mapper = new Function<BsonString, String>() {
		@Override
		public String apply(BsonString val) {
			return val.getValue();
		}

	};
	HashSet<String> outV = new HashSet<String>();
	edges.distinct(Tokens.OUT_VERTEX, BsonString.class)
			.filter(new BsonDocument(Tokens.OUT_VERTEX, new BsonDocument(Tokens.FC.$ne.toString(), new BsonNull())))
			.map(mapper).into(outV);
	idSet.addAll(outV);
	HashSet<String> inV = new HashSet<String>();
	edges.distinct(Tokens.IN_VERTEX, BsonString.class)
			.filter(new BsonDocument(Tokens.IN_VERTEX, new BsonDocument(Tokens.FC.$ne.toString(), new BsonNull())))
			.map(mapper).into(inV);
	idSet.addAll(inV);

	MongoCursor<BsonDocument> vi = vertices.find(Tokens.FLT_VERTEX_FIELD_NOT_INCLUDED)
			.projection(Tokens.PRJ_ONLY_ID).iterator();
	while (vi.hasNext()) {
		BsonDocument d = vi.next();
		idSet.add(d.getString(Tokens.ID).getValue());
	}

	HashSet<String> vertex = new HashSet<String>();
	vertices.distinct(Tokens.VERTEX, BsonString.class)
			.filter(new BsonDocument(Tokens.VERTEX, new BsonDocument(Tokens.FC.$ne.toString(), new BsonNull())))
			.map(mapper).into(vertex);
	idSet.addAll(vertex);
	if (isParallel)
		return idSet.parallelStream().map(s -> new ChronoVertex(s, this)).collect(Collectors.toSet())
				.parallelStream();
	else
		return idSet.parallelStream().map(s -> new ChronoVertex(s, this)).collect(Collectors.toSet()).stream();
}