com.mongodb.BasicDBObjectBuilder Java Examples

The following examples show how to use com.mongodb.BasicDBObjectBuilder. 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: InitialSetupMigration.java    From spring-boot-completablefuture with MIT License 7 votes vote down vote up
@ChangeSet(order = "01",
           author = "developer",
           id = "01-addUsers")
public void addUsers(final DB db) {
    final DBCollection userCollection = db.getCollection(User.COLLECTION_NAME);

    userCollection.insert(BasicDBObjectBuilder
                                  .start()
                                  .add(FIELD_NAME_ID, new ObjectId("590f86d92449343841cc2c3f"))
                                  .add(User.FIELD_NAME_FIRST_NAME, "User")
                                  .add(User.FIELD_NAME_LAST_NAME, "One")
                                  .add(User.FIELD_NAME_EMAIL, "[email protected]")
                                  .get());

    userCollection.insert(BasicDBObjectBuilder
                                  .start()
                                  .add(FIELD_NAME_ID, new ObjectId("590f86d92449343841cc2c40"))
                                  .add(User.FIELD_NAME_FIRST_NAME, "User")
                                  .add(User.FIELD_NAME_LAST_NAME, "Two")
                                  .add(User.FIELD_NAME_EMAIL, "[email protected]")
                                  .get());
}
 
Example #2
Source File: ContainerDocumentAccessorTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateEntity() {
    ContainerDocumentAccessor cda = Mockito.spy(testAccessor);
    Map<String, Object> updateDocCriteria = new HashMap<String, Object>();
    updateDocCriteria.put("event", "Tardy");
    DBObject pullObject = BasicDBObjectBuilder.start().push("$pull").add("body.attendanceEvent", updateDocCriteria).get();
    DBObject resultingAttendanceEvent = createResultAttendance(null);
    NeutralSchema attendanceSchema = createMockAttendanceSchema();

    when(mongoTemplate.getCollection(ATTENDANCE)).thenReturn(mockCollection);
    when(mockCollection.findAndModify(Mockito.any(DBObject.class), (DBObject) Mockito.isNull(), (DBObject) Mockito.isNull(),
            Mockito.eq(false), Mockito.eq(pullObject), Mockito.eq(true), Mockito.eq(false))).thenReturn(resultingAttendanceEvent);
    when(mongoTemplate.findAndRemove(Mockito.any(Query.class), Mockito.eq(Entity.class), Mockito.eq(ATTENDANCE))).thenReturn(entity); // just return something non-null
    when(mockCollection.update(Mockito.any(DBObject.class), Mockito.any(DBObject.class), Mockito.eq(true), Mockito.eq(false), Mockito.eq(WriteConcern.SAFE))).thenReturn(writeResult);
    when(schemaRepo.getSchema(EntityNames.ATTENDANCE)).thenReturn(attendanceSchema);

    String result = cda.updateContainerDoc(entity);

    Mockito.verify(cda, Mockito.times(1)).deleteContainerNonSubDocs(Mockito.eq(entity));
    Mockito.verify(cda, Mockito.times(1)).insertContainerDoc(Mockito.any(DBObject.class), Mockito.eq(entity));
    assertTrue(result.equals(ID));
}
 
Example #3
Source File: MongoEntityTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testCreateCalculatedValue() throws IllegalAccessException, InvocationTargetException,
        NoSuchMethodException {
    Map<String, Object> body = new HashMap<String, Object>();
    Map<String, Object> calcValue = new HashMap<String, Object>();
    Map<String, Object> assessments = new HashMap<String, Object>();
    Map<String, Object> mathTest = new HashMap<String, Object>();
    Map<String, Object> highestEver = new HashMap<String, Object>();
    highestEver.put("ScaleScore", "28.0");
    mathTest.put("HighestEver", highestEver);
    assessments.put("ACT", mathTest);
    calcValue.put("assessments", assessments);
    DBObject dbObject = new BasicDBObjectBuilder().add("_id", "42").add("body", body)
            .add("calculatedValues", calcValue).get();
    CalculatedData<String> data = MongoEntity.fromDBObject(dbObject).getCalculatedValues();
    assertEquals(
            Arrays.asList(new CalculatedDatum<String>("assessments", "HighestEver", "ACT", "ScaleScore", "28.0")),
            data.getCalculatedValues());
}
 
Example #4
Source File: MongoAffiliationBuilder.java    From sissi with Apache License 2.0 6 votes vote down vote up
@Override
public boolean update(JID jid, String affiliation) {
	try {
		// {"affiliations.$.affiliation":Xxx}
		BasicDBObjectBuilder entity = BasicDBObjectBuilder.start().add(Dictionary.FIELD_AFFILIATIONS + ".$." + Dictionary.FIELD_AFFILIATION, affiliation);
		if (ItemAffiliation.OWNER.equals(affiliation)) {
			// {"creator":jid.bare}
			// 如果为Owner则同时更新创建者
			entity.add(Dictionary.FIELD_CREATOR, jid.asStringWithBare());
		}
		// {"jid":group.bare,"affiliations.jid":jid.bare"},{"$set":...entity...}
		return MongoUtils.success(MongoAffiliationBuilder.this.config.collection().update(BasicDBObjectBuilder.start().add(Dictionary.FIELD_JID, this.group.asStringWithBare()).add(Dictionary.FIELD_AFFILIATIONS + "." + Dictionary.FIELD_JID, jid.asStringWithBare()).get(), BasicDBObjectBuilder.start().add("$set", entity.get()).get(), true, false, WriteConcern.SAFE));
	} catch (MongoException e) {
		// {"jid":group.bare},{"$addToSet":{"affiliations":{"jid":Xxx,"affiliation":Xxx}}}
		return MongoUtils.success(MongoAffiliationBuilder.this.config.collection().update(BasicDBObjectBuilder.start().add(Dictionary.FIELD_JID, this.group.asStringWithBare()).get(), BasicDBObjectBuilder.start("$addToSet", BasicDBObjectBuilder.start(Dictionary.FIELD_AFFILIATIONS, BasicDBObjectBuilder.start().add(Dictionary.FIELD_JID, jid.asStringWithBare()).add(Dictionary.FIELD_AFFILIATION, affiliation).get()).get()).get(), true, false, WriteConcern.SAFE));
	}
}
 
Example #5
Source File: CauseActionConverterTest.java    From DotCi with MIT License 6 votes vote down vote up
@Test
public void should_get_cause_from_dbObject() throws Exception {
    BasicDBObject cause1DbObject = new BasicDBObject("cause1", "cause1");
    DBObject causes = new BasicDBObjectBuilder().add("causes", Arrays.asList(cause1DbObject)).get();

    Mapper mapper = Mockito.mock(Mapper.class);
    Cause cause1 = new NullBuildCause();
    when(mapper.fromDBObject(null, cause1DbObject, null)).thenReturn(cause1);

    CauseActionConverter converter = new CauseActionConverter();
    converter.setMapper(mapper);
    CauseAction action = converter.decode(CauseAction.class, causes, Mockito.mock(MappedField.class));

    Assert.assertEquals(1, action.getCauses().size());
    Assert.assertEquals(cause1, action.getCauses().get(0));

}
 
Example #6
Source File: MapReduceExercise.java    From mongodb-hadoop-workshop with Apache License 2.0 6 votes vote down vote up
@Override
public void reduce(final IntWritable key, final Iterable<DoubleWritable> values, final Context context)
  throws IOException, InterruptedException {
    DescriptiveStatistics stats = new DescriptiveStatistics();
    for(DoubleWritable rating : values) {
        stats.addValue(rating.get());
    }

    BasicBSONObject query = new BasicBSONObject("movieid", key.get());
    DBObject statValues = new BasicDBObjectBuilder().start()
        .add("mean", stats.getMean())
        .add("median", stats.getPercentile(50))
        .add("std", stats.getStandardDeviation())
        .add("count", stats.getN())
        .add("total", stats.getSum())
        .get();
    BasicBSONObject movieStats = new BasicBSONObject("stats", statValues);
    BasicBSONObject update = new BasicBSONObject("$set", movieStats);

    context.write(NullWritable.get(), new MongoUpdateWritable(query, update));
}
 
Example #7
Source File: MapReduceExercise.java    From mongodb-hadoop-workshop with Apache License 2.0 6 votes vote down vote up
@Override
public void reduce(final IntWritable key, final Iterable<DoubleWritable> values, final Context context)
  throws IOException, InterruptedException {
    DescriptiveStatistics stats = new DescriptiveStatistics();
    for(DoubleWritable rating : values) {
        stats.addValue(rating.get());
    }

    DBObject builder = new BasicDBObjectBuilder().start()
        .add("movieid", key.get())
        .add("mean", stats.getMean())
        .add("median", stats.getPercentile(50))
        .add("std", stats.getStandardDeviation())
        .add("count", stats.getN())
        .add("total", stats.getSum())
        .get();

    BSONWritable doc = new BSONWritable(builder);

    context.write(NullWritable.get(), doc);
}
 
Example #8
Source File: FSDelegation.java    From sissi with Apache License 2.0 6 votes vote down vote up
@Override
public Delegation push(Exchanger exchanger) {
	// {"host":Xxx}
	Map<String, Object> peek = this.persistent.peek(MongoUtils.asMap(BasicDBObjectBuilder.start(Dictionary.FIELD_HOST, exchanger.host()).get()));
	ByteTransferBuffer buffer = null;
	try {
		buffer = new ByteTransferBuffer(new BufferedInputStream(new FileInputStream(new File(FSDelegation.this.dir, peek.get(Dictionary.FIELD_SID).toString()))), Long.valueOf(peek.get(Dictionary.FIELD_SIZE).toString())).write(exchanger);
		return this;
	} catch (Exception e) {
		this.log.warn(e.toString());
		Trace.trace(this.log, e);
		throw new RuntimeException(e);
	} finally {
		IOUtil.closeQuietly(buffer);
	}
}
 
Example #9
Source File: MongoMucRelationContext.java    From sissi with Apache License 2.0 6 votes vote down vote up
@Override
public MongoMucRelationContext establish(JID from, Relation relation) {
	try {
		// {"jid":relation.jid,"roles.path":from.asString}, {"$set":{"roles.nick":relation.name}}
		if (MongoUtils.success(this.config.collection().update(BasicDBObjectBuilder.start(this.buildQuery(relation.jid()).toMap()).add(Dictionary.FIELD_ROLES + "." + Dictionary.FIELD_PATH, from.asString()).get(), BasicDBObjectBuilder.start("$set", BasicDBObjectBuilder.start().add(Dictionary.FIELD_ROLES + ".$." + Dictionary.FIELD_NICK, relation.name()).get()).get(), true, false, WriteConcern.SAFE))) {
			// The positional $ operator cannot be used for queries which traverse more than one array
			// https://jira.mongodb.org/browse/SERVER-13509
			// {"jid":relation.jid,"affiliations.jid":from.bare}, {"$set":{"affiliations.nick":relation.name}}
			this.config.collection().update(BasicDBObjectBuilder.start(this.buildQuery(relation.jid()).toMap()).add(Dictionary.FIELD_AFFILIATIONS + "." + Dictionary.FIELD_JID, from.asStringWithBare()).get(), BasicDBObjectBuilder.start("$set", BasicDBObjectBuilder.start().add(Dictionary.FIELD_AFFILIATIONS + ".$." + Dictionary.FIELD_NICK, relation.name()).get()).get());
		}
	} catch (MongoException e) {
		String role = ItemRole.toString(this.mapping[this.vcardContext.exists(this.jidBuilder.build(relation.jid())) ? ItemAffiliation.parse(relation.cast(MucRelation.class).affiliation()).ordinal() : ItemAffiliation.OWNER.ordinal()]);
		// 如果已存在岗位(新增用户)
		if (this.affiliation(from, this.jidBuilder.build(relation.jid()), null) != null) {
			DBObject query = this.buildQuery(relation.jid());
			query.put(Dictionary.FIELD_AFFILIATIONS + "." + Dictionary.FIELD_JID, from.asStringWithBare());
			// {"jid":jid,"affiliations.jid":from.bare}, {"$inc":{"configs.maxusers":1},"$set":{"affiliations.nick":relation.name,"$addToSet":{"roles":全部属性}}
			this.config.collection().update(query, BasicDBObjectBuilder.start().add("$inc", this.countIncMaxUsers).add("$set", BasicDBObjectBuilder.start(Dictionary.FIELD_AFFILIATIONS + ".$." + Dictionary.FIELD_NICK, relation.name()).get()).add("$addToSet", BasicDBObjectBuilder.start().add(Dictionary.FIELD_ROLES, BasicDBObjectBuilder.start().add(Dictionary.FIELD_JID, from.asStringWithBare()).add(Dictionary.FIELD_PATH, from.asString()).add(Dictionary.FIELD_RESOURCE, from.resource()).add(Dictionary.FIELD_NICK, relation.name()).add(Dictionary.FIELD_ROLE, role).add(Dictionary.FIELD_ACTIVATE, System.currentTimeMillis()).get()).get()).get(), true, false, WriteConcern.SAFE);
		} else {
			
			// {"jid":jid}, {"$setOnInsert", {...plus...,"configs.activate":true,"creator":from.bare,"$inc":{"configs.maxusers":1},"$addToSet":{"affiliations":...全部属性...,"roles":...全部属性...}
			this.config.collection().update(this.buildQuery(relation.jid()), BasicDBObjectBuilder.start().add("$setOnInsert", BasicDBObjectBuilder.start(relation.plus()).add(Dictionary.FIELD_CONFIGS + "." + Dictionary.FIELD_ACTIVATE, false).add(Dictionary.FIELD_CREATOR, from.asStringWithBare()).get()).add("$inc", this.countIncMaxUsers).add("$addToSet", BasicDBObjectBuilder.start().add(Dictionary.FIELD_AFFILIATIONS, BasicDBObjectBuilder.start().add(Dictionary.FIELD_JID, from.asStringWithBare()).add(Dictionary.FIELD_AFFILIATION, relation.cast(MucRelation.class).affiliation()).add(Dictionary.FIELD_NICK, relation.name()).get()).add(Dictionary.FIELD_ROLES, BasicDBObjectBuilder.start().add(Dictionary.FIELD_JID, from.asStringWithBare()).add(Dictionary.FIELD_PATH, from.asString()).add(Dictionary.FIELD_RESOURCE, from.resource()).add(Dictionary.FIELD_NICK, relation.name()).add(Dictionary.FIELD_ROLE, role).add(Dictionary.FIELD_ACTIVATE, System.currentTimeMillis()).get()).get()).get(), true, false, WriteConcern.SAFE);
		}
	}
	return this;
}
 
Example #10
Source File: ContainerDocumentAccessorTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteEntityAndContainerDoc() {
    ContainerDocumentAccessor cda = Mockito.spy(testAccessor);
    Map<String, Object> updateDocCriteria = new HashMap<String, Object>();
    updateDocCriteria.put("event", "Tardy");
    DBObject pullObject = BasicDBObjectBuilder.start().push("$pull").add("body.attendanceEvent", updateDocCriteria).get();
    DBObject resultingAttendanceEvent = createResultAttendance(null);

    NeutralSchema attendanceSchema = createMockAttendanceSchema();

    when(mongoTemplate.getCollection(ATTENDANCE)).thenReturn(mockCollection);
    when(mockCollection.findAndModify(Mockito.any(DBObject.class), (DBObject) Mockito.isNull(), (DBObject) Mockito.isNull(),
            Mockito.eq(false), Mockito.eq(pullObject), Mockito.eq(true), Mockito.eq(false))).thenReturn(resultingAttendanceEvent);
    when(mongoTemplate.findAndRemove(Mockito.any(Query.class), Mockito.eq(Entity.class), Mockito.eq(ATTENDANCE))).thenReturn(entity); // just return something non-null
    when(schemaRepo.getSchema(EntityNames.ATTENDANCE)).thenReturn(attendanceSchema);

    boolean result = cda.deleteContainerNonSubDocs(entity);

    Mockito.verify(mockCollection, Mockito.times(1)).findAndModify(Mockito.any(DBObject.class), (DBObject) Mockito.isNull(), (DBObject) Mockito.isNull(),
            Mockito.eq(false), Mockito.eq(pullObject), Mockito.eq(true), Mockito.eq(false));
    Mockito.verify(mongoTemplate, Mockito.times(1)).findAndRemove(Mockito.any(Query.class), Mockito.eq(Entity.class), Mockito.eq(ATTENDANCE));
    assertTrue(result);
}
 
Example #11
Source File: MongoEntityTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testCreateAggregate() {
    Map<String, Object> body = new HashMap<String, Object>();
    Map<String, Object> aggregate = new HashMap<String, Object>();
    Map<String, Object> assessments = new HashMap<String, Object>();
    Map<String, Object> mathTest = new HashMap<String, Object>();
    Map<String, Integer> highestEver = new HashMap<String, Integer>();
    highestEver.put("E", 15);
    highestEver.put("2", 20);
    mathTest.put("HighestEver", highestEver);
    assessments.put("ACT", mathTest);
    aggregate.put("assessments", assessments);
    DBObject dbObject = new BasicDBObjectBuilder().add("_id", "42").add("body", body)
            .add("aggregations", aggregate).get();
    CalculatedData<Map<String, Integer>> data = MongoEntity.fromDBObject(dbObject).getAggregates();
    assertEquals(Arrays.asList(new CalculatedDatum<Map<String, Integer>>("assessments", "HighestEver", "ACT",
            "aggregate", highestEver)), data.getCalculatedValues());
    
}
 
Example #12
Source File: ManualEmbeddedMongoDbIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@DisplayName("Given object When save object using MongoDB template Then object can be found")
@Test
void test() throws Exception {
    // given
    DBObject objectToSave = BasicDBObjectBuilder.start()
        .add("key", "value")
        .get();

    // when
    mongoTemplate.save(objectToSave, "collection");

    // then
    assertThat(mongoTemplate.findAll(DBObject.class, "collection")).extracting("key")
        .containsOnly("value");
}
 
Example #13
Source File: MongoMucRelationContext.java    From sissi with Apache License 2.0 5 votes vote down vote up
@Override
public JIDs mapping(JID group) {
	// {"$match":{"jid":group.bare}}, {"$unwind":"$roles"}, {"$match":{"roles.nick":Xxx}}, {"$project":{"roles":"$roles"}}, {"$group":{"_id":"$roles.jid","resource":{"$push":"$roles.resource"}}}
	AggregationOutput output = this.config.collection().aggregate(this.buildMatcher(group), this.unwindRoles, BasicDBObjectBuilder.start().add("$match", BasicDBObjectBuilder.start(Dictionary.FIELD_ROLES + "." + Dictionary.FIELD_NICK, group.resource()).get()).get(), this.projectRoles, this.groupMapping);
	@SuppressWarnings("deprecation")
	List<?> result = MongoUtils.asList(output.getCommandResult(), Dictionary.FIELD_RESULT);
	return result.isEmpty() ? this.jids : this.extract(DBObject.class.cast(result.get(0)));
}
 
Example #14
Source File: MongoRoomBuilder.java    From sissi with Apache License 2.0 5 votes vote down vote up
public String reserved(JID jid) {
	// {"$match":{"jid":group.bare}}, {"$unwind":"$affiliations"}, {"$match":{"affiliations.jid":jid.bare}}, {"$project":{"nick":"$affiliations.nick"}}
	AggregationOutput output = MongoRoomBuilder.this.config.collection().aggregate(BasicDBObjectBuilder.start("$match", BasicDBObjectBuilder.start(Dictionary.FIELD_JID, this.group.asStringWithBare()).get()).get(), MongoRoomBuilder.this.unwind, BasicDBObjectBuilder.start("$match", BasicDBObjectBuilder.start(Dictionary.FIELD_AFFILIATIONS + "." + Dictionary.FIELD_JID, jid.asStringWithBare()).get()).get(), MongoRoomBuilder.this.project);
	@SuppressWarnings("deprecation")
	List<?> result = MongoUtils.asList(output.getCommandResult(), Dictionary.FIELD_RESULT);
	return result.isEmpty() ? null : MongoUtils.asString(DBObject.class.cast(result.get(0)), Dictionary.FIELD_NICK);
}
 
Example #15
Source File: MongoMucRelation4AffiliationContext.java    From sissi with Apache License 2.0 5 votes vote down vote up
@Override
public MongoMucRelationContext update(JID from, JID to, String status) {
	// 1,更新成功 2,允许级联 3,岗位为Outcast或岗位受限制
	if (this.affiliationBuilder.build(to).update(from, status) && this.cascade && (ItemAffiliation.OUTCAST.equals(status) || !ItemAffiliation.parse(status).contains(MongoUtils.asString(MongoUtils.asDBObject(this.config.collection().findOne(BasicDBObjectBuilder.start(Dictionary.FIELD_JID, to.asStringWithBare()).get(), this.filterUpdate), Dictionary.FIELD_CONFIGS), Dictionary.FIELD_AFFILIATION)))) {
		super.remove(from, to, true);
	}
	return this;
}
 
Example #16
Source File: MongoTemplate.java    From light-task-scheduler with Apache License 2.0 5 votes vote down vote up
private BasicDBObject parseFieldsString(final String fields) {
    BasicDBObjectBuilder ret = BasicDBObjectBuilder.start();
    final String[] parts = fields.split(",");
    for (String s : parts) {
        s = s.trim();
        int dir = 1;
        if (s.startsWith("-")) {
            dir = -1;
            s = s.substring(1).trim();
        }
        ret = ret.add(s, dir);
    }
    return (BasicDBObject) ret.get();
}
 
Example #17
Source File: MongoMucRelation4RoleContext.java    From sissi with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public Set<JID> iSubscribedWho(JID from) {
	// {"$match":{"roles.jid":from.bare,"roles.resource":from.resource}}
	DBObject match = BasicDBObjectBuilder.start("$match", BasicDBObjectBuilder.start().add(Dictionary.FIELD_ROLES + "." + Dictionary.FIELD_JID, from.asStringWithBare()).add(Dictionary.FIELD_ROLES + "." + Dictionary.FIELD_RESOURCE, from.resource()).get()).get();
	// match, {"$unwind":"$roles"}, match, {"$project":{"jid":"$jid","resource":"$roles.nick"}}
	return new JIDGroup(MongoUtils.asList(this.config.collection().aggregate(match, super.unwindRoles, match, this.projectSubscribed).getCommandResult(), Dictionary.FIELD_RESULT));
}
 
Example #18
Source File: MongoMucRelation4RoleContext.java    From sissi with Apache License 2.0 5 votes vote down vote up
public Set<Relation> myRelations(JID from, String role) {
	// {"$match":{"jid":group.bare}}, {"$unwind":"$roles"}, {"$match":{"roles.role":Xxx}}, {"$group":{"_id":{"jid":"$jid","creator":"$creator","affiliations":"$affiliations"},"roles":{"$addToSet":"$roles"}}}, {"$project":{"jid":"$_id.jid","creator":"$_id.creator","affiliations":"$_id.affiliations","roles":"$roles"}}
	AggregationOutput output = super.config.collection().aggregate(this.buildMatcher(from), super.unwindRoles, BasicDBObjectBuilder.start().add("$match", BasicDBObjectBuilder.start(Dictionary.FIELD_ROLES + "." + Dictionary.FIELD_ROLE, role).get()).get(), this.group, this.projectRole);
	@SuppressWarnings("deprecation")
	List<?> result = MongoUtils.asList(output.getCommandResult(), Dictionary.FIELD_RESULT);
	return result.isEmpty() ? this.relations : new MongoRelations(DBObject.class.cast(result.get(0)));
}
 
Example #19
Source File: PersonConverter.java    From journaldev with MIT License 5 votes vote down vote up
public static DBObject toDBObject(Person p) {

		BasicDBObjectBuilder builder = BasicDBObjectBuilder.start()
				.append("name", p.getName()).append("country", p.getCountry());
		if (p.getId() != null)
			builder = builder.append("_id", new ObjectId(p.getId()));
		return builder.get();
	}
 
Example #20
Source File: MongoRelationRosterContext.java    From sissi with Apache License 2.0 5 votes vote down vote up
@Override
public MongoRelationRosterContext establish(JID from, Relation relation) {
	// {"$set":{(...relation.plus()...),"nick":relation.name(),"activate":true},"$setOnInsert":{"status":0}}
	// {"$setOnInsert":{"activate":false,"status":0}}
	if (MongoUtils.success(this.config.collection().update(this.buildQuery(from.asStringWithBare(), relation.jid()), BasicDBObjectBuilder.start().add("$set", BasicDBObjectBuilder.start(relation.plus()).add(Dictionary.FIELD_NICK, relation.name()).add(Dictionary.FIELD_ACTIVATE, true).get()).add("$setOnInsert", this.initMaster).get(), true, false, WriteConcern.SAFE)) && MongoUtils.success(this.config.collection().update(this.buildQuery(relation.jid(), from.asStringWithBare()), BasicDBObjectBuilder.start("$setOnInsert", this.initSlave).get(), true, false, WriteConcern.SAFE))) {
		return this;
	}
	this.log.error("Establish warning: " + from.asStringWithBare() + " / " + relation.jid());
	return this;
}
 
Example #21
Source File: MongoRelationRosterContext.java    From sissi with Apache License 2.0 5 votes vote down vote up
@Override
public MongoRelationRosterContext update(JID from, JID to, String state) {
	// {"$unset":{"ack":true},"$bit":{"status",this.update.Xxx}}
	// {"$bit":{"status",this.update.Xxx}}
	if (MongoUtils.success(this.config.collection().update(this.buildQuery(from.asStringWithBare(), to.asStringWithBare()), BasicDBObjectBuilder.start().add("$unset", BasicDBObjectBuilder.start(Dictionary.FIELD_ACK, true).get()).add("$bit", BasicDBObjectBuilder.start().add(Dictionary.FIELD_STATUS, this.update.get(state).getTo()).get()).get(), true, false, WriteConcern.SAFE)) && MongoUtils.success(this.config.collection().update(this.buildQuery(to.asStringWithBare(), from.asStringWithBare()), BasicDBObjectBuilder.start("$bit", BasicDBObjectBuilder.start().add(Dictionary.FIELD_STATUS, this.update.get(state).getFrom()).get()).get(), true, false, WriteConcern.SAFE))) {
		this.relationCascade.update(to, from);
		return this;
	}
	this.log.error("Update warning: " + from.asStringWithBare() + " / " + to.asStringWithBare() + " / " + state);
	return this;
}
 
Example #22
Source File: MongoRegisterContext.java    From sissi with Apache License 2.0 5 votes vote down vote up
@Override
public boolean register(String username, Fields fields) {
	try {
		return this.valid(fields) ? MongoUtils.success(this.config.collection().update(BasicDBObjectBuilder.start(Dictionary.FIELD_USERNAME, username).get(), BasicDBObjectBuilder.start("$set", BasicDBObjectBuilder.start(super.entities(fields, BasicDBObjectBuilder.start()).toMap()).add(Dictionary.FIELD_ACTIVATE, true).get()).get(), true, false, WriteConcern.SAFE)) : false;
	} catch (MongoException e) {
		return false;
	}
}
 
Example #23
Source File: MongoPersistent.java    From sissi with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<Element> pull(JID jid) {
	DBObject query = BasicDBObjectBuilder.start().add(Dictionary.FIELD_TO, jid.asStringWithBare()).add("$or", this.activate).add(Dictionary.FIELD_CLASS, this.support).add(Dictionary.FIELD_RESEND, BasicDBObjectBuilder.start("$lt", this.resend).get()).get();
	Elements elements = new Elements(this.config.collection().find(query), this.elements);
	// {"$set:{"activate":false,"$inc":{"resend":1}}}
	this.config.collection().update(query, BasicDBObjectBuilder.start().add("$set", BasicDBObjectBuilder.start(Dictionary.FIELD_ACTIVATE, false).get()).add("$inc", BasicDBObjectBuilder.start(Dictionary.FIELD_RESEND, 1).get()).get(), false, true);
	return elements;
}
 
Example #24
Source File: MongoFieldsContext.java    From sissi with Apache License 2.0 5 votes vote down vote up
/**
 * @param field
 * @param builder
 * @param build 是否构建并返回
 * @return
 */
private DBObject entity(Field<?> field, BasicDBObjectBuilder builder, boolean build) {
	String name = null;
	if (field.hasChild()) {
		this.embed(field, builder);
	} else if ((name = this.mapping.mapping(field)) != null) {
		// 如果不存在Field子节点则保存值并终止
		builder.add(name, field.getValue());
	}
	return build ? builder.get() : null;
}
 
Example #25
Source File: MongoFieldsContext.java    From sissi with Apache License 2.0 5 votes vote down vote up
private void embed(Field<?> field, BasicDBObjectBuilder builder) {
	Fields fields = field.getChildren();
	String name = null;
	if (fields.isEmbed()) {
		this.entities(fields, builder);
	} else if ((name = this.mapping.mapping(field)) != null) {
		// 非嵌入式则创建新Key保存Field子节点,Key = Field.name
		builder.add(name, this.entities(fields, BasicDBObjectBuilder.start()));
	}
}
 
Example #26
Source File: MongoAddressing.java    From sissi with Apache License 2.0 5 votes vote down vote up
/**
 * For FindXxx</p>{"jid",Xxx,"resource":Xxx(如果使用资源)}
 * 
 * @param jid
 * @param usingResource
 * @return
 */
private DBObject buildQueryWithSmartResource(JID jid, boolean usingResource) {
	// JID,Resource
	BasicDBObjectBuilder query = BasicDBObjectBuilder.start(Dictionary.FIELD_JID, jid.asStringWithBare());
	if (usingResource && !jid.isBare()) {
		query.add(Dictionary.FIELD_RESOURCE, jid.resource());
	}
	return query.get();
}
 
Example #27
Source File: MongoDbSpringIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@DisplayName("Given object When save object using MongoDB template Then object can be found")
@Test
public void test(@Autowired MongoTemplate mongoTemplate) {
    // given
    DBObject objectToSave = BasicDBObjectBuilder.start()
        .add("key", "value")
        .get();

    // when
    mongoTemplate.save(objectToSave, "collection");

    // then
    assertThat(mongoTemplate.findAll(DBObject.class, "collection")).extracting("key")
        .containsOnly("value");
}
 
Example #28
Source File: BridgeExchangerContext.java    From sissi with Apache License 2.0 5 votes vote down vote up
/**
 * {"host":host,"date":Xxx}
 * 
 * @param host
 * @param date
 * @return
 */
private DBObject build(String host, boolean date) {
	BasicDBObjectBuilder builder = BasicDBObjectBuilder.start(Dictionary.FIELD_HOST, host);
	if (date) {
		builder.add(this.date, System.currentTimeMillis());
	}
	return builder.get();
}
 
Example #29
Source File: ContainerDocumentAccessorTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
private DBObject createResultAttendance(String date) {
    Map<String, Object> attendanceBody = new HashMap<String, Object>();
    List<Map<String, Object>> attendanceEvent = new ArrayList<Map<String, Object>>();
    if (date != null) {
        Map<String, Object> attendanceElement = new HashMap<String, Object>();
        attendanceElement.put("date", date);
        attendanceEvent.add(attendanceElement);
    }
    attendanceBody.put("attendanceEvent", attendanceEvent);
    return BasicDBObjectBuilder.start().add("body", attendanceBody).get();
}
 
Example #30
Source File: MongoPersistent.java    From sissi with Apache License 2.0 5 votes vote down vote up
/**
 * @param resend 最大重发次数
 * @param config
 * @param elements
 */
public MongoPersistent(int resend, MongoConfig config, List<PersistentElement> elements) {
	super();
	this.resend = resend;
	this.config = config;
	this.elements = elements;
	List<String> support = new ArrayList<String>();
	for (PersistentElement each : elements) {
		support.add(each.support().getSimpleName());
	}
	this.support = BasicDBObjectBuilder.start("$in", support.toArray(new String[] {})).get();
}