org.bson.BsonValue Java Examples

The following examples show how to use org.bson.BsonValue. 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: 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 #2
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 #3
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 #4
Source File: UpdateDescription.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Unilaterally merge an update description into this update description.
 * @param otherDescription the update description to merge into this
 * @return this merged update description
 */
public UpdateDescription merge(@Nullable final UpdateDescription otherDescription) {
  if (otherDescription != null) {
    for (final Map.Entry<String, BsonValue> entry : this.updatedFields.entrySet()) {
      if (otherDescription.removedFields.contains(entry.getKey())) {
        this.updatedFields.remove(entry.getKey());
      }
    }
    for (final String removedField : this.removedFields) {
      if (otherDescription.updatedFields.containsKey(removedField)) {
        this.removedFields.remove(removedField);
      }
    }

    this.removedFields.addAll(otherDescription.removedFields);
    this.updatedFields.putAll(otherDescription.updatedFields);
  }

  return this;
}
 
Example #5
Source File: CaptureUtil.java    From epcis with Apache License 2.0 6 votes vote down vote up
private BsonDocument convertToExtensionDocument(Map<String, String> namespaces, BsonDocument extension) {
	BsonDocument ext = new BsonDocument();
	for (String key : extension.keySet()) {
		String[] namespaceAndKey = key.split("#");
		if (namespaceAndKey.length != 2)
			continue;
		String namespace = namespaceAndKey[0];
		if (!namespaces.containsKey(namespace))
			continue;
		ext.put("@" + encodeMongoObjectKey(namespace), new BsonString(namespaces.get(namespace)));
		BsonValue extValue = extension.get(key);
		if (extValue instanceof BsonDocument) {
			ext.put(encodeMongoObjectKey(key), convertToExtensionDocument(namespaces, extValue.asDocument()));
		} else {
			ext.put(encodeMongoObjectKey(key), extValue);
		}
	}
	return ext;
}
 
Example #6
Source File: DecimalFieldConverter.java    From mongo-kafka with Apache License 2.0 6 votes vote down vote up
@Override
public BsonValue toBson(final Object data) {
  if (data instanceof BigDecimal) {
    if (format.equals(Format.DECIMAL128)) {
      return new BsonDecimal128(new Decimal128((BigDecimal) data));
    }
    if (format.equals(Format.LEGACYDOUBLE)) {
      return new BsonDouble(((BigDecimal) data).doubleValue());
    }
  }

  throw new DataException(
      "Error: decimal conversion not possible when data is of type "
          + data.getClass().getName()
          + " and format is "
          + format);
}
 
Example #7
Source File: DataSynchronizer.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a synthesized change event for a remote document.
 *
 * @param ns         the namspace where the document lives.
 * @param documentId the _id of the document.
 * @param document   the remote document.
 * @return a synthesized change event for a remote document.
 */
private CompactChangeEvent<BsonDocument> getSynthesizedRemoteChangeEventForDocument(
    final MongoNamespace ns,
    final BsonValue documentId,
    final BsonDocument document
) {
  // a. When the document is looked up, if it cannot be found the synthesized change event is a
  // DELETE, otherwise it's a REPLACE.
  if (document == null) {
    return ChangeEvents.compactChangeEventForLocalDelete(
        documentId,
        false // when synthesizing remote events, writes shouldn't be pending
    );
  }
  return ChangeEvents.compactChangeEventForLocalReplace(documentId, document, false);
}
 
Example #8
Source File: ReactiveMongoOperations.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static Uni<Void> persistOrUpdate(ReactiveMongoCollection collection, List<Object> entities) {
    //this will be an ordered bulk: it's less performant than a unordered one but will fail at the first failed write
    List<WriteModel> bulk = new ArrayList<>();
    for (Object entity : entities) {
        //we transform the entity as a document first
        BsonDocument document = getBsonDocument(collection, entity);

        //then we get its id field and create a new Document with only this one that will be our replace query
        BsonValue id = document.get(ID);
        if (id == null) {
            //insert with autogenerated ID
            bulk.add(new InsertOneModel(entity));
        } else {
            //insert with user provided ID or update
            BsonDocument query = new BsonDocument().append(ID, id);
            bulk.add(new ReplaceOneModel(query, entity,
                    new ReplaceOptions().upsert(true)));
        }
    }

    return collection.bulkWrite(bulk).onItem().ignore().andContinueWithNull();
}
 
Example #9
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 #10
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 #11
Source File: LocalSyncWriteModelContainer.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
boolean wrapForRecovery(final Callable<Boolean> callable) {
  final List<BsonValue> idsAsList = new ArrayList<>();
  idsAsList.addAll(ids);

  final List<BsonDocument> oldDocs = localCollection.find(
      new BsonDocument("_id", new BsonDocument("$in", new BsonArray(idsAsList)))
  ).into(new ArrayList<>());

  if (oldDocs.size() > 0) {
    undoCollection.insertMany(oldDocs);
  }

  boolean result;
  try {
    result = callable.call();
  } catch (Exception e) {
    result = false;
  }

  if (result && oldDocs.size() > 0) {
    undoCollection.deleteMany(new Document("_id", new Document("$in", ids)));
  }

  return result;
}
 
Example #12
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 #13
Source File: IdStrategyTest.java    From mongo-kafka with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("test PartialKeyStrategy with Block List")
void testPartialKeyStrategyBlockList() {
  BsonDocument keyDoc = BsonDocument.parse("{keyPart1: 123, keyPart2: 'ABC', keyPart3: true}");
  BsonDocument expected = BsonDocument.parse("{keyPart2: 'ABC', keyPart3: true}");

  MongoSinkTopicConfig cfg =
      createTopicConfig(
          format(
              "{'%s': '%s', '%s': 'keyPart1'}",
              DOCUMENT_ID_STRATEGY_PARTIAL_KEY_PROJECTION_TYPE_CONFIG,
              BLOCKLIST,
              DOCUMENT_ID_STRATEGY_PARTIAL_KEY_PROJECTION_LIST_CONFIG));

  IdStrategy ids = new PartialKeyStrategy();
  ids.configure(cfg);
  SinkDocument sd = new SinkDocument(keyDoc, null);
  BsonValue id = ids.generateId(sd, null);

  assertAll(
      "id checks",
      () -> assertTrue(id instanceof BsonDocument),
      () -> assertEquals(expected, id.asDocument()));
  assertEquals(new BsonDocument(), ids.generateId(new SinkDocument(null, null), null));
}
 
Example #14
Source File: ChangeEvents.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a change event for a local update of a document in the given namespace referring
 * to the given document _id.
 *
 * @param documentId the _id of the document that was updated.
 * @param updateDescription the update specifier.
 * @param documentVersion the version document for the document version after this update.
 * @param documentHash the hash of this document (sanitized) after the update
 * @return a change event for a local update of a document in the given namespace referring
 *         to the given document _id.
 */
static CompactChangeEvent<BsonDocument> compactChangeEventForLocalUpdate(
    final BsonValue documentId,
    final UpdateDescription updateDescription,
    final BsonDocument documentVersion,
    final Long documentHash,
    final boolean writePending
) {
  return new CompactChangeEvent<>(
      OperationType.UPDATE,
      null,
      new BsonDocument("_id", documentId),
      updateDescription,
      (documentVersion == null)
          ? null
          : DocumentVersionInfo.Version.fromBsonDocument(documentVersion),
      documentHash,
      writePending);
}
 
Example #15
Source File: PartialKeyStrategy.java    From kafka-connect-mongodb with Apache License 2.0 5 votes vote down vote up
@Override
public BsonValue generateId(SinkDocument doc, SinkRecord orig) {

    fieldProjector.process(doc,orig);
    //NOTE: If there is no key doc present the strategy
    //simply returns an empty BSON document per default.
    return doc.getKeyDoc().orElseGet(() -> new BsonDocument());

}
 
Example #16
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 #17
Source File: TriggerEngine.java    From epcis with Apache License 2.0 5 votes vote down vote up
private static Set<String> addEPCtoSet(Set<String> epcSet, BsonArray epcList) {
	Iterator<BsonValue> epcIterator = epcList.iterator();
	while (epcIterator.hasNext()) {
		BsonDocument epcDocument = epcIterator.next().asDocument();
		epcSet.add(epcDocument.getString("epc").getValue());
	}
	return epcSet;
}
 
Example #18
Source File: AbstractMongoSnapshotAdapter.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private static JsonObject convertSnapshotEntityToJson(final Object rawSnapshotEntity) {
    checkNotNull(rawSnapshotEntity, "raw snapshot entity");
    if (rawSnapshotEntity instanceof BsonValue) {
        return convertToJson((BsonValue) rawSnapshotEntity);
    }
    final String pattern = "Unable to create a Jsonifiable from <{0}>! Expected was a BsonDocument instance.";
    throw new IllegalArgumentException(MessageFormat.format(pattern, rawSnapshotEntity.getClass()));
}
 
Example #19
Source File: Operations.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
<ResultT> WatchOperation<ResultT> watch(
    final Set<BsonValue> ids,
    final boolean useCompactEvents,
    final Class<ResultT> resultClass) {
  return new WatchOperation<>(
      namespace,
      ids,
      useCompactEvents,
      codecRegistry.get(resultClass)
  );
}
 
Example #20
Source File: MongoReaderUtil.java    From epcis with Apache License 2.0 5 votes vote down vote up
static EPCISEventExtensionType putEPCISEventExtensionType(BsonDocument dbObject, int zone) {
	EPCISEventExtensionType eeet = new EPCISEventExtensionType();
	if (dbObject.get("eventID") != null) {
		eeet.setEventID(dbObject.getString("eventID").getValue());
	} else {
		if (dbObject.containsKey("_id")) {
			eeet.setEventID(dbObject.getObjectId("_id").getValue().toHexString());
		}
	}
	if (dbObject.get("errorDeclaration") != null) {
		ErrorDeclarationType edt = new ErrorDeclarationType();
		BsonDocument error = dbObject.getDocument("errorDeclaration");
		if (error.containsKey("declarationTime")) {
			edt.setDeclarationTime(getXMLGregorianCalendar(error.getDateTime("declarationTime")));
		}
		if (error.containsKey("reason")) {
			edt.setReason(error.getString("reason").getValue());
		}
		if (error.containsKey("correctiveEventIDs")) {
			BsonArray correctiveEventIDs = error.getArray("correctiveEventIDs");
			List<String> correctiveIDs = new ArrayList<String>();
			Iterator<BsonValue> cIDIterator = correctiveEventIDs.iterator();
			while (cIDIterator.hasNext()) {
				String cID = cIDIterator.next().asString().getValue();
				correctiveIDs.add(cID);
			}
			if (correctiveIDs.size() != 0) {
				CorrectiveEventIDsType ceit = new CorrectiveEventIDsType();
				ceit.setCorrectiveEventID(correctiveIDs);
				edt.setCorrectiveEventIDs(ceit);
			}
		}
		if (error.containsKey("any")) {
			edt.setAny(putAny(error.getDocument("any"), null));
		}
		eeet.setErrorDeclaration(edt);
	}
	return eeet;
}
 
Example #21
Source File: ChangeEvent.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Serializes this change event into a {@link BsonDocument}.
 * @return the serialized document.
 */
@Override
public BsonDocument toBsonDocument() {
  final BsonDocument asDoc = new BsonDocument();
  asDoc.put(Fields.ID_FIELD, id);

  asDoc.put(Fields.OPERATION_TYPE_FIELD, new BsonString(getOperationType().toRemote()));

  final BsonDocument nsDoc = new BsonDocument();
  nsDoc.put(Fields.NS_DB_FIELD, new BsonString(ns.getDatabaseName()));
  nsDoc.put(Fields.NS_COLL_FIELD, new BsonString(getNamespace().getCollectionName()));
  asDoc.put(Fields.NS_FIELD, nsDoc);

  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());
  }

  asDoc.put(Fields.WRITE_PENDING_FIELD, new BsonBoolean(hasUncommittedWrites()));
  return asDoc;
}
 
Example #22
Source File: CoreDocumentSynchronizationConfig.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
public BsonValue getDocumentId() {
  docLock.readLock().lock();
  try {
    return documentId;
  } finally {
    docLock.readLock().unlock();
  }
}
 
Example #23
Source File: VertexEvent.java    From epcis with Apache License 2.0 5 votes vote down vote up
/**
 * set key value only active at the timestamp or interval
 * 
 * @param key
 * @param value
 */
@Override
public void setProperty(String key, Object value) {
	if (!(value instanceof BsonValue))
		throw ExceptionFactory.propertyValueShouldBeInstanceOfBsonValue();
	else
		vertex.setTimestampProperty(timestamp, key, (BsonValue) value);
}
 
Example #24
Source File: ResultDecoders.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
public RemoteInsertManyResult decode(
    final BsonReader reader,
    final DecoderContext decoderContext
) {
  final BsonDocument document = (new BsonDocumentCodec()).decode(reader, decoderContext);
  keyPresent(Fields.INSERTED_IDS_FIELD, document);
  final BsonArray arr = document.getArray(Fields.INSERTED_IDS_FIELD);
  final Map<Long, BsonValue> insertedIds = new HashMap<>();
  for (int i = 0; i < arr.size(); i++) {
    insertedIds.put((long) i, arr.get(i));
  }

  return new RemoteInsertManyResult(insertedIds);
}
 
Example #25
Source File: Jsons.java    From immutables with Apache License 2.0 5 votes vote down vote up
/**
 * Creates reader for position at {@code value}
 */
static JsonReader readerAt(BsonValue value) throws IOException {
  BsonDocument doc = new BsonDocument("value", value);
  BsonReader reader = new BsonReader(new BsonDocumentReader(doc));
  // advance AFTER value token
  reader.beginObject();
  check(reader.peek()).is(JsonToken.NAME);
  check(reader.nextName()).is("value");
  return reader;
}
 
Example #26
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 #27
Source File: DecimalFieldConverter.java    From kafka-connect-mongodb with Apache License 2.0 5 votes vote down vote up
@Override
public BsonValue toBson(Object data) {

    if(data instanceof BigDecimal) {
        if(format.equals(Format.DECIMAL128))
            return new BsonDecimal128(new Decimal128((BigDecimal)data));

        if(format.equals(Format.LEGACYDOUBLE))
            return new BsonDouble(((BigDecimal)data).doubleValue());
    }

    throw new DataException("error: decimal conversion not possible when data is"
                    + " of type "+data.getClass().getName() + " and format is "+format);

}
 
Example #28
Source File: ClientEncryptionImpl.java    From mongo-java-driver-reactivestreams with Apache License 2.0 5 votes vote down vote up
@Override
public Publisher<BsonBinary> encrypt(final BsonValue value, final EncryptOptions options) {
    return new ObservableToPublisher<BsonBinary>(com.mongodb.async.client.Observables.observe(
            new Block<com.mongodb.async.SingleResultCallback<BsonBinary>>(){
                @Override
                public void apply(final com.mongodb.async.SingleResultCallback<BsonBinary> callback) {
                    wrapped.encrypt(value, options, callback);
                }
            }));
}
 
Example #29
Source File: DataSynchronizer.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the resolution of resolving the conflict between a local and remote event using
 * the given conflict resolver.
 *
 * @param conflictResolver the conflict resolver to use.
 * @param documentId       the document id related to the conflicted events.
 * @param localEvent       the conflicted local event.
 * @param remoteEvent      the conflicted remote event.
 * @return the resolution to the conflict.
 */
@SuppressWarnings("unchecked")
private Object resolveConflictWithResolver(
    final ConflictHandler conflictResolver,
    final MongoNamespace ns,
    final BsonValue documentId,
    final ChangeEvent localEvent,
    final CompactChangeEvent remoteEvent
) {
  final ConflictResolution resolution = conflictResolver.resolveConflict(
      documentId,
      localEvent,
      remoteEvent);

  switch (resolution.getType()) {
    case FROM_LOCAL:
      return localEvent.getFullDocument();
    case FROM_REMOTE:
      if (remoteEvent.getOperationType() == OperationType.UPDATE) {
        // we can compute the remote full document by fetching the full document
        return this.getRemoteCollection(ns).findOne(getDocumentIdFilter(documentId));
      } else {
        // for inserts, replaces, and deletes, we always want the full document in the remote
        // update since it will be populated for inserts and replaced and null for deletes
        return remoteEvent.getFullDocument();
      }
    case WITH_DOCUMENT:
      return ((ConflictResolution.WithDocument) resolution).getFullDocumentForResolution();
    default:
      throw new IllegalStateException("unknown conflict resolution type");
  }
}
 
Example #30
Source File: EntityCodec.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
@Override
public BsonValue getDocumentId(T document) {
    Object id = idHandler.get(document);
    if (id instanceof ObjectId) return new BsonObjectId((ObjectId) id);
    if (id instanceof String) new BsonString((String) id);
    throw new Error(format("unsupported id type, id={}", id));
}