下面列出了com.mongodb.DBObject#get ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void importCollection() {
DBCursor cursor = mongo.getCollection("staffCohortAssociation").find();
while (cursor.hasNext()) {
DBObject spa = cursor.next();
Map<String, Object> body = (Map) spa.get("body");
List<String> staffIds = (List) body.get("staffId");
for (String staffId : staffIds) {
for (Vertex staff : graph.getVertices("mongoid", staffId)) {
List<String> cohortIds = (List) body.get("cohortId");
for (String cohortId : cohortIds)
for (Vertex program : graph.getVertices("mongoid", cohortId)) {
Edge e = graph.addEdge(null, program, staff, "staffCohort");
e.setProperty("mongoid", spa.get("_id"));
// This may not be safe.
e.setProperty("endDate", body.containsKey("endDate") ? body.get("endDate") : "");
e.setProperty("studentRecordAccess", body.get("studentRecordAccess"));
}
}
}
}
}
@Override
public boolean checkEmailVerified(UserId userId) {
DBObject query = createDBObject();
query.put(Constant._ID, userId.getInternal());
DBObject field = createDBObject();
field.put(EMAIL_VERIFIED, Constant.ONE);
DBObject dbObj = MongoDBUtil.queryFromMongo(query, databaseName, namespace, USER_COLL_NAME, field);
if ( dbObj != null ) {
DBObject obj = (DBObject)dbObj.get("profile");
if ( obj != null ) {
Boolean emailVerified = (Boolean)obj.get(UserChangeFlag.VERIFIED.value());
if (emailVerified != null ) {
return emailVerified.booleanValue();
}
}
}
return false;
}
@Override
public void importCollection() {
DBCursor cursor = mongo.getCollection("studentCohortAssociation").find();
while (cursor.hasNext()) {
DBObject spa = cursor.next();
Map<String, Object> body = (Map) spa.get("body");
for (Vertex student : graph.getVertices("mongoid", body.get("studentId"))) {
for (Vertex program : graph.getVertices("mongoid", body.get("cohortId"))) {
Edge e = graph.addEdge(null, program, student, "studentCohort");
e.setProperty("mongoid", spa.get("_id"));
// This may not be safe.
e.setProperty("endDate", body.get("endDate"));
}
}
}
}
private Object getPrincipalObject(Object principal) {
if(principal instanceof DBObject) {
DBObject principalDBObject = (DBObject)principal;
String userName = (String) principalDBObject.get("username");
String password = "";
boolean enabled = (boolean) principalDBObject.get("enabled");
boolean accountNonExpired = (boolean) principalDBObject.get("accountNonExpired");
boolean credentialsNonExpired = (boolean) principalDBObject.get("credentialsNonExpired");
boolean accountNonLocked = (boolean) principalDBObject.get("accountNonLocked");
return new org.springframework.security.core.userdetails.User(userName, password, enabled,
accountNonExpired, credentialsNonExpired, accountNonLocked, Collections.EMPTY_LIST);
} else {
return principal;
}
}
@Override
public List<Content> getFeedFor(final User user, final int limit) {
List<Content> result = new ArrayList<Content>(limit);
DBCursor cursor = buckets.find(
findBy(BUCKET_OWNER_KEY, user.getUserId()), getFields(BUCKET_CONTENT_KEY)).
sort(sortByDecending(BUCKET_ID_KEY)).batchSize(config.bucket_read_batch_size);
try{
while(cursor.hasNext() && result.size() < limit){
DBObject currentBucket = cursor.next();
@SuppressWarnings("unchecked")
List<DBObject> contentList = (List<DBObject>)currentBucket.get(BUCKET_CONTENT_KEY);
int bucketSize = contentList.size();
for(int i = bucketSize - 1; i >= 0; --i){
result.add(new Content(contentList.get(i)));
if(result.size() >= limit)
break;
}
}
} finally {
cursor.close();
}
return result;
}
public List<Long> getAllCollectionUUIDs(DBCollection collection) {
List<Long> ids = new ArrayList<Long>();
BasicDBObject query = new BasicDBObject();
BasicDBObject keys = new BasicDBObject();
keys.put("_id", 1); // 0 means exclude, rest are included
DBCursor cur = collection.find(query, keys);
while (cur.hasNext()) {
DBObject o = cur.next();
long uuid = (Integer)o.get("_id"); // checked: db type IS int
ids.add(uuid);
}
cur.close();
return ids;
}
public Map<String, Long> constructAllInChIs() {
Map<String, Long> chems = new HashMap<String, Long>();
BasicDBObject keys = new BasicDBObject();
keys.append("_id", true);
keys.append("InChI", true);
DBCursor cur = constructCursorForMatchingChemicals(null, null, keys);
while (cur.hasNext()) {
DBObject o = cur.next();
long uuid = (Long)o.get("_id"); // checked: db type IS long
String inchi = (String)o.get("InChI");
chems.put(inchi, uuid);
}
cur.close();
return chems;
}
private String calculateStatusForFeature(final DBObject feature) {
String currentBgStatus = "passed", currentStepsStatus = "passed";
final BasicDBList scenarios = (BasicDBList) feature.get("elements");
for (final Object scenario : scenarios) {
final BasicDBObject background = (BasicDBObject) ((BasicDBObject) scenario).get("background");
if (background != null) {
final BasicDBList bgsteps = (BasicDBList) background.get("steps");
currentBgStatus = calculateStatusForSteps(currentBgStatus, bgsteps);
}
final BasicDBList steps = (BasicDBList) ((BasicDBObject) scenario).get("steps");
if (steps != null) {
currentStepsStatus = calculateStatusForSteps(currentStepsStatus, steps);
}
}
return compareStatusPriority(currentBgStatus, currentStepsStatus);
}
@Override
public void fromDBObject(DBObject dbObject, MappedField mf, Object entity, EntityCache cache, Mapper mapper) {
BasicDBList cowlist = (BasicDBList) dbObject.get(mf.getNameToStore());
if (cowlist == null)
throw new IllegalArgumentException("Improperly formatted DBObject for CopyOnWriteList");
List core = new ArrayList();
for (Object obj : cowlist) {
DBObject listEntryDbObj = (DBObject) obj;
// Hack until we can coax MappedField to understand what CopyOnWriteList is. Eliminate as soon as possible.
// Currently mf.getSubType() is null because MappedField does not use Iterable to determine a list and thus
// does not check for subtypes.
Class clazz = mapper.getOptions().getObjectFactory().createInstance(mapper, mf, listEntryDbObj).getClass();
core.add(mapper.fromDBObject(clazz, listEntryDbObj, cache));
}
mf.setFieldValue(entity, new CopyOnWriteList(core));
}
/**
* Delete an user from database by his/her name, including all the bag and
* relation data.
*
* @param userName
* @return
*/
@Override
public void removeUser(String userName) {
DBObject query = createDBObject(LOGIN_USERNAME, userName);
DBObject field = createDBObject(_ID, 1);
DBObject userObj = MongoDBUtil.queryFromMongo(query, databaseName, namespace, USER_COLL_NAME, field);
if ( userObj == null ) {
return;
}
byte[] bytes = (byte[])userObj.get(_ID);
if ( bytes != null ) {
UserId userId = UserId.fromBytes(bytes);
this.removeUser(userId);
}
}
@Test
public void testSaveBag6() throws Exception {
User user = manager.createDefaultUser();
UserId userId = new UserId("test001");
user.set_id(userId);
user.setUsername("test001");
user.setChannel("testSaveUser");
for ( int i=0; i<1; i++ ) {
user.addTool(makeBuffTool(i));
}
user.addRelation(makeRelation(user));
user.setBag(makeBag(user, 6));
manager.saveUser(user, true);
manager.saveUserBag(user, true);
Bag bag = user.getBag();
assertTrue(!bag.clearGeneralChangeFlag());
assertEquals(0, bag.clearMarkedChangeFlag().size());
//Test delete otherPropData
int expectLength = bag.getOtherPropDatas().size();
int modifyIndex = expectLength - 1;
PropData weapon = bag.getOtherPropDatas().get(modifyIndex);
bag.removeOtherPropDatas(modifyIndex+Bag.BAG_WEAR_COUNT);
manager.saveUserBag(user, true);
bag = manager.queryUserBag(user);
DBObject actual = MongoDBUtil.queryFromMongo(MongoDBUtil.createDBObject(), "testdb", null,
"bags", MongoDBUtil.createDBObject("items", Constant.ONE));
DBObject items = (DBObject)actual.get("items");
int actualLength = items.keySet().size();
assertEquals(expectLength, actualLength);
PropData weapon2 = bag.getOtherPropDatas().get(modifyIndex-1);
assertTrue(!weapon.getName().equals(weapon2.getName()));
}
private AccountData objectToRobot(ParticipantId id, DBObject robot) {
String url = (String) robot.get(ROBOT_URL_FIELD);
String secret = (String) robot.get(ROBOT_SECRET_FIELD);
RobotCapabilities capabilities =
objectToCapabilities((DBObject) robot.get(ROBOT_CAPABILITIES_FIELD));
boolean verified = (Boolean) robot.get(ROBOT_VERIFIED_FIELD);
return new RobotAccountDataImpl(id, url, secret, capabilities, verified);
}
@Override
public void insertRow(Object row) {
if ( row instanceof DBObject ) {
DBObject dbObj = ((DBObject) row);
String key = (String)dbObj.get(COLUMNS[0]);
Object value = dbObj.get(COLUMNS[1]);
this.dbObject.put(key, value);
reload();
isDataChanged = true;
}
}
public static String getFeatureStatus(final DBObject feature) {
final List<String> allStatuses = new ArrayList<>();
final BasicDBList featureElements = (BasicDBList) feature.get("elements");
if (featureElements != null) {
for (Object featureElement : featureElements) {
final DBObject scenario = (DBObject) featureElement;
if (isScenarioKeyword((String) scenario.get("keyword"))) {
allStatuses.add(getScenarioStatus(scenario));
}
}
}
return reduceStatuses(allStatuses).getTextName();
}
/**
* Parse an element (table row) representing a complex type and return the associated NR map.
*/
private Map<String, Object> parseDbElement(DBObject dbElement, int joinKey, String entityName,
List<DBCollection> supportingCollections) {
Map<String, Object> result = new HashMap<String, Object>();
Set<String> keySet = dbElement.keySet();
// add all entries from this table rowprefix
for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
String curKey = it.next();
if (curKey.equals("_id") || curKey.equals("JoinKey") || curKey.equals("ParentJoinKey")) {
continue;
}
String curVal = "" + dbElement.get(curKey);
addMapEntry(curKey, curVal, result);
/**
* Now pick up the supporting list of list files.
* The outer 'if' statement ensures this is only called if
* further levels of hierarchy exist
*/
for (Iterator<DBCollection> iter = supportingCollections.iterator(); iter.hasNext();) {
String collectionName = iter.next().toString();
if (collectionName.lastIndexOf('_') == entityName.length()) {
String listName = collectionName.substring(entityName.length() + 1);
addMapEntry(listName,
getListFromCollection(collectionName, joinKey, supportingCollections), result);
}
}
}
return result;
}
@SuppressWarnings("unchecked")
private <V> V getValueImpl(String name, V defaultVal, Class<V> type) {
BasicDBObject find = new BasicDBObject("nation", nation);
BasicDBObject query = new BasicDBObject(name, 1);
try (DBCursor cursor = this.users.find(find, query)) {
if (cursor.hasNext()) {
DBObject result = cursor.next();
Object obj = result.get(name);
//Auto-magically convert any strings to numbers, if we requested a number type
if (obj instanceof String && Number.class.isAssignableFrom(type)) {
try {
double val = Double.parseDouble((String)obj);
if (type == Double.class) {
return (V) Double.valueOf(val);
} else if (type == Float.class) {
return (V) Float.valueOf((float)val);
} else if (type == Integer.class) {
return (V) Integer.valueOf((int)val);
} else if (type == Long.class) {
return (V) Long.valueOf((long)val);
}
} catch (NumberFormatException e) {
return defaultVal;
}
} else if (obj instanceof String && Boolean.class.isAssignableFrom(type)) {
return (V) Boolean.valueOf("true".equalsIgnoreCase((String)obj));
}
return type.cast(obj);
}
}
return defaultVal;
}
@Test public void testModifierSetComplexArrayGrouping() throws Exception {
List<MongoDbOutputMeta.MongoField> paths = new ArrayList<MongoDbOutputMeta.MongoField>( 2 );
MongoDbOutputData data = new MongoDbOutputData();
VariableSpace vars = new Variables();
MongoDbOutputMeta.MongoField mf = mf( "field1", true, "bob.fred[0].george" );
mf.m_modifierUpdateOperation = "$set";
mf.m_modifierOperationApplyPolicy = "Insert&Update";
mf.init( vars );
paths.add( mf );
mf = mf( "field2", true, "bob.fred[0].george" );
mf.m_modifierUpdateOperation = "$set";
mf.m_modifierOperationApplyPolicy = "Insert&Update";
mf.init( vars );
paths.add( mf );
RowMetaInterface rm = new RowMeta();
rm.addValueMeta( new ValueMetaString( "field1" ) );
rm.addValueMeta( new ValueMetaString( "field2" ) );
Object[] dummyRow = new Object[] { "value1", "value2" };
DBObject
modifierUpdate =
data.getModifierUpdateObject( paths, rm, dummyRow, vars, MongoDbOutputData.MongoTopLevel.RECORD );
assertTrue( modifierUpdate != null );
assertTrue( modifierUpdate.get( "$set" ) != null );
DBObject setOpp = (DBObject) modifierUpdate.get( "$set" );
// in this case, we have the same path up to the array (bob.fred). The
// remaining
// terminal fields should be grouped into one record "george" as the first
// entry in
// the array - so there should be one entry for $set
assertEquals( setOpp.keySet().size(), 1 );
// check the resulting update structure
assertEquals( JSON.serialize( modifierUpdate ),
"{ \"$set\" : { \"bob.fred\" : [ { \"george\" : { \"field1\" : \"value1\" , \"field2\" : \"value2\"}}]}}" );
}
@Test
public void testSaveBag7() throws Exception {
User user = manager.createDefaultUser();
UserId userId = new UserId("test-997");
user.set_id(userId);
user.setUsername("test001");
user.setChannel("testSaveUser");
for ( int i=0; i<1; i++ ) {
user.addTool(makeBuffTool(i));
}
user.addRelation(makeRelation(user));
int expectOtherPropSize = 5;
Bag bag = new Bag();
for ( int i=0; i<expectOtherPropSize; i++) {
bag.addOtherPropDatas(makePropData(1000+i));
}
bag.wearPropData(Constant.BAG_WEAR_COUNT+0, PropDataEquipIndex.WEAPON.index());
bag.wearPropData(Constant.BAG_WEAR_COUNT+1, PropDataEquipIndex.RING1.index());
bag.wearPropData(Constant.BAG_WEAR_COUNT+2, PropDataEquipIndex.RING2.index());
user.setBag(bag);
manager.saveUser(user, true);
manager.saveUserBag(user, true);
bag = user.getBag();
assertTrue(!bag.clearGeneralChangeFlag());
assertEquals(0, bag.clearMarkedChangeFlag().size());
assertEquals(5, bag.getOtherPropDatas().size());
//unwear something
bag.wearPropData(PropDataEquipIndex.WEAPON.index(), -1);
manager.saveUserBag(user, true);
Bag actualBag = manager.queryUserBag(user);
assertEquals(5, actualBag.getOtherPropDatas().size());
assertNull(actualBag.getWearPropDatas().get(PropDataEquipIndex.WEAPON.index()));
//Test delete otherPropData
int expectLength = bag.getOtherPropDatas().size();
int modifyIndex = expectLength - 1;
PropData weapon = bag.getOtherPropDatas().get(modifyIndex);
bag.removeOtherPropDatas(modifyIndex+Bag.BAG_WEAR_COUNT);
user.setBag(bag);
manager.saveUserBag(user, true);
bag = manager.queryUserBag(user);
DBObject actual = MongoDBUtil.queryFromMongo(MongoDBUtil.createDBObject(), "testdb", null,
"bags", MongoDBUtil.createDBObject("items", Constant.ONE));
DBObject items = (DBObject)actual.get("items");
int actualLength = items.keySet().size();
assertEquals(expectLength, actualLength);
PropData weapon2 = bag.getOtherPropDatas().get(modifyIndex-1);
assertTrue(!weapon.getName().equals(weapon2.getName()));
}
public static Object as(DBObject db, String key) {
Object value = db != null ? db.get(key) : null;
return value != null ? value : null;
}
public Organism convertDBObjectToOrg(DBObject o) {
Long id = (long) o.get("org_id");
String name = (String) o.get("name");
return new Organism(id, name);
}