Java Code Examples for org.bson.BsonDocument#get()
The following examples show how to use
org.bson.BsonDocument#get() .
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: UpdateOneTimestampsStrategy.java From mongo-kafka with Apache License 2.0 | 6 votes |
@Override public WriteModel<BsonDocument> createWriteModel(final SinkDocument document) { BsonDocument vd = document .getValueDoc() .orElseThrow( () -> new DataException( "Error: cannot build the WriteModel since the value document was missing unexpectedly")); BsonDateTime dateTime = new BsonDateTime(Instant.now().toEpochMilli()); return new UpdateOneModel<>( new BsonDocument(ID_FIELD, vd.get(ID_FIELD)), new BsonDocument("$set", vd.append(FIELD_NAME_MODIFIED_TS, dateTime)) .append("$setOnInsert", new BsonDocument(FIELD_NAME_INSERTED_TS, dateTime)), UPDATE_OPTIONS); }
Example 2
Source File: CaptureUtil.java From epcis with Apache License 2.0 | 6 votes |
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 3
Source File: MongoReaderUtil.java From epcis with Apache License 2.0 | 6 votes |
static List<QuantityElementType> putQuantityElementTypeList(BsonArray quantityDBList) { List<QuantityElementType> qetList = new ArrayList<QuantityElementType>(); for (int i = 0; i < quantityDBList.size(); i++) { QuantityElementType qet = new QuantityElementType(); BsonDocument quantityDBObject = quantityDBList.get(i).asDocument(); BsonValue epcClassObject = quantityDBObject.get("epcClass"); BsonValue quantity = quantityDBObject.get("quantity"); BsonValue uom = quantityDBObject.get("uom"); if (epcClassObject != null) { qet.setEpcClass(epcClassObject.asString().getValue()); if (quantity != null) { double quantityDouble = quantity.asDouble().getValue(); qet.setQuantity(BigDecimal.valueOf(quantityDouble)); } if (uom != null) qet.setUom(uom.asString().getValue()); qetList.add(qet); } } return qetList; }
Example 4
Source File: UpdateOneTimestampsStrategy.java From kafka-connect-mongodb with Apache License 2.0 | 6 votes |
@Override public WriteModel<BsonDocument> createWriteModel(SinkDocument document) { BsonDocument vd = document.getValueDoc().orElseThrow( () -> new DataException("error: cannot build the WriteModel since" + " the value document was missing unexpectedly") ); BsonDateTime dateTime = new BsonDateTime(Instant.now().toEpochMilli()); return new UpdateOneModel<>( new BsonDocument(DBCollection.ID_FIELD_NAME, vd.get(DBCollection.ID_FIELD_NAME)), new BsonDocument("$set", vd.append(FIELDNAME_MODIFIED_TS, dateTime)) .append("$setOnInsert", new BsonDocument(FIELDNAME_INSERTED_TS, dateTime)), UPDATE_OPTIONS ); }
Example 5
Source File: CaptureUtil.java From epcis with Apache License 2.0 | 6 votes |
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: ReactiveMongoOperations.java From quarkus with Apache License 2.0 | 6 votes |
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 7
Source File: ResultDecoders.java From stitch-android-sdk with Apache License 2.0 | 6 votes |
public RemoteUpdateResult decode( final BsonReader reader, final DecoderContext decoderContext) { final BsonDocument document = (new BsonDocumentCodec()).decode(reader, decoderContext); keyPresent(Fields.MATCHED_COUNT_FIELD, document); keyPresent(Fields.MODIFIED_COUNT_FIELD, document); final long matchedCount = document.getNumber(Fields.MATCHED_COUNT_FIELD).longValue(); final long modifiedCount = document.getNumber(Fields.MODIFIED_COUNT_FIELD).longValue(); if (!document.containsKey(Fields.UPSERTED_ID_FIELD)) { return new RemoteUpdateResult(matchedCount, modifiedCount, null); } return new RemoteUpdateResult( matchedCount, modifiedCount, document.get(Fields.UPSERTED_ID_FIELD)); }
Example 8
Source File: BsonUtil.java From ditto with Eclipse Public License 2.0 | 6 votes |
/** * Allows to extract values from {@link Bson} objects by specifying a dot-separated path, * e.g. {@code thing.policyId}. * * <p>NOTE: Arrays are currently not supported.</p> * * @param bsonObj the Bson object. * @param path the path. * @param <T> the type to which the value will be cast. * @return the value or {@code null}. * @throws NullPointerException if any argument is {@code null}. * @throws ClassCastException if the value has not the expected type. */ @Nullable public static <T> T getValueByPath(final Bson bsonObj, final String path) { checkNotNull(bsonObj, "BSON object which provides the value"); checkNotNull(path, "path"); final BsonDocument doc = toBsonDocument(bsonObj); final List<String> paths = Arrays.asList(path.split("\\.")); if (paths.isEmpty()) { throw new IllegalArgumentException("Empty path not allowed"); } final String topLevelKey = paths.get(0); final String remainingPath = String.join(".", paths.subList(1, paths.size())); final BsonValue subBson = doc.get(topLevelKey); if (subBson == null) { return null; } else if (remainingPath.isEmpty()) { @SuppressWarnings("unchecked") final T result = (T) subBson; return result; } return getValueByPath((Bson) subBson, remainingPath); }
Example 9
Source File: MongoDbInsert.java From kafka-connect-mongodb with Apache License 2.0 | 6 votes |
@Override public WriteModel<BsonDocument> perform(SinkDocument doc) { BsonDocument valueDoc = doc.getValueDoc().orElseThrow( () -> new DataException("error: value doc must not be missing for insert operation") ); try { BsonDocument insertDoc = BsonDocument.parse( valueDoc.get(JSON_DOC_FIELD_PATH).asString().getValue() ); return new ReplaceOneModel<>( new BsonDocument(DBCollection.ID_FIELD_NAME, insertDoc.get(DBCollection.ID_FIELD_NAME)), insertDoc, UPDATE_OPTIONS ); } catch(Exception exc) { throw new DataException(exc); } }
Example 10
Source File: MongoOperations.java From quarkus with Apache License 2.0 | 6 votes |
private static void persistOrUpdate(MongoCollection 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))); } } collection.bulkWrite(bulk); }
Example 11
Source File: CachedChronoElement.java From epcis with Apache License 2.0 | 5 votes |
/** * @param timestamp * @param key * @return property value for the given key at the given timestamp */ public BsonValue getTimestampPropertyValue(final Long timestamp, final String key) { BsonDocument timestampProperties = getTimestampProperties(timestamp); if (timestampProperties != null) return (BsonValue) timestampProperties.get(key); return null; }
Example 12
Source File: ChronoElement.java From epcis with Apache License 2.0 | 5 votes |
/** * @param timestamp * @param key * @return property value for the given key at the given timestamp */ public BsonValue getTimestampPropertyValue(final Long timestamp, final String key) { BsonDocument timestampProperties = getTimestampProperties(timestamp, new String[] { key }); if (timestampProperties.containsKey(key)) return timestampProperties.get(key); else return null; }
Example 13
Source File: BsonGeneratorTest.java From immutables with Apache License 2.0 | 5 votes |
private static BsonValue writeAndReturnValue(IoConsumer<BsonGenerator> consumer) throws IOException { BsonDocumentWriter writer = new BsonDocumentWriter(new BsonDocument()); BsonGenerator generator = generatorFor(writer); generator.writeStartObject(); generator.writeFieldName("value"); consumer.accept(generator); generator.writeEndObject(); BsonDocument doc = writer.getDocument(); check(doc.keySet()).has("value"); return doc.get("value"); }
Example 14
Source File: MongoReaderUtil.java From epcis with Apache License 2.0 | 5 votes |
static List<QuantityElementType> putQuantityElementTypeList(BsonArray quantityDBList) { List<QuantityElementType> qetList = new ArrayList<QuantityElementType>(); for (int i = 0; i < quantityDBList.size(); i++) { QuantityElementType qet = new QuantityElementType(); BsonDocument quantityDBObject = quantityDBList.get(i).asDocument(); BsonValue epcClassObject = quantityDBObject.get("epcClass"); BsonValue quantity = quantityDBObject.get("quantity"); BsonValue uom = quantityDBObject.get("uom"); if (epcClassObject != null) { qet.setEpcClass(epcClassObject.asString().getValue()); if (quantity != null) { double quantityDouble = quantity.asDouble().getValue(); qet.setQuantity(BigDecimal.valueOf(quantityDouble)); } if (uom != null) qet.setUom(uom.asString().getValue()); qetList.add(qet); } } return qetList; }
Example 15
Source File: MongoReaderUtil.java From epcis with Apache License 2.0 | 5 votes |
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 16
Source File: ReactiveMongoOperations.java From quarkus with Apache License 2.0 | 5 votes |
private static Uni<Void> update(ReactiveMongoCollection collection, Object entity) { //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); BsonDocument query = new BsonDocument().append(ID, id); return collection.replaceOne(query, entity).onItem().ignore().andContinueWithNull(); }
Example 17
Source File: ReactiveMongoOperations.java From quarkus with Apache License 2.0 | 5 votes |
public static Uni<Void> delete(Object entity) { ReactiveMongoCollection collection = mongoCollection(entity); BsonDocument document = getBsonDocument(collection, entity); BsonValue id = document.get(ID); BsonDocument query = new BsonDocument().append(ID, id); return collection.deleteOne(query).onItem().ignore().andContinueWithNull(); }
Example 18
Source File: BsonParserTest.java From immutables with Apache License 2.0 | 4 votes |
private static BsonValue maybeUnwrap(BsonDocument document) { return document.containsKey("ignore") ? document.get("ignore") : document; }
Example 19
Source File: DataSynchronizer.java From stitch-android-sdk with Apache License 2.0 | 4 votes |
/** * Replaces a single synchronized document by its given id with the given full document * replacement. No replacement will occur if the _id is not being synchronized. * * @param nsConfig the namespace sync configuration of the namespace where the document lives. * @param documentId the _id of the document. * @param document the replacement document. */ @CheckReturnValue private LocalSyncWriteModelContainer updateOrUpsertOneFromResolution( final NamespaceSynchronizationConfig nsConfig, final BsonValue documentId, final BsonDocument document, final BsonDocument atVersion, final CompactChangeEvent<BsonDocument> remoteEvent ) { final MongoNamespace namespace = nsConfig.getNamespace(); final ChangeEvent<BsonDocument> event; final Lock lock = this.syncConfig.getNamespaceConfig(namespace).getLock().writeLock(); lock.lock(); final CoreDocumentSynchronizationConfig config; final BsonDocument docForStorage; try { config = syncConfig.getSynchronizedDocument(namespace, documentId); if (config == null) { return null; } // Remove forbidden fields from the resolved document before it will updated/upserted in the // local collection. docForStorage = sanitizeDocument(document); if (document.get("_id") == null && remoteEvent.getDocumentKey().get("_id") != null) { document.put("_id", remoteEvent.getDocumentKey().get("_id")); } if (remoteEvent.getOperationType() == OperationType.DELETE) { event = ChangeEvents.changeEventForLocalInsert(namespace, docForStorage, true); } else { if (remoteEvent.getFullDocument() != null) { event = ChangeEvents.changeEventForLocalUpdate( namespace, documentId, sanitizeUpdateDescription(UpdateDescription.diff( sanitizeDocument(remoteEvent.getFullDocument()), docForStorage)), docForStorage, true); } else { // We can't compute an update description here since we don't know what the remote full // document looks like. This means that if rules prevent us from writing to the entire // document, we would need to fetch the document to compute the update description, which // is not something we want to do. One potential option to get around this would be to // change the server-side logic for replaces to add a "merge" argument, that would // translate the replace sent by this client to an update that only modifies the fields // it has the permission to see. // See STITCH-2888 event = ChangeEvents.changeEventForLocalReplace( namespace, documentId, document, true ); } } } finally { lock.unlock(); } config.setSomePendingWrites( logicalT, atVersion, HashUtils.hash(docForStorage), event); final LocalSyncWriteModelContainer syncWriteModelContainer = newWriteModelContainer(nsConfig); syncWriteModelContainer.addDocIDs(documentId); syncWriteModelContainer.addLocalWrite( new ReplaceOneModel<>(getDocumentIdFilter(documentId), docForStorage, new ReplaceOptions().upsert(true))); syncWriteModelContainer.addLocalChangeEvent(event); syncWriteModelContainer.addConfigWrite( new ReplaceOneModel<>(CoreDocumentSynchronizationConfig.getDocFilter( namespace, config.getDocumentId()), config)); return syncWriteModelContainer; }
Example 20
Source File: MongoReaderUtil.java From epcis with Apache License 2.0 | 4 votes |
static EPCISEventExtensionType putEPCISExtension(EPCISEventExtensionType object, BsonDocument extension) { /* * Extension of extension may be deprecated if (extension.get("any") != * null) { BsonDocument anyObject = extension.getDocument("any"); // Get * Namespaces Iterator<String> anyKeysIterN = * anyObject.keySet().iterator(); Map<String, String> nsMap = new * HashMap<String, String>(); while (anyKeysIterN.hasNext()) { String * anyKeyN = anyKeysIterN.next(); String valueN = * anyObject.getString(anyKeyN).getValue(); if (anyKeyN.startsWith("@")) * { nsMap.put(anyKeyN.substring(1, anyKeyN.length()), valueN); } } // * Process Any Iterator<String> anyKeysIter = * anyObject.keySet().iterator(); List<Object> elementList = new * ArrayList<Object>(); while (anyKeysIter.hasNext()) { String anyKey = * anyKeysIter.next(); if (anyKey.startsWith("@")) continue; String * value = anyObject.get(anyKey).toString(); // Get Namespace String[] * anyKeyCheck = anyKey.split(":"); String namespace = null; String * namespaceURI = null; if (anyKeyCheck.length == 2) { namespace = * anyKeyCheck[0]; namespaceURI = nsMap.get(namespace).toString(); } if * (anyKey != null && value != null) { DocumentBuilderFactory dbf = * DocumentBuilderFactory.newInstance(); DocumentBuilder builder = * dbf.newDocumentBuilder(); Document doc = builder.newDocument(); * * Node node = doc.createElement("value"); node.setTextContent(value); * Element element = doc.createElement(anyKey); if (namespace != null) { * element.setAttribute("xmlns:" + namespace, namespaceURI); } * element.appendChild(node); elementList.add(element); } } * object.setAny(elementList); } */ if (extension.get("otherAttributes") != null) { Map<QName, String> otherAttributes = new HashMap<QName, String>(); BsonDocument otherAttributeObject = extension.getDocument("otherAttributes"); Iterator<String> otherKeysIter = otherAttributeObject.keySet().iterator(); while (otherKeysIter.hasNext()) { String anyKey = otherKeysIter.next(); String value = otherAttributeObject.getString(anyKey).getValue(); otherAttributes.put(new QName("", anyKey), value); } object.setOtherAttributes(otherAttributes); } return object; }