@Test public void testPatchAppliedCleanly() throws Exception { for (int i = 0; i < jsonNode.size(); i++) { BsonDocument node = jsonNode.get(i).asDocument(); BsonValue first = node.get("first"); BsonValue second = node.get("second"); BsonArray patch = node.getArray("patch"); String message = node.containsKey("message") ? node.getString("message").getValue() : ""; // System.out.println("Test # " + i); // System.out.println(first); // System.out.println(second); // System.out.println(patch); BsonValue secondPrime = BsonPatch.apply(patch, first); // System.out.println(secondPrime); Assert.assertThat(message, secondPrime, equalTo(second)); } }
@Test public void testRenderedOperationsExceptMoveAndCopy() throws Exception { BsonDocument source = new BsonDocument(); source.put("age", new BsonInt32(10)); BsonDocument target = new BsonDocument(); target.put("height", new BsonInt32(10)); EnumSet<DiffFlags> flags = DiffFlags.dontNormalizeOpIntoMoveAndCopy().clone(); //only have ADD, REMOVE, REPLACE, Don't normalize operations into MOVE & COPY BsonArray diff = BsonDiff.asBson(source, target, flags); // System.out.println(source); // System.out.println(target); // System.out.println(diff); for (BsonValue d : diff) { Assert.assertNotEquals(Operation.MOVE.rfcName(), d.asDocument().getString("op").getValue()); Assert.assertNotEquals(Operation.COPY.rfcName(), d.asDocument().getString("op").getValue()); } BsonValue targetPrime = BsonPatch.apply(diff, source); // System.out.println(targetPrime); Assert.assertTrue(target.equals(targetPrime)); }
/** * Converts a binary uuid to a standard uuid * * @param json The json string (should contain "$binary" and "$type" or something like that) * @return The uuid */ private UUID convertBinaryUUID(String key, String json) { BsonDocument document = BsonDocument.parse(json); BsonValue value = document.get(key); if(!(value instanceof BsonBinary)) { return null; } byte[] bytes = ((BsonBinary) value).getData(); ByteBuffer bb = ByteBuffer.wrap(bytes); bb.order(ByteOrder.LITTLE_ENDIAN); long l1 = bb.getLong(); long l2 = bb.getLong(); return new UUID(l1, l2); }
private ArrayList<BsonValue> getBsonValueList(Field field, Collection values, BsonMapperConfig bsonMapperConfig, Class<?> componentType) { ArrayList<BsonValue> arrayList = new ArrayList<BsonValue>(); for (Object o : values) { if (o == null) { continue; } Class<?> oClazz = o.getClass(); if (Utils.isArrayType(oClazz)) { BsonArray innerBsonArray = new BsonArray(); encode(innerBsonArray, field, o, bsonMapperConfig); arrayList.add(innerBsonArray); } if (componentType.isInstance(o)) { if (BsonValueConverterRepertory.isCanConverterValueType(componentType)) { arrayList.add(BsonValueConverterRepertory.getValueConverterByClazz(componentType).encode(o)); } else { BsonDocument arrayEle = new BsonDocument(); BsonValueConverterRepertory.getBsonDocumentConverter().encode(arrayEle, o, bsonMapperConfig); arrayList.add(arrayEle); } } else { throw new BsonMapperConverterException(String.format("array field has element which has different type with declaring componentType.field name: %s", field.getName())); } } return arrayList; }
@Test public void readFrom() throws Exception { BsonDocument bsonDocument1 = getBsonDocument(); BsonMapper bsonMapper = DefaultBsonMapper.defaultBsonMapper(); BsonTest bsonTest = bsonMapper.readFrom(bsonDocument1, BsonTest.class); System.out.println(bsonTest.getTestDouble()); System.out.println(bsonTest.getTestString()); System.out.println(bsonTest.getTestArray()); System.out.println(Arrays.toString(bsonTest.getTestBinary().getData())); System.out.println(bsonTest.getTestObjectId()); System.out.println(bsonTest.getTestStringObjectId()); System.out.println(bsonTest.isTestBoolean()); System.out.println(bsonTest.getTestDate()); System.out.println(bsonTest.getTestNull()); System.out.println(bsonTest.getTestInt()); System.out.println(bsonTest.getTestLong()); System.out.println(bsonTest); }
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)); }
@Test public void testRecursiveDocuments() throws IOException { BsonDocument topDoc = new BsonDocument(); final int count = 3; for (int i = 0; i < count; ++i) { BsonDocument bsonDoc = new BsonDocument(); BsonWriter bw = new BsonDocumentWriter(bsonDoc); bw.writeStartDocument(); bw.writeName("k1" + i); bw.writeString("drillMongo1" + i); bw.writeName("k2" + i); bw.writeString("drillMongo2" + i); bw.writeEndDocument(); bw.flush(); topDoc.append("doc" + i, bsonDoc); } writer.reset(); bsonReader.write(writer, new BsonDocumentReader(topDoc)); SingleMapReaderImpl mapReader = (SingleMapReaderImpl) writer.getMapVector().getReader(); for (int i = 0; i < count; ++i) { SingleMapReaderImpl reader = (SingleMapReaderImpl) mapReader.reader("doc" + i); assertEquals("drillMongo1" + i, reader.reader("k1" + i).readText().toString()); assertEquals("drillMongo2" + i, reader.reader("k2" + i).readText().toString()); } }
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; }
private BsonDocument fromObject(Object value) { final BsonDocument document = new BsonDocument(); final TypeParser<?> metadata = getTypeParser(value.getClass()); final BsonArray lazyStack = new BsonArray(); for(PrimaryField field : metadata.getAllFields()) { final Object fieldValue = extractValue(value, field); final BsonValue parsedValue; checkRequired(field, fieldValue); parsedValue = topParser.toBson(fieldValue, field); if(parsedValue instanceof BsonLazyObjectId) { lazyStack.add(parsedValue); } else { document.put(field.getName(), parsedValue); } } document.append(SmofParser.ON_INSERT, lazyStack); return document; }
private SmofInsertResult replace(T element, SmofOpOptions options) { final SmofInsertResult result = new SmofInsertResultImpl(); result.setSuccess(true); options.upsert(true); if(options.isBypassCache() || !cache.asMap().containsValue(element)) { final BsonDocument document = parser.toBson(element); final Bson query = createUniquenessQuery(document); result.setPostInserts(BsonUtils.extrackPosInsertions(document)); options.setReturnDocument(ReturnDocument.AFTER); document.remove(Element.ID); final BsonDocument resDoc = collection.findOneAndReplace(query, document, options.toFindOneAndReplace()); element.setId(resDoc.get(Element.ID).asObjectId().getValue()); cache.put(element.getId(), element); } return result; }
public static BsonValue filterValue(BsonValue value) { BsonValue returnedValue = QUESTION_MARK_BSON; if (value instanceof BsonDocument) { returnedValue = filterParameters((BsonDocument) value); } else if (value instanceof BsonArray) { BsonArray array = (BsonArray) value; array = array.clone(); returnedValue = array; int length = array.size(); for (int i = 0; i < length; ++i) { BsonValue bsonValue = array.get(i); array.set(i, filterValue(bsonValue)); } } return returnedValue; }
@Test public void testArrayOfDocumentType() throws IOException { BsonDocument bsonDoc = new BsonDocument(); BsonWriter bw = new BsonDocumentWriter(bsonDoc); bw.writeStartDocument(); bw.writeName("a"); bw.writeString("MongoDB"); bw.writeName("b"); bw.writeStartArray(); bw.writeStartDocument(); bw.writeName("c"); bw.writeInt32(1); bw.writeEndDocument(); bw.writeEndArray(); bw.writeEndDocument(); bw.flush(); writer.reset(); bsonReader.write(writer, new BsonDocumentReader(bsonDoc)); FieldReader reader = writer.getMapVector().getReader(); SingleMapReaderImpl mapReader = (SingleMapReaderImpl) reader; FieldReader reader3 = mapReader.reader("b"); assertEquals("MongoDB", mapReader.reader("a").readText().toString()); }
BsonValue toBson() { @SuppressWarnings("unchecked") Encoder<T> encoder = BsonEncoding.encoderFor((Class<T>) value.getClass(), adapter); BsonDocument bson = new BsonDocument(); org.bson.BsonWriter writer = new BsonDocumentWriter(bson); // Bson doesn't allow to write directly scalars / primitives, they have to be embedded in a document. writer.writeStartDocument(); writer.writeName("$"); encoder.encode(writer, value, EncoderContext.builder().build()); writer.writeEndDocument(); writer.flush(); return bson.get("$"); }
/** * 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()); }
@Test public void gsonToBson() throws Exception { JsonObject obj = new JsonObject(); obj.addProperty("boolean", true); obj.addProperty("int32", 32); obj.addProperty("int64", 64L); obj.addProperty("double", 42.42D); obj.addProperty("string", "foo"); obj.add("null", JsonNull.INSTANCE); obj.add("array", new JsonArray()); obj.add("object", new JsonObject()); BsonDocument doc = new BsonDocument(); TypeAdapters.JSON_ELEMENT.write(new BsonWriter(new BsonDocumentWriter(doc)), obj); check(doc.keySet()).notEmpty(); check(doc.get("boolean").getBsonType()).is(BsonType.BOOLEAN); check(doc.get("boolean").asBoolean()); check(doc.get("int32").getBsonType()).is(BsonType.INT32); check(doc.get("int32").asInt32().getValue()).is(32); check(doc.get("int64").getBsonType()).is(BsonType.INT64); check(doc.get("int64").asInt64().getValue()).is(64L); check(doc.get("double").getBsonType()).is(BsonType.DOUBLE); check(doc.get("double").asDouble().getValue()).is(42.42D); check(doc.get("string").getBsonType()).is(BsonType.STRING); check(doc.get("string").asString().getValue()).is("foo"); check(doc.get("null").getBsonType()).is(BsonType.NULL); check(doc.get("null").isNull()); check(doc.get("array").getBsonType()).is(BsonType.ARRAY); check(doc.get("array").asArray()).isEmpty(); check(doc.get("object").getBsonType()).is(BsonType.DOCUMENT); check(doc.get("object").asDocument().keySet()).isEmpty(); }
@Override public Bson get() { List<Projection> projections = getProjections(); BsonDocument response = new BsonDocument("_id", new BsonInt32(0)); for (Projection p : projections) { response.append(p.getName(), new BsonInt32(1)); } return response; }
@Override public Bson get() { BsonDocument orderByObject = new BsonDocument(); List<OrderBy> orderBys = getOrderBys(); for (OrderBy orderBy : orderBys) { orderByObject.put(orderBy.getName(), new BsonInt32(orderBy.isAscending() ? 1 : -1)); } return orderByObject; }
@Test public void testParseToBson() { Bson bson = parser.get(Bson.class, "a, b.c"); BsonDocument bsonDocument = toBsonDocument(bson); assertThat(bsonDocument.size(), is(3)); assertThat(bsonDocument, hasEntry("_id", new BsonInt32(0))); assertThat(bsonDocument, hasEntry("a", new BsonInt32(1))); assertThat(bsonDocument, hasEntry("b.c", new BsonInt32(1))); }
@Test public void testParseToBson() { Bson bson = parser.get(Bson.class, "a = 1"); BsonDocument bsonDocument = toBsonDocument(bson); assertThat(bsonDocument.size(), is(1)); assertThat(bsonDocument, hasEntry("a", new BsonInt32(1))); }
@Test public void testParseToBson() { Bson bson = parser.get(Bson.class, "a, b"); BsonDocument bsonDocument = toBsonDocument(bson); assertThat(bsonDocument.size(), is(2)); assertThat(bsonDocument, hasEntry("a", new BsonInt32(-1))); assertThat(bsonDocument, hasEntry("b", new BsonInt32(-1))); }
@Test public void testSingleProjection() { BsonDocument bsonDocument = parse("a,b"); assertThat(bsonDocument.size(), is(3)); assertThat(bsonDocument, hasEntry("_id", new BsonInt32(0))); assertThat(bsonDocument, hasEntry("a", new BsonInt32(1))); assertThat(bsonDocument, hasEntry("b", new BsonInt32(1))); }
@Test public void testMultipleProjections() { BsonDocument bsonDocument = parse("a.b, c.d.e, f, g"); assertThat(bsonDocument.size(), is(5)); assertThat(bsonDocument, hasEntry("_id", new BsonInt32(0))); assertThat(bsonDocument, hasEntry("a.b", new BsonInt32(1))); assertThat(bsonDocument, hasEntry("c.d.e", new BsonInt32(1))); assertThat(bsonDocument, hasEntry("f", new BsonInt32(1))); assertThat(bsonDocument, hasEntry("g", new BsonInt32(1))); }
@Test public void testStarProjection() { BsonDocument bsonDocument = parse("*"); assertThat(bsonDocument.size(), is(1)); assertThat(bsonDocument, hasEntry("_id", new BsonInt32(0))); }
@Test public void testEmptyProjection() { BsonDocument bsonDocument = parse(""); assertThat(bsonDocument.size(), is(1)); assertThat(bsonDocument, hasEntry("_id", new BsonInt32(0))); }
@Test public void testNullProjection() { BsonDocument bsonDocument = parse(null); assertThat(bsonDocument.size(), is(1)); assertThat(bsonDocument, hasEntry("_id", new BsonInt32(0))); }
@Test public void testSingleField() { String orderBy = "a desc"; BsonDocument bsonDocument = parse(orderBy); assertThat(bsonDocument.size(), is(1)); assertThat(bsonDocument, hasEntry("a", new BsonInt32(-1))); }
@Test public void testMultipleFields() { String orderBy = "a asc, b desc, c.d.e asc"; BsonDocument bsonDocument = parse(orderBy); assertThat(bsonDocument.size(), is(3)); assertThat(bsonDocument, hasEntry("a", new BsonInt32(1))); assertThat(bsonDocument, hasEntry("b", new BsonInt32(-1))); assertThat(bsonDocument, hasEntry("c.d.e", new BsonInt32(1))); }
@Test public void testDefaultOrderIsDescending() { String orderBy = "a, b.c"; BsonDocument bsonDocument = parse(orderBy); assertThat(bsonDocument.size(), is(2)); assertThat(bsonDocument, hasEntry("a", new BsonInt32(-1))); assertThat(bsonDocument, hasEntry("b.c", new BsonInt32(-1))); }
private static BsonArray getBsonNodes(List<Diff> diffs, EnumSet<DiffFlags> flags) { final BsonArray patch = new BsonArray(); for (Diff diff : diffs) { BsonDocument bsonNode = getBsonNode(diff, flags); patch.add(bsonNode); } return patch; }
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; }
private void testOperation() throws Exception { BsonDocument node = p.getNode(); BsonValue doc = node.get("node"); BsonValue expected = node.get("expected"); BsonArray patch = node.getArray("op"); String message = node.containsKey("message") ? node.getString("message").getValue() : ""; BsonValue result = BsonPatch.apply(patch, doc); String failMessage = "The following test failed: \n" + "message: " + message + '\n' + "at: " + p.getSourceFile(); assertEquals(failMessage, expected, result); }
private void testError() throws ClassNotFoundException { BsonDocument node = p.getNode(); BsonValue first = node.get("node"); BsonArray patch = node.getArray("op"); String message = node.containsKey("message") ? node.getString("message").getValue() : ""; Class<?> type = node.containsKey("type") ? exceptionType(node.getString("type").getValue()) : BsonPatchApplicationException.class; try { BsonPatch.apply(patch, first); fail(errorMessage("Failure expected: " + message)); } catch (Exception e) { if (matchOnErrors()) { StringWriter fullError = new StringWriter(); e.printStackTrace(new PrintWriter(fullError)); assertThat( errorMessage("Operation failed but with wrong exception type", e), e, instanceOf(type)); if (message != null) { assertThat( errorMessage("Operation failed but with wrong message", e), e.getMessage(), containsString(message)); // equalTo would be better, but fail existing tests } } } }
@Test public void withFlagReplaceShouldTreatMissingValuesAsNull() throws IOException { BsonDocument source = BsonDocument.parse("{\"a\":\"test\"}"); BsonDocument expected = BsonDocument.parse("{\"a\":null}"); BsonDocument result = BsonPatch.apply(replaceNodeWithMissingValue, source, EnumSet.of(MISSING_VALUES_AS_NULLS)).asDocument(); assertThat(result, equalTo(expected)); }
@Test public void withFlagIgnoreRemoveNoneExistingArrayElement() throws IOException { BsonDocument source = BsonDocument.parse("{\"b\": []}"); BsonDocument expected = BsonDocument.parse("{\"b\": []}"); BsonDocument result = BsonPatch.apply(removeNoneExistingArrayElement, source, EnumSet.of(REMOVE_NONE_EXISTING_ARRAY_ELEMENT)).asDocument(); assertThat(result, equalTo(expected)); }
@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()); }
@Test public void testMoveValueGeneratedHasNoValue() throws IOException { BsonValue jsonNode1 = BsonDocument.parse("{ \"foo\": { \"bar\": \"baz\", \"waldo\": \"fred\" }, \"qux\": { \"corge\": \"grault\" } }"); BsonValue jsonNode2 = BsonDocument.parse("{ \"foo\": { \"bar\": \"baz\" }, \"qux\": { \"corge\": \"grault\", \"thud\": \"fred\" } }"); BsonArray patch = BsonArray.parse("[{\"op\":\"move\",\"from\":\"/foo/waldo\",\"path\":\"/qux/thud\"}]"); BsonArray diff = BsonDiff.asBson(jsonNode1, jsonNode2); assertThat(diff, equalTo(patch)); }
@Test public void testMoveArrayGeneratedHasNoValue() throws IOException { BsonValue jsonNode1 = BsonDocument.parse("{ \"foo\": [ \"all\", \"grass\", \"cows\", \"eat\" ] }"); BsonValue jsonNode2 = BsonDocument.parse("{ \"foo\": [ \"all\", \"cows\", \"eat\", \"grass\" ] }"); BsonArray patch = BsonArray.parse("[{\"op\":\"move\",\"from\":\"/foo/1\",\"path\":\"/foo/3\"}]"); BsonArray diff = BsonDiff.asBson(jsonNode1, jsonNode2); assertThat(diff, equalTo(patch)); }
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; }