org.bson.codecs.ValueCodecProvider Java Examples

The following examples show how to use org.bson.codecs.ValueCodecProvider. 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: SharedFongoResource.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean doInitialize(
    ResourceSpecifier aSpecifier, Map<String, Object> aAdditionalParams)
    throws ResourceInitializationException {
  // Work whether it's a list of DB Objects or a single
  if ("{}".equals(fongoData) || "[]".equals(fongoData) || Strings.isNullOrEmpty(fongoData)) {
    return true;
  }

  if (fongoData.trim().startsWith("[")) {
    CodecRegistry codecRegistry =
        CodecRegistries.fromProviders(
            Arrays.asList(
                new ValueCodecProvider(),
                new BsonValueCodecProvider(),
                new DocumentCodecProvider()));
    JsonReader reader = new JsonReader(fongoData);
    BsonArrayCodec arrayReader = new BsonArrayCodec(codecRegistry);

    BsonArray docArray = arrayReader.decode(reader, DecoderContext.builder().build());

    for (BsonValue doc : docArray.getValues()) {
      fongo
          .getDatabase(BALEEN)
          .getCollection(fongoCollection)
          .insertOne(Document.parse(doc.asDocument().toJson()));
    }
  } else if (fongoData.trim().startsWith("{")) {
    Document data = Document.parse(fongoData);
    fongo.getDatabase(BALEEN).getCollection(fongoCollection).insertOne(data);
  } else {
    getMonitor().error("Unsupported type");
    throw new ResourceInitializationException();
  }

  return true;
}