@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)); }
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)); }
@Override public void setConfig(Map<String, String> config) { tableName = config.get(PREFIX); if (config.containsKey(SEPARATE_VERSION)) { separateVersion = Boolean.valueOf(config.get(SEPARATE_VERSION)); } String dirName; if (tableName == null || tableName.isEmpty()) { tableName = "__data__" + instanceName; dirName = "__dir__" + instanceName; } else { dirName = "__dir__" + tableName; } MongoCollection<Document> collection = getCollection(); collection.createIndex(new Document(KEY, new BsonInt32(1))); dirRepo.setInstanceName(instanceName); Map<String, String> dirConfig = ImmutableMap.of(PREFIX, dirName); dirRepo.setConfig(dirConfig); dirRepo.setRepoDescription(String.format("Mongo - %s", tableName)); }
@Test public void removalListening() { String firstName = "firstName"; for (int i = 0; i < userUtil.cacheSize + 2; i++) { // just create those users in time factory.create(User.class).setUsername("" + i).setPassword("123456").setMemberSince(DateTime.now()).setPictureCount(new AtomicInteger(10)).save(); User u = userUtil.getUser("" + i); u.getPictureCount().incrementAndGet(); u.setFirstName("" + i); } MongoCollection coll = db.getCollection(EntityUtils.getCollectionName(User.class)); assertEquals(22, coll.count()); MongoCursor<Document> cursor = coll.find().sort(new BsonDocument(Entity.ID, new BsonInt32(1))).iterator(); Document doc = cursor.next(); assertEquals("0", doc.get(Entity.ID)); assertEquals("0", doc.get(firstName)); doc = cursor.next(); assertEquals("1", doc.get(Entity.ID)); assertEquals("1", doc.get(firstName)); doc = cursor.next(); assertFalse(doc.containsKey(firstName)); }
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); } }
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); } }
/** * Add an edge to the graph. The added edges requires a recommended identifier, * a tail vertex, an head vertex, and a label. Like adding a vertex, the * provided object identifier may be ignored by the implementation. * * @param outVertexID: * the vertex on the tail of the edge * @param inVertexID: * the vertex on the head of the edge * @param label: * the label associated with the edge * @return the newly created edge */ public ChronoEdge addEdge(final String outVertexID, final String inVertexID, final String label) { if (label == null) throw ExceptionFactory.edgeLabelCanNotBeNull(); String edgeID = Converter.getEdgeID(outVertexID, label, inVertexID); BsonDocument doc = edges.find(new BsonDocument(Tokens.OUT_VERTEX, new BsonString(outVertexID)) .append(Tokens.LABEL, new BsonString(label)).append(Tokens.IN_VERTEX, new BsonString(inVertexID))) .projection(new BsonDocument(Tokens.ID, new BsonInt32(0))).first(); if (doc == null) { BsonDocument e = new BsonDocument(); e.put(Tokens.OUT_VERTEX, new BsonString(outVertexID)); e.put(Tokens.IN_VERTEX, new BsonString(inVertexID)); e.put(Tokens.LABEL, new BsonString(label)); edges.insertOne(e); } return new ChronoEdge(edgeID, outVertexID, inVertexID, label, this); }
/** * Add an edge to the graph. The added edges requires a recommended identifier, * a tail vertex, an head vertex, and a label. Like adding a vertex, the * provided object identifier may be ignored by the implementation. * * @param id: * outVertexID|label|inVertexID */ public ChronoEdge getEdge(String id) { if (id == null) throw ExceptionFactory.edgeIdCanNotBeNull(); String[] idArr = id.split("\\|"); if (idArr.length != 3) return null; BsonDocument edgeDoc = edges.find(new BsonDocument(Tokens.OUT_VERTEX, new BsonString(idArr[0])) .append(Tokens.LABEL, new BsonString(idArr[1])).append(Tokens.IN_VERTEX, new BsonString(idArr[2]))) .projection(new BsonDocument(Tokens.ID, new BsonInt32(0))).first(); if (edgeDoc == null) return null; else return new ChronoEdge(id, this); }
private void addWriteErrors( final List<BulkWriteError> wes, final Representation rep) { wes.stream().forEach(error -> { Representation nrep = new Representation(); nrep.addProperty("index", new BsonInt32(error.getIndex())); nrep.addProperty("mongodbErrorCode", new BsonInt32(error.getCode())); nrep.addProperty("httpStatus", new BsonInt32( ResponseHelper.getHttpStatusFromErrorCode( error.getCode()))); nrep.addProperty("message", new BsonString( ResponseHelper.getMessageFromErrorCode( error.getCode()))); rep.addRepresentation("rh:error", nrep); }); }
private void addEmbeddedData( List<BsonDocument> embeddedData, final Representation rep, final String requestPath, final HttpServerExchange exchange, final RequestContext context) throws IllegalQueryParamenterException { if (embeddedData != null) { addReturnedProperty(embeddedData, rep); if (!embeddedData.isEmpty()) { embeddedDocuments( embeddedData, requestPath, exchange, context, rep); } } else { rep.addProperty(_RETURNED, new BsonInt32(0)); } }
@Test public void testGetUriWithFilterMany() { 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()); } }
@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()); } }
@Test public void convert_bson_to_record() { BsonDocument doc = new BsonDocument(); doc.put("name", new BsonString("Dominic")); doc.put("age", new BsonInt32(39)); BsonRecordDeserialiser deserialiser = BsonRecordDeserialiser.builder() .readString(Person.name) .readInteger(Person.age) .get(); Record result = deserialiser.apply(doc); assertTrue("name not set", Person.name.get(result).isPresent()); assertEquals("incorrect name", "Dominic", Person.name.get(result).get()); assertTrue("age not set", Person.age.get(result).isPresent()); assertEquals("incorrect age", 39, (int) Person.age.get(result).get()); }
@Test public void convert_bson_to_record_when_field_names_do_not_match_key_names() { BsonDocument doc = new BsonDocument(); doc.put("foo", new BsonString("Dominic")); doc.put("bar", new BsonInt32(39)); BsonRecordDeserialiser deserialiser = BsonRecordDeserialiser.builder() .readString(Person.name, "foo") .readInteger(Person.age, "bar") .get(); Record result = deserialiser.apply(doc); assertTrue("name not set", Person.name.get(result).isPresent()); assertEquals("incorrect name", "Dominic", Person.name.get(result).get()); assertTrue("age not set", Person.age.get(result).isPresent()); assertEquals("incorrect age", 39, (int) Person.age.get(result).get()); }
@Test public void convert_bson_to_record_with_custom_type() { BsonDocument doc = new BsonDocument(); doc.put("foo", new BsonString("Dominic")); doc.put("bar", new BsonInt32(39)); doc.put("favouriteColour", new BsonString("0xFF0000")); BsonRecordDeserialiser deserialiser = BsonRecordDeserialiser.builder() .readString(Person.name) .readInteger(Person.age) .read(Person.favouriteColour, Person.colourFromBson) .get(); Record result = deserialiser.apply(doc); assertThat(Person.favouriteColour.get(result), not(isEmpty())); assertEquals("mismatched colour", Color.RED, Person.favouriteColour.get(result).get()); }
@Test public void calculateKeys() { MappedClass mappedClass = getMorphia().getMapper().getMappedClass(IndexedClass.class); BsonDocument keys = indexHelper.calculateKeys(mappedClass, new IndexBuilder() .fields(new FieldBuilder() .value("text") .type(IndexType.TEXT) .weight(1), new FieldBuilder() .value("nest") .type(IndexType.DESC))); assertEquals(new BsonDocument() .append("text", new BsonString("text")) .append("nest", new BsonInt32(-1)), keys); }
/** * 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()); }
@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))); }
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 Integer getInt32FromInner(Object key) { BsonInt32 int32 = innerBsonDocument.getInt32(key); if (int32 != null) { return (Integer) BsonValueConverterRepertory.getValueConverterByBsonType(int32.getBsonType()).decode(int32); } else { return null; } }
@Override public SmofUpdate<T> pop(String fieldName, boolean removeFirst) { validateFieldName(fieldName, ARRAY); final BsonValue bsonValue = new BsonInt32(removeFirst ? -1 : 1); putOrAppend(POP, fieldName, bsonValue); return this; }
@Override public SmofUpdate<T> pushAll(String fieldName, int index, Collection<?> values) { final SmofField field = validateFieldName(fieldName, ARRAY); final BsonValue bsonValue = parser.toBson(values, field); final BsonDocument bsonDocument = new BsonDocument(EACH.getOperator(), bsonValue); bsonDocument.append(POSITION.getOperator(), new BsonInt32(index)); putOrAppend(PUSH, fieldName, bsonDocument); return this; }
@Override public void setConfig(String logId, Map<String, String> config) { tableName = config.get(TABLE_NAME); this.logId = logId; try { getAuditCollection().createIndex(new BsonDocument(WHEN, new BsonInt32(1))); } catch (MongoException e) { log.info("setConfig failed on " + tableName + ": " + e.getMessage()); log.debug(ExceptionToString.format(e)); } }