Java Code Examples for org.bson.BsonValue#isDocument()

The following examples show how to use org.bson.BsonValue#isDocument() . 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: BlockListProjector.java    From mongo-kafka with Apache License 2.0 6 votes vote down vote up
private void handleWildcard(
    final String firstPart, final String otherParts, final BsonDocument doc) {
  Iterator<Map.Entry<String, BsonValue>> iter = doc.entrySet().iterator();
  while (iter.hasNext()) {
    Map.Entry<String, BsonValue> entry = iter.next();
    BsonValue value = entry.getValue();

    // NOTE: never try to remove the _id field
    if (entry.getKey().equals(ID_FIELD)) {
      continue;
    }

    if (firstPart.equals(FieldProjector.DOUBLE_WILDCARD)) {
      iter.remove();
    } else if (firstPart.equals(FieldProjector.SINGLE_WILDCARD)) {
      if (!value.isDocument()) {
        iter.remove();
      } else if (!otherParts.isEmpty()) {
        doProjection(otherParts, (BsonDocument) value);
      }
    }
  }
}
 
Example 2
Source File: Renamer.java    From mongo-kafka with Apache License 2.0 6 votes vote down vote up
private void doRenaming(final String field, final BsonDocument doc) {
  BsonDocument modifications = new BsonDocument();
  Iterator<Map.Entry<String, BsonValue>> iter = doc.entrySet().iterator();
  while (iter.hasNext()) {
    Map.Entry<String, BsonValue> entry = iter.next();
    String oldKey = entry.getKey();
    BsonValue value = entry.getValue();
    String newKey = renamed(field, oldKey);

    if (!oldKey.equals(newKey)) {
      // IF NEW KEY ALREADY EXISTS WE THEN DON'T RENAME
      // AS IT WOULD CAUSE OTHER DATA TO BE SILENTLY OVERWRITTEN
      // WHICH IS ALMOST NEVER WHAT YOU WANT
      // MAYBE LOG WARNING HERE?
      doc.computeIfAbsent(newKey, k -> modifications.putIfAbsent(k, value));
      iter.remove();
    }
    if (value.isDocument()) {
      String pathToField = field + SUB_FIELD_DOT_SEPARATOR + newKey;
      doRenaming(pathToField, value.asDocument());
    }
  }
  doc.putAll(modifications);
}
 
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: BlacklistProjector.java    From kafka-connect-mongodb with Apache License 2.0 6 votes vote down vote up
private void handleWildcard(String firstPart, String otherParts, BsonDocument doc) {
    Iterator<Map.Entry<String, BsonValue>> iter = doc.entrySet().iterator();
    while(iter.hasNext()) {
        Map.Entry<String, BsonValue> entry = iter.next();
        BsonValue value = entry.getValue();

        //NOTE: never try to remove the _id field
        if(entry.getKey().equals(DBCollection.ID_FIELD_NAME))
            continue;

        if(firstPart.equals(FieldProjector.DOUBLE_WILDCARD)) {
            iter.remove();
        }

        if(firstPart.equals(FieldProjector.SINGLE_WILDCARD)) {
            if(!value.isDocument()) {
                iter.remove();
            } else {
                if(!otherParts.isEmpty()) {
                    doProjection(otherParts, (BsonDocument)value);
                }
            }
        }
    }
}
 
Example 5
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 6
Source File: AbstractBasicDBMapper.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private static JsonValue mapBsonValueToJsonValue(@Nullable final BsonValue bsonValue,
        final Function<String, String> jsonKeyNameReviser) {
    final JsonValue result;
    if (bsonValue == null || bsonValue.isNull()) {
        result = JsonFactory.nullLiteral();
    } else if (bsonValue.isString()) {
        result = JsonFactory.newValue(bsonValue.asString().getValue());
    } else if (bsonValue.isNumber()) {
        result = mapBsonNumberToJsonNumber(bsonValue.asNumber());
    } else if (bsonValue.isDocument()) {
        result = mapBsonDocumentToJsonObject(bsonValue.asDocument(), jsonKeyNameReviser);
    } else if (bsonValue.isArray()) {
        result = mapBsonArrayToJsonArray(bsonValue.asArray(), jsonKeyNameReviser);
    } else if (bsonValue.isBoolean()) {
        result = JsonFactory.newValue(bsonValue.asBoolean().getValue());
    } else if (bsonValue.isTimestamp()) {
        final Instant instant = Instant.ofEpochSecond(bsonValue.asTimestamp().getTime());
        result = JsonFactory.newValue(instant.toString());
    } else {
        result = JsonFactory.nullLiteral();
    }
    return result;
}
 
Example 7
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 8
Source File: TupleCodecProvider.java    From immutables with Apache License 2.0 5 votes vote down vote up
Object decode(BsonValue bson) {
  final Object value;
  if (isNullable && bson.isNull()) {
    // return NULL if field is nullable and BSON is null
    value = null;
  } else if (!bson.isDocument()) {
    value = decoder.decode(new BsonValueReader(bson), DecoderContext.builder().build());
  } else {
    value = decoder.decode(new BsonDocumentReader(bson.asDocument()), DecoderContext.builder().build());
  }
  return value;
}
 
Example 9
Source File: GridFSTest.java    From mongo-java-driver-reactivestreams with Apache License 2.0 5 votes vote down vote up
private List<BsonDocument> processChunks(final BsonArray bsonArray, final List<BsonDocument> documents) {
    for (BsonValue rawDocument : bsonArray.getValues()) {
        if (rawDocument.isDocument()) {
            documents.add(parseHexDocument(rawDocument.asDocument()));
        }
    }
    return documents;
}
 
Example 10
Source File: GridFSTest.java    From mongo-java-driver-rx with Apache License 2.0 5 votes vote down vote up
private List<BsonDocument> processChunks(final BsonArray bsonArray, final List<BsonDocument> documents) {
    for (BsonValue rawDocument : bsonArray.getValues()) {
        if (rawDocument.isDocument()) {
            documents.add(parseHexDocument(rawDocument.asDocument()));
        }
    }
    return documents;
}
 
Example 11
Source File: TupleCodecProvider.java    From immutables with Apache License 2.0 4 votes vote down vote up
private static BsonDocument fromValue(BsonValue value) {
  return value.isDocument() ? value.asDocument() : new BsonDocument("value", value);
}
 
Example 12
Source File: BlockListProjector.java    From mongo-kafka with Apache License 2.0 4 votes vote down vote up
@Override
protected void doProjection(final String field, final BsonDocument doc) {
  if (!field.contains(FieldProjector.SUB_FIELD_DOT_SEPARATOR)) {
    if (field.equals(FieldProjector.SINGLE_WILDCARD)
        || field.equals(FieldProjector.DOUBLE_WILDCARD)) {
      handleWildcard(field, "", doc);
      return;
    }

    // NOTE: never try to remove the _id field
    if (!field.equals(ID_FIELD)) {
      doc.remove(field);
    }
    return;
  }

  int dotIdx = field.indexOf(FieldProjector.SUB_FIELD_DOT_SEPARATOR);
  String firstPart = field.substring(0, dotIdx);
  String otherParts = field.length() >= dotIdx ? field.substring(dotIdx + 1) : "";

  if (firstPart.equals(FieldProjector.SINGLE_WILDCARD)
      || firstPart.equals(FieldProjector.DOUBLE_WILDCARD)) {
    handleWildcard(firstPart, otherParts, doc);
    return;
  }

  BsonValue value = doc.get(firstPart);
  if (value != null) {
    if (value.isDocument()) {
      doProjection(otherParts, value.asDocument());
    }
    if (value.isArray()) {
      BsonArray values = value.asArray();
      for (BsonValue v : values.getValues()) {
        if (v != null && v.isDocument()) {
          doProjection(otherParts, v.asDocument());
        }
      }
    }
  }
}
 
Example 13
Source File: ChangeEvent.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * Deserializes a {@link BsonDocument} into an instance of change event.
 * @param document the serialized document
 * @return the deserialized change event
 */
public static ChangeEvent fromBsonDocument(final BsonDocument document) {
  keyPresent(Fields.ID_FIELD, document);
  keyPresent(Fields.OPERATION_TYPE_FIELD, document);
  keyPresent(Fields.NS_FIELD, document);
  keyPresent(Fields.DOCUMENT_KEY_FIELD, document);

  final BsonDocument nsDoc = document.getDocument(Fields.NS_FIELD);

  final UpdateDescription updateDescription;
  if (document.containsKey(Fields.UPDATE_DESCRIPTION_FIELD)) {
    updateDescription = UpdateDescription.fromBsonDocument(
        document.getDocument(Fields.UPDATE_DESCRIPTION_FIELD)
    );
  } else {
    updateDescription = null;
  }

  final BsonDocument fullDocument;
  if (document.containsKey(Fields.FULL_DOCUMENT_FIELD)) {
    final BsonValue fdVal = document.get(Fields.FULL_DOCUMENT_FIELD);
    if (fdVal.isDocument()) {
      fullDocument = fdVal.asDocument();
    } else {
      fullDocument = null;
    }
  } else {
    fullDocument = null;
  }

  return new ChangeEvent<>(
      document.getDocument(Fields.ID_FIELD),
      OperationType.fromRemote(document.getString(Fields.OPERATION_TYPE_FIELD).getValue()),
      fullDocument,
      new MongoNamespace(
          nsDoc.getString(Fields.NS_DB_FIELD).getValue(),
          nsDoc.getString(Fields.NS_COLL_FIELD).getValue()),
      document.getDocument(Fields.DOCUMENT_KEY_FIELD),
      updateDescription,
      document.getBoolean(Fields.WRITE_PENDING_FIELD, BsonBoolean.FALSE).getValue());
}
 
Example 14
Source File: CompactChangeEvent.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * Deserializes a {@link BsonDocument} into an instance of change event.
 * @param document the serialized document
 * @return the deserialized change event
 */
public static CompactChangeEvent fromBsonDocument(final BsonDocument document) {
  keyPresent(Fields.OPERATION_TYPE_FIELD, document);
  keyPresent(Fields.DOCUMENT_KEY_FIELD, document);

  final BsonDocument fullDocument;
  if (document.containsKey(Fields.FULL_DOCUMENT_FIELD)) {
    final BsonValue fdVal = document.get(Fields.FULL_DOCUMENT_FIELD);
    if (fdVal.isDocument()) {
      fullDocument = fdVal.asDocument();
    } else {
      fullDocument = null;
    }
  } else {
    fullDocument = null;
  }

  final UpdateDescription updateDescription;
  if (document.containsKey(Fields.UPDATE_DESCRIPTION_FIELD)) {
    updateDescription = UpdateDescription.fromBsonDocument(
        document.getDocument(Fields.UPDATE_DESCRIPTION_FIELD)
    );
  } else {
    updateDescription = null;
  }

  final DocumentVersionInfo.Version stitchDocumentVersion;
  if (document.containsKey(Fields.STITCH_DOCUMENT_VERSION_FIELD)) {
    stitchDocumentVersion = DocumentVersionInfo.Version
        .fromBsonDocument(document.getDocument(Fields.STITCH_DOCUMENT_VERSION_FIELD));
  } else {
    stitchDocumentVersion = null;
  }

  final Long stitchDocumentHash;
  if (document.containsKey(Fields.STITCH_DOCUMENT_HASH_FIELD)) {
    stitchDocumentHash = document.getInt64(
        Fields.STITCH_DOCUMENT_HASH_FIELD
    ).getValue();
  } else {
    stitchDocumentHash = null;
  }

  return new CompactChangeEvent<>(
      OperationType.fromRemote(document.getString(Fields.OPERATION_TYPE_FIELD).getValue()),
      fullDocument,
      document.getDocument(Fields.DOCUMENT_KEY_FIELD),
      updateDescription,
      stitchDocumentVersion,
      stitchDocumentHash,
      document.getBoolean(Fields.WRITE_PENDING_FIELD, BsonBoolean.FALSE).getValue());
}
 
Example 15
Source File: WhitelistProjector.java    From kafka-connect-mongodb with Apache License 2.0 4 votes vote down vote up
@Override
protected void doProjection(String field, BsonDocument doc) {

    //special case short circuit check for '**' pattern
    //this is essentially the same as not using
    //whitelisting at all but instead take the full record
    if(fields.contains(FieldProjector.DOUBLE_WILDCARD)) {
        return;
    }

    Iterator<Map.Entry<String, BsonValue>> iter = doc.entrySet().iterator();
    while(iter.hasNext()) {
        Map.Entry<String, BsonValue> entry = iter.next();

        String key = field.isEmpty() ? entry.getKey()
                : field + FieldProjector.SUB_FIELD_DOT_SEPARATOR + entry.getKey();
        BsonValue value = entry.getValue();

        if(!fields.contains(key)
                //NOTE: always keep the _id field
                && !key.equals(DBCollection.ID_FIELD_NAME)) {

            if(!checkForWildcardMatch(key))
                iter.remove();

        }

        if(value != null) {
            if(value.isDocument()) {
                //short circuit check to avoid recursion
                //if 'key.**' pattern exists
                String matchDoubleWildCard = key
                        + FieldProjector.SUB_FIELD_DOT_SEPARATOR
                        + FieldProjector.DOUBLE_WILDCARD;
                if(!fields.contains(matchDoubleWildCard)) {
                    doProjection(key, (BsonDocument)value);
                }
            }
            if(value.isArray()) {
                BsonArray values = (BsonArray)value;
                for(BsonValue v : values.getValues()) {
                    if(v != null && v.isDocument()) {
                        doProjection(key,(BsonDocument)v);
                    }
                }
            }
        }

    }
}
 
Example 16
Source File: BlacklistProjector.java    From kafka-connect-mongodb with Apache License 2.0 4 votes vote down vote up
@Override
protected void doProjection(String field, BsonDocument doc) {

    if(!field.contains(FieldProjector.SUB_FIELD_DOT_SEPARATOR)) {

        if(field.equals(FieldProjector.SINGLE_WILDCARD)
                || field.equals(FieldProjector.DOUBLE_WILDCARD)) {
            handleWildcard(field,"",doc);
            return;
        }

        //NOTE: never try to remove the _id field
        if(!field.equals(DBCollection.ID_FIELD_NAME))
            doc.remove(field);

        return;
    }

    int dotIdx = field.indexOf(FieldProjector.SUB_FIELD_DOT_SEPARATOR);
    String firstPart = field.substring(0,dotIdx);
    String otherParts = field.length() >= dotIdx
                            ? field.substring(dotIdx+1) : "";

    if(firstPart.equals(FieldProjector.SINGLE_WILDCARD)
        || firstPart.equals(FieldProjector.DOUBLE_WILDCARD)) {
        handleWildcard(firstPart,otherParts,doc);
        return;
    }

    BsonValue value = doc.get(firstPart);
    if(value != null) {
        if(value.isDocument()) {
            doProjection(otherParts, (BsonDocument)value);
        }
        if(value.isArray()) {
            BsonArray values = (BsonArray)value;
            for(BsonValue v : values.getValues()) {
                if(v != null && v.isDocument()) {
                    doProjection(otherParts,(BsonDocument)v);
                }
            }
        }
    }

}
 
Example 17
Source File: AllowListProjector.java    From mongo-kafka with Apache License 2.0 4 votes vote down vote up
@Override
protected void doProjection(final String field, final BsonDocument doc) {
  // special case short circuit check for '**' pattern
  // this is essentially the same as not using
  // whitelisting at all but instead take the full record
  if (getFields().contains(FieldProjector.DOUBLE_WILDCARD)) {
    return;
  }

  Iterator<Map.Entry<String, BsonValue>> iter = doc.entrySet().iterator();
  while (iter.hasNext()) {
    Map.Entry<String, BsonValue> entry = iter.next();
    String key =
        field.isEmpty()
            ? entry.getKey()
            : field + FieldProjector.SUB_FIELD_DOT_SEPARATOR + entry.getKey();
    BsonValue value = entry.getValue();

    // NOTE: always keep the _id field
    if ((!getFields().contains(key) && !key.equals(ID_FIELD)) && !checkForWildcardMatch(key)) {
      iter.remove();
    }

    if (value != null) {
      if (value.isDocument()) {
        // short circuit check to avoid recursion
        // if 'key.**' pattern exists
        String matchDoubleWildCard =
            key + FieldProjector.SUB_FIELD_DOT_SEPARATOR + FieldProjector.DOUBLE_WILDCARD;
        if (!getFields().contains(matchDoubleWildCard)) {
          doProjection(key, (BsonDocument) value);
        }
      }
      if (value.isArray()) {
        BsonArray values = (BsonArray) value;
        for (BsonValue v : values.getValues()) {
          if (v != null && v.isDocument()) {
            doProjection(key, (BsonDocument) v);
          }
        }
      }
    }
  }
}