@Test public void testCustomizedBsonConverter() throws Exception { BsonValueConverterRepertory.registerCustomizedBsonConverter(String.class, new AbstractBsonConverter<String, BsonString>() { @Override public String decode(BsonReader bsonReader) { return "replace string"; } @Override public void encode(BsonWriter bsonWriter, String value) { } @Override public String decode(BsonValue bsonValue) { return "replace string"; } @Override public BsonString encode(String object) { return new BsonString("replace string"); } }); readFrom(); }
public static BsonDocument getBsonDocument() { BsonDocument bsonObj = new BsonDocument().append("testDouble", new BsonDouble(20.777)); List<BsonDocument> list = new ArrayList<BsonDocument>(); list.add(bsonObj); list.add(bsonObj); byte[] bytes = new byte[3]; bytes[0] = 3; bytes[1] = 2; bytes[2] = 1; BsonDocument bsonDocument = new BsonDocument().append("testDouble", new BsonDouble(20.99)) .append("testString", new BsonString("testStringV")) .append("testArray", new BsonArray(list)); return new BsonDocument().append("testDouble", new BsonDouble(20.99)) .append("testString", new BsonString("testStringV")) .append("testArray", new BsonArray(list)) .append("bson_test", bsonDocument) .append("testBinary", new BsonBinary(bytes)) .append("testBsonUndefined", new BsonUndefined()) .append("testObjectId", new BsonObjectId()) .append("testStringObjectId", new BsonObjectId()) .append("testBoolean", new BsonBoolean(true)) .append("testDate", new BsonDateTime(time)) .append("testNull", new BsonNull()) .append("testInt", new BsonInt32(233)) .append("testLong", new BsonInt64(233332)); }
@Test public void testBsonDocumentDeSerialize() { BsonDocument document = new BsonDocument().append("a", new BsonString("MongoDB")) .append("b", new BsonArray(Arrays.asList(new BsonInt32(1), new BsonInt32(2)))) .append("c", new BsonBoolean(true)) .append("d", new BsonDateTime(0)); String json = oson.useAttribute(false).setValueOnly(true).serialize(document); String expected = "{\"a\":\"MongoDB\",\"b\":[1,2],\"c\":true,\"d\":0}"; assertEquals(expected, json); BsonDocument document2 = oson.deserialize(json, BsonDocument.class); assertEquals(expected, oson.serialize(document2)); }
private BsonValue fromGridRef(SmofGridRef fileRef, PrimaryField fieldOpts) { if(fileRef.isEmpty()) { return new BsonNull(); } if(fileRef.getId() == null) { final SmofObject annotation = fieldOpts.getSmofAnnotationAs(SmofObject.class); if(fileRef.getBucketName() == null) { fileRef.setBucketName(annotation.bucketName()); } //TODO test if upload file adds id to fileRef if(!annotation.preInsert() && !fieldOpts.isForcePreInsert()) { return new BsonLazyObjectId(fieldOpts.getName(), fileRef); } fieldOpts.setForcePreInsert(false); dispatcher.insert(fileRef); } final BsonDocument bsonRef = new BsonDocument("id", new BsonObjectId(fileRef.getId())) .append("bucket", new BsonString(fileRef.getBucketName())); return bsonRef; }
@Override public Optional<Event> get(final RyaURI subject) throws EventStorageException { requireNonNull(subject); try { final Document document = mongo.getDatabase(ryaInstanceName) .getCollection(COLLECTION_NAME) .find( new BsonDocument(EventDocumentConverter.SUBJECT, new BsonString(subject.getData())) ) .first(); return document == null ? Optional.empty() : Optional.of( EVENT_CONVERTER.fromDocument(document) ); } catch(final MongoException | DocumentConverterException e) { throw new EventStorageException("Could not get the Event with Subject '" + subject.getData() + "'.", e); } }
@SuppressWarnings({"rawtypes", "unchecked"}) @Before public void setUp() throws Exception { interceptor = new MongoDBMethodInterceptor(); Config.Plugin.MongoDB.TRACE_PARAM = true; when(enhancedInstance.getSkyWalkingDynamicField()).thenReturn("127.0.0.1:27017"); BsonDocument document = new BsonDocument(); document.append("name", new BsonString("by")); MongoNamespace mongoNamespace = new MongoNamespace("test.user"); Decoder decoder = PowerMockito.mock(Decoder.class); FindOperation findOperation = new FindOperation(mongoNamespace, decoder); findOperation.filter(document); arguments = new Object[] {findOperation}; argumentTypes = new Class[] {findOperation.getClass()}; }
/** * set timestamp properties (replace) for the given timestamp * * @param timestamp * @param timestampProperties */ public void setTimestampProperties(final Long timestamp, BsonDocument timestampProperties) { if (timestampProperties == null) timestampProperties = new BsonDocument(); if (this instanceof ChronoVertex) { graph.getVertexEvents().findOneAndReplace( new BsonDocument(Tokens.VERTEX, new BsonString(this.id)).append(Tokens.TIMESTAMP, new BsonDateTime(timestamp)), Converter.makeTimestampVertexEventDocumentWithoutID(timestampProperties, this.id, timestamp), new FindOneAndReplaceOptions().upsert(true)); } else { ChronoEdge e = (ChronoEdge) this; graph.getEdgeEvents().findOneAndReplace( new BsonDocument(Tokens.OUT_VERTEX, new BsonString(e.getOutVertex().toString())) .append(Tokens.LABEL, new BsonString(e.getLabel())) .append(Tokens.TIMESTAMP, new BsonDateTime(timestamp)) .append(Tokens.IN_VERTEX, new BsonString(e.getInVertex().toString())), Converter.makeTimestampEdgeEventDocumentWithoutID(timestampProperties, this.id, timestamp), new FindOneAndReplaceOptions().upsert(true)); } }
@Test public void testGetUriWithFilterManyIdsWithSpaces() { BsonValue[] ids = new BsonValue[]{ new BsonString("Three Imaginary Boys"), new BsonString("Seventeen Seconds") }; RequestContext context = prepareRequestContext(); String expResult = "/dbName/collName?filter={'_id':{'$in':[\'Three Imaginary Boys\','Seventeen Seconds\']}}"; String result; try { result = URLUtils.getUriWithFilterMany(context, "dbName", "collName", ids); assertEquals(expResult, result); } catch (UnsupportedDocumentIdException ex) { fail(ex.getMessage()); } }
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; }
public static void addSpecialProperties(final Representation rep, RequestContext.TYPE type, BsonDocument data) { rep.addProperty("_type", new BsonString(type.name())); Object etag = data.get("_etag"); if (etag != null && etag instanceof ObjectId) { if (data.get("_lastupdated_on") == null) { // add the _lastupdated_on in case the _etag field is present and its value is an ObjectId rep.addProperty("_lastupdated_on", new BsonString(Instant.ofEpochSecond(((ObjectId) etag).getTimestamp()).toString())); } } Object id = data.get("_id"); // generate the _created_on timestamp from the _id if this is an instance of ObjectId if (data.get("_created_on") == null && id != null && id instanceof ObjectId) { rep.addProperty("_created_on", new BsonString(Instant.ofEpochSecond(((ObjectId) id).getTimestamp()).toString())); } }
public List<String> getSubscriptionIDs(String queryName) { List<String> retList = new ArrayList<String>(); MongoCollection<BsonDocument> collection = Configuration.mongoDatabase.getCollection("Subscription", BsonDocument.class); Iterator<BsonDocument> subIterator = collection .find(new BsonDocument("pollParameters.queryName", new BsonString(queryName)), BsonDocument.class) .iterator(); while (subIterator.hasNext()) { BsonDocument subscription = subIterator.next(); retList.add(subscription.getString("subscriptionID").asString().getValue()); } return retList; }
public BsonDocument putOutputQuantityList(BsonDocument base, List<QuantityElement> outputQuantityList) { BsonArray quantityArray = new BsonArray(); for (QuantityElement quantityElement : outputQuantityList) { BsonDocument bsonQuantityElement = new BsonDocument("epcClass", new BsonString(quantityElement.getEpcClass())); if (quantityElement.getQuantity() != null) { bsonQuantityElement.put("quantity", new BsonDouble(quantityElement.getQuantity())); } if (quantityElement.getUom() != null) { bsonQuantityElement.put("uom", new BsonString(quantityElement.getUom())); } quantityArray.add(bsonQuantityElement); } base.put("outputQuantityList", quantityArray); return base; }
static BsonDocument getINFamilyQueryObject(String type, String field, String csv) { String[] paramValueArr = csv.split(","); BsonArray subObjectList = new BsonArray(); for (int i = 0; i < paramValueArr.length; i++) { String val = paramValueArr[i].trim(); BsonDocument dbo = new BsonDocument(); dbo.put(type, new BsonString(val)); subObjectList.add(dbo); } if (subObjectList.isEmpty() == false) { BsonDocument query = new BsonDocument(); query.put(field, new BsonDocument("$in", subObjectList)); return query; } return null; }
public void unsubscribe(String subscriptionID) { MongoCollection<BsonDocument> collection = Configuration.mongoDatabase.getCollection("Subscription", BsonDocument.class); // Its size should be 0 or 1 BsonDocument s = collection .findOneAndDelete(new BsonDocument("subscriptionID", new BsonString(subscriptionID))); if (s != null) { SubscriptionType subscription = new SubscriptionType(s); if (subscription.isScheduledSubscription() == true) { // Remove from current Quartz removeScheduleFromQuartz(subscription); }else{ TriggerEngine.removeTriggerSubscription(subscription.getSubscriptionID()); } } }
public static BsonDocument getBsonGeoPoint(String pointString) { try { BsonDocument pointDoc = new BsonDocument(); pointDoc.put("type", new BsonString("Point")); String[] pointArr = pointString.split(","); if (pointArr.length != 2) return null; BsonArray arr = new BsonArray(); arr.add(new BsonDouble(Double.parseDouble(pointArr[0]))); arr.add(new BsonDouble(Double.parseDouble(pointArr[1]))); pointDoc.put("coordinates", arr); return pointDoc; } catch (NumberFormatException e) { e.printStackTrace(); return null; } }
private static BsonValue converseType(String value) { String[] valArr = value.split("\\^"); if (valArr.length != 2) { return new BsonString(value); } try { String type = valArr[1]; if (type.equals("int")) { return new BsonInt32(Integer.parseInt(valArr[0])); } else if (type.equals("long")) { return new BsonInt64(Long.parseLong(valArr[0])); } else if (type.equals("double")) { return new BsonDouble(Double.parseDouble(valArr[0])); } else if (type.equals("boolean")) { return new BsonBoolean(Boolean.parseBoolean(valArr[0])); } else { return new BsonString(value); } } catch (NumberFormatException e) { return new BsonString(value); } }
private boolean addNamedEventQueryToDB(String name, String description, PollParameters p) { MongoCollection<BsonDocument> namedEventQueryCollection = Configuration.mongoDatabase.getCollection("NamedEventQuery", BsonDocument.class); MongoCollection<BsonDocument> eventDataCollection = Configuration.mongoDatabase.getCollection("EventData", BsonDocument.class); BsonDocument existingDoc = namedEventQueryCollection.find(new BsonDocument("name", new BsonString(name))).first(); if (existingDoc == null) { BsonDocument bson = PollParameters.asBsonDocument(p); bson.put("name", new BsonString(name)); bson.put("description", new BsonString(description)); namedEventQueryCollection.insertOne(bson); } else { return false; } // Create Index with the given NamedEventQuery name and background option IndexOptions indexOptions = new IndexOptions().name(name).background(true); BsonDocument indexDocument = makeIndexObject(p); eventDataCollection.createIndex(indexDocument, indexOptions); Configuration.logger.log(Level.INFO, "NamedEventQuery: " + name + " is added to DB. "); return true; }
public BsonDocument putInputQuantityList(BsonDocument base, List<QuantityElement> inputQuantityList) { BsonArray quantityArray = new BsonArray(); for (QuantityElement quantityElement : inputQuantityList) { BsonDocument bsonQuantityElement = new BsonDocument("epcClass", new BsonString(quantityElement.getEpcClass())); if (quantityElement.getQuantity() != null) { bsonQuantityElement.put("quantity", new BsonDouble(quantityElement.getQuantity())); } if (quantityElement.getUom() != null) { bsonQuantityElement.put("uom", new BsonString(quantityElement.getUom())); } quantityArray.add(bsonQuantityElement); } base.put("inputQuantityList", quantityArray); return base; }
public List<String> getSubscriptionIDs(String queryName) { List<String> retList = new ArrayList<String>(); MongoCollection<BsonDocument> collection = Configuration.mongoDatabase.getCollection("Subscription", BsonDocument.class); Iterator<BsonDocument> subIterator = collection .find(new BsonDocument("queryName", new BsonString(queryName)), BsonDocument.class).iterator(); while (subIterator.hasNext()) { BsonDocument subscription = subIterator.next(); retList.add(subscription.getString("subscriptionID").asString().getValue()); } return retList; }
public String getSubscriptionIDsREST(@PathVariable String queryName) { JSONArray retArray = new JSONArray(); MongoCollection<BsonDocument> collection = Configuration.mongoDatabase.getCollection("Subscription", BsonDocument.class); Iterator<BsonDocument> subIterator = collection .find(new BsonDocument("queryName", new BsonString(queryName)), BsonDocument.class).iterator(); while (subIterator.hasNext()) { BsonDocument subscription = subIterator.next(); retArray.put(subscription.getString("subscriptionID").asString()); } return retArray.toString(1); }
/** * @deprecated internal method of getEdges */ @Deprecated private Iterable<Edge> getOutEdges(final String... labels) { HashSet<Edge> edgeSet = new HashSet<Edge>(); BsonDocument filter = new BsonDocument(); BsonDocument inner = new BsonDocument(); filter.put("_outV", new BsonString(this.toString())); inner.put("$in", Converter.getBsonArrayOfBsonString(labels)); filter.put("_label", inner); Iterator<BsonDocument> it = graph.getEdgeCollection().find(filter).iterator(); while (it.hasNext()) { BsonDocument d = it.next(); edgeSet.add(new ChronoEdge(d.getString("_id").getValue(), this.graph)); } return edgeSet; }
private void updateInitialRecordTime(String subscriptionID, String initialRecordTime) { MongoCollection<BsonDocument> collection = Configuration.mongoDatabase.getCollection("Subscription", BsonDocument.class); BsonDocument subscription = collection.find(new BsonDocument("subscriptionID", new BsonString(subscriptionID))) .first(); subscription.put("initialRecordTime", new BsonString(initialRecordTime)); if (subscription != null) { collection.findOneAndReplace(new BsonDocument("subscriptionID", new BsonString(subscriptionID)), subscription); } Configuration.logger.log(Level.INFO, "InitialRecordTime of Subscription ID: " + subscriptionID + " is updated to DB. "); }
public BsonDocument putQuantityList(BsonDocument base, List<QuantityElement> quantityList) { BsonArray quantityArray = new BsonArray(); for (QuantityElement quantityElement : quantityList) { BsonDocument bsonQuantityElement = new BsonDocument("epcClass", new BsonString(quantityElement.getEpcClass())); if (quantityElement.getQuantity() != null) { bsonQuantityElement.put("quantity", new BsonDouble(quantityElement.getQuantity())); } if (quantityElement.getUom() != null) { bsonQuantityElement.put("uom", new BsonString(quantityElement.getUom())); } quantityArray.add(bsonQuantityElement); } base.put("quantityList", quantityArray); return base; }
/** * Geospatial query * * @param key * should be indexed by 2dsphere * db.vertices.createIndex({"urn:oliot:ubv:mda:gps" : "2dsphere"}) * @param lon * @param lat * @param radius * in metres db.vertices.find({ "urn:oliot:ubv:mda:gps" : { $near : { * $geometry: { type: "Point", coordinates: [ -1.1673,52.93]}, * $maxDistance: 50000}}}) * * @return */ public HashSet<ChronoVertex> getChronoVertexSet(String key, double lon, double lat, double radius) { HashSet<ChronoVertex> ret = new HashSet<ChronoVertex>(); BsonArray coordinates = new BsonArray(); coordinates.add(new BsonDouble(lon)); coordinates.add(new BsonDouble(lat)); BsonDocument geometry = new BsonDocument(); geometry.put("type", new BsonString("Point")); geometry.put("coordinates", coordinates); BsonDocument near = new BsonDocument(); near.put("$geometry", geometry); near.put("$maxDistance", new BsonDouble(radius)); BsonDocument geoquery = new BsonDocument(); geoquery.put("$near", near); BsonDocument queryDoc = new BsonDocument(); queryDoc.put(key, geoquery); MongoCursor<BsonDocument> cursor = vertices.find(queryDoc).projection(Tokens.PRJ_ONLY_ID).iterator(); while (cursor.hasNext()) { BsonDocument v = cursor.next(); ret.add(new ChronoVertex(v.getString(Tokens.ID).getValue(), this)); } return ret; }
private Set<ChronoEdge> getOutChronoEdgeSet(final BsonArray labels, final int branchFactor) { HashSet<ChronoEdge> edgeSet = new HashSet<ChronoEdge>(); BsonDocument filter = new BsonDocument(); BsonDocument inner = new BsonDocument(); filter.put(Tokens.OUT_VERTEX, new BsonString(this.toString())); if (labels != null && labels.size() != 0) { inner.put(Tokens.FC.$in.toString(), labels); filter.put(Tokens.LABEL, inner); } Iterator<BsonDocument> it = null; if (branchFactor == Integer.MAX_VALUE) it = graph.getEdgeCollection().find(filter).projection(Tokens.PRJ_ONLY_ID).iterator(); else it = graph.getEdgeCollection().find(filter).projection(Tokens.PRJ_ONLY_ID).limit(branchFactor).iterator(); while (it.hasNext()) { BsonDocument d = it.next(); edgeSet.add(new ChronoEdge(d.getString(Tokens.ID).getValue(), this.graph)); } return edgeSet; }
@Test public void testGetUriWithFilterManyString() { BsonValue[] ids = new BsonValue[]{ new BsonInt32(1), new BsonDouble(20.0d), new BsonString("id")}; RequestContext context = prepareRequestContext(); String expResult = "/dbName/collName?filter={'_id':{'$in':[1,20.0,'id']}}"; String result; try { result = URLUtils.getUriWithFilterMany(context, "dbName", "collName", ids); assertEquals(expResult, result); } catch (UnsupportedDocumentIdException ex) { fail(ex.getMessage()); } }
public static BsonDocument asBsonDocument(SubscriptionType subscription) { BsonDocument bson = new BsonDocument(); if (subscription.getSubscriptionID() != null) { bson.put("subscriptionID", new BsonString(subscription.getSubscriptionID())); } if (subscription.getDest() != null) { bson.put("dest", new BsonString(subscription.getDest())); } if (subscription.getSchedule() != null) { bson.put("schedule", new BsonString(subscription.getSchedule())); } if (subscription.getTrigger() != null) { bson.put("trigger", new BsonString(subscription.getTrigger())); } if (subscription.getInitialRecordTime() != null) { bson.put("initialRecordTime", new BsonString(subscription.getInitialRecordTime())); } bson.put("reportIfEmpty", new BsonBoolean(subscription.getReportIfEmpty())); bson.put("pollParameters", PollParameters.asBsonDocument(subscription.getPollParameters())); return bson; }
public BsonDocument putILMD(BsonDocument base, Map<String, String> namespaces, Map<String, Map<String, Object>> ilmds) { BsonDocument bsonILMD = new BsonDocument(); for (String nsKey : ilmds.keySet()) { if (!namespaces.containsKey(nsKey)) continue; bsonILMD.put("@" + nsKey, new BsonString(namespaces.get(nsKey))); Map<String, Object> ilmdElementList = ilmds.get(nsKey); for (String ilmdKey : ilmdElementList.keySet()) { Object ilmdElement = ilmdElementList.get(ilmdKey); // Convert element to BSON BsonValue convertedILMDElement = convertToBsonValue(ilmdElement); bsonILMD.put(nsKey + ":" + ilmdKey, convertedILMDElement); } } base.put("ilmd", bsonILMD); return base; }
public BsonDocument putExtensions(BsonDocument base, Map<String, String> namespaces, Map<String, Map<String, Object>> extensions) { BsonDocument extension = new BsonDocument(); for (String nsKey : extensions.keySet()) { if (!namespaces.containsKey(nsKey)) continue; extension.put("@" + nsKey, new BsonString(namespaces.get(nsKey))); Map<String, Object> extensionList = extensions.get(nsKey); for (String extensionKey : extensionList.keySet()) { Object extensionElement = extensionList.get(extensionKey); // Convert element to BSON BsonValue convertedExtensionElement = convertToBsonValue(extensionElement); extension.put(nsKey + ":" + extensionKey, convertedExtensionElement); } } base.put("any", extension); return base; }
/** * 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()); }
public void process() { MongoDatabase db = mongoClient.getDatabase("local"); MongoCollection<RawBsonDocument> oplog = db.getCollection("oplog.rs", RawBsonDocument.class); RawBsonDocument lastOplogEntry = oplog.find().sort(new Document("$natural", -1)).first(); BsonTimestamp lastTimestamp = (BsonTimestamp) lastOplogEntry.get("ts"); System.out.println(lastTimestamp); Document query = new Document("ts", new Document("$lt", lastTimestamp)); for (RawBsonDocument doc : oplog.find(query).noCursorTimeout(true)) { BsonString ns = (BsonString) doc.get("ns"); BsonString op = (BsonString) doc.get("op"); // ignore no-op if (!op.getValue().equals("n")) { OplogEntryKey key = new OplogEntryKey(ns.getValue(), op.getValue()); EntryAccumulator accum = accumulators.get(key); if (accum == null) { accum = new EntryAccumulator(key); accumulators.put(key, accum); } long len = doc.getByteBuffer().asNIO().array().length; accum.addExecution(len); } if (stop) { mongoClient.close(); report(); break; } } }
private static BsonDocument getBsonNode(Diff diff, EnumSet<DiffFlags> flags) { BsonDocument bsonNode = new BsonDocument(); bsonNode.put(Constants.OP, new BsonString(diff.getOperation().rfcName())); switch (diff.getOperation()) { case MOVE: case COPY: bsonNode.put(Constants.FROM, new BsonString(PathUtils.getPathRepresentation(diff.getPath()))); // required {from} only in case of Move Operation bsonNode.put(Constants.PATH, new BsonString(PathUtils.getPathRepresentation(diff.getToPath()))); // destination Path break; case REMOVE: bsonNode.put(Constants.PATH, new BsonString(PathUtils.getPathRepresentation(diff.getPath()))); if (!flags.contains(DiffFlags.OMIT_VALUE_ON_REMOVE)) bsonNode.put(Constants.VALUE, diff.getValue()); break; case REPLACE: if (flags.contains(DiffFlags.ADD_ORIGINAL_VALUE_ON_REPLACE)) { bsonNode.put(Constants.FROM_VALUE, diff.getSrcValue()); } case ADD: case TEST: bsonNode.put(Constants.PATH, new BsonString(PathUtils.getPathRepresentation(diff.getPath()))); bsonNode.put(Constants.VALUE, diff.getValue()); break; default: // Safety net throw new IllegalArgumentException("Unknown operation specified:" + diff.getOperation()); } return bsonNode; }
@Test public void testRenderedRemoveOperationOmitsValueByDefault() throws Exception { BsonDocument source = new BsonDocument(); BsonDocument target = new BsonDocument(); source.put("field", new BsonString("value")); BsonArray diff = BsonDiff.asBson(source, target); Assert.assertEquals(Operation.REMOVE.rfcName(), diff.get(0).asDocument().getString("op").getValue()); Assert.assertEquals("/field", diff.get(0).asDocument().getString("path").getValue()); Assert.assertNull(diff.get(0).asDocument().get("value")); }
@Test public void testRenderedRemoveOperationRetainsValueIfOmitDiffFlagNotSet() throws Exception { BsonDocument source = new BsonDocument(); BsonDocument target = new BsonDocument(); source.put("field", new BsonString("value")); EnumSet<DiffFlags> flags = DiffFlags.defaults().clone(); Assert.assertTrue("Expected OMIT_VALUE_ON_REMOVE by default", flags.remove(DiffFlags.OMIT_VALUE_ON_REMOVE)); BsonArray diff = BsonDiff.asBson(source, target, flags); Assert.assertEquals(Operation.REMOVE.rfcName(), diff.get(0).asDocument().getString("op").getValue()); Assert.assertEquals("/field", diff.get(0).asDocument().getString("path").getValue()); Assert.assertEquals("value", diff.get(0).asDocument().getString("value").getValue()); }
public static BsonArray generate(int count) { BsonArray jsonNode = new BsonArray(); for (int i = 0; i < count; i++) { BsonDocument objectNode = new BsonDocument(); objectNode.put("name", new BsonString(name.get(random.nextInt(name.size())))); objectNode.put("age", new BsonInt32(age.get(random.nextInt(age.size())))); objectNode.put("gender", new BsonString(gender.get(random.nextInt(gender.size())))); BsonArray countryNode = getArrayNode(country.subList(random.nextInt(country.size() / 2), (country.size() / 2) + random.nextInt(country.size() / 2))); objectNode.put("country", countryNode); BsonArray friendNode = getArrayNode(friends.subList(random.nextInt(friends.size() / 2), (friends.size() / 2) + random.nextInt(friends.size() / 2))); objectNode.put("friends", friendNode); jsonNode.add(objectNode); } return jsonNode; }
private static BsonArray getArrayNode(List<String> args) { BsonArray countryNode = new BsonArray(); for(String arg : args){ countryNode.add(new BsonString(arg)); } return countryNode; }
@Override public String getString(Object key) { BsonString bsonString = innerBsonDocument.getString(key); if (bsonString != null) { return (String) BsonValueConverterRepertory.getValueConverterByBsonType(bsonString.getBsonType()).decode(bsonString); } else { return null; } }
private BsonDocument getBsonDocumentHasDeepLayer() { BsonDocument bsonObj = new BsonDocument().append("testDouble", new BsonDouble(20.777)); List<BsonDocument> list = new ArrayList<BsonDocument>(); list.add(bsonObj); list.add(bsonObj); BsonDocument deepBsonDocument = new BsonDocument().append("testDouble", new BsonDouble(20.99)) .append("testString", new BsonString("testStringV")) .append("testArray", new BsonArray(list)); BsonDocument bsonDocument1 = new BsonDocument().append("testDouble", new BsonDouble(20.99)) .append("testString", new BsonString("testStringV")) .append("bson_test", deepBsonDocument); BsonDocument bsonDocument2 = new BsonDocument().append("testDouble", new BsonDouble(20.99)) .append("testString", new BsonString("testStringV")) .append("bson_test", bsonDocument1); BsonDocument bsonDocument3 = new BsonDocument().append("testDouble", new BsonDouble(20.99)) .append("testString", new BsonString("testStringV")) .append("bson_test", bsonDocument2) .append("testArray", new BsonArray(list)); BsonDocument bsonDocument4 = new BsonDocument().append("testDouble", new BsonDouble(20.99)) .append("testString", new BsonString("testStringV")) .append("bson_test", bsonDocument3) .append("testArray", new BsonArray(list)); BsonDocument bsonDocument5 = new BsonDocument().append("testDouble", new BsonDouble(20.99)) .append("testString", new BsonString("testStringV")) .append("bson_test", bsonDocument4) .append("testArray", new BsonArray(list)); return new BsonDocument().append("testDouble", new BsonDouble(20.99)) .append("bson_test", bsonDocument5) .append("testLong", new BsonInt64(233332)); }